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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
/**
 * agent-supervisor — autonomous agent state for one assistant message.
 *
 * The chat loop in `runWithTools` is a single-LLM ReAct cycle. To turn
 * that into a Plan/Act/Observe/Reflect supervisor without doubling the
 * LLM call count, we use an inline-tag protocol: the model is instructed
 * to emit `<plan>...</plan>`, `<step_update>...</step_update>` and
 * `<reflection>...</reflection>` blocks (each on its own line) inside its
 * normal text stream. This module consumes the streamed text, extracts
 * those blocks, hides them from the user-visible delta, validates them
 * against the actual tool calls performed, and persists everything to
 * the `agent_runs` table.
 *
 * It also owns two per-turn safeguards:
 *   - circuit breaker: after N transient failures from a single tool, the
 *     remaining calls to that tool short-circuit with a structured
 *     `circuit_open` payload that suggests alternate sources;
 *   - per-turn cache: identical (tool, args) calls reuse the prior
 *     successful result so retries with reworded queries don't re-hit
 *     the same upstream.
 */
import { eq } from "drizzle-orm";
import {
  db,
  agentRuns,
  conversations,
  type AgentRunRow,
} from "@workspace/db";
import { newId } from "./ids";
import { logger } from "./logger";

// ----------------------------------------------------------------- types

export interface AgentPlanStep {
  id: string;
  goal: string;
  candidate_tools?: string[];
  success_criteria?: string;
}

export interface AgentPlan {
  steps: AgentPlanStep[];
}

export type AgentStepStatus =
  | "pending"
  | "running"
  | "done"
  | "failed"
  | "skipped";

export interface AgentEvidenceRef {
  /** "url" | "pmid" | "doi" | "uniprot" | "ot" | "id" | "numeric" | "result" */
  type: string;
  ref: string;
  tool: string;
}

export interface AgentStepState {
  id: string;
  goal: string;
  status: AgentStepStatus;
  candidate_tools?: string[];
  success_criteria?: string;
  note?: string;
  evidence_count: number;
  evidence_refs?: AgentEvidenceRef[];
  updated_at: string;
}

export interface AgentToolRoute {
  iteration: number;
  step_id: string | null;
  tool_call_id: string;
  tool_name: string;
  args_summary: string;
  outcome: "success" | "error" | "circuit_open" | "cache_hit";
  error_code?: string;
  retryable?: boolean;
  attempts?: number;
  duration_ms: number;
  at: string;
}

export interface AgentReflection {
  step_states?: Array<{
    id: string;
    status: AgentStepStatus;
    evidence_count?: number;
  }>;
  unresolved?: Array<{ id: string; reason?: string }>;
  confidence?: number;
  summary?: string;
}

export interface AgentValidator {
  passed: boolean;
  downgraded: Array<{ id: string; from: AgentStepStatus; reason: string }>;
  notes: string[];
}

export interface PublicAgentRun {
  id: string;
  conversation_id: string;
  message_id: string;
  status: "running" | "complete" | "error";
  plan: AgentPlan | null;
  steps: AgentStepState[];
  tool_routes: AgentToolRoute[];
  reflection: AgentReflection | null;
  validator: AgentValidator | null;
  iterations: number;
  input_tokens: number;
  output_tokens: number;
  started_at: string;
  finished_at: string | null;
  /**
   * Long-term memory usage for this turn. Only populated on freshly
   * generated runs (lazy historical loads return `null`).
   */
  memory?: AgentMemoryUsage | null;
}

export interface AgentMemoryUnresolved {
  id: string;
  goal: string;
  note?: string;
  source_run_id: string;
  recorded_at: string;
}

export interface AgentMemoryRecord {
  unresolved_steps: AgentMemoryUnresolved[];
  updated_at: string;
}

export interface LearnedMemoryFact {
  kind: string;
  content: string;
  confidence: number;
  salience: number;
  persisted_id?: string | null;
}

/** A single long-term memory fact injected into this turn's prompt. */
export interface InjectedMemoryFact {
  id: string;
  kind: string;
  content: string;
}

/** Per-turn metadata about long-term memory injection + extraction. */
export interface AgentMemoryUsage {
  enabled: boolean;
  used_fact_ids: string[];
  injected: InjectedMemoryFact[];
  injected_tokens: number;
  injected_count: number;
  learned: LearnedMemoryFact[];
  persisted_count: number;
}

// ----------------------------------------------------------------- constants

export const CIRCUIT_BREAKER_THRESHOLD = 2;
const TRANSIENT_ERROR_CODES = new Set([
  "rate_limited",
  "upstream_unavailable",
  "network_error",
  "timeout",
]);

// ----------------------------------------------------------------- AgentRunState

type EmitFn = (ev: { event: string; data: Record<string, unknown> }) => void;

export class AgentRunState {
  readonly id: string;
  readonly conversationId: string;
  readonly userId: string;
  readonly messageId: string;
  readonly startedAt: Date;

  plan: AgentPlan | null = null;
  steps: Map<string, AgentStepState> = new Map();
  toolRoutes: AgentToolRoute[] = [];
  reflection: AgentReflection | null = null;
  validator: AgentValidator | null = null;
  iterations = 0;

  /** Auto-extracted memory facts emitted via `<memory_fact>` this turn. */
  learnedFacts: LearnedMemoryFact[] = [];
  /** Set by messages.ts when memory is enabled — gates auto-extraction. */
  memoryAutoExtractEnabled = false;

  // per-turn safety nets
  private failureCounts: Map<string, number> = new Map();
  private openCircuits: Set<string> = new Set();
  private resultCache: Map<string, unknown> = new Map();

  // streaming-tag parser state
  private pendingLine = "";
  private inZone: { tag: TagName; buffer: string } | null = null;

  // currently active step (set on the most recent step_update->running)
  private activeStepId: string | null = null;

  private emit: EmitFn;

  constructor(args: {
    conversationId: string;
    userId: string;
    messageId: string;
    emit: EmitFn;
  }) {
    this.id = newId("arun");
    this.conversationId = args.conversationId;
    this.userId = args.userId;
    this.messageId = args.messageId;
    this.startedAt = new Date();
    this.emit = args.emit;
  }

  // ------------------------------------------------------ tag streaming

  /**
   * Feed a raw text delta from the LLM stream. Returns the substring that
   * is safe to forward to the user (with `<plan>` / `<step_update>` /
   * `<reflection>` blocks removed). Side effects: parses any closed tag
   * blocks and emits `agent_plan` / `agent_step` / `agent_reflection`
   * SSE events.
   *
   * Tag blocks must be on their own lines, e.g.
   *
   *   <plan>{"steps":[...]}</plan>
   */
  ingestTextDelta(delta: string): string {
    if (!delta) return "";
    const combined = this.pendingLine + delta;
    let visible = "";
    let cursor = 0;
    while (true) {
      const nl = combined.indexOf("\n", cursor);
      if (nl < 0) {
        // partial last line — keep buffered for next ingest
        this.pendingLine = combined.slice(cursor);
        break;
      }
      const line = combined.slice(cursor, nl);
      cursor = nl + 1;
      const out = this.processLine(line, /* isComplete */ true);
      if (out !== null) visible += out + "\n";
    }
    return visible;
  }

  /** Drain any partial buffered line at the end of an LLM iteration. */
  flushPending(): string {
    if (!this.pendingLine) return "";
    const out = this.processLine(this.pendingLine, /* isComplete */ false);
    this.pendingLine = "";
    return out ?? "";
  }

  private processLine(line: string, isComplete: boolean): string | null {
    // Already inside a structured zone — keep accumulating until close tag
    if (this.inZone) {
      const close = `</${this.inZone.tag}>`;
      const idx = line.indexOf(close);
      if (idx < 0) {
        this.inZone.buffer += line + "\n";
        return null;
      }
      this.inZone.buffer += line.slice(0, idx);
      const tag = this.inZone.tag;
      const json = this.inZone.buffer.trim();
      this.inZone = null;
      this.handleTagJson(tag, json);
      const tail = line.slice(idx + close.length);
      // Tail after close tag on the same line — treat as a fresh line so
      // recursion handles a same-line opening of another tag.
      if (tail) return this.processLine(tail, isComplete);
      return null;
    }

    const trimmed = line.trim();
    // Detect a tag opener. Allow opening + closing on the same line.
    for (const tag of ALL_TAGS) {
      const open = `<${tag}>`;
      const close = `</${tag}>`;
      if (trimmed.startsWith(open)) {
        const restAfterOpen = trimmed.slice(open.length);
        const closeIdx = restAfterOpen.indexOf(close);
        if (closeIdx >= 0) {
          const json = restAfterOpen.slice(0, closeIdx).trim();
          this.handleTagJson(tag, json);
          return null;
        }
        // Tag opened but not closed on this line — enter zone
        this.inZone = { tag, buffer: restAfterOpen + "\n" };
        return null;
      }
    }
    return line;
  }

  private handleTagJson(tag: TagName, json: string) {
    let parsed: unknown;
    try {
      parsed = JSON.parse(json);
    } catch (err) {
      logger.debug({ tag, jsonLen: json.length, err }, "agent tag parse failed");
      return;
    }
    if (tag === "plan") {
      this.applyPlan(parsed);
    } else if (tag === "step_update") {
      this.applyStepUpdate(parsed);
    } else if (tag === "reflection") {
      this.applyReflection(parsed);
    } else if (tag === "memory_fact") {
      this.applyMemoryFact(parsed);
    }
  }

  private applyMemoryFact(raw: unknown) {
    if (!this.memoryAutoExtractEnabled) return;
    if (this.learnedFacts.length >= MAX_LEARNED_FACTS_PER_TURN) return;
    if (!raw || typeof raw !== "object") return;
    const r = raw as Record<string, unknown>;
    const content = typeof r.content === "string" ? r.content.trim() : "";
    if (!content) return;
    const kindRaw = typeof r.kind === "string" ? r.kind : "other";
    const kind = VALID_MEMORY_KINDS.has(kindRaw) ? kindRaw : "other";
    const confidence =
      typeof r.confidence === "number" && Number.isFinite(r.confidence)
        ? Math.max(0, Math.min(1, r.confidence))
        : 0.7;
    const salience =
      typeof r.salience === "number" && Number.isFinite(r.salience)
        ? Math.max(0, Math.min(1, r.salience))
        : 0.6;
    const fact: LearnedMemoryFact = {
      kind,
      content:
        content.length > MAX_FACT_CONTENT_CHARS
          ? content.slice(0, MAX_FACT_CONTENT_CHARS)
          : content,
      confidence,
      salience,
    };
    this.learnedFacts.push(fact);
    this.emit({
      event: "agent_memory_learned",
      data: {
        agent_run_id: this.id,
        message_id: this.messageId,
        fact,
      },
    });
  }

  private applyPlan(raw: unknown) {
    if (!raw || typeof raw !== "object") return;
    const stepsRaw = (raw as { steps?: unknown }).steps;
    if (!Array.isArray(stepsRaw)) return;
    const steps: AgentPlanStep[] = [];
    for (const s of stepsRaw) {
      if (!s || typeof s !== "object") continue;
      const r = s as Record<string, unknown>;
      const id = typeof r.id === "string" && r.id ? r.id : `s${steps.length + 1}`;
      const goal = typeof r.goal === "string" ? r.goal : "";
      if (!goal) continue;
      steps.push({
        id,
        goal,
        candidate_tools: Array.isArray(r.candidate_tools)
          ? (r.candidate_tools.filter((x) => typeof x === "string") as string[])
          : undefined,
        success_criteria:
          typeof r.success_criteria === "string" ? r.success_criteria : undefined,
      });
    }
    if (!steps.length) return;
    // Only accept the first plan emitted in a turn — subsequent plans
    // would invalidate already-recorded step state.
    if (this.plan) return;
    this.plan = { steps };
    const now = new Date().toISOString();
    for (const s of steps) {
      this.steps.set(s.id, {
        id: s.id,
        goal: s.goal,
        status: "pending",
        candidate_tools: s.candidate_tools,
        success_criteria: s.success_criteria,
        evidence_count: 0,
        updated_at: now,
      });
    }
    this.emit({
      event: "agent_plan",
      data: {
        agent_run_id: this.id,
        message_id: this.messageId,
        plan: this.plan,
        steps: Array.from(this.steps.values()),
      },
    });
  }

  private applyStepUpdate(raw: unknown) {
    if (!raw || typeof raw !== "object") return;
    const r = raw as Record<string, unknown>;
    const id = typeof r.id === "string" ? r.id : "";
    if (!id) return;
    let step = this.steps.get(id);
    if (!step) {
      // Late step introduced after plan — accept it as a synthetic step
      step = {
        id,
        goal: typeof r.goal === "string" ? r.goal : id,
        status: "pending",
        evidence_count: 0,
        updated_at: new Date().toISOString(),
      };
      this.steps.set(id, step);
    }
    const status = typeof r.status === "string" ? (r.status as AgentStepStatus) : null;
    if (status && VALID_STATUSES.has(status)) {
      step.status = status;
      if (status === "running") this.activeStepId = id;
    }
    if (typeof r.note === "string") step.note = r.note;
    step.updated_at = new Date().toISOString();
    this.emit({
      event: "agent_step",
      data: {
        agent_run_id: this.id,
        message_id: this.messageId,
        step: { ...step },
      },
    });
  }

  private applyReflection(raw: unknown) {
    if (!raw || typeof raw !== "object") return;
    const r = raw as Record<string, unknown>;
    const reflection: AgentReflection = {};
    if (Array.isArray(r.step_states)) {
      reflection.step_states = (r.step_states as unknown[])
        .map((s) => {
          if (!s || typeof s !== "object") return null;
          const x = s as Record<string, unknown>;
          if (typeof x.id !== "string") return null;
          const status = typeof x.status === "string" ? (x.status as AgentStepStatus) : "pending";
          if (!VALID_STATUSES.has(status)) return null;
          return {
            id: x.id,
            status,
            evidence_count:
              typeof x.evidence_count === "number" ? x.evidence_count : undefined,
          };
        })
        .filter((x): x is NonNullable<typeof x> => x !== null);
    }
    if (Array.isArray(r.unresolved)) {
      reflection.unresolved = (r.unresolved as unknown[])
        .map((s) => {
          if (typeof s === "string") return { id: s };
          if (s && typeof s === "object" && typeof (s as Record<string, unknown>).id === "string") {
            const x = s as Record<string, unknown>;
            return { id: x.id as string, reason: typeof x.reason === "string" ? x.reason : undefined };
          }
          return null;
        })
        .filter((x): x is NonNullable<typeof x> => x !== null);
    }
    if (typeof r.confidence === "number") reflection.confidence = r.confidence;
    if (typeof r.summary === "string") reflection.summary = r.summary;
    this.reflection = reflection;
    // Apply step_states to the live map so the panel reflects the model's
    // own self-assessment alongside any in-flight `step_update`s.
    if (reflection.step_states) {
      for (const s of reflection.step_states) {
        const step = this.steps.get(s.id);
        if (!step) continue;
        step.status = s.status;
        if (typeof s.evidence_count === "number") step.evidence_count = s.evidence_count;
        step.updated_at = new Date().toISOString();
      }
    }
    this.emit({
      event: "agent_reflection",
      data: {
        agent_run_id: this.id,
        message_id: this.messageId,
        reflection,
        steps: Array.from(this.steps.values()),
      },
    });
  }

  // ---------------------------------------------------- tool dispatch

  noteIteration() {
    this.iterations += 1;
  }

  /** Cache key for de-duplicating identical tool calls within a turn. */
  private cacheKey(toolName: string, args: Record<string, unknown>): string {
    let argStr = "";
    try {
      argStr = JSON.stringify(args);
    } catch {
      argStr = String(Object.keys(args).sort().join(","));
    }
    return `${toolName}::${argStr}`;
  }

  /** Returns a cached successful result if one exists for this call. */
  cacheLookup(toolName: string, args: Record<string, unknown>): unknown | undefined {
    return this.resultCache.get(this.cacheKey(toolName, args));
  }

  /**
   * Compute the per-source key used by the circuit breaker. We include the
   * concrete upstream identifier (research-engine `task_mode`, an explicit
   * `source` argument, or the underlying engine endpoint) so a single
   * misbehaving source does not trip the breaker for every other variant
   * of the same tool. Falls back to the bare tool name when no
   * disambiguator is available.
   */
  circuitKey(toolName: string, args: Record<string, unknown>): string {
    const sub =
      typeof args.task_mode === "string" && args.task_mode
        ? `task_mode:${args.task_mode}`
        : typeof args.source === "string" && args.source
          ? `source:${args.source}`
          : typeof args.endpoint === "string" && args.endpoint
            ? `endpoint:${args.endpoint}`
            : typeof args.database === "string" && args.database
              ? `db:${args.database}`
              : null;
    return sub ? `${toolName}#${sub}` : toolName;
  }

  circuitCheck(
    toolName: string,
    args: Record<string, unknown> = {},
  ): null | {
    error: string;
    error_code: "circuit_open";
    retryable: false;
    source: string;
    suggestion: string;
  } {
    const key = this.circuitKey(toolName, args);
    if (!this.openCircuits.has(key)) return null;
    return {
      error: `Source ${key} disabled for this turn after repeated transient failures.`,
      error_code: "circuit_open",
      retryable: false,
      source: key,
      suggestion: alternativeSuggestion(toolName),
    };
  }

  /**
   * Record the outcome of a tool call — update circuit-breaker counters,
   * cache successful results, and append a tool route entry.
   */
  recordToolOutcome(args: {
    toolCallId: string;
    toolName: string;
    args: Record<string, unknown>;
    result: unknown;
    isError: boolean;
    durationMs: number;
    fromCache?: boolean;
    fromCircuit?: boolean;
  }) {
    const errCode = errorCodeOf(args.result, args.isError);
    const transient = errCode ? TRANSIENT_ERROR_CODES.has(errCode) : false;
    const sourceKey = this.circuitKey(args.toolName, args.args);
    if (transient) {
      const next = (this.failureCounts.get(sourceKey) ?? 0) + 1;
      this.failureCounts.set(sourceKey, next);
      if (next >= CIRCUIT_BREAKER_THRESHOLD) {
        this.openCircuits.add(sourceKey);
      }
    } else if (!args.isError) {
      // Cache successful results for the rest of the turn.
      this.resultCache.set(this.cacheKey(args.toolName, args.args), args.result);
      // Successful call also bumps evidence count for the active step and
      // extracts any source-linked refs (URLs / PMIDs / accessions) so the
      // validator can later check that "done" steps actually have evidence.
      if (this.activeStepId) {
        const step = this.steps.get(this.activeStepId);
        if (step) {
          step.evidence_count += 1;
          const refs = extractEvidenceRefs(args.result, args.toolName);
          if (refs.length) {
            step.evidence_refs = (step.evidence_refs ?? []).concat(refs).slice(0, 25);
          }
          step.updated_at = new Date().toISOString();
        }
      }
    }
    const route: AgentToolRoute = {
      iteration: this.iterations,
      step_id: this.activeStepId,
      tool_call_id: args.toolCallId,
      tool_name: args.toolName,
      args_summary: summariseArgs(args.args),
      outcome: args.fromCircuit
        ? "circuit_open"
        : args.fromCache
        ? "cache_hit"
        : args.isError
        ? "error"
        : "success",
      error_code: errCode ?? undefined,
      retryable:
        args.isError && args.result && typeof args.result === "object"
          ? Boolean((args.result as Record<string, unknown>).retryable)
          : undefined,
      attempts:
        args.result && typeof args.result === "object" && typeof (args.result as Record<string, unknown>).attempts === "number"
          ? ((args.result as Record<string, unknown>).attempts as number)
          : undefined,
      duration_ms: args.durationMs,
      at: new Date().toISOString(),
    };
    this.toolRoutes.push(route);
    this.emit({
      event: "agent_tool_route",
      data: {
        agent_run_id: this.id,
        message_id: this.messageId,
        route,
      },
    });
  }

  // ---------------------------------------------------- validation + persist

  /**
   * Reconcile model-claimed step states with the actual tool route log
   * and the evidence collected from successful tool results. A `done`
   * step is downgraded to `failed` when *any* of these machine-checkable
   * conditions hold:
   *
   *   - no successful tool route was recorded for the step
   *     (`reason: "no_evidence"`),
   *   - no source-linked evidence reference (URL / PMID / DOI / accession
   *     / structured id) is present on the step
   *     (`reason: "no_source_link"`),
   *   - the step's `success_criteria` calls out a numeric quantity but
   *     none of the captured evidence carries a numeric ref
   *     (`reason: "missing_numeric_evidence"`),
   *   - the model's own reflection lists this step under `unresolved`
   *     while the plan still claims `done`
   *     (`reason: "reflection_inconsistent"`).
   *
   * The validator never *upgrades* — it only downgrades and records
   * notes. Recovery (one extra tool round) is the caller's job and is
   * driven by `needsRecoveryRound()`.
   */
  runValidator(): AgentValidator {
    const downgraded: AgentValidator["downgraded"] = [];
    const notes: string[] = [];
    const successByStep = new Map<string, number>();
    for (const r of this.toolRoutes) {
      if (r.outcome !== "success" && r.outcome !== "cache_hit") continue;
      if (!r.step_id) continue;
      successByStep.set(r.step_id, (successByStep.get(r.step_id) ?? 0) + 1);
    }
    const reflectionUnresolved = new Set(
      (this.reflection?.unresolved ?? []).map((u) => u.id),
    );
    for (const step of this.steps.values()) {
      if (step.status !== "done") continue;
      const reasons: string[] = [];
      const success = successByStep.get(step.id) ?? 0;
      if (success === 0) reasons.push("no_evidence");
      const refs = step.evidence_refs ?? [];
      const hasSourceLink = refs.some(
        (r) =>
          r.type === "url" ||
          r.type === "pmid" ||
          r.type === "doi" ||
          r.type === "uniprot" ||
          r.type === "ot" ||
          r.type === "id",
      );
      if (success > 0 && !hasSourceLink) reasons.push("no_source_link");
      if (
        mentionsNumericClaim(step.success_criteria, step.goal) &&
        !refs.some((r) => r.type === "numeric")
      ) {
        reasons.push("missing_numeric_evidence");
      }
      if (reflectionUnresolved.has(step.id)) {
        reasons.push("reflection_inconsistent");
      }
      if (reasons.length === 0) continue;
      const reason = reasons[0]!;
      downgraded.push({ id: step.id, from: step.status, reason });
      step.status = "failed";
      const noteSuffix = `downgraded: ${reasons.join(", ")}`;
      step.note = step.note ? `${step.note} | ${noteSuffix}` : noteSuffix;
      step.updated_at = new Date().toISOString();
    }
    if (this.openCircuits.size) {
      notes.push(
        `Circuit breaker tripped for: ${Array.from(this.openCircuits).join(", ")}`,
      );
    }
    const passed = downgraded.length === 0;
    this.validator = { passed, downgraded, notes };
    return this.validator;
  }

  /** True when at least one step needs another tool call to satisfy. */
  needsRecoveryRound(): boolean {
    if (!this.validator) return false;
    return this.validator.downgraded.length > 0;
  }

  /**
   * Emit a consolidated `agent_run_snapshot` SSE event reflecting the
   * current plan / step / tool-route state. Called after every iteration
   * of the runWithTools loop so an in-chat panel that drops a delta (or
   * a client that reconnects mid-run) can rehydrate from a single payload
   * instead of having to replay every individual delta.
   */
  emitSnapshot(args: {
    status: PublicAgentRun["status"];
    finishedAt?: Date | null;
    inputTokens: number;
    outputTokens: number;
    memory?: AgentMemoryUsage | null;
  }): void {
    this.emit({
      event: "agent_run_snapshot",
      data: {
        agent_run: this.toPublic(
          args.status,
          args.finishedAt ?? null,
          { input: args.inputTokens, output: args.outputTokens },
          args.memory ?? null,
        ),
      },
    });
  }

  toPublic(
    status: PublicAgentRun["status"],
    finishedAt: Date | null,
    tokens: { input: number; output: number },
    memory: AgentMemoryUsage | null = null,
  ): PublicAgentRun {
    return {
      id: this.id,
      conversation_id: this.conversationId,
      message_id: this.messageId,
      status,
      plan: this.plan,
      steps: Array.from(this.steps.values()),
      tool_routes: this.toolRoutes,
      reflection: this.reflection,
      validator: this.validator,
      iterations: this.iterations,
      input_tokens: tokens.input,
      output_tokens: tokens.output,
      started_at: this.startedAt.toISOString(),
      finished_at: finishedAt ? finishedAt.toISOString() : null,
      memory,
    };
  }

  /**
   * Upsert the agent_run row. Called after each iteration so the panel
   * survives client refreshes mid-turn, and again at the end with the
   * final terminal state.
   */
  async persist(args: {
    status: PublicAgentRun["status"];
    finishedAt: Date | null;
    inputTokens: number;
    outputTokens: number;
  }): Promise<void> {
    const payload = {
      id: this.id,
      conversationId: this.conversationId,
      userId: this.userId,
      messageId: this.messageId,
      status: args.status,
      plan: this.plan as unknown,
      steps: Array.from(this.steps.values()) as unknown,
      toolRoutes: this.toolRoutes as unknown,
      reflection: this.reflection as unknown,
      validator: this.validator as unknown,
      inputTokens: args.inputTokens,
      outputTokens: args.outputTokens,
      iterations: this.iterations,
      startedAt: this.startedAt,
      finishedAt: args.finishedAt,
    };
    try {
      await db
        .insert(agentRuns)
        .values(payload as never)
        .onConflictDoUpdate({
          target: agentRuns.id,
          set: {
            status: payload.status,
            plan: payload.plan as never,
            steps: payload.steps as never,
            toolRoutes: payload.toolRoutes as never,
            reflection: payload.reflection as never,
            validator: payload.validator as never,
            inputTokens: payload.inputTokens,
            outputTokens: payload.outputTokens,
            iterations: payload.iterations,
            finishedAt: payload.finishedAt,
          },
        });
    } catch (err) {
      logger.warn({ err, agentRunId: this.id }, "agent_run persist failed");
    }
  }

  /**
   * Build the working-memory record that would be persisted for the next
   * turn. Returns null when there is nothing left unresolved (callers are
   * expected to clear stored memory in that case). Pure / DB-free so the
   * cross-turn carry-over is testable without spinning up Postgres.
   */
  buildPendingWorkingMemory(): AgentMemoryRecord | null {
    const unresolved: AgentMemoryUnresolved[] = [];
    const reflectionUnresolved = new Set(
      (this.reflection?.unresolved ?? []).map((u) => u.id),
    );
    for (const step of this.steps.values()) {
      const isLeftover =
        step.status === "failed" ||
        step.status === "skipped" ||
        reflectionUnresolved.has(step.id);
      if (!isLeftover) continue;
      unresolved.push({
        id: step.id,
        goal: step.goal,
        note: step.note,
        source_run_id: this.id,
        recorded_at: new Date().toISOString(),
      });
    }
    if (!unresolved.length) return null;
    return {
      unresolved_steps: unresolved.slice(0, 10),
      updated_at: new Date().toISOString(),
    };
  }

  /**
   * Persist unresolved/failed steps into the conversation's working
   * memory so the next turn's system prompt can carry them forward.
   */
  async writeWorkingMemory(): Promise<void> {
    const record = this.buildPendingWorkingMemory();
    if (!record) {
      // Clear stale memory once all prior items are resolved.
      try {
        await db
          .update(conversations)
          .set({ agentMemory: null as unknown as object })
          .where(eq(conversations.id, this.conversationId));
      } catch (err) {
        logger.warn({ err }, "clear agent_memory failed");
      }
      return;
    }
    try {
      await db
        .update(conversations)
        .set({ agentMemory: record as unknown as object })
        .where(eq(conversations.id, this.conversationId));
    } catch (err) {
      logger.warn({ err }, "write agent_memory failed");
    }
  }
}

// ----------------------------------------------------------------- helpers

const VALID_STATUSES: Set<AgentStepStatus> = new Set([
  "pending",
  "running",
  "done",
  "failed",
  "skipped",
]);

type TagName = "plan" | "step_update" | "reflection" | "memory_fact";
const ALL_TAGS: TagName[] = ["plan", "step_update", "reflection", "memory_fact"];

const VALID_MEMORY_KINDS: ReadonlySet<string> = new Set([
  "preference",
  "fact",
  "interest",
  "domain",
  "terminology",
  "summary",
]);
/** Hard cap on auto-extracted memory facts per turn. */
export const MAX_LEARNED_FACTS_PER_TURN = 5;
const MAX_FACT_CONTENT_CHARS = 500;

function errorCodeOf(result: unknown, isError: boolean): string | null {
  if (!isError) return null;
  if (!result || typeof result !== "object") return null;
  const code = (result as Record<string, unknown>).error_code;
  return typeof code === "string" ? code : null;
}

function summariseArgs(args: Record<string, unknown>): string {
  try {
    const json = JSON.stringify(args);
    return json.length > 160 ? json.slice(0, 157) + "..." : json;
  } catch {
    return Object.keys(args).join(",");
  }
}

/**
 * Heuristic detector for numeric claims in a step's goal / success
 * criteria. Triggers on explicit digits, percent signs, and bilingual
 * keywords like "数量 / 个数 / count / number / how many". Used by the
 * validator to enforce numeric-claim traceability.
 */
function mentionsNumericClaim(
  criteria: string | undefined,
  goal: string | undefined,
): boolean {
  const text = `${criteria ?? ""}\n${goal ?? ""}`.toLowerCase();
  if (!text.trim()) return false;
  if (/\d/.test(text)) return true;
  if (/%/.test(text)) return true;
  return /(count|number|how many|n=|总数|数量|个数|条数|篇数|多少)/i.test(
    text,
  );
}

const URL_REGEX = /https?:\/\/[^\s"'<>)]+/gi;
const PMID_REGEX = /\b(?:pmid|pubmed[_\s-]*id)[:\s]*([0-9]{4,9})\b/gi;
const DOI_REGEX = /\b10\.\d{4,9}\/[\w./()\-:;]+/gi;
const UNIPROT_REGEX = /\b[OPQ][0-9][A-Z0-9]{3}[0-9]\b|\b[A-NR-Z][0-9](?:[A-Z][A-Z0-9]{2}[0-9]){1,2}\b/g;
const OT_REGEX = /\b(?:ENSG\d{6,}|EFO_\d{4,}|MONDO_\d{4,})\b/g;

/**
 * Pull source-linked evidence refs out of a successful tool result. We
 * do a depth-limited traversal so a deeply nested object (e.g. a full
 * PubMed hit list) still yields useful refs without blowing the stack
 * or copying megabytes of payload.
 */
function extractEvidenceRefs(
  result: unknown,
  toolName: string,
): AgentEvidenceRef[] {
  if (!result || (typeof result !== "object" && typeof result !== "string")) {
    return [];
  }
  const refs: AgentEvidenceRef[] = [];
  const seen = new Set<string>();
  const push = (type: string, ref: string) => {
    const key = `${type}:${ref}`;
    if (seen.has(key)) return;
    seen.add(key);
    refs.push({ type, ref, tool: toolName });
  };
  const visit = (node: unknown, depth: number) => {
    if (refs.length >= 25) return;
    if (depth > 4 || node == null) return;
    if (typeof node === "string") {
      let m: RegExpExecArray | null;
      URL_REGEX.lastIndex = 0;
      while ((m = URL_REGEX.exec(node))) push("url", m[0]);
      PMID_REGEX.lastIndex = 0;
      while ((m = PMID_REGEX.exec(node))) push("pmid", m[1]!);
      DOI_REGEX.lastIndex = 0;
      while ((m = DOI_REGEX.exec(node))) push("doi", m[0]);
      UNIPROT_REGEX.lastIndex = 0;
      while ((m = UNIPROT_REGEX.exec(node))) push("uniprot", m[0]);
      OT_REGEX.lastIndex = 0;
      while ((m = OT_REGEX.exec(node))) push("ot", m[0]);
      return;
    }
    if (typeof node === "number" && Number.isFinite(node)) {
      push("numeric", String(node));
      return;
    }
    if (Array.isArray(node)) {
      for (const x of node.slice(0, 20)) visit(x, depth + 1);
      return;
    }
    if (typeof node === "object") {
      for (const [k, v] of Object.entries(node as Record<string, unknown>)) {
        const lk = k.toLowerCase();
        if (typeof v === "string") {
          if (lk === "pmid") push("pmid", v);
          else if (lk === "doi") push("doi", v);
          else if (lk === "url" || lk.endsWith("_url")) push("url", v);
          else if (lk === "accession" || lk === "uniprot_id") push("uniprot", v);
          else if (lk === "id" || lk.endsWith("_id")) push("id", v);
        }
        if (typeof v === "number" && Number.isFinite(v)) {
          if (lk === "count" || lk === "n" || lk === "total" || lk.endsWith("_count")) {
            push("numeric", `${k}=${v}`);
          }
        }
        visit(v, depth + 1);
      }
    }
  };
  visit(result, 0);
  return refs;
}

function alternativeSuggestion(toolName: string): string {
  switch (toolName) {
    case "search_pubmed":
      return "Try query_opentargets for target↔disease evidence or lookup_uniprot for protein metadata.";
    case "lookup_uniprot":
      return "Try search_pubmed for the same protein name, or query_opentargets if you need disease links.";
    case "query_opentargets":
      return "Try search_pubmed with a clinical/mechanistic query, or create_research_task for a structured pipeline.";
    default:
      return "Switch to an alternative tool or rephrase the query for a different source.";
  }
}

/**
 * Format the next-turn system-prompt section that carries forward
 * unresolved steps. Returns an empty string when there is nothing to
 * carry forward, so callers can `if (text) sysParts.push(text)`.
 *
 * Exported so tests can verify the cross-turn working-memory payload
 * actually lands in the prompt without having to spin up the full
 * /messages/stream pipeline.
 */
export function formatCarryOverPrompt(
  memory: AgentMemoryRecord | null,
): string {
  if (!memory || !memory.unresolved_steps.length) return "";
  const lines = memory.unresolved_steps
    .map((u) => `- ${u.id}: ${u.goal}${u.note ? ` (${u.note})` : ""}`)
    .join("\n");
  return (
    "Carry-over from the previous turn — these subgoals were left " +
    "unresolved or failed. If the user has not redirected you, " +
    "pick them up; otherwise acknowledge briefly and proceed:\n" +
    lines
  );
}

// ----------------------------------------------------------------- public lookup

export async function loadAgentRunByMessage(
  messageId: string,
  userId: string,
): Promise<PublicAgentRun | null> {
  const rows = await db
    .select()
    .from(agentRuns)
    .where(eq(agentRuns.messageId, messageId))
    .limit(1);
  const row = rows[0];
  if (!row) return null;
  if (row.userId !== userId) return null;
  return rowToPublic(row);
}

export function rowToPublic(row: AgentRunRow): PublicAgentRun {
  return {
    id: row.id,
    conversation_id: row.conversationId,
    message_id: row.messageId,
    status: (row.status as PublicAgentRun["status"]) ?? "complete",
    plan: (row.plan as AgentPlan | null) ?? null,
    steps: Array.isArray(row.steps) ? (row.steps as AgentStepState[]) : [],
    tool_routes: Array.isArray(row.toolRoutes)
      ? (row.toolRoutes as AgentToolRoute[])
      : [],
    reflection: (row.reflection as AgentReflection | null) ?? null,
    validator: (row.validator as AgentValidator | null) ?? null,
    iterations: row.iterations,
    input_tokens: row.inputTokens,
    output_tokens: row.outputTokens,
    started_at: row.startedAt.toISOString(),
    finished_at: row.finishedAt ? row.finishedAt.toISOString() : null,
    memory: null,
  };
}

export async function loadConversationAgentMemory(
  conversationId: string,
): Promise<AgentMemoryRecord | null> {
  const rows = await db
    .select({ agentMemory: conversations.agentMemory })
    .from(conversations)
    .where(eq(conversations.id, conversationId))
    .limit(1);
  const m = rows[0]?.agentMemory as AgentMemoryRecord | null | undefined;
  if (!m || !Array.isArray(m.unresolved_steps) || !m.unresolved_steps.length) {
    return null;
  }
  return m;
}