omnius 1.0.537 → 1.0.539

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1209,8 +1209,8 @@ var init_model_broker = __esm({
1209
1209
  }
1210
1210
  /** Restore a set of previously evicted Ollama models, oldest first. */
1211
1211
  async restoreOllamaModels(models, options2 = {}) {
1212
- const unique2 = dedupeLoadedModels(models.filter((m2) => m2.host === "ollama")).sort((a2, b) => a2.lastUsedAt - b.lastUsedAt);
1213
- for (const model of unique2) {
1212
+ const unique3 = dedupeLoadedModels(models.filter((m2) => m2.host === "ollama")).sort((a2, b) => a2.lastUsedAt - b.lastUsedAt);
1213
+ for (const model of unique3) {
1214
1214
  await this.warmOllamaModel(model.name, options2.keepAlive ?? "30m").catch(() => false);
1215
1215
  }
1216
1216
  }
@@ -16121,8 +16121,8 @@ function mapItemKind(value2) {
16121
16121
  }
16122
16122
  return "custom";
16123
16123
  }
16124
- function mapScopeRow(row) {
16125
- const r2 = row;
16124
+ function mapScopeRow(row2) {
16125
+ const r2 = row2;
16126
16126
  return {
16127
16127
  id: String(r2.id ?? ""),
16128
16128
  name: String(r2.name ?? ""),
@@ -16136,8 +16136,8 @@ function mapScopeRow(row) {
16136
16136
  updatedAt: String(r2.updated_at ?? "")
16137
16137
  };
16138
16138
  }
16139
- function mapItemRow(row) {
16140
- const r2 = row;
16139
+ function mapItemRow(row2) {
16140
+ const r2 = row2;
16141
16141
  return {
16142
16142
  id: String(r2.id ?? ""),
16143
16143
  scopeId: String(r2.scope_id ?? ""),
@@ -16158,8 +16158,8 @@ function mapItemRow(row) {
16158
16158
  updatedAt: String(r2.updated_at ?? "")
16159
16159
  };
16160
16160
  }
16161
- function mapChunkRow(row) {
16162
- const r2 = row;
16161
+ function mapChunkRow(row2) {
16162
+ const r2 = row2;
16163
16163
  return {
16164
16164
  id: String(r2.id ?? ""),
16165
16165
  itemId: String(r2.item_id ?? ""),
@@ -16172,8 +16172,8 @@ function mapChunkRow(row) {
16172
16172
  createdAt: String(r2.created_at ?? "")
16173
16173
  };
16174
16174
  }
16175
- function mapEmbeddingSetRow(row) {
16176
- const r2 = row;
16175
+ function mapEmbeddingSetRow(row2) {
16176
+ const r2 = row2;
16177
16177
  const setType = r2.set_type === "filter" ? "filter" : "full";
16178
16178
  return {
16179
16179
  id: String(r2.id ?? ""),
@@ -16187,8 +16187,8 @@ function mapEmbeddingSetRow(row) {
16187
16187
  updatedAt: String(r2.updated_at ?? "")
16188
16188
  };
16189
16189
  }
16190
- function mapEmbeddingRow(row) {
16191
- const r2 = row;
16190
+ function mapEmbeddingRow(row2) {
16191
+ const r2 = row2;
16192
16192
  return {
16193
16193
  id: String(r2.id ?? ""),
16194
16194
  chunkId: String(r2.chunk_id ?? ""),
@@ -16200,8 +16200,8 @@ function mapEmbeddingRow(row) {
16200
16200
  createdAt: String(r2.created_at ?? "")
16201
16201
  };
16202
16202
  }
16203
- function mapProvenanceRow(row) {
16204
- const r2 = row;
16203
+ function mapProvenanceRow(row2) {
16204
+ const r2 = row2;
16205
16205
  return {
16206
16206
  id: String(r2.id ?? ""),
16207
16207
  itemId: String(r2.item_id ?? ""),
@@ -16214,8 +16214,8 @@ function mapProvenanceRow(row) {
16214
16214
  createdAt: String(r2.created_at ?? "")
16215
16215
  };
16216
16216
  }
16217
- function mapLinkRow(row) {
16218
- const r2 = row;
16217
+ function mapLinkRow(row2) {
16218
+ const r2 = row2;
16219
16219
  return {
16220
16220
  id: String(r2.id ?? ""),
16221
16221
  sourceItemId: String(r2.source_item_id ?? ""),
@@ -16234,8 +16234,8 @@ function mapJobStatus(value2) {
16234
16234
  }
16235
16235
  return "pending";
16236
16236
  }
16237
- function mapJobRow(row) {
16238
- const r2 = row;
16237
+ function mapJobRow(row2) {
16238
+ const r2 = row2;
16239
16239
  return {
16240
16240
  id: String(r2.id ?? ""),
16241
16241
  jobType: String(r2.job_type ?? ""),
@@ -16259,8 +16259,8 @@ function mapGraphNodeType(value2) {
16259
16259
  }
16260
16260
  return "concept";
16261
16261
  }
16262
- function mapGraphNodeRow(row) {
16263
- const r2 = row;
16262
+ function mapGraphNodeRow(row2) {
16263
+ const r2 = row2;
16264
16264
  return {
16265
16265
  id: String(r2.id ?? ""),
16266
16266
  scopeId: String(r2.scope_id ?? ""),
@@ -16274,8 +16274,8 @@ function mapGraphNodeRow(row) {
16274
16274
  lastSeenAt: String(r2.last_seen_at ?? "")
16275
16275
  };
16276
16276
  }
16277
- function mapGraphEdgeRow(row) {
16278
- const r2 = row;
16277
+ function mapGraphEdgeRow(row2) {
16278
+ const r2 = row2;
16279
16279
  return {
16280
16280
  id: String(r2.id ?? ""),
16281
16281
  scopeId: String(r2.scope_id ?? ""),
@@ -16291,8 +16291,8 @@ function mapGraphEdgeRow(row) {
16291
16291
  createdAt: String(r2.created_at ?? "")
16292
16292
  };
16293
16293
  }
16294
- function mapItemNodeRow(row) {
16295
- const r2 = row;
16294
+ function mapItemNodeRow(row2) {
16295
+ const r2 = row2;
16296
16296
  return {
16297
16297
  itemId: String(r2.item_id ?? ""),
16298
16298
  nodeId: String(r2.node_id ?? ""),
@@ -16303,8 +16303,8 @@ function mapItemNodeRow(row) {
16303
16303
  updatedAt: String(r2.updated_at ?? "")
16304
16304
  };
16305
16305
  }
16306
- function mapCandidateRow(row, source, score) {
16307
- const r2 = row;
16306
+ function mapCandidateRow(row2, source, score) {
16307
+ const r2 = row2;
16308
16308
  const scope = {
16309
16309
  id: String(r2.scope_id ?? ""),
16310
16310
  name: String(r2.scope_name ?? ""),
@@ -16396,12 +16396,12 @@ var init_unifiedMemoryStore = __esm({
16396
16396
  return scope;
16397
16397
  }
16398
16398
  getScopeByName(name10) {
16399
- const row = this.db.prepare("SELECT * FROM memory_scope WHERE name = ?").get(name10);
16400
- return row ? mapScopeRow(row) : null;
16399
+ const row2 = this.db.prepare("SELECT * FROM memory_scope WHERE name = ?").get(name10);
16400
+ return row2 ? mapScopeRow(row2) : null;
16401
16401
  }
16402
16402
  getScopeById(id2) {
16403
- const row = this.db.prepare("SELECT * FROM memory_scope WHERE id = ?").get(id2);
16404
- return row ? mapScopeRow(row) : null;
16403
+ const row2 = this.db.prepare("SELECT * FROM memory_scope WHERE id = ?").get(id2);
16404
+ return row2 ? mapScopeRow(row2) : null;
16405
16405
  }
16406
16406
  ensureEmbeddingSet(input) {
16407
16407
  const existing = this.getEmbeddingSetBySlug(input.slug);
@@ -16423,12 +16423,12 @@ var init_unifiedMemoryStore = __esm({
16423
16423
  return this.ensureEmbeddingSet({ slug: this.defaultEmbeddingSetSlug, setType: "full" });
16424
16424
  }
16425
16425
  getEmbeddingSetBySlug(slug) {
16426
- const row = this.db.prepare("SELECT * FROM memory_embedding_set WHERE slug = ?").get(slug);
16427
- return row ? mapEmbeddingSetRow(row) : null;
16426
+ const row2 = this.db.prepare("SELECT * FROM memory_embedding_set WHERE slug = ?").get(slug);
16427
+ return row2 ? mapEmbeddingSetRow(row2) : null;
16428
16428
  }
16429
16429
  getEmbeddingSetById(id2) {
16430
- const row = this.db.prepare("SELECT * FROM memory_embedding_set WHERE id = ?").get(id2);
16431
- return row ? mapEmbeddingSetRow(row) : null;
16430
+ const row2 = this.db.prepare("SELECT * FROM memory_embedding_set WHERE id = ?").get(id2);
16431
+ return row2 ? mapEmbeddingSetRow(row2) : null;
16432
16432
  }
16433
16433
  upsertItem(input) {
16434
16434
  const txn = this.db.transaction(() => {
@@ -16506,50 +16506,50 @@ var init_unifiedMemoryStore = __esm({
16506
16506
  return txn();
16507
16507
  }
16508
16508
  getItem(id2) {
16509
- const row = this.db.prepare("SELECT * FROM memory_item WHERE id = ?").get(id2);
16510
- return row ? mapItemRow(row) : null;
16509
+ const row2 = this.db.prepare("SELECT * FROM memory_item WHERE id = ?").get(id2);
16510
+ return row2 ? mapItemRow(row2) : null;
16511
16511
  }
16512
16512
  countItems() {
16513
- const row = this.db.prepare(`
16513
+ const row2 = this.db.prepare(`
16514
16514
  SELECT COUNT(*) AS count
16515
16515
  FROM memory_item
16516
16516
  WHERE deleted_at IS NULL
16517
16517
  AND (expires_at IS NULL OR expires_at > ?)
16518
16518
  `).get(this.nowIso());
16519
- return toNumber(row?.count, 0);
16519
+ return toNumber(row2?.count, 0);
16520
16520
  }
16521
16521
  countChunks() {
16522
- const row = this.db.prepare(`
16522
+ const row2 = this.db.prepare(`
16523
16523
  SELECT COUNT(*) AS count
16524
16524
  FROM memory_chunk c
16525
16525
  JOIN memory_item i ON i.id = c.item_id
16526
16526
  WHERE i.deleted_at IS NULL
16527
16527
  AND (i.expires_at IS NULL OR i.expires_at > ?)
16528
16528
  `).get(this.nowIso());
16529
- return toNumber(row?.count, 0);
16529
+ return toNumber(row2?.count, 0);
16530
16530
  }
16531
16531
  countEmbeddings(embeddingSetSlug) {
16532
16532
  if (embeddingSetSlug) {
16533
16533
  const set = this.getEmbeddingSetBySlug(embeddingSetSlug);
16534
16534
  if (!set)
16535
16535
  return 0;
16536
- const row2 = this.db.prepare(`
16536
+ const row3 = this.db.prepare(`
16537
16537
  SELECT COUNT(*) AS count
16538
16538
  FROM memory_embedding_v2
16539
16539
  WHERE embedding_set_id = ?
16540
16540
  `).get(set.id);
16541
- return toNumber(row2?.count, 0);
16541
+ return toNumber(row3?.count, 0);
16542
16542
  }
16543
- const row = this.db.prepare("SELECT COUNT(*) AS count FROM memory_embedding_v2").get();
16544
- return toNumber(row?.count, 0);
16543
+ const row2 = this.db.prepare("SELECT COUNT(*) AS count FROM memory_embedding_v2").get();
16544
+ return toNumber(row2?.count, 0);
16545
16545
  }
16546
16546
  countGraphNodes() {
16547
- const row = this.db.prepare("SELECT COUNT(*) AS count FROM memory_graph_node").get();
16548
- return toNumber(row?.count, 0);
16547
+ const row2 = this.db.prepare("SELECT COUNT(*) AS count FROM memory_graph_node").get();
16548
+ return toNumber(row2?.count, 0);
16549
16549
  }
16550
16550
  countGraphEdges(activeOnly = true) {
16551
- const row = activeOnly ? this.db.prepare("SELECT COUNT(*) AS count FROM memory_graph_edge WHERE valid_until IS NULL").get() : this.db.prepare("SELECT COUNT(*) AS count FROM memory_graph_edge").get();
16552
- return toNumber(row?.count, 0);
16551
+ const row2 = activeOnly ? this.db.prepare("SELECT COUNT(*) AS count FROM memory_graph_edge WHERE valid_until IS NULL").get() : this.db.prepare("SELECT COUNT(*) AS count FROM memory_graph_edge").get();
16552
+ return toNumber(row2?.count, 0);
16553
16553
  }
16554
16554
  getChunks(itemId2) {
16555
16555
  const rows = this.db.prepare(`
@@ -16558,8 +16558,8 @@ var init_unifiedMemoryStore = __esm({
16558
16558
  return rows.map(mapChunkRow);
16559
16559
  }
16560
16560
  getChunk(id2) {
16561
- const row = this.db.prepare("SELECT * FROM memory_chunk WHERE id = ?").get(id2);
16562
- return row ? mapChunkRow(row) : null;
16561
+ const row2 = this.db.prepare("SELECT * FROM memory_chunk WHERE id = ?").get(id2);
16562
+ return row2 ? mapChunkRow(row2) : null;
16563
16563
  }
16564
16564
  storeChunkEmbedding(chunkId, vector, options2 = {}) {
16565
16565
  const chunk = this.getChunk(chunkId);
@@ -16582,12 +16582,12 @@ var init_unifiedMemoryStore = __esm({
16582
16582
  input_hash = excluded.input_hash,
16583
16583
  created_at = excluded.created_at
16584
16584
  `).run(id2, chunkId, embeddingSet.id, encodeMemoryVector(normalized), options2.model ?? embeddingSet.model, normalized.length, inputHash, now2);
16585
- const row = this.db.prepare(`
16585
+ const row2 = this.db.prepare(`
16586
16586
  SELECT * FROM memory_embedding_v2 WHERE chunk_id = ? AND embedding_set_id = ?
16587
16587
  `).get(chunkId, embeddingSet.id);
16588
- if (!row)
16588
+ if (!row2)
16589
16589
  throw new Error(`Failed to store embedding for memory chunk ${chunkId}`);
16590
- return mapEmbeddingRow(row);
16590
+ return mapEmbeddingRow(row2);
16591
16591
  }
16592
16592
  recordProvenance(itemId2, input) {
16593
16593
  const id2 = randomUUID4();
@@ -16597,10 +16597,10 @@ var init_unifiedMemoryStore = __esm({
16597
16597
  (id, item_id, source_type, source_id, source_uri, observed_at, actor, metadata_json, created_at)
16598
16598
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
16599
16599
  `).run(id2, itemId2, input.sourceType, input.sourceId ?? "", input.sourceUri ?? "", input.observedAt ?? null, input.actor ?? "", stringifyJson(input.metadata), now2);
16600
- const row = this.db.prepare("SELECT * FROM memory_provenance WHERE id = ?").get(id2);
16601
- if (!row)
16600
+ const row2 = this.db.prepare("SELECT * FROM memory_provenance WHERE id = ?").get(id2);
16601
+ if (!row2)
16602
16602
  throw new Error(`Failed to record provenance for memory item ${itemId2}`);
16603
- return mapProvenanceRow(row);
16603
+ return mapProvenanceRow(row2);
16604
16604
  }
16605
16605
  getProvenance(itemId2) {
16606
16606
  const rows = this.db.prepare(`
@@ -16620,13 +16620,13 @@ var init_unifiedMemoryStore = __esm({
16620
16620
  evidence = excluded.evidence,
16621
16621
  metadata_json = excluded.metadata_json
16622
16622
  `).run(id2, input.sourceItemId, input.targetItemId, input.linkType ?? "related", clamp012(input.weight ?? 0.5), input.evidence ?? "", stringifyJson(input.metadata), now2);
16623
- const row = this.db.prepare(`
16623
+ const row2 = this.db.prepare(`
16624
16624
  SELECT * FROM memory_link_v2
16625
16625
  WHERE source_item_id = ? AND target_item_id = ? AND link_type = ?
16626
16626
  `).get(input.sourceItemId, input.targetItemId, input.linkType ?? "related");
16627
- if (!row)
16627
+ if (!row2)
16628
16628
  throw new Error("Failed to create memory link");
16629
- return mapLinkRow(row);
16629
+ return mapLinkRow(row2);
16630
16630
  }
16631
16631
  searchLexical(query, options2 = {}) {
16632
16632
  const terms2 = extractSearchTerms(query);
@@ -16654,11 +16654,11 @@ var init_unifiedMemoryStore = __esm({
16654
16654
  LIMIT ?
16655
16655
  `;
16656
16656
  const rows = this.db.prepare(sql).all(...termParams, ...filters.params, limit);
16657
- return rows.map((row, index) => {
16658
- const rowText = `${row.item_title ?? ""} ${row.chunk_text ?? ""}`;
16657
+ return rows.map((row2, index) => {
16658
+ const rowText = `${row2.item_title ?? ""} ${row2.chunk_text ?? ""}`;
16659
16659
  const hitScore = lexicalHitScore(rowText, terms2);
16660
16660
  const rankScore = Math.max(hitScore, 1 / (index + 1));
16661
- const match = mapCandidateRow(row, "lexical", rankScore);
16661
+ const match = mapCandidateRow(row2, "lexical", rankScore);
16662
16662
  match.rank = index + 1;
16663
16663
  match.rawScore = hitScore;
16664
16664
  match.scoreBreakdown.lexical = rankScore;
@@ -16692,12 +16692,12 @@ var init_unifiedMemoryStore = __esm({
16692
16692
  LIMIT ?
16693
16693
  `;
16694
16694
  const rows = this.db.prepare(sql).all(query.length, ...embeddingFilter.params, ...filters.params, scanLimit);
16695
- const matches = rows.map((row) => {
16696
- const rowData = row;
16695
+ const matches = rows.map((row2) => {
16696
+ const rowData = row2;
16697
16697
  const embedding = decodeMemoryVector(rowData.embedding_vector);
16698
16698
  const similarity3 = cosineMemorySimilarity(query, embedding);
16699
16699
  const score = clamp012((similarity3 + 1) / 2);
16700
- const match = mapCandidateRow(row, "vector", score);
16700
+ const match = mapCandidateRow(row2, "vector", score);
16701
16701
  match.embedding = embedding;
16702
16702
  match.vectorSimilarity = similarity3;
16703
16703
  match.rawScore = similarity3;
@@ -16708,8 +16708,8 @@ var init_unifiedMemoryStore = __esm({
16708
16708
  return matches.filter((match) => match.score >= (options2.minScore ?? 0)).sort((a2, b) => b.score - a2.score).slice(0, limit).map((match, index) => ({ ...match, rank: index + 1 }));
16709
16709
  }
16710
16710
  recordAccess(itemIds) {
16711
- const unique2 = [...new Set(itemIds)].filter(Boolean);
16712
- if (unique2.length === 0)
16711
+ const unique3 = [...new Set(itemIds)].filter(Boolean);
16712
+ if (unique3.length === 0)
16713
16713
  return;
16714
16714
  const update2 = this.db.prepare(`
16715
16715
  UPDATE memory_item
@@ -16719,7 +16719,7 @@ var init_unifiedMemoryStore = __esm({
16719
16719
  `);
16720
16720
  const now2 = this.nowIso();
16721
16721
  const txn = this.db.transaction(() => {
16722
- for (const id2 of unique2)
16722
+ for (const id2 of unique3)
16723
16723
  update2.run(now2, id2);
16724
16724
  });
16725
16725
  txn();
@@ -16738,8 +16738,8 @@ var init_unifiedMemoryStore = __esm({
16738
16738
  return job;
16739
16739
  }
16740
16740
  getJob(id2) {
16741
- const row = this.db.prepare("SELECT * FROM memory_job_queue WHERE id = ?").get(id2);
16742
- return row ? mapJobRow(row) : null;
16741
+ const row2 = this.db.prepare("SELECT * FROM memory_job_queue WHERE id = ?").get(id2);
16742
+ return row2 ? mapJobRow(row2) : null;
16743
16743
  }
16744
16744
  claimJobs(jobTypes, limit = 10) {
16745
16745
  if (jobTypes.length === 0)
@@ -16839,13 +16839,13 @@ var init_unifiedMemoryStore = __esm({
16839
16839
  metadata_json = excluded.metadata_json,
16840
16840
  last_seen_at = excluded.last_seen_at
16841
16841
  `).run(id2, input.scopeId, normalized, input.text.trim(), nodeType, clamp012(input.weight ?? 0.5), stringifyJson(input.metadata), now2, now2);
16842
- const row = this.db.prepare(`
16842
+ const row2 = this.db.prepare(`
16843
16843
  SELECT * FROM memory_graph_node
16844
16844
  WHERE scope_id = ? AND normalized_text = ? AND node_type = ?
16845
16845
  `).get(input.scopeId, normalized, nodeType);
16846
- if (!row)
16846
+ if (!row2)
16847
16847
  throw new Error(`Failed to upsert graph node ${input.text}`);
16848
- return mapGraphNodeRow(row);
16848
+ return mapGraphNodeRow(row2);
16849
16849
  }
16850
16850
  linkItemToGraphNode(input) {
16851
16851
  const now2 = this.nowIso();
@@ -16859,12 +16859,12 @@ var init_unifiedMemoryStore = __esm({
16859
16859
  evidence = excluded.evidence,
16860
16860
  updated_at = excluded.updated_at
16861
16861
  `).run(input.itemId, input.nodeId, relation, clamp012(input.weight ?? 0.5), input.evidence ?? "", now2, now2);
16862
- const row = this.db.prepare(`
16862
+ const row2 = this.db.prepare(`
16863
16863
  SELECT * FROM memory_item_node WHERE item_id = ? AND node_id = ? AND relation = ?
16864
16864
  `).get(input.itemId, input.nodeId, relation);
16865
- if (!row)
16865
+ if (!row2)
16866
16866
  throw new Error("Failed to link memory item to graph node");
16867
- return mapItemNodeRow(row);
16867
+ return mapItemNodeRow(row2);
16868
16868
  }
16869
16869
  createGraphEdge(input) {
16870
16870
  const id2 = input.id ?? randomUUID4();
@@ -16880,14 +16880,14 @@ var init_unifiedMemoryStore = __esm({
16880
16880
  metadata_json = excluded.metadata_json,
16881
16881
  valid_until = NULL
16882
16882
  `).run(id2, input.scopeId, input.sourceNodeId, input.targetNodeId, relation, clamp012(input.weight ?? 0.5), input.sourceItemId ?? null, input.evidence ?? "", stringifyJson(input.metadata), now2, now2);
16883
- const row = this.db.prepare(`
16883
+ const row2 = this.db.prepare(`
16884
16884
  SELECT * FROM memory_graph_edge
16885
16885
  WHERE scope_id = ? AND source_node_id = ? AND target_node_id = ? AND relation = ?
16886
16886
  AND (source_item_id = ? OR (source_item_id IS NULL AND ? IS NULL))
16887
16887
  `).get(input.scopeId, input.sourceNodeId, input.targetNodeId, relation, input.sourceItemId ?? null, input.sourceItemId ?? null);
16888
- if (!row)
16888
+ if (!row2)
16889
16889
  throw new Error("Failed to create graph edge");
16890
- return mapGraphEdgeRow(row);
16890
+ return mapGraphEdgeRow(row2);
16891
16891
  }
16892
16892
  clearItemGraph(itemId2) {
16893
16893
  this.db.prepare("DELETE FROM memory_item_node WHERE item_id = ?").run(itemId2);
@@ -16917,11 +16917,11 @@ var init_unifiedMemoryStore = __esm({
16917
16917
  ORDER BY n.mention_count DESC, n.weight DESC, i.importance DESC, c.sequence ASC
16918
16918
  LIMIT ?
16919
16919
  `).all(...nodeParams, ...filters.params, limit);
16920
- return rows.map((row, index) => {
16921
- const r2 = row;
16920
+ return rows.map((row2, index) => {
16921
+ const r2 = row2;
16922
16922
  const hitScore = Math.min(1, toNumber(r2.graph_mention_count, 1) / 10 * 0.4 + toNumber(r2.graph_node_weight, 0.5) * 0.4 + toNumber(r2.graph_item_weight, 0.5) * 0.2);
16923
16923
  const rankScore = Math.max(hitScore, 1 / (index + 1));
16924
- const match = mapCandidateRow(row, "graph", rankScore);
16924
+ const match = mapCandidateRow(row2, "graph", rankScore);
16925
16925
  match.rank = index + 1;
16926
16926
  match.rawScore = hitScore;
16927
16927
  match.scoreBreakdown.graph = rankScore;
@@ -16988,7 +16988,7 @@ var init_unifiedMemoryStore = __esm({
16988
16988
  ORDER BY updated_at ASC
16989
16989
  LIMIT ?
16990
16990
  `).all(cutoff, maxItems);
16991
- const itemIds = rows.map((row) => String(row.id ?? "")).filter(Boolean);
16991
+ const itemIds = rows.map((row2) => String(row2.id ?? "")).filter(Boolean);
16992
16992
  if (itemIds.length === 0)
16993
16993
  return { decayed: 0, itemIds: [] };
16994
16994
  const txn = this.db.transaction(() => {
@@ -17078,9 +17078,9 @@ var init_unifiedMemoryStore = __esm({
17078
17078
  ORDER BY i.importance DESC, i.updated_at DESC, c.sequence ASC
17079
17079
  LIMIT ?
17080
17080
  `).all(...params, ...filters.params, limit);
17081
- return rows.map((row, index) => {
17081
+ return rows.map((row2, index) => {
17082
17082
  const score = 1 / (index + 1);
17083
- const match = mapCandidateRow(row, "lexical", score);
17083
+ const match = mapCandidateRow(row2, "lexical", score);
17084
17084
  match.rank = index + 1;
17085
17085
  match.scoreBreakdown.lexical = score;
17086
17086
  match.scoreBreakdown.itemQuality = itemQuality(match.item);
@@ -17977,18 +17977,18 @@ var init_memoryPrefill = __esm({
17977
17977
  });
17978
17978
 
17979
17979
  // packages/memory/dist/repoProfileStore.js
17980
- function rowToProfile(row) {
17980
+ function rowToProfile(row2) {
17981
17981
  return {
17982
- repoRoot: row.repo_root,
17983
- languages: JSON.parse(row.languages),
17984
- frameworks: JSON.parse(row.frameworks),
17985
- buildSystem: row.build_system,
17986
- testCommands: JSON.parse(row.test_commands),
17987
- lintCommands: JSON.parse(row.lint_commands),
17988
- packageManager: row.package_manager,
17989
- notes: row.notes ?? null,
17990
- createdAt: row.created_at,
17991
- updatedAt: row.updated_at
17982
+ repoRoot: row2.repo_root,
17983
+ languages: JSON.parse(row2.languages),
17984
+ frameworks: JSON.parse(row2.frameworks),
17985
+ buildSystem: row2.build_system,
17986
+ testCommands: JSON.parse(row2.test_commands),
17987
+ lintCommands: JSON.parse(row2.lint_commands),
17988
+ packageManager: row2.package_manager,
17989
+ notes: row2.notes ?? null,
17990
+ createdAt: row2.created_at,
17991
+ updatedAt: row2.updated_at
17992
17992
  };
17993
17993
  }
17994
17994
  var RepoProfileStore;
@@ -18020,8 +18020,8 @@ var init_repoProfileStore = __esm({
18020
18020
  }
18021
18021
  /** Retrieve a profile by repository root path, or `null` if not found. */
18022
18022
  get(repoRoot) {
18023
- const row = this.db.prepare("SELECT * FROM repo_profiles WHERE repo_root = ?").get(repoRoot);
18024
- return row ? rowToProfile(row) : null;
18023
+ const row2 = this.db.prepare("SELECT * FROM repo_profiles WHERE repo_root = ?").get(repoRoot);
18024
+ return row2 ? rowToProfile(row2) : null;
18025
18025
  }
18026
18026
  /** List all stored repository profiles. */
18027
18027
  list() {
@@ -18037,19 +18037,19 @@ var init_repoProfileStore = __esm({
18037
18037
  });
18038
18038
 
18039
18039
  // packages/memory/dist/fileSummaryStore.js
18040
- function rowToSummary(row) {
18040
+ function rowToSummary(row2) {
18041
18041
  return {
18042
- filePath: row.file_path,
18043
- repoRoot: row.repo_root,
18044
- purpose: row.purpose,
18045
- exports: JSON.parse(row.exports),
18046
- imports: JSON.parse(row.imports),
18047
- domain: row.domain,
18048
- riskLevel: row.risk_level,
18049
- relatedTests: JSON.parse(row.related_tests),
18050
- notes: row.notes ?? null,
18051
- createdAt: row.created_at,
18052
- updatedAt: row.updated_at
18042
+ filePath: row2.file_path,
18043
+ repoRoot: row2.repo_root,
18044
+ purpose: row2.purpose,
18045
+ exports: JSON.parse(row2.exports),
18046
+ imports: JSON.parse(row2.imports),
18047
+ domain: row2.domain,
18048
+ riskLevel: row2.risk_level,
18049
+ relatedTests: JSON.parse(row2.related_tests),
18050
+ notes: row2.notes ?? null,
18051
+ createdAt: row2.created_at,
18052
+ updatedAt: row2.updated_at
18053
18053
  };
18054
18054
  }
18055
18055
  var FileSummaryStore;
@@ -18082,8 +18082,8 @@ var init_fileSummaryStore = __esm({
18082
18082
  }
18083
18083
  /** Retrieve a file summary by path, or `null` if not found. */
18084
18084
  get(filePath) {
18085
- const row = this.db.prepare("SELECT * FROM file_summaries WHERE file_path = ?").get(filePath);
18086
- return row ? rowToSummary(row) : null;
18085
+ const row2 = this.db.prepare("SELECT * FROM file_summaries WHERE file_path = ?").get(filePath);
18086
+ return row2 ? rowToSummary(row2) : null;
18087
18087
  }
18088
18088
  /** List all file summaries for a repository. */
18089
18089
  listByRepo(repoRoot) {
@@ -18110,19 +18110,19 @@ var init_fileSummaryStore = __esm({
18110
18110
 
18111
18111
  // packages/memory/dist/taskMemoryStore.js
18112
18112
  import { randomUUID as randomUUID5 } from "node:crypto";
18113
- function rowToTask(row) {
18113
+ function rowToTask(row2) {
18114
18114
  return {
18115
- id: row.id,
18116
- sessionId: row.session_id,
18117
- repoRoot: row.repo_root,
18118
- goal: row.goal,
18119
- constraints: JSON.parse(row.constraints),
18120
- filesTouched: JSON.parse(row.files_touched),
18121
- patches: JSON.parse(row.patches),
18122
- outcome: row.outcome,
18123
- qualityScore: row.quality_score ?? null,
18124
- notes: row.notes ?? null,
18125
- createdAt: row.created_at
18115
+ id: row2.id,
18116
+ sessionId: row2.session_id,
18117
+ repoRoot: row2.repo_root,
18118
+ goal: row2.goal,
18119
+ constraints: JSON.parse(row2.constraints),
18120
+ filesTouched: JSON.parse(row2.files_touched),
18121
+ patches: JSON.parse(row2.patches),
18122
+ outcome: row2.outcome,
18123
+ qualityScore: row2.quality_score ?? null,
18124
+ notes: row2.notes ?? null,
18125
+ createdAt: row2.created_at
18126
18126
  };
18127
18127
  }
18128
18128
  var TaskMemoryStore;
@@ -18148,8 +18148,8 @@ var init_taskMemoryStore = __esm({
18148
18148
  }
18149
18149
  /** Retrieve a task record by id, or `null` if not found. */
18150
18150
  getById(id2) {
18151
- const row = this.db.prepare("SELECT * FROM task_memory WHERE id = ?").get(id2);
18152
- return row ? rowToTask(row) : null;
18151
+ const row2 = this.db.prepare("SELECT * FROM task_memory WHERE id = ?").get(id2);
18152
+ return row2 ? rowToTask(row2) : null;
18153
18153
  }
18154
18154
  /** List all tasks associated with a session. */
18155
18155
  listBySession(sessionId) {
@@ -18180,19 +18180,19 @@ var init_taskMemoryStore = __esm({
18180
18180
 
18181
18181
  // packages/memory/dist/patchHistoryStore.js
18182
18182
  import { randomUUID as randomUUID6 } from "node:crypto";
18183
- function rowToPatch(row) {
18183
+ function rowToPatch(row2) {
18184
18184
  return {
18185
- id: row.id,
18186
- taskId: row.task_id,
18187
- sessionId: row.session_id,
18188
- repoRoot: row.repo_root,
18189
- filePath: row.file_path,
18190
- diff: row.diff,
18191
- status: row.status,
18192
- appliedAt: row.applied_at ?? null,
18193
- revertedAt: row.reverted_at ?? null,
18194
- notes: row.notes ?? null,
18195
- createdAt: row.created_at
18185
+ id: row2.id,
18186
+ taskId: row2.task_id,
18187
+ sessionId: row2.session_id,
18188
+ repoRoot: row2.repo_root,
18189
+ filePath: row2.file_path,
18190
+ diff: row2.diff,
18191
+ status: row2.status,
18192
+ appliedAt: row2.applied_at ?? null,
18193
+ revertedAt: row2.reverted_at ?? null,
18194
+ notes: row2.notes ?? null,
18195
+ createdAt: row2.created_at
18196
18196
  };
18197
18197
  }
18198
18198
  var PatchHistoryStore;
@@ -18218,8 +18218,8 @@ var init_patchHistoryStore = __esm({
18218
18218
  }
18219
18219
  /** Retrieve a patch by id, or `null` if not found. */
18220
18220
  getById(id2) {
18221
- const row = this.db.prepare("SELECT * FROM patch_history WHERE id = ?").get(id2);
18222
- return row ? rowToPatch(row) : null;
18221
+ const row2 = this.db.prepare("SELECT * FROM patch_history WHERE id = ?").get(id2);
18222
+ return row2 ? rowToPatch(row2) : null;
18223
18223
  }
18224
18224
  /** List all patches associated with a task. */
18225
18225
  listByTask(taskId) {
@@ -18255,21 +18255,21 @@ var init_patchHistoryStore = __esm({
18255
18255
 
18256
18256
  // packages/memory/dist/failureStore.js
18257
18257
  import { randomUUID as randomUUID7 } from "node:crypto";
18258
- function rowToFailure(row) {
18258
+ function rowToFailure(row2) {
18259
18259
  return {
18260
- id: row.id,
18261
- taskId: row.task_id,
18262
- sessionId: row.session_id,
18263
- repoRoot: row.repo_root,
18264
- failureType: row.failure_type,
18265
- fingerprint: row.fingerprint,
18266
- filePath: row.file_path ?? null,
18267
- errorMessage: row.error_message,
18268
- context: row.context !== null ? JSON.parse(row.context) : null,
18269
- resolved: row.resolved === 1,
18270
- resolvedAt: row.resolved_at ?? null,
18271
- notes: row.notes ?? null,
18272
- createdAt: row.created_at
18260
+ id: row2.id,
18261
+ taskId: row2.task_id,
18262
+ sessionId: row2.session_id,
18263
+ repoRoot: row2.repo_root,
18264
+ failureType: row2.failure_type,
18265
+ fingerprint: row2.fingerprint,
18266
+ filePath: row2.file_path ?? null,
18267
+ errorMessage: row2.error_message,
18268
+ context: row2.context !== null ? JSON.parse(row2.context) : null,
18269
+ resolved: row2.resolved === 1,
18270
+ resolvedAt: row2.resolved_at ?? null,
18271
+ notes: row2.notes ?? null,
18272
+ createdAt: row2.created_at
18273
18273
  };
18274
18274
  }
18275
18275
  var FailureStore;
@@ -18296,8 +18296,8 @@ var init_failureStore = __esm({
18296
18296
  }
18297
18297
  /** Retrieve a failure by id, or `null` if not found. */
18298
18298
  getById(id2) {
18299
- const row = this.db.prepare("SELECT * FROM failures WHERE id = ?").get(id2);
18300
- return row ? rowToFailure(row) : null;
18299
+ const row2 = this.db.prepare("SELECT * FROM failures WHERE id = ?").get(id2);
18300
+ return row2 ? rowToFailure(row2) : null;
18301
18301
  }
18302
18302
  /** List failures filtered by type. */
18303
18303
  listByType(failureType) {
@@ -18331,21 +18331,21 @@ var init_failureStore = __esm({
18331
18331
 
18332
18332
  // packages/memory/dist/validationStore.js
18333
18333
  import { randomUUID as randomUUID8 } from "node:crypto";
18334
- function rowToRun(row) {
18334
+ function rowToRun(row2) {
18335
18335
  return {
18336
- id: row.id,
18337
- taskId: row.task_id,
18338
- sessionId: row.session_id,
18339
- repoRoot: row.repo_root,
18340
- runType: row.run_type,
18341
- command: row.command,
18342
- passed: row.passed === 1,
18343
- durationMs: row.duration_ms ?? null,
18344
- output: row.output ?? null,
18345
- errorOutput: row.error_output ?? null,
18346
- coveragePercent: row.coverage_percent ?? null,
18347
- notes: row.notes ?? null,
18348
- createdAt: row.created_at
18336
+ id: row2.id,
18337
+ taskId: row2.task_id,
18338
+ sessionId: row2.session_id,
18339
+ repoRoot: row2.repo_root,
18340
+ runType: row2.run_type,
18341
+ command: row2.command,
18342
+ passed: row2.passed === 1,
18343
+ durationMs: row2.duration_ms ?? null,
18344
+ output: row2.output ?? null,
18345
+ errorOutput: row2.error_output ?? null,
18346
+ coveragePercent: row2.coverage_percent ?? null,
18347
+ notes: row2.notes ?? null,
18348
+ createdAt: row2.created_at
18349
18349
  };
18350
18350
  }
18351
18351
  var ValidationStore;
@@ -18372,8 +18372,8 @@ var init_validationStore = __esm({
18372
18372
  }
18373
18373
  /** Retrieve a validation run by id, or `null` if not found. */
18374
18374
  getById(id2) {
18375
- const row = this.db.prepare("SELECT * FROM validation_runs WHERE id = ?").get(id2);
18376
- return row ? rowToRun(row) : null;
18375
+ const row2 = this.db.prepare("SELECT * FROM validation_runs WHERE id = ?").get(id2);
18376
+ return row2 ? rowToRun(row2) : null;
18377
18377
  }
18378
18378
  /** List all validation runs for a given task. */
18379
18379
  listByTask(taskId) {
@@ -18398,11 +18398,11 @@ var init_validationStore = __esm({
18398
18398
  * (common in tests) are ordered deterministically by insertion order.
18399
18399
  */
18400
18400
  latestByTask(taskId) {
18401
- const row = this.db.prepare(`SELECT * FROM validation_runs
18401
+ const row2 = this.db.prepare(`SELECT * FROM validation_runs
18402
18402
  WHERE task_id = ?
18403
18403
  ORDER BY created_at DESC, rowid DESC
18404
18404
  LIMIT 1`).get(taskId);
18405
- return row ? rowToRun(row) : null;
18405
+ return row2 ? rowToRun(row2) : null;
18406
18406
  }
18407
18407
  };
18408
18408
  }
@@ -18577,14 +18577,14 @@ var init_toolPatternStore = __esm({
18577
18577
  }));
18578
18578
  }
18579
18579
  // -- Helpers -------------------------------------------------------------
18580
- hydrate(row) {
18580
+ hydrate(row2) {
18581
18581
  return {
18582
- id: row["id"],
18583
- taskId: row["task_id"],
18584
- sessionId: row["session_id"],
18585
- repoRoot: row["repo_root"],
18586
- sequence: JSON.parse(row["sequence"] || "[]"),
18587
- createdAt: row["created_at"]
18582
+ id: row2["id"],
18583
+ taskId: row2["task_id"],
18584
+ sessionId: row2["session_id"],
18585
+ repoRoot: row2["repo_root"],
18586
+ sequence: JSON.parse(row2["sequence"] || "[]"),
18587
+ createdAt: row2["created_at"]
18588
18588
  };
18589
18589
  }
18590
18590
  };
@@ -19418,8 +19418,8 @@ var init_episodeStore = __esm({
19418
19418
  const result = this.db.prepare(`UPDATE episodes SET reuse_count = COALESCE(reuse_count, 0) + ? WHERE id = ?`).run(safeDelta, id2);
19419
19419
  if (result.changes === 0)
19420
19420
  return null;
19421
- const row = this.db.prepare(`SELECT reuse_count FROM episodes WHERE id = ?`).get(id2);
19422
- return row?.reuse_count ?? null;
19421
+ const row2 = this.db.prepare(`SELECT reuse_count FROM episodes WHERE id = ?`).get(id2);
19422
+ return row2?.reuse_count ?? null;
19423
19423
  } catch {
19424
19424
  return null;
19425
19425
  }
@@ -19558,10 +19558,10 @@ var init_episodeStore = __esm({
19558
19558
  params.push(Math.min(limit * 5, 500));
19559
19559
  let rows = this.db.prepare(sql).all(...params);
19560
19560
  if (query.metadataFilter || query.soundClass || query.rmsRange) {
19561
- rows = rows.filter((row) => {
19561
+ rows = rows.filter((row2) => {
19562
19562
  let meta = null;
19563
19563
  try {
19564
- meta = row.metadata ? typeof row.metadata === "string" ? JSON.parse(row.metadata) : row.metadata : null;
19564
+ meta = row2.metadata ? typeof row2.metadata === "string" ? JSON.parse(row2.metadata) : row2.metadata : null;
19565
19565
  } catch {
19566
19566
  return false;
19567
19567
  }
@@ -19587,8 +19587,8 @@ var init_episodeStore = __esm({
19587
19587
  return true;
19588
19588
  });
19589
19589
  }
19590
- const scored = rows.map((row) => {
19591
- const ep = this.rowToEpisode(row);
19590
+ const scored = rows.map((row2) => {
19591
+ const ep = this.rowToEpisode(row2);
19592
19592
  const tau = DECAY_TAU[ep.decayClass] ?? DECAY_TAU.daily;
19593
19593
  const recency = tau === Infinity ? 1 : Math.exp(-(now2 - ep.timestamp) / tau);
19594
19594
  const importance = ep.importance / 10;
@@ -19676,8 +19676,8 @@ var init_episodeStore = __esm({
19676
19676
  }
19677
19677
  /** Get a single episode by ID. */
19678
19678
  get(id2) {
19679
- const row = this.db.prepare("SELECT * FROM episodes WHERE id = ?").get(id2);
19680
- return row ? this.rowToEpisode(row) : null;
19679
+ const row2 = this.db.prepare("SELECT * FROM episodes WHERE id = ?").get(id2);
19680
+ return row2 ? this.rowToEpisode(row2) : null;
19681
19681
  }
19682
19682
  /** Get recent episodes (for context assembly). */
19683
19683
  recent(limit = 10, sessionId) {
@@ -19726,30 +19726,30 @@ var init_episodeStore = __esm({
19726
19726
  }
19727
19727
  }
19728
19728
  // ─── Internal ────────────────────────────────────────────────────────────
19729
- rowToEpisode(row) {
19729
+ rowToEpisode(row2) {
19730
19730
  return {
19731
- id: row.id,
19732
- timestamp: row.timestamp,
19733
- sessionId: row.session_id,
19734
- taskId: row.task_id,
19735
- turnNumber: row.turn_number,
19736
- modality: row.modality,
19737
- toolName: row.tool_name,
19738
- content: row.content,
19739
- contentHash: row.content_hash,
19740
- metadata: row.metadata ? JSON.parse(row.metadata) : null,
19741
- embedding: row.embedding ? new Float32Array(new Uint8Array(row.embedding).buffer) : null,
19731
+ id: row2.id,
19732
+ timestamp: row2.timestamp,
19733
+ sessionId: row2.session_id,
19734
+ taskId: row2.task_id,
19735
+ turnNumber: row2.turn_number,
19736
+ modality: row2.modality,
19737
+ toolName: row2.tool_name,
19738
+ content: row2.content,
19739
+ contentHash: row2.content_hash,
19740
+ metadata: row2.metadata ? JSON.parse(row2.metadata) : null,
19741
+ embedding: row2.embedding ? new Float32Array(new Uint8Array(row2.embedding).buffer) : null,
19742
19742
  // Belt-and-braces: rows from pre-fix DBs may have null importance
19743
19743
  // (from legacy inserts with NaN that SQLite coerced to NULL).
19744
19744
  // Re-sanitize on read so downstream code always sees a valid number.
19745
- importance: sanitizeImportance(row.importance),
19746
- decayClass: row.decay_class,
19747
- strength: typeof row.strength === "number" && Number.isFinite(row.strength) ? row.strength : 1,
19748
- lastRetrieved: row.last_retrieved,
19749
- clipEmbedding: row.clip_embedding ? new Float32Array(new Uint8Array(row.clip_embedding).buffer) : null,
19750
- gist: row.gist,
19751
- sourceEpisodeId: row.source_episode_id,
19752
- reuseCount: typeof row.reuse_count === "number" ? row.reuse_count : 0
19745
+ importance: sanitizeImportance(row2.importance),
19746
+ decayClass: row2.decay_class,
19747
+ strength: typeof row2.strength === "number" && Number.isFinite(row2.strength) ? row2.strength : 1,
19748
+ lastRetrieved: row2.last_retrieved,
19749
+ clipEmbedding: row2.clip_embedding ? new Float32Array(new Uint8Array(row2.clip_embedding).buffer) : null,
19750
+ gist: row2.gist,
19751
+ sourceEpisodeId: row2.source_episode_id,
19752
+ reuseCount: typeof row2.reuse_count === "number" ? row2.reuse_count : 0
19753
19753
  };
19754
19754
  }
19755
19755
  };
@@ -19848,13 +19848,13 @@ var init_temporalGraph = __esm({
19848
19848
  /** Find a node by text (case-insensitive). */
19849
19849
  findNode(text2, nodeType) {
19850
19850
  const sql = nodeType ? "SELECT * FROM kg_nodes WHERE text = ? AND node_type = ? LIMIT 1" : "SELECT * FROM kg_nodes WHERE text = ? LIMIT 1";
19851
- const row = nodeType ? this.db.prepare(sql).get(text2, nodeType) : this.db.prepare(sql).get(text2);
19852
- return row ? this.rowToNode(row) : null;
19851
+ const row2 = nodeType ? this.db.prepare(sql).get(text2, nodeType) : this.db.prepare(sql).get(text2);
19852
+ return row2 ? this.rowToNode(row2) : null;
19853
19853
  }
19854
19854
  /** Get a node by ID. */
19855
19855
  getNode(id2) {
19856
- const row = this.db.prepare("SELECT * FROM kg_nodes WHERE id = ?").get(id2);
19857
- return row ? this.rowToNode(row) : null;
19856
+ const row2 = this.db.prepare("SELECT * FROM kg_nodes WHERE id = ?").get(id2);
19857
+ return row2 ? this.rowToNode(row2) : null;
19858
19858
  }
19859
19859
  /** List all nodes of a given type. */
19860
19860
  nodesByType(nodeType, limit = 100) {
@@ -19993,30 +19993,30 @@ var init_temporalGraph = __esm({
19993
19993
  }
19994
19994
  }
19995
19995
  // ─── Internal ────────────────────────────────────────────────────────────
19996
- rowToNode(row) {
19996
+ rowToNode(row2) {
19997
19997
  return {
19998
- id: row.id,
19999
- text: row.text,
20000
- nodeType: row.node_type,
20001
- embedding: row.embedding ? new Float32Array(new Uint8Array(row.embedding).buffer) : null,
20002
- firstSeen: row.first_seen,
20003
- lastSeen: row.last_seen,
20004
- mentionCount: row.mention_count
19998
+ id: row2.id,
19999
+ text: row2.text,
20000
+ nodeType: row2.node_type,
20001
+ embedding: row2.embedding ? new Float32Array(new Uint8Array(row2.embedding).buffer) : null,
20002
+ firstSeen: row2.first_seen,
20003
+ lastSeen: row2.last_seen,
20004
+ mentionCount: row2.mention_count
20005
20005
  };
20006
20006
  }
20007
- rowToEdge(row) {
20007
+ rowToEdge(row2) {
20008
20008
  return {
20009
- id: row.id,
20010
- srcId: row.src_id,
20011
- dstId: row.dst_id,
20012
- relation: row.relation,
20013
- fact: row.fact,
20014
- edgeType: row.edge_type,
20015
- validFrom: row.valid_from,
20016
- validUntil: row.valid_until,
20017
- confidence: row.confidence,
20018
- sourceEpisodeId: row.source_episode_id,
20019
- modality: row.modality
20009
+ id: row2.id,
20010
+ srcId: row2.src_id,
20011
+ dstId: row2.dst_id,
20012
+ relation: row2.relation,
20013
+ fact: row2.fact,
20014
+ edgeType: row2.edge_type,
20015
+ validFrom: row2.valid_from,
20016
+ validUntil: row2.valid_until,
20017
+ confidence: row2.confidence,
20018
+ sourceEpisodeId: row2.source_episode_id,
20019
+ modality: row2.modality
20020
20020
  };
20021
20021
  }
20022
20022
  };
@@ -20610,10 +20610,10 @@ var init_proceduralMemoryStore = __esm({
20610
20610
  }
20611
20611
  /** Get a memory by ID. Returns null if not found or soft-deleted. */
20612
20612
  get(id2) {
20613
- const row = this.db.prepare(`
20613
+ const row2 = this.db.prepare(`
20614
20614
  SELECT * FROM procedural_memory WHERE id = ? AND deleted_at IS NULL
20615
20615
  `).get(id2);
20616
- return row ? this._mapRow(row) : null;
20616
+ return row2 ? this._mapRow(row2) : null;
20617
20617
  }
20618
20618
  /** List all active memories, ordered by utility*confidence descending. */
20619
20619
  list(limit = 100, offset = 0) {
@@ -20704,12 +20704,12 @@ var init_proceduralMemoryStore = __esm({
20704
20704
  WHERE pm.deleted_at IS NULL
20705
20705
  `).all();
20706
20706
  const results = [];
20707
- for (const row of rows) {
20708
- const stored = new Float32Array(row.vector.buffer, row.vector.byteOffset, row.vector.byteLength / 4);
20707
+ for (const row2 of rows) {
20708
+ const stored = new Float32Array(row2.vector.buffer, row2.vector.byteOffset, row2.vector.byteLength / 4);
20709
20709
  const sim = cosineSimilarity2(queryVector, stored);
20710
20710
  if (sim >= minSimilarity) {
20711
20711
  results.push({
20712
- memory: this._mapRow(row),
20712
+ memory: this._mapRow(row2),
20713
20713
  score: sim,
20714
20714
  matchType: "semantic"
20715
20715
  });
@@ -20732,10 +20732,10 @@ var init_proceduralMemoryStore = __esm({
20732
20732
  }
20733
20733
  /** Check if a memory has an embedding. */
20734
20734
  hasEmbedding(memoryId) {
20735
- const row = this.db.prepare(`
20735
+ const row2 = this.db.prepare(`
20736
20736
  SELECT COUNT(*) as cnt FROM memory_embedding WHERE memory_id = ?
20737
20737
  `).get(memoryId);
20738
- return row?.cnt > 0;
20738
+ return row2?.cnt > 0;
20739
20739
  }
20740
20740
  // ── Links ───────────────────────────────────────────────────────────
20741
20741
  /** Create a link between two memories. */
@@ -20804,10 +20804,10 @@ var init_proceduralMemoryStore = __esm({
20804
20804
  // ── Stats ───────────────────────────────────────────────────────────
20805
20805
  /** Count active memories. */
20806
20806
  count() {
20807
- const row = this.db.prepare(`
20807
+ const row2 = this.db.prepare(`
20808
20808
  SELECT COUNT(*) as cnt FROM procedural_memory WHERE deleted_at IS NULL
20809
20809
  `).get();
20810
- return row?.cnt ?? 0;
20810
+ return row2?.cnt ?? 0;
20811
20811
  }
20812
20812
  /** Migration helper: import from flat JSON metabolism store. */
20813
20813
  importFromJson(entries) {
@@ -20834,21 +20834,21 @@ var init_proceduralMemoryStore = __esm({
20834
20834
  return imported;
20835
20835
  }
20836
20836
  // ── Internal ────────────────────────────────────────────────────────
20837
- _mapRow(row) {
20837
+ _mapRow(row2) {
20838
20838
  return {
20839
- id: row.id,
20840
- type: row.type,
20841
- category: row.category,
20842
- content: row.content,
20843
- triggerPattern: row.trigger_pattern,
20844
- steps: row.steps,
20845
- sourceTrace: row.source_trace,
20846
- utility: row.utility,
20847
- confidence: row.confidence,
20848
- accessCount: row.access_count,
20849
- deletedAt: row.deleted_at,
20850
- createdAt: row.created_at,
20851
- updatedAt: row.updated_at
20839
+ id: row2.id,
20840
+ type: row2.type,
20841
+ category: row2.category,
20842
+ content: row2.content,
20843
+ triggerPattern: row2.trigger_pattern,
20844
+ steps: row2.steps,
20845
+ sourceTrace: row2.source_trace,
20846
+ utility: row2.utility,
20847
+ confidence: row2.confidence,
20848
+ accessCount: row2.access_count,
20849
+ deletedAt: row2.deleted_at,
20850
+ createdAt: row2.created_at,
20851
+ updatedAt: row2.updated_at
20852
20852
  };
20853
20853
  }
20854
20854
  };
@@ -23247,16 +23247,16 @@ var init_selfModel = __esm({
23247
23247
  // ── private helpers ────────────────────────────────────────────────────────
23248
23248
  scalarCount(sql) {
23249
23249
  try {
23250
- const row = this.db.prepare(sql).get();
23251
- return row?.c ?? 0;
23250
+ const row2 = this.db.prepare(sql).get();
23251
+ return row2?.c ?? 0;
23252
23252
  } catch {
23253
23253
  return 0;
23254
23254
  }
23255
23255
  }
23256
23256
  tableCount(name10) {
23257
23257
  try {
23258
- const row = this.db.prepare(`SELECT COUNT(*) AS c FROM ${name10}`).get();
23259
- return row?.c ?? 0;
23258
+ const row2 = this.db.prepare(`SELECT COUNT(*) AS c FROM ${name10}`).get();
23259
+ return row2?.c ?? 0;
23260
23260
  } catch {
23261
23261
  return 0;
23262
23262
  }
@@ -23282,8 +23282,8 @@ var init_selfModel = __esm({
23282
23282
  const critEnd = safe(b.critical, 10) + 1;
23283
23283
  const q = (lo, hi) => {
23284
23284
  try {
23285
- const row = this.db.prepare(`SELECT COUNT(*) AS c FROM episodes WHERE importance >= ? AND importance < ?`).get(lo, hi);
23286
- return row?.c ?? 0;
23285
+ const row2 = this.db.prepare(`SELECT COUNT(*) AS c FROM episodes WHERE importance >= ? AND importance < ?`).get(lo, hi);
23286
+ return row2?.c ?? 0;
23287
23287
  } catch {
23288
23288
  return 0;
23289
23289
  }
@@ -23874,16 +23874,16 @@ function lightSleep(db, options2 = {}) {
23874
23874
  SET content = ?,
23875
23875
  metadata = json_patch(COALESCE(metadata, '{}'), json_object('compressedAt', ?))
23876
23876
  WHERE id = ?`);
23877
- for (const row of rows) {
23878
- const truncated = (row.content ?? "").slice(0, gistMaxChars);
23879
- const gist = (row.content ?? "").length > gistMaxChars ? truncated + "…" : truncated;
23877
+ for (const row2 of rows) {
23878
+ const truncated = (row2.content ?? "").slice(0, gistMaxChars);
23879
+ const gist = (row2.content ?? "").length > gistMaxChars ? truncated + "…" : truncated;
23880
23880
  try {
23881
- updateStmt.run(gist, start2, row.id);
23882
- compressed.push(row.id);
23881
+ updateStmt.run(gist, start2, row2.id);
23882
+ compressed.push(row2.id);
23883
23883
  } catch {
23884
23884
  try {
23885
- db.prepare(`UPDATE episodes SET content = ? WHERE id = ?`).run(gist, row.id);
23886
- compressed.push(row.id);
23885
+ db.prepare(`UPDATE episodes SET content = ? WHERE id = ?`).run(gist, row2.id);
23886
+ compressed.push(row2.id);
23887
23887
  } catch {
23888
23888
  }
23889
23889
  }
@@ -24000,8 +24000,8 @@ function cosineSim(a2, b) {
24000
24000
  }
24001
24001
  function episodeCount(db) {
24002
24002
  try {
24003
- const row = db.prepare(`SELECT COUNT(*) AS c FROM episodes`).get();
24004
- return row?.c ?? 0;
24003
+ const row2 = db.prepare(`SELECT COUNT(*) AS c FROM episodes`).get();
24004
+ return row2?.c ?? 0;
24005
24005
  } catch {
24006
24006
  return 0;
24007
24007
  }
@@ -24042,48 +24042,48 @@ function sanitizeBig5(p2) {
24042
24042
  function pairKey(a2, b) {
24043
24043
  return a2 <= b ? { lo: a2, hi: b } : { lo: b, hi: a2 };
24044
24044
  }
24045
- function rowToOpinion(row) {
24045
+ function rowToOpinion(row2) {
24046
24046
  return {
24047
- id: row.id,
24048
- topic: row.topic,
24049
- agentId: row.agent_id,
24050
- opinion: row.opinion,
24051
- confidence: row.confidence,
24052
- timestamp: row.timestamp
24047
+ id: row2.id,
24048
+ topic: row2.topic,
24049
+ agentId: row2.agent_id,
24050
+ opinion: row2.opinion,
24051
+ confidence: row2.confidence,
24052
+ timestamp: row2.timestamp
24053
24053
  };
24054
24054
  }
24055
- function rowToAgent(row) {
24055
+ function rowToAgent(row2) {
24056
24056
  return {
24057
- id: row.id,
24058
- name: row.name,
24059
- type: row.type,
24060
- firstMet: row.first_met,
24061
- lastInteraction: row.last_interaction,
24062
- interactionCount: row.interaction_count,
24063
- personality: sanitizeBig5(JSON.parse(row.personality)),
24064
- trust: JSON.parse(row.trust),
24065
- metadata: row.metadata ? JSON.parse(row.metadata) : null
24057
+ id: row2.id,
24058
+ name: row2.name,
24059
+ type: row2.type,
24060
+ firstMet: row2.first_met,
24061
+ lastInteraction: row2.last_interaction,
24062
+ interactionCount: row2.interaction_count,
24063
+ personality: sanitizeBig5(JSON.parse(row2.personality)),
24064
+ trust: JSON.parse(row2.trust),
24065
+ metadata: row2.metadata ? JSON.parse(row2.metadata) : null
24066
24066
  };
24067
24067
  }
24068
- function rowToRelationship(row) {
24068
+ function rowToRelationship(row2) {
24069
24069
  return {
24070
- agentA: row.agent_a,
24071
- agentB: row.agent_b,
24072
- strength: row.strength,
24073
- valence: row.valence,
24074
- reciprocity: row.reciprocity,
24075
- lastUpdated: row.last_updated,
24076
- history: JSON.parse(row.history ?? "[]")
24070
+ agentA: row2.agent_a,
24071
+ agentB: row2.agent_b,
24072
+ strength: row2.strength,
24073
+ valence: row2.valence,
24074
+ reciprocity: row2.reciprocity,
24075
+ lastUpdated: row2.last_updated,
24076
+ history: JSON.parse(row2.history ?? "[]")
24077
24077
  };
24078
24078
  }
24079
- function rowToLesson(row) {
24079
+ function rowToLesson(row2) {
24080
24080
  return {
24081
- id: row.id,
24082
- sourceAgent: row.source_agent,
24083
- lesson: row.lesson,
24084
- confidence: row.confidence,
24085
- adopted: row.adopted === 1,
24086
- timestamp: row.timestamp
24081
+ id: row2.id,
24082
+ sourceAgent: row2.source_agent,
24083
+ lesson: row2.lesson,
24084
+ confidence: row2.confidence,
24085
+ adopted: row2.adopted === 1,
24086
+ timestamp: row2.timestamp
24087
24087
  };
24088
24088
  }
24089
24089
  var NEUTRAL_BIG5, SocialMemoryStore;
@@ -24176,10 +24176,10 @@ var init_socialMemory = __esm({
24176
24176
  return this.getAgent(id2);
24177
24177
  }
24178
24178
  getAgent(id2) {
24179
- const row = this.db.prepare(`SELECT * FROM social_agents WHERE id = ?`).get(id2);
24180
- if (!row)
24179
+ const row2 = this.db.prepare(`SELECT * FROM social_agents WHERE id = ?`).get(id2);
24180
+ if (!row2)
24181
24181
  return null;
24182
- return rowToAgent(row);
24182
+ return rowToAgent(row2);
24183
24183
  }
24184
24184
  listAgents() {
24185
24185
  const rows = this.db.prepare(`SELECT * FROM social_agents ORDER BY last_interaction DESC`).all();
@@ -24254,10 +24254,10 @@ var init_socialMemory = __esm({
24254
24254
  }
24255
24255
  getRelationship(agentA, agentB) {
24256
24256
  const { lo, hi } = pairKey(agentA, agentB);
24257
- const row = this.db.prepare(`SELECT * FROM social_relationships WHERE agent_a = ? AND agent_b = ?`).get(lo, hi);
24258
- if (!row)
24257
+ const row2 = this.db.prepare(`SELECT * FROM social_relationships WHERE agent_a = ? AND agent_b = ?`).get(lo, hi);
24258
+ if (!row2)
24259
24259
  return null;
24260
- return rowToRelationship(row);
24260
+ return rowToRelationship(row2);
24261
24261
  }
24262
24262
  listRelationshipsFor(agent) {
24263
24263
  const rows = this.db.prepare(`SELECT * FROM social_relationships WHERE agent_a = ? OR agent_b = ?`).all(agent, agent);
@@ -24937,10 +24937,10 @@ function ensureSchema(db) {
24937
24937
  function checkEmbeddingDrift(db, current) {
24938
24938
  ensureSchema(db);
24939
24939
  try {
24940
- const row = db.prepare(`SELECT model_name, dim, set_at_ts FROM embedding_meta WHERE id = 1`).get();
24941
- if (!row)
24940
+ const row2 = db.prepare(`SELECT model_name, dim, set_at_ts FROM embedding_meta WHERE id = 1`).get();
24941
+ if (!row2)
24942
24942
  return { driftDetected: false };
24943
- const prev = { model: row.model_name, dim: row.dim, ts: row.set_at_ts };
24943
+ const prev = { model: row2.model_name, dim: row2.dim, ts: row2.set_at_ts };
24944
24944
  const drift = prev.model !== current.model || prev.dim !== current.dim;
24945
24945
  return { driftDetected: drift, previous: prev };
24946
24946
  } catch {
@@ -25503,10 +25503,10 @@ function maintainEpisodes(dbPath, options2, shouldStop) {
25503
25503
  stats.duplicateDeleted = deleteEpisodes(db, duplicateIds.slice(0, options2.maxEpisodeDeletes ?? 1e3), !!options2.dryRun);
25504
25504
  const remainingDeleteBudget = Math.max(0, (options2.maxEpisodeDeletes ?? 1e3) - stats.duplicateDeleted);
25505
25505
  if (remainingDeleteBudget > 0) {
25506
- const lowSignalIds = candidates.filter((row) => !duplicateIds.includes(row.id)).map((row) => ({
25507
- id: row.id,
25508
- score: memoryUtilityScore(row, Date.now())
25509
- })).filter((row) => row.score < (options2.minUtilityScore ?? 0.18)).sort((a2, b) => a2.score - b.score).slice(0, remainingDeleteBudget).map((row) => row.id);
25506
+ const lowSignalIds = candidates.filter((row2) => !duplicateIds.includes(row2.id)).map((row2) => ({
25507
+ id: row2.id,
25508
+ score: memoryUtilityScore(row2, Date.now())
25509
+ })).filter((row2) => row2.score < (options2.minUtilityScore ?? 0.18)).sort((a2, b) => a2.score - b.score).slice(0, remainingDeleteBudget).map((row2) => row2.id);
25510
25510
  stats.lowSignalDeleted = deleteEpisodes(db, lowSignalIds, !!options2.dryRun);
25511
25511
  }
25512
25512
  }
@@ -25545,9 +25545,9 @@ function loadEpisodeCandidates(db, limit) {
25545
25545
  }
25546
25546
  }
25547
25547
  function deleteEpisodes(db, ids, dryRun) {
25548
- const unique2 = [...new Set(ids)].filter(Boolean);
25549
- if (dryRun || unique2.length === 0)
25550
- return unique2.length;
25548
+ const unique3 = [...new Set(ids)].filter(Boolean);
25549
+ if (dryRun || unique3.length === 0)
25550
+ return unique3.length;
25551
25551
  let deleted = 0;
25552
25552
  const stmt = db.prepare(`DELETE FROM episodes WHERE id = ?`);
25553
25553
  const tx = db.transaction((rows) => {
@@ -25556,7 +25556,7 @@ function deleteEpisodes(db, ids, dryRun) {
25556
25556
  deleted += Number(result.changes ?? 0);
25557
25557
  }
25558
25558
  });
25559
- tx(unique2);
25559
+ tx(unique3);
25560
25560
  return deleted;
25561
25561
  }
25562
25562
  function maintainGraph(dbPath, options2, shouldStop) {
@@ -25631,33 +25631,33 @@ function loadGraphNodeCandidates(db, limit) {
25631
25631
  function vectorDuplicateNodePairs(rows, threshold) {
25632
25632
  const pairs = [];
25633
25633
  const buckets = /* @__PURE__ */ new Map();
25634
- for (const row of rows) {
25635
- const bucketKey = row.nodeType || "entity";
25634
+ for (const row2 of rows) {
25635
+ const bucketKey = row2.nodeType || "entity";
25636
25636
  const bucket = buckets.get(bucketKey) ?? [];
25637
- const vector = vectorFor(row.embedding, row.text);
25637
+ const vector = vectorFor(row2.embedding, row2.text);
25638
25638
  let merged = false;
25639
25639
  for (let i2 = 0; i2 < bucket.length; i2++) {
25640
25640
  const other = bucket[i2];
25641
25641
  const otherVector = vectorFor(other.embedding, other.text);
25642
25642
  if (cosine2(vector, otherVector) < threshold)
25643
25643
  continue;
25644
- const keep = graphNodeScore(row) > graphNodeScore(other) ? row : other;
25645
- const drop = keep.id === row.id ? other : row;
25644
+ const keep = graphNodeScore(row2) > graphNodeScore(other) ? row2 : other;
25645
+ const drop = keep.id === row2.id ? other : row2;
25646
25646
  pairs.push({ keepId: keep.id, dropId: drop.id });
25647
- if (keep.id === row.id)
25648
- bucket[i2] = row;
25647
+ if (keep.id === row2.id)
25648
+ bucket[i2] = row2;
25649
25649
  merged = true;
25650
25650
  break;
25651
25651
  }
25652
25652
  if (!merged)
25653
- bucket.push(row);
25653
+ bucket.push(row2);
25654
25654
  buckets.set(bucketKey, bucket);
25655
25655
  }
25656
25656
  return pairs;
25657
25657
  }
25658
25658
  function mergeGraphNodes(db, pairs, dryRun) {
25659
25659
  const seen = /* @__PURE__ */ new Set();
25660
- const unique2 = pairs.filter((pair) => {
25660
+ const unique3 = pairs.filter((pair) => {
25661
25661
  if (!pair.keepId || !pair.dropId || pair.keepId === pair.dropId)
25662
25662
  return false;
25663
25663
  if (seen.has(pair.dropId))
@@ -25665,8 +25665,8 @@ function mergeGraphNodes(db, pairs, dryRun) {
25665
25665
  seen.add(pair.dropId);
25666
25666
  return true;
25667
25667
  });
25668
- if (dryRun || unique2.length === 0)
25669
- return unique2.length;
25668
+ if (dryRun || unique3.length === 0)
25669
+ return unique3.length;
25670
25670
  let merged = 0;
25671
25671
  const tx = db.transaction((rows) => {
25672
25672
  const src2 = db.prepare(`UPDATE kg_edges SET src_id = ? WHERE src_id = ?`);
@@ -25684,7 +25684,7 @@ function mergeGraphNodes(db, pairs, dryRun) {
25684
25684
  merged += Number(deleted.changes ?? 0);
25685
25685
  }
25686
25686
  });
25687
- tx(unique2);
25687
+ tx(unique3);
25688
25688
  return merged;
25689
25689
  }
25690
25690
  function dedupeGraphEdges(db, limit, dryRun) {
@@ -25699,7 +25699,7 @@ function dedupeGraphEdges(db, limit, dryRun) {
25699
25699
  FROM kg_edges
25700
25700
  )
25701
25701
  WHERE rn > 1
25702
- LIMIT ?`).all(Math.max(1, limit)).map((row) => row.id);
25702
+ LIMIT ?`).all(Math.max(1, limit)).map((row2) => row2.id);
25703
25703
  } catch {
25704
25704
  return 0;
25705
25705
  }
@@ -25717,7 +25717,7 @@ function pruneInactiveEdges(db, limit, dryRun) {
25717
25717
  AND valid_until < ?
25718
25718
  AND COALESCE(confidence, 1) < 0.55
25719
25719
  ORDER BY valid_until ASC
25720
- LIMIT ?`).all(cutoff, Math.max(1, limit)).map((row) => row.id);
25720
+ LIMIT ?`).all(cutoff, Math.max(1, limit)).map((row2) => row2.id);
25721
25721
  } catch {
25722
25722
  return 0;
25723
25723
  }
@@ -25735,7 +25735,7 @@ function pruneOrphanNodes(db, limit, dryRun) {
25735
25735
  AND COALESCE(n.last_seen, 0) < ?
25736
25736
  AND NOT EXISTS (SELECT 1 FROM kg_edges e WHERE e.src_id = n.id OR e.dst_id = n.id)
25737
25737
  ORDER BY n.last_seen ASC
25738
- LIMIT ?`).all(cutoff, Math.max(1, limit)).map((row) => row.id);
25738
+ LIMIT ?`).all(cutoff, Math.max(1, limit)).map((row2) => row2.id);
25739
25739
  } catch {
25740
25740
  return 0;
25741
25741
  }
@@ -25745,8 +25745,8 @@ function pruneOrphanNodes(db, limit, dryRun) {
25745
25745
  }
25746
25746
  function countNodes(db) {
25747
25747
  try {
25748
- const row = db.prepare("SELECT COUNT(*) AS n FROM kg_nodes").get();
25749
- return Number(row?.n ?? 0);
25748
+ const row2 = db.prepare("SELECT COUNT(*) AS n FROM kg_nodes").get();
25749
+ return Number(row2?.n ?? 0);
25750
25750
  } catch {
25751
25751
  return 0;
25752
25752
  }
@@ -25779,27 +25779,27 @@ function selectCapEvictionCandidates(db, options2, withText) {
25779
25779
  LIMIT ?`).all(protectCut, shortlistLimit);
25780
25780
  const degStmt = db.prepare("SELECT COUNT(*) AS d FROM kg_edges WHERE src_id = ? OR dst_id = ?");
25781
25781
  const scored = [];
25782
- for (const row of shortlist) {
25783
- if (protect.has(row.id))
25782
+ for (const row2 of shortlist) {
25783
+ if (protect.has(row2.id))
25784
25784
  continue;
25785
25785
  let deg = 0;
25786
25786
  try {
25787
- deg = Number(degStmt.get(row.id, row.id)?.d ?? 0);
25787
+ deg = Number(degStmt.get(row2.id, row2.id)?.d ?? 0);
25788
25788
  } catch {
25789
25789
  deg = 0;
25790
25790
  }
25791
25791
  if (deg >= hubDegreeGuard)
25792
25792
  continue;
25793
- const ageMs = Math.max(0, now2 - row.ls);
25793
+ const ageMs = Math.max(0, now2 - row2.ls);
25794
25794
  const recency = Math.exp(-ageMs / (30 * DAY));
25795
- const utility = Math.log1p(row.mc) * 0.5 + Math.min(deg, 8) / 8 * 0.3 + recency * 0.2;
25795
+ const utility = Math.log1p(row2.mc) * 0.5 + Math.min(deg, 8) / 8 * 0.3 + recency * 0.2;
25796
25796
  scored.push({
25797
- id: row.id,
25798
- text: row.text,
25799
- nodeType: row.nodeType,
25800
- mentionCount: row.mc,
25797
+ id: row2.id,
25798
+ text: row2.text,
25799
+ nodeType: row2.nodeType,
25800
+ mentionCount: row2.mc,
25801
25801
  degree: deg,
25802
- lastSeen: row.ls,
25802
+ lastSeen: row2.ls,
25803
25803
  score: utility
25804
25804
  });
25805
25805
  }
@@ -25920,43 +25920,43 @@ function deleteById(db, table, ids) {
25920
25920
  function vectorDuplicateIds(rows, threshold) {
25921
25921
  const duplicateIds = [];
25922
25922
  const buckets = /* @__PURE__ */ new Map();
25923
- for (const row of rows) {
25924
- const key = `${row.toolName}\0${row.modality}`;
25923
+ for (const row2 of rows) {
25924
+ const key = `${row2.toolName}\0${row2.modality}`;
25925
25925
  const bucket = buckets.get(key) ?? [];
25926
- const vector = vectorFor(row.embedding, row.content);
25926
+ const vector = vectorFor(row2.embedding, row2.content);
25927
25927
  let absorbed = false;
25928
25928
  for (let i2 = 0; i2 < bucket.length; i2++) {
25929
25929
  const other = bucket[i2];
25930
25930
  const otherVector = vectorFor(other.embedding, other.content);
25931
25931
  if (cosine2(vector, otherVector) < threshold)
25932
25932
  continue;
25933
- const keep = memoryUtilityScore(row, Date.now()) > memoryUtilityScore(other, Date.now()) ? row : other;
25934
- const drop = keep.id === row.id ? other : row;
25933
+ const keep = memoryUtilityScore(row2, Date.now()) > memoryUtilityScore(other, Date.now()) ? row2 : other;
25934
+ const drop = keep.id === row2.id ? other : row2;
25935
25935
  duplicateIds.push(drop.id);
25936
- if (keep.id === row.id)
25937
- bucket[i2] = row;
25936
+ if (keep.id === row2.id)
25937
+ bucket[i2] = row2;
25938
25938
  absorbed = true;
25939
25939
  break;
25940
25940
  }
25941
25941
  if (!absorbed)
25942
- bucket.push(row);
25942
+ bucket.push(row2);
25943
25943
  buckets.set(key, bucket);
25944
25944
  }
25945
25945
  return [...new Set(duplicateIds)];
25946
25946
  }
25947
- function memoryUtilityScore(row, now2) {
25948
- const tau = DECAY_TAU2[row.decayClass] ?? DECAY_TAU2.daily;
25949
- const retention = tau === Number.POSITIVE_INFINITY ? 1 : Math.exp(-Math.max(0, now2 - row.lastAccessed) / tau);
25950
- const importance = clamp018(row.importance / 10);
25951
- const strength = clamp018(Math.log2(Math.max(1, row.strength)) / 4);
25952
- const reuse = clamp018(Math.log1p(Math.max(0, row.reuseCount)) / Math.log(9));
25953
- const recentUse = now2 - row.lastAccessed <= 6 * HOUR ? 1 : 0;
25947
+ function memoryUtilityScore(row2, now2) {
25948
+ const tau = DECAY_TAU2[row2.decayClass] ?? DECAY_TAU2.daily;
25949
+ const retention = tau === Number.POSITIVE_INFINITY ? 1 : Math.exp(-Math.max(0, now2 - row2.lastAccessed) / tau);
25950
+ const importance = clamp018(row2.importance / 10);
25951
+ const strength = clamp018(Math.log2(Math.max(1, row2.strength)) / 4);
25952
+ const reuse = clamp018(Math.log1p(Math.max(0, row2.reuseCount)) / Math.log(9));
25953
+ const recentUse = now2 - row2.lastAccessed <= 6 * HOUR ? 1 : 0;
25954
25954
  return importance * 0.42 + retention * 0.22 + strength * 0.16 + reuse * 0.16 + recentUse * 0.04;
25955
25955
  }
25956
- function graphNodeScore(row) {
25957
- const age = Math.max(0, Date.now() - row.lastSeen);
25956
+ function graphNodeScore(row2) {
25957
+ const age = Math.max(0, Date.now() - row2.lastSeen);
25958
25958
  const recency = Math.exp(-age / (30 * DAY));
25959
- return Math.log1p(Math.max(0, row.mentionCount)) * 0.7 + recency * 0.3;
25959
+ return Math.log1p(Math.max(0, row2.mentionCount)) * 0.7 + recency * 0.3;
25960
25960
  }
25961
25961
  function vectorFor(rawEmbedding, text2) {
25962
25962
  const decoded = decodeEmbedding(rawEmbedding);
@@ -44758,8 +44758,8 @@ function jsonToCSV(data, separator = ",") {
44758
44758
  };
44759
44759
  const lines = [
44760
44760
  headers.map((h) => esc(h)).join(separator),
44761
- ...data.map((row) => {
44762
- const obj = row;
44761
+ ...data.map((row2) => {
44762
+ const obj = row2;
44763
44763
  return headers.map((h) => esc(obj[h])).join(separator);
44764
44764
  })
44765
44765
  ];
@@ -44771,8 +44771,8 @@ function jsonToMarkdownTable(data) {
44771
44771
  const headers = Object.keys(data[0]);
44772
44772
  const headerRow = `| ${headers.join(" | ")} |`;
44773
44773
  const sepRow = `| ${headers.map(() => "---").join(" | ")} |`;
44774
- const dataRows = data.map((row) => {
44775
- const obj = row;
44774
+ const dataRows = data.map((row2) => {
44775
+ const obj = row2;
44776
44776
  return `| ${headers.map((h) => String(obj[h] ?? "")).join(" | ")} |`;
44777
44777
  });
44778
44778
  return [headerRow, sepRow, ...dataRows].join("\n") + "\n";
@@ -47485,12 +47485,12 @@ var init_identity2 = __esm({
47485
47485
  function from2({ name: name10, code: code8, encode: encode15, minDigestLength, maxDigestLength }) {
47486
47486
  return new Hasher(name10, code8, encode15, minDigestLength, maxDigestLength);
47487
47487
  }
47488
- function createDigest(digest3, code8, truncate4) {
47489
- if (truncate4 != null && truncate4 !== digest3.byteLength) {
47490
- if (truncate4 > digest3.byteLength) {
47488
+ function createDigest(digest3, code8, truncate5) {
47489
+ if (truncate5 != null && truncate5 !== digest3.byteLength) {
47490
+ if (truncate5 > digest3.byteLength) {
47491
47491
  throw new Error(`Invalid truncate option, must be less than or equal to ${digest3.byteLength}`);
47492
47492
  }
47493
- digest3 = digest3.subarray(0, truncate4);
47493
+ digest3 = digest3.subarray(0, truncate5);
47494
47494
  }
47495
47495
  return create(code8, digest3);
47496
47496
  }
@@ -80435,7 +80435,7 @@ var require_truncate = __commonJS({
80435
80435
  function isLowSurrogate(codePoint) {
80436
80436
  return codePoint >= 56320 && codePoint <= 57343;
80437
80437
  }
80438
- module.exports = function truncate4(getLength, string2, byteLength) {
80438
+ module.exports = function truncate5(getLength, string2, byteLength) {
80439
80439
  if (typeof string2 !== "string") {
80440
80440
  throw new Error("Input must be string");
80441
80441
  }
@@ -80466,9 +80466,9 @@ var require_truncate = __commonJS({
80466
80466
  var require_truncate_utf8_bytes = __commonJS({
80467
80467
  "../node_modules/truncate-utf8-bytes/index.js"(exports, module) {
80468
80468
  "use strict";
80469
- var truncate4 = require_truncate();
80469
+ var truncate5 = require_truncate();
80470
80470
  var getLength = Buffer.byteLength.bind(Buffer);
80471
- module.exports = truncate4.bind(null, getLength);
80471
+ module.exports = truncate5.bind(null, getLength);
80472
80472
  }
80473
80473
  });
80474
80474
 
@@ -80476,7 +80476,7 @@ var require_truncate_utf8_bytes = __commonJS({
80476
80476
  var require_sanitize_filename = __commonJS({
80477
80477
  "../node_modules/sanitize-filename/index.js"(exports, module) {
80478
80478
  "use strict";
80479
- var truncate4 = require_truncate_utf8_bytes();
80479
+ var truncate5 = require_truncate_utf8_bytes();
80480
80480
  var illegalRe = /[\/\?<>\\:\*\|"]/g;
80481
80481
  var controlRe = /[\x00-\x1f\x80-\x9f]/g;
80482
80482
  var reservedRe = /^\.+$/;
@@ -80492,7 +80492,7 @@ var require_sanitize_filename = __commonJS({
80492
80492
  }
80493
80493
  var sanitized = input.replace(illegalRe, replacement).replace(controlRe, replacement).replace(reservedRe, replacement).replace(windowsReservedRe, replacement);
80494
80494
  sanitized = replaceTrailingDotsAndSpaces(sanitized, replacement);
80495
- return truncate4(sanitized, 255);
80495
+ return truncate5(sanitized, 255);
80496
80496
  }
80497
80497
  module.exports = function(input, options2) {
80498
80498
  var replacement = options2 && options2.replacement || "";
@@ -100071,15 +100071,15 @@ var require_x509_cjs = __commonJS({
100071
100071
  const view = pvtsutils.BufferSourceConverter.toUint8Array(buffer2);
100072
100072
  const res = [];
100073
100073
  for (let i2 = 0; i2 < view.length; ) {
100074
- const row = [];
100074
+ const row2 = [];
100075
100075
  for (let j = 0; j < 16 && i2 < view.length; j++) {
100076
100076
  if (j === 8) {
100077
- row.push("");
100077
+ row2.push("");
100078
100078
  }
100079
100079
  const hex = view[i2++].toString(16).padStart(2, "0");
100080
- row.push(hex);
100080
+ row2.push(hex);
100081
100081
  }
100082
- res.push(`${pad}${row.join(" ")}`);
100082
+ res.push(`${pad}${row2.join(" ")}`);
100083
100083
  }
100084
100084
  return res;
100085
100085
  }
@@ -289969,11 +289969,11 @@ function parseCSV(text2, separator = ",") {
289969
289969
  const rows = [];
289970
289970
  for (let i2 = 1; i2 < lines.length; i2++) {
289971
289971
  const values = parseLine(lines[i2]);
289972
- const row = {};
289972
+ const row2 = {};
289973
289973
  for (let j = 0; j < headers.length; j++) {
289974
- row[headers[j]] = (values[j] ?? "").trim();
289974
+ row2[headers[j]] = (values[j] ?? "").trim();
289975
289975
  }
289976
- rows.push(row);
289976
+ rows.push(row2);
289977
289977
  }
289978
289978
  return rows;
289979
289979
  }
@@ -290004,11 +290004,11 @@ function parseMarkdownTables(text2) {
290004
290004
  if (!dataLine.startsWith("|") || !dataLine.endsWith("|"))
290005
290005
  break;
290006
290006
  const values = dataLine.split("|").filter((c9) => c9.trim() !== "").map((c9) => c9.trim());
290007
- const row = {};
290007
+ const row2 = {};
290008
290008
  for (let j = 0; j < headers.length; j++) {
290009
- row[headers[j]] = values[j] ?? "";
290009
+ row2[headers[j]] = values[j] ?? "";
290010
290010
  }
290011
- rows.push(row);
290011
+ rows.push(row2);
290012
290012
  i2++;
290013
290013
  }
290014
290014
  if (rows.length > 0) {
@@ -293696,9 +293696,9 @@ Run autoresearch(action="setup") to begin.`,
293696
293696
  } catch {
293697
293697
  }
293698
293698
  }
293699
- const row = `${commitHash} ${valBpb.toFixed(6)} ${memGb.toFixed(1)} keep ${desc}
293699
+ const row2 = `${commitHash} ${valBpb.toFixed(6)} ${memGb.toFixed(1)} keep ${desc}
293700
293700
  `;
293701
- appendFileSync3(tsvPath, row, "utf-8");
293701
+ appendFileSync3(tsvPath, row2, "utf-8");
293702
293702
  return {
293703
293703
  success: true,
293704
293704
  output: `Kept: ${commitHash} | val_bpb=${valBpb.toFixed(6)} | ${memGb.toFixed(1)}GB | ${desc}
@@ -293729,9 +293729,9 @@ Branch advanced. Ready for next experiment.`,
293729
293729
  commitHash = execSync21("git rev-parse --short HEAD", { cwd: workspace, encoding: "utf-8", timeout: 5e3 }).trim();
293730
293730
  } catch {
293731
293731
  }
293732
- const row = `${commitHash} ${valBpb.toFixed(6)} ${memGb.toFixed(1)} discard ${desc}
293732
+ const row2 = `${commitHash} ${valBpb.toFixed(6)} ${memGb.toFixed(1)} discard ${desc}
293733
293733
  `;
293734
- appendFileSync3(tsvPath, row, "utf-8");
293734
+ appendFileSync3(tsvPath, row2, "utf-8");
293735
293735
  try {
293736
293736
  execSync21("git checkout -- train.py", { cwd: workspace, encoding: "utf-8", timeout: 5e3 });
293737
293737
  } catch {
@@ -446532,8 +446532,8 @@ ${lanes.join("\n")}
446532
446532
  const headerPadding = Math.max(numberLength(maxErrors) - leftColumnHeadingLength, 0);
446533
446533
  let tabularData = "";
446534
446534
  tabularData += " ".repeat(headerPadding) + headerRow + "\n";
446535
- fileToErrorCount.forEach((row) => {
446536
- const [file, errorCount] = row;
446535
+ fileToErrorCount.forEach((row2) => {
446536
+ const [file, errorCount] = row2;
446537
446537
  const errorCountDigitsLength = Math.log(errorCount) * Math.LOG10E + 1 | 0;
446538
446538
  const leftPadding = errorCountDigitsLength < leftPaddingGoal ? " ".repeat(leftPaddingGoal - errorCountDigitsLength) : "";
446539
446539
  const fileRef = prettyPathForFileError(file, host.getCurrentDirectory());
@@ -497694,9 +497694,9 @@ ${options2.prefix}` : "\n" : options2.prefix
497694
497694
  }
497695
497695
  return map22;
497696
497696
  }
497697
- function getRuleBucketIndex(row, column) {
497698
- Debug.assert(row <= 166 && column <= 166, "Must compute formatting context from tokens");
497699
- return row * mapRowLength + column;
497697
+ function getRuleBucketIndex(row2, column) {
497698
+ Debug.assert(row2 <= 166 && column <= 166, "Must compute formatting context from tokens");
497699
+ return row2 * mapRowLength + column;
497700
497700
  }
497701
497701
  var maskBitSize = 5;
497702
497702
  var mask = 31;
@@ -503283,11 +503283,11 @@ ${options2.prefix}` : "\n" : options2.prefix
503283
503283
  return true;
503284
503284
  }
503285
503285
  const set = /* @__PURE__ */ new Map();
503286
- let unique2 = 0;
503286
+ let unique3 = 0;
503287
503287
  for (const v of arr1) {
503288
503288
  if (set.get(v) !== true) {
503289
503289
  set.set(v, true);
503290
- unique2++;
503290
+ unique3++;
503291
503291
  }
503292
503292
  }
503293
503293
  for (const v of arr2) {
@@ -503297,10 +503297,10 @@ ${options2.prefix}` : "\n" : options2.prefix
503297
503297
  }
503298
503298
  if (isSet === true) {
503299
503299
  set.set(v, false);
503300
- unique2--;
503300
+ unique3--;
503301
503301
  }
503302
503302
  }
503303
- return unique2 === 0;
503303
+ return unique3 === 0;
503304
503304
  }
503305
503305
  function typeAcquisitionChanged(opt1, opt2) {
503306
503306
  return opt1.enable !== opt2.enable || !setIsEqualTo(opt1.include, opt2.include) || !setIsEqualTo(opt1.exclude, opt2.exclude);
@@ -545424,17 +545424,17 @@ var init_code_graph_db = __esm({
545424
545424
  * single source of truth for column→field translation; if the schema
545425
545425
  * gains/renames a column, only this method needs updating.
545426
545426
  */
545427
- rowToSymbol(row) {
545427
+ rowToSymbol(row2) {
545428
545428
  return {
545429
- id: row.id,
545430
- filePath: row.file_path,
545431
- name: row.name,
545432
- kind: row.kind,
545433
- startLine: row.start_line ?? 0,
545434
- endLine: row.end_line ?? 0,
545435
- signature: row.signature ?? "",
545436
- docstring: row.docstring ?? "",
545437
- exported: !!row.exported
545429
+ id: row2.id,
545430
+ filePath: row2.file_path,
545431
+ name: row2.name,
545432
+ kind: row2.kind,
545433
+ startLine: row2.start_line ?? 0,
545434
+ endLine: row2.end_line ?? 0,
545435
+ signature: row2.signature ?? "",
545436
+ docstring: row2.docstring ?? "",
545437
+ exported: !!row2.exported
545438
545438
  };
545439
545439
  }
545440
545440
  /** Get all symbols for a file. */
@@ -545559,16 +545559,16 @@ var init_code_graph_db = __esm({
545559
545559
  }
545560
545560
  /** Get graph statistics. */
545561
545561
  getStats() {
545562
- const row = this.stmts.getStats.get();
545562
+ const row2 = this.stmts.getStats.get();
545563
545563
  return {
545564
- ...row,
545564
+ ...row2,
545565
545565
  lastFullIndex: this.db.prepare(`SELECT MAX(last_indexed) as t FROM files`).get()?.t ?? null
545566
545566
  };
545567
545567
  }
545568
545568
  /** Get the stored hash for a file (for change detection). */
545569
545569
  getFileHash(relPath) {
545570
- const row = this.stmts.getFile.get(relPath);
545571
- return row?.hash ?? null;
545570
+ const row2 = this.stmts.getFile.get(relPath);
545571
+ return row2?.hash ?? null;
545572
545572
  }
545573
545573
  /** Compact query: top-N files by import count (pseudo-PageRank). */
545574
545574
  getTopFiles(limit = 20) {
@@ -567353,32 +567353,32 @@ async function scanOllamaProcesses(options2 = {}) {
567353
567353
  readGpuMemoryByPid(system)
567354
567354
  ]);
567355
567355
  const snapshots = [];
567356
- for (const row of psRows) {
567357
- const serve = isOllamaServeCommand(row.command);
567358
- const runner = !serve && isOllamaRunnerCommand(row.command);
567356
+ for (const row2 of psRows) {
567357
+ const serve = isOllamaServeCommand(row2.command);
567358
+ const runner = !serve && isOllamaRunnerCommand(row2.command);
567359
567359
  if (!serve && !runner)
567360
567360
  continue;
567361
- const env2 = serve ? await readProcEnv(system, row.pid) : { readable: false, values: {} };
567361
+ const env2 = serve ? await readProcEnv(system, row2.pid) : { readable: false, values: {} };
567362
567362
  const ports = uniqueNumbers([
567363
- ...portMap.get(row.pid) ?? [],
567363
+ ...portMap.get(row2.pid) ?? [],
567364
567364
  ...serve ? portsFromEnv(env2.values) : []
567365
567365
  ]);
567366
567366
  const ollamaApiPorts = serve ? await probeOllamaPorts(system, ports) : [];
567367
567367
  snapshots.push({
567368
- pid: row.pid,
567369
- ppid: row.ppid,
567370
- command: row.command,
567371
- cpuPct: row.cpuPct,
567372
- memPct: row.memPct,
567373
- elapsedMs: row.elapsedMs,
567368
+ pid: row2.pid,
567369
+ ppid: row2.ppid,
567370
+ command: row2.command,
567371
+ cpuPct: row2.cpuPct,
567372
+ memPct: row2.memPct,
567373
+ elapsedMs: row2.elapsedMs,
567374
567374
  ports,
567375
567375
  ollamaApiPorts,
567376
567376
  envReadable: env2.readable,
567377
567377
  env: env2.values,
567378
- gpuMemoryMb: gpuMemoryByPid.get(row.pid) ?? null,
567378
+ gpuMemoryMb: gpuMemoryByPid.get(row2.pid) ?? null,
567379
567379
  isOllamaServe: serve,
567380
567380
  isOllamaRunner: runner,
567381
- runnerModelBlob: runner ? parseRunnerModelBlob(row.command) : null
567381
+ runnerModelBlob: runner ? parseRunnerModelBlob(row2.command) : null
567382
567382
  });
567383
567383
  }
567384
567384
  const decisions = classifyOllamaProcesses(snapshots, {
@@ -573255,6 +573255,295 @@ var init_reflectionBuffer = __esm({
573255
573255
  }
573256
573256
  });
573257
573257
 
573258
+ // packages/orchestrator/dist/trajectory-checkpoint.js
573259
+ function sanitizeTrajectoryText(value2, max = 260) {
573260
+ const text2 = String(value2 ?? "").replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "").replace(CONTROL_RE, " ").replace(/\s+/g, " ").trim();
573261
+ return text2.length > max ? `${text2.slice(0, Math.max(0, max - 1))}…` : text2;
573262
+ }
573263
+ function trajectoryCheckpointFingerprint(checkpoint) {
573264
+ return [
573265
+ checkpoint.assessment,
573266
+ checkpoint.goal,
573267
+ checkpoint.phase ?? "",
573268
+ checkpoint.currentStep ?? "",
573269
+ checkpoint.completedWork.join(""),
573270
+ checkpoint.groundedFacts.map((fact) => `${fact.statement}\0${fact.evidence}\0${fact.freshness}`).join(""),
573271
+ checkpoint.openQuestions.join(""),
573272
+ checkpoint.nextAction,
573273
+ checkpoint.successEvidence,
573274
+ checkpoint.doNotRepeat.join("")
573275
+ ].join("");
573276
+ }
573277
+ function buildTrajectoryCheckpoint(input) {
573278
+ const state = input.taskState;
573279
+ const goal = sanitizeTrajectoryText(state.originalGoal || state.goal, 600) || "Recover the concrete user goal before mutating project files.";
573280
+ const observations = input.observations.slice(-16);
573281
+ const outcome = [...observations].reverse().find((item) => item.type === "tool_result" || item.type === "error");
573282
+ const outcomeText = sanitizeTrajectoryText(outcome?.content, 240);
573283
+ const latestFailure = [...observations].reverse().find((item) => item.type === "tool_result" && item.success === false || item.type === "error");
573284
+ const failureText = sanitizeTrajectoryText(latestFailure?.content, 300);
573285
+ const fallbackFailure = input.recentFailures?.at(-1);
573286
+ const combinedFailure = [
573287
+ failureText,
573288
+ sanitizeTrajectoryText(fallbackFailure?.error || fallbackFailure?.output, 300)
573289
+ ].filter(Boolean).join(" ");
573290
+ const focus = sanitizeTrajectoryText(input.focusDirective, 300);
573291
+ const targetPath = inferTargetPath(combinedFailure || outcomeText || focus) ?? latestFailure?.targetPath ?? mostRecentTargetForTool(observations, latestFailure?.toolName);
573292
+ const targetFreshness = targetPath ? input.evidenceFreshness?.(targetPath) ?? "unknown" : "unknown";
573293
+ const modifiedFiles = Array.from(state.modifiedFiles).slice(-3);
573294
+ const fullWriteIssue = (latestFailure?.toolName === "file_write" || fallbackFailure?.tool === "file_write" || /file_write/i.test(combinedFailure)) && /FULL FILE (?:WRITE LOOP BLOCKED|REWRITE CONTRACT)|overwrite(?:=true)?|expected_hash|Refusing to overwrite existing file/i.test(combinedFailure);
573295
+ const fullWriteRecoveredByMutation = fullWriteIssue && Boolean(targetPath) && modifiedFiles.some(([path16]) => sameProjectPath(path16, targetPath)) && typeof latestFailure?.turn === "number" && typeof input.lastMutationTurn === "number" && input.lastMutationTurn > latestFailure.turn;
573296
+ const explicitBlock = /(?:permission denied|needs user input|ask_user|cannot proceed|external dependency|\[.*BLOCKED\])/i.test(combinedFailure);
573297
+ const hasRecentFailure = Boolean(combinedFailure);
573298
+ const verifierDue = modifiedFiles.length > 0 && (input.lastVerifier?.turn === void 0 || input.lastMutationTurn !== void 0 && (input.lastVerifier.turn ?? -1) < input.lastMutationTurn);
573299
+ let assessment = "on_trajectory";
573300
+ let nextAction = sanitizeTrajectoryText(state.nextAction, 260) || "Take one narrow, evidence-backed action that advances the active task.";
573301
+ let successEvidence = "A tool result directly confirms the next action advanced the stated goal.";
573302
+ const openQuestions = [];
573303
+ const doNotRepeat = [];
573304
+ if (fullWriteIssue && !fullWriteRecoveredByMutation) {
573305
+ assessment = "recovery_required";
573306
+ const target = targetPath || "the existing target file";
573307
+ nextAction = targetFreshness === "fresh" ? `Use file_edit/file_patch for the local change in ${target}; do not resume full-file writes.` : `file_read ${target}, then prefer file_edit/file_patch for the local change.`;
573308
+ successEvidence = targetFreshness === "fresh" ? "A targeted mutation based on the freshly read file, or an explicit evidence-backed blocker." : "Fresh current file evidence followed by a targeted mutation, or an explicit evidence-backed blocker.";
573309
+ doNotRepeat.push(`file_write ${target} with another changed full-file payload before fresh read evidence.`);
573310
+ if (targetFreshness !== "fresh") {
573311
+ openQuestions.push(`Current bytes/hash for ${target} are not freshly evidenced.`);
573312
+ }
573313
+ } else if (explicitBlock && !fullWriteRecoveredByMutation) {
573314
+ assessment = "blocked";
573315
+ nextAction = "Resolve or report the explicit blocker with the evidence that established it.";
573316
+ successEvidence = "A new observation removes the blocker or documents why it cannot be removed.";
573317
+ doNotRepeat.push("Retrying the blocked action unchanged without new evidence.");
573318
+ } else if (focus) {
573319
+ assessment = "recovery_required";
573320
+ nextAction = extractFocusNextAction(focus) || nextAction;
573321
+ successEvidence = "The focus recovery requirement is satisfied by a fresh tool observation.";
573322
+ doNotRepeat.push("Ignoring the active focus recovery directive.");
573323
+ } else if (hasRecentFailure && !fullWriteRecoveredByMutation) {
573324
+ assessment = "recovery_required";
573325
+ nextAction = "Use the newest failure evidence to make one different, narrow diagnostic or repair action.";
573326
+ successEvidence = "The next tool result changes, resolves, or explicitly narrows the observed failure.";
573327
+ doNotRepeat.push("Retrying the same failed action with unchanged prerequisites.");
573328
+ } else if (verifierDue) {
573329
+ assessment = "verification_due";
573330
+ nextAction = "Run the declared verifier or the narrowest relevant validation for the recent mutation.";
573331
+ successEvidence = "A post-mutation verifier result is recorded.";
573332
+ }
573333
+ if (fullWriteIssue && fullWriteRecoveredByMutation) {
573334
+ doNotRepeat.push("Returning to unguarded file_write after the targeted repair; verify the repair first.");
573335
+ }
573336
+ const groundedFacts = [];
573337
+ if (state.currentStep.trim()) {
573338
+ groundedFacts.push({
573339
+ statement: `Current work: ${sanitizeTrajectoryText(state.currentStep, 180)}`,
573340
+ evidence: `task_state@tool_call_${state.toolCallCount}`,
573341
+ freshness: "unknown"
573342
+ });
573343
+ }
573344
+ if (outcomeText) {
573345
+ const status = outcome?.success === false ? "failed" : "observed";
573346
+ groundedFacts.push({
573347
+ statement: `${outcome?.toolName ?? "runner"} ${status}: ${outcomeText}`,
573348
+ evidence: `turn:${outcome?.turn ?? input.turn}:${outcome?.type ?? "event"}`,
573349
+ freshness: "fresh"
573350
+ });
573351
+ }
573352
+ if (modifiedFiles.length > 0) {
573353
+ groundedFacts.push({
573354
+ statement: `Recent project mutations: ${modifiedFiles.map(([path16, action]) => `${path16} (${action})`).join(", ")}`,
573355
+ evidence: `task_state@tool_call_${state.toolCallCount}`,
573356
+ freshness: "unknown"
573357
+ });
573358
+ }
573359
+ if (input.lastVerifier?.summary) {
573360
+ groundedFacts.push({
573361
+ statement: `Latest verifier ${input.lastVerifier.passed === true ? "passed" : input.lastVerifier.passed === false ? "failed" : "reported"}: ${sanitizeTrajectoryText(input.lastVerifier.summary, 180)}`,
573362
+ evidence: `verifier@turn_${input.lastVerifier.turn ?? "unknown"}`,
573363
+ freshness: "fresh"
573364
+ });
573365
+ }
573366
+ if (targetPath) {
573367
+ groundedFacts.push({
573368
+ statement: `Evidence for ${targetPath}: ${targetFreshness}`,
573369
+ evidence: `evidence_ledger:${targetPath}`,
573370
+ freshness: targetFreshness
573371
+ });
573372
+ }
573373
+ if (focus) {
573374
+ groundedFacts.push({
573375
+ statement: `Active recovery directive: ${focus}`,
573376
+ evidence: "focus_supervisor",
573377
+ freshness: "fresh"
573378
+ });
573379
+ }
573380
+ const completedWork = state.completedSteps.slice(-MAX_COMPLETED).map((value2) => sanitizeTrajectoryText(value2, 180)).filter(Boolean);
573381
+ if (state.pendingSteps.length > 0 && !state.nextAction.trim()) {
573382
+ openQuestions.push(`Choose the next pending task: ${sanitizeTrajectoryText(state.pendingSteps[0], 180)}`);
573383
+ }
573384
+ const checkpointWithoutIdentity = {
573385
+ schemaVersion: 1,
573386
+ trigger: sanitizeTrajectoryText(input.trigger || inferTrigger(outcome), 80),
573387
+ assessment,
573388
+ goal,
573389
+ phase: sanitizeTrajectoryText(state.phase, 60) || void 0,
573390
+ currentStep: sanitizeTrajectoryText(state.currentStep, 180) || void 0,
573391
+ completedWork,
573392
+ groundedFacts: groundedFacts.slice(0, MAX_FACTS),
573393
+ openQuestions: unique2(openQuestions, 2),
573394
+ nextAction: sanitizeTrajectoryText(nextAction, 320),
573395
+ successEvidence: sanitizeTrajectoryText(successEvidence, 280),
573396
+ doNotRepeat: unique2(doNotRepeat, MAX_CONSTRAINTS)
573397
+ };
573398
+ const fingerprint = trajectoryCheckpointFingerprint(checkpointWithoutIdentity);
573399
+ return {
573400
+ ...checkpointWithoutIdentity,
573401
+ id: `trajectory-${input.turn}-${shortHash2(fingerprint)}`,
573402
+ revision: input.revision,
573403
+ turn: input.turn
573404
+ };
573405
+ }
573406
+ function renderTrajectoryCheckpoint(checkpoint, maxChars = 1100) {
573407
+ const lines = [
573408
+ "[TRAJECTORY CHECKPOINT]",
573409
+ `revision=${checkpoint.revision} turn=${checkpoint.turn} trigger=${checkpoint.trigger}`,
573410
+ `Goal: ${checkpoint.goal}`,
573411
+ `Assessment: ${checkpoint.assessment}`,
573412
+ checkpoint.phase ? `Phase: ${checkpoint.phase}` : null,
573413
+ checkpoint.currentStep ? `Current step: ${checkpoint.currentStep}` : null,
573414
+ checkpoint.completedWork.length > 0 ? `Completed evidence-backed work: ${checkpoint.completedWork.join("; ")}` : null,
573415
+ checkpoint.groundedFacts.length > 0 ? "Grounded facts:" : null,
573416
+ ...checkpoint.groundedFacts.map((fact) => `- [${fact.evidence}; ${fact.freshness}] ${fact.statement}`),
573417
+ checkpoint.openQuestions.length > 0 ? "Open questions:" : null,
573418
+ ...checkpoint.openQuestions.map((question) => `- ${question}`),
573419
+ `Required next action: ${checkpoint.nextAction}`,
573420
+ `Success evidence: ${checkpoint.successEvidence}`,
573421
+ checkpoint.doNotRepeat.length > 0 ? "Do not repeat:" : null,
573422
+ ...checkpoint.doNotRepeat.map((constraint) => `- ${constraint}`),
573423
+ "Attention rule: reconcile the next tool call with this checkpoint. Treat stale or unknown evidence as a reason to read or verify. Do not quote this checkpoint or produce a reasoning transcript."
573424
+ ].filter((line) => Boolean(line));
573425
+ return truncate(lines.join("\n"), maxChars);
573426
+ }
573427
+ function scopeTrajectoryCheckpoint(checkpoint, delegatedScope, exitEvidence) {
573428
+ if (!checkpoint)
573429
+ return null;
573430
+ return {
573431
+ parentGoal: checkpoint.goal,
573432
+ delegatedScope: sanitizeTrajectoryText(delegatedScope, 320),
573433
+ assessment: checkpoint.assessment,
573434
+ relevantConstraint: checkpoint.doNotRepeat[0],
573435
+ exitEvidence: sanitizeTrajectoryText(exitEvidence, 260)
573436
+ };
573437
+ }
573438
+ function renderScopedTrajectoryCheckpoint(slice2) {
573439
+ if (!slice2)
573440
+ return "";
573441
+ return [
573442
+ "[PARENT TRAJECTORY SCOPE]",
573443
+ `Parent goal: ${slice2.parentGoal}`,
573444
+ `Delegated scope: ${slice2.delegatedScope}`,
573445
+ `Parent assessment: ${slice2.assessment}`,
573446
+ slice2.relevantConstraint ? `Relevant constraint: ${slice2.relevantConstraint}` : null,
573447
+ `Exit evidence required: ${slice2.exitEvidence}`,
573448
+ "Use this as scoped orientation. Verify your own file and tool facts before acting."
573449
+ ].filter((line) => Boolean(line)).join("\n");
573450
+ }
573451
+ function inferTrigger(outcome) {
573452
+ if (!outcome)
573453
+ return "task_start";
573454
+ if (outcome.type === "compaction")
573455
+ return "compaction";
573456
+ if (outcome.type === "error")
573457
+ return "error";
573458
+ if (outcome.type === "tool_result") {
573459
+ return outcome.success === false ? "tool_failure" : "tool_result";
573460
+ }
573461
+ return outcome.type;
573462
+ }
573463
+ function inferTargetPath(value2) {
573464
+ const text2 = String(value2 ?? "");
573465
+ const patterns = [
573466
+ /\]\s+([^\s,;]+\.[a-zA-Z0-9_-]+)\s+has already/i,
573467
+ /existing file\s+([^\s,;]+)/i,
573468
+ /(?:file_read|file_write|file_edit|file_patch)\s+([^\s,;]+)/i,
573469
+ /(?:path|file)\s*[=:]\s*["']([^"']+)["']/i
573470
+ ];
573471
+ for (const pattern of patterns) {
573472
+ const candidate = pattern.exec(text2)?.[1]?.trim();
573473
+ if (candidate)
573474
+ return candidate.replace(/[.)\]}]+$/, "");
573475
+ }
573476
+ return null;
573477
+ }
573478
+ function mostRecentTargetForTool(observations, toolName) {
573479
+ for (const observation of [...observations].reverse()) {
573480
+ if (observation.type === "tool_call" && observation.targetPath && (!toolName || observation.toolName === toolName)) {
573481
+ return observation.targetPath;
573482
+ }
573483
+ }
573484
+ return null;
573485
+ }
573486
+ function sameProjectPath(left, right) {
573487
+ const normalize3 = (value2) => String(value2 ?? "").replace(/\\/g, "/").replace(/^\.\/+/, "").replace(/\/+/g, "/").replace(/\/+$/, "");
573488
+ const a2 = normalize3(left);
573489
+ const b = normalize3(right);
573490
+ return Boolean(a2 && b) && (a2 === b || a2.endsWith(`/${b}`) || b.endsWith(`/${a2}`));
573491
+ }
573492
+ function extractFocusNextAction(value2) {
573493
+ const match = /(?:Required next action|Next action)\s*:\s*(.+?)(?=\s+(?:Success evidence|Do not repeat|Attention rule)|$)/i.exec(value2);
573494
+ if (match?.[1])
573495
+ return sanitizeTrajectoryText(match[1], 300);
573496
+ const required = /required_next_action=([a-z_]+)/i.exec(value2)?.[1];
573497
+ switch (required) {
573498
+ case "read_authoritative_target":
573499
+ return "Read the authoritative target before attempting another mutation.";
573500
+ case "disambiguate_edit_match":
573501
+ return "Read the current target and disambiguate the intended edit match.";
573502
+ case "edit_different_target":
573503
+ return "Choose a different evidence-backed target for the next edit.";
573504
+ case "run_verification":
573505
+ return "Run the required verification before additional exploration or completion.";
573506
+ case "use_cached_evidence":
573507
+ return "Use the already-rendered evidence before requesting another identical read.";
573508
+ case "update_todos":
573509
+ return "Update the task plan to reflect the current evidence before continuing.";
573510
+ case "delegate_isolated_fix":
573511
+ return "Delegate the isolated repair with a concrete exit-evidence contract.";
573512
+ case "creative_pivot_or_research":
573513
+ return "Take a different diagnostic or research action grounded in the latest failure.";
573514
+ case "report_blocked":
573515
+ case "report_incomplete":
573516
+ return "Report the current blocker or incomplete state with the evidence that established it.";
573517
+ default:
573518
+ return null;
573519
+ }
573520
+ }
573521
+ function unique2(values, limit) {
573522
+ return [...new Set(values.map((value2) => sanitizeTrajectoryText(value2)).filter(Boolean))].slice(0, limit);
573523
+ }
573524
+ function truncate(value2, max) {
573525
+ const clean5 = String(value2 ?? "").trim();
573526
+ return clean5.length > max ? `${clean5.slice(0, Math.max(0, max - 1))}…` : clean5;
573527
+ }
573528
+ function shortHash2(value2) {
573529
+ let hash = 2166136261;
573530
+ for (let i2 = 0; i2 < value2.length; i2++) {
573531
+ hash ^= value2.charCodeAt(i2);
573532
+ hash = Math.imul(hash, 16777619);
573533
+ }
573534
+ return (hash >>> 0).toString(16).padStart(8, "0");
573535
+ }
573536
+ var CONTROL_RE, MAX_FACTS, MAX_COMPLETED, MAX_CONSTRAINTS;
573537
+ var init_trajectory_checkpoint = __esm({
573538
+ "packages/orchestrator/dist/trajectory-checkpoint.js"() {
573539
+ "use strict";
573540
+ CONTROL_RE = /[\x00-\x1F\x7F]/g;
573541
+ MAX_FACTS = 5;
573542
+ MAX_COMPLETED = 3;
573543
+ MAX_CONSTRAINTS = 3;
573544
+ }
573545
+ });
573546
+
573258
573547
  // packages/orchestrator/dist/taskHandoff.js
573259
573548
  import * as fs4 from "node:fs";
573260
573549
  import * as path5 from "node:path";
@@ -573290,6 +573579,12 @@ function buildTaskHandoff(params) {
573290
573579
  toolsUsed,
573291
573580
  turns: params.turns
573292
573581
  });
573582
+ const trajectory = params.trajectory ? {
573583
+ assessment: params.trajectory.assessment,
573584
+ nextAction: sanitizeTrajectoryText(params.trajectory.nextAction, 360),
573585
+ successEvidence: sanitizeTrajectoryText(params.trajectory.successEvidence, 360),
573586
+ doNotRepeat: params.trajectory.doNotRepeat.slice(0, 3).map((item) => sanitizeTrajectoryText(item, 220)).filter(Boolean)
573587
+ } : void 0;
573293
573588
  return {
573294
573589
  v: 2,
573295
573590
  sessionId: params.sessionId,
@@ -573303,6 +573598,7 @@ function buildTaskHandoff(params) {
573303
573598
  endedAt: Date.now(),
573304
573599
  artifactMode,
573305
573600
  quality,
573601
+ ...trajectory ? { trajectory } : {},
573306
573602
  ...params.transcriptPath ? { transcriptPath: params.transcriptPath } : {}
573307
573603
  };
573308
573604
  }
@@ -573374,6 +573670,14 @@ function buildHandoffMessagePair(h) {
573374
573670
  const toolsBlock = h.toolsUsed.length ? h.toolsUsed.map((t2) => ` - ${t2}`).join("\n") : " (none)";
573375
573671
  const actionsBlock = h.lastActions.length ? h.lastActions.map((a2) => ` - ${a2}`).join("\n") : " (none recorded)";
573376
573672
  const summaryBlock = h.priorSummary || "(no summary captured)";
573673
+ const trajectoryBlock = h.trajectory ? [
573674
+ "Prior trajectory (STALE orientation — verify before acting):",
573675
+ ` Assessment: ${h.trajectory.assessment}`,
573676
+ ` Next: ${h.trajectory.nextAction || "(not captured)"}`,
573677
+ ` Proof: ${h.trajectory.successEvidence || "(not captured)"}`,
573678
+ ...h.trajectory.doNotRepeat.length ? [` Guard: ${h.trajectory.doNotRepeat.join("; ")}`] : [],
573679
+ ""
573680
+ ] : [];
573377
573681
  const transcriptHint = h.transcriptPath ? `
573378
573682
 
573379
573683
  If you need verbatim details from the prior task (specific code, exact error messages, or content beyond this summary), file_read the transcript at: ${h.transcriptPath}` : "";
@@ -573395,6 +573699,7 @@ If you need verbatim details from the prior task (specific code, exact error mes
573395
573699
  "Summary:",
573396
573700
  summaryBlock,
573397
573701
  "",
573702
+ ...trajectoryBlock,
573398
573703
  "Last actions:",
573399
573704
  actionsBlock,
573400
573705
  transcriptHint,
@@ -573414,6 +573719,7 @@ var init_taskHandoff = __esm({
573414
573719
  "packages/orchestrator/dist/taskHandoff.js"() {
573415
573720
  "use strict";
573416
573721
  init_artifactQuality();
573722
+ init_trajectory_checkpoint();
573417
573723
  DEFAULT_TTL_MS2 = 24 * 60 * 60 * 1e3;
573418
573724
  MAX_SUMMARY_CHARS = 8e3;
573419
573725
  MAX_FILES = 30;
@@ -574060,7 +574366,7 @@ var init_codeGraphLink = __esm({
574060
574366
 
574061
574367
  // packages/orchestrator/dist/artifactContract.js
574062
574368
  import { createHash as createHash29 } from "node:crypto";
574063
- function shortHash2(content) {
574369
+ function shortHash3(content) {
574064
574370
  if (!content)
574065
574371
  return "empty";
574066
574372
  try {
@@ -574101,7 +574407,7 @@ var init_artifactContract = __esm({
574101
574407
  }
574102
574408
  update(path16, mutation, content, fileSize2) {
574103
574409
  const existing = this._contracts.get(path16);
574104
- const hash = content !== void 0 ? shortHash2(content) : existing?.hash ?? "unknown";
574410
+ const hash = content !== void 0 ? shortHash3(content) : existing?.hash ?? "unknown";
574105
574411
  const size = fileSize2 ?? existing?.size ?? 0;
574106
574412
  const mutationCount = (existing?.mutationCount ?? 0) + (mutation ? 1 : 0);
574107
574413
  const role = mutation ? existing?.role === "read" || existing?.role === "read-write" ? "read-write" : "write" : existing?.role === "write" || existing?.role === "read-write" ? "read-write" : "read";
@@ -574377,7 +574683,7 @@ var init_artifactContract = __esm({
574377
574683
  dedupeKey(content, cls) {
574378
574684
  if (cls.dedupeKey)
574379
574685
  return cls.dedupeKey;
574380
- return `exact:${shortHash2(content)}`;
574686
+ return `exact:${shortHash3(content)}`;
574381
574687
  }
574382
574688
  dropPriority(cls) {
574383
574689
  if (cls.preserve)
@@ -577146,7 +577452,7 @@ function isControlSignal(signal) {
577146
577452
  return signal.kind === "runtime_guidance" || signal.kind === "action_contract" || signal.kind === "recent_failure";
577147
577453
  }
577148
577454
  function isEvidenceSignal(signal) {
577149
- return signal.kind === "goal" || signal.kind === "user_steering" || signal.kind === "task_state" || signal.kind === "known_files" || signal.kind === "tool_cache" || signal.kind === "git_state" || signal.kind === "memory" || signal.kind === "semantic_chunk" || signal.kind === "session_history" || signal.kind === "anchor" || signal.kind === "handoff" || signal.kind === "environment" || signal.kind === "compaction_summary";
577455
+ return signal.kind === "goal" || signal.kind === "user_steering" || signal.kind === "trajectory_checkpoint" || signal.kind === "task_state" || signal.kind === "known_files" || signal.kind === "tool_cache" || signal.kind === "git_state" || signal.kind === "memory" || signal.kind === "semantic_chunk" || signal.kind === "session_history" || signal.kind === "anchor" || signal.kind === "handoff" || signal.kind === "environment" || signal.kind === "compaction_summary";
577150
577456
  }
577151
577457
  function signalFromBlock(kind, source, content, options2 = {}) {
577152
577458
  const normalized = normalizeSignalContent(content ?? "");
@@ -577176,6 +577482,7 @@ var init_context_fabric = __esm({
577176
577482
  PRIORITY = {
577177
577483
  GOAL: 100,
577178
577484
  ACTION_CONTRACT: 98,
577485
+ TRAJECTORY: 97,
577179
577486
  USER_STEERING: 95,
577180
577487
  RUNTIME_GUIDANCE: 94,
577181
577488
  GIT_STATE: 86,
@@ -577195,6 +577502,7 @@ var init_context_fabric = __esm({
577195
577502
  KIND_ORDER = [
577196
577503
  "goal",
577197
577504
  "user_steering",
577505
+ "trajectory_checkpoint",
577198
577506
  "runtime_guidance",
577199
577507
  "action_contract",
577200
577508
  "git_state",
@@ -577214,6 +577522,7 @@ var init_context_fabric = __esm({
577214
577522
  KIND_LABELS = {
577215
577523
  goal: "Goal",
577216
577524
  user_steering: "User Steering",
577525
+ trajectory_checkpoint: "Trajectory Checkpoint",
577217
577526
  runtime_guidance: "Runtime Guidance",
577218
577527
  action_contract: "Next Action Contract",
577219
577528
  git_state: "Git State",
@@ -577233,6 +577542,7 @@ var init_context_fabric = __esm({
577233
577542
  DEFAULT_KIND_CHAR_BUDGET = {
577234
577543
  goal: 900,
577235
577544
  user_steering: 1400,
577545
+ trajectory_checkpoint: 1200,
577236
577546
  runtime_guidance: 900,
577237
577547
  action_contract: 1400,
577238
577548
  git_state: 1400,
@@ -577556,6 +577866,8 @@ function runtimeControlSemanticKey(content) {
577556
577866
  return null;
577557
577867
  if (content.includes("[ACTIVE CONTEXT FRAME]"))
577558
577868
  return "context.active-frame";
577869
+ if (content.includes("[TRAJECTORY CHECKPOINT]"))
577870
+ return "context.trajectory-checkpoint";
577559
577871
  if (content.includes("[NEXT ACTION CONTRACT]"))
577560
577872
  return "context.next-action";
577561
577873
  if (content.includes("[RUNTIME DIRECTIVE]")) {
@@ -577629,7 +577941,7 @@ function retireDuplicateToolFailures(messages2) {
577629
577941
  }
577630
577942
  out[index] = {
577631
577943
  ...message2,
577632
- content: "[retired_duplicate_tool_failure] a newer matching failure appears later. Use that latest diagnostic; retry only after refreshing prerequisite evidence or correcting the arguments."
577944
+ content: "[retired_duplicate_tool_failure] a newer matching result appears later. Use that latest diagnostic; retry only after refreshing prerequisite evidence or correcting the arguments."
577633
577945
  };
577634
577946
  }
577635
577947
  return out;
@@ -578002,7 +578314,7 @@ function recordContextWindowDump(input) {
578002
578314
  String(input.turn ?? ""),
578003
578315
  String(input.attempt ?? "")
578004
578316
  ].join("|");
578005
- const id2 = `${timestamp.replace(/[:.]/g, "-")}-${input.agentType}-${shortHash3(stable)}`;
578317
+ const id2 = `${timestamp.replace(/[:.]/g, "-")}-${input.agentType}-${shortHash4(stable)}`;
578006
578318
  const metrics2 = analyzeContextWindowDumpRequest(input.request);
578007
578319
  const record = {
578008
578320
  schemaVersion: 1,
@@ -578323,7 +578635,7 @@ function trimString(value2, max) {
578323
578635
  function safeId(value2) {
578324
578636
  return String(value2 || "unknown").replace(/[^a-zA-Z0-9_.:-]/g, "_").slice(0, 160);
578325
578637
  }
578326
- function shortHash3(value2) {
578638
+ function shortHash4(value2) {
578327
578639
  return createHash30("sha256").update(value2).digest("hex").slice(0, 10);
578328
578640
  }
578329
578641
  function pruneOldDumpFiles(dir) {
@@ -578768,7 +579080,7 @@ function recordDebugToolEvent(input) {
578768
579080
  if (!shouldRecordToolEvent(input, diagnoses))
578769
579081
  return null;
578770
579082
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
578771
- const argsHash = shortHash4(argsPreview);
579083
+ const argsHash = shortHash5(argsPreview);
578772
579084
  const eventId = [
578773
579085
  timestamp.replace(/[:.]/g, "-"),
578774
579086
  safeId2(input.toolName),
@@ -578839,7 +579151,7 @@ function recordDebugContextWindowDump(input) {
578839
579151
  const eventId = [
578840
579152
  timestamp.replace(/[:.]/g, "-"),
578841
579153
  "context",
578842
- shortHash4(input.record.id)
579154
+ shortHash5(input.record.id)
578843
579155
  ].join("-");
578844
579156
  const eventDir = join112(paths.runDir, "events", turnDir(input.record.turn));
578845
579157
  const eventPath = join112(eventDir, `${eventId}.json`);
@@ -578881,6 +579193,56 @@ function recordDebugContextWindowDump(input) {
578881
579193
  writeEventAndIndexes(paths, event, eventPath);
578882
579194
  return event;
578883
579195
  }
579196
+ function recordDebugTrajectoryCheckpoint(input) {
579197
+ if (debugArtifactDisabled())
579198
+ return null;
579199
+ const checkpoint = input.checkpoint;
579200
+ const cwd4 = resolve55(input.cwd || process.cwd());
579201
+ const runId = safeId2(input.runId || input.sessionId || "unknown-run");
579202
+ const sessionId = safeId2(input.sessionId || runId);
579203
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
579204
+ const paths = debugRunPaths(cwd4, runId, input.stateDir);
579205
+ const eventId = [
579206
+ timestamp.replace(/[:.]/g, "-"),
579207
+ "trajectory",
579208
+ shortHash5(checkpoint.id)
579209
+ ].join("-");
579210
+ const eventDir = join112(paths.runDir, "events", turnDir(checkpoint.turn));
579211
+ const eventPath = join112(eventDir, `${eventId}.json`);
579212
+ const diagnoses = [
579213
+ "trajectory-checkpoint",
579214
+ `trajectory-${checkpoint.assessment.replace(/_/g, "-")}`
579215
+ ];
579216
+ const event = {
579217
+ schemaVersion: 1,
579218
+ id: eventId,
579219
+ kind: "trajectory_checkpoint",
579220
+ timestamp,
579221
+ runId,
579222
+ sessionId,
579223
+ cwd: cwd4,
579224
+ turn: checkpoint.turn,
579225
+ trajectory: {
579226
+ revision: checkpoint.revision,
579227
+ assessment: checkpoint.assessment,
579228
+ nextAction: trim(checkpoint.nextAction, 500),
579229
+ successEvidence: trim(checkpoint.successEvidence, 500),
579230
+ doNotRepeat: checkpoint.doNotRepeat.slice(0, 3).map((value2) => trim(value2, 300))
579231
+ },
579232
+ diagnoses,
579233
+ summary: `Trajectory ${checkpoint.assessment}: ${trim(checkpoint.nextAction, 220)}`,
579234
+ anchors: buildAnchors(cwd4, runId, paths, [
579235
+ {
579236
+ label: "event_json",
579237
+ kind: "event",
579238
+ path: eventPath,
579239
+ note: "Evidence-bound trajectory checkpoint."
579240
+ }
579241
+ ])
579242
+ };
579243
+ writeEventAndIndexes(paths, event, eventPath);
579244
+ return event;
579245
+ }
578884
579246
  function debugRunPaths(cwd4, runId, stateDir) {
578885
579247
  const root = debugArtifactRoot(cwd4, stateDir);
578886
579248
  const runDir = join112(root, "runs", safeId2(runId));
@@ -578931,6 +579293,7 @@ function updateRunIndex(paths, event, eventPath) {
578931
579293
  eventCount: 0,
578932
579294
  toolEventCount: 0,
578933
579295
  contextDumpCount: 0,
579296
+ trajectoryCheckpointCount: 0,
578934
579297
  successCount: 0,
578935
579298
  failureCount: 0,
578936
579299
  mutationCount: 0,
@@ -578948,6 +579311,9 @@ function updateRunIndex(paths, event, eventPath) {
578948
579311
  index.summary.toolEventCount++;
578949
579312
  if (event.kind === "context_window_dump")
578950
579313
  index.summary.contextDumpCount++;
579314
+ if (event.kind === "trajectory_checkpoint") {
579315
+ index.summary.trajectoryCheckpointCount = (index.summary.trajectoryCheckpointCount ?? 0) + 1;
579316
+ }
578951
579317
  if (event.success === true)
578952
579318
  index.summary.successCount++;
578953
579319
  if (event.success === false)
@@ -579505,7 +579871,7 @@ function trim(value2, max) {
579505
579871
  function safeId2(value2) {
579506
579872
  return String(value2 || "unknown").replace(/[^a-zA-Z0-9_.:-]/g, "_").slice(0, 160);
579507
579873
  }
579508
- function shortHash4(value2) {
579874
+ function shortHash5(value2) {
579509
579875
  return createHash31("sha256").update(value2).digest("hex").slice(0, 10);
579510
579876
  }
579511
579877
  var DEBUG_LIBRARY_DIR, RUN_EVENTS_LIMIT, PREVIEW_LIMIT;
@@ -579932,6 +580298,16 @@ var init_focusSupervisor = __esm({
579932
580298
  }
579933
580299
  return action;
579934
580300
  }
580301
+ /**
580302
+ * In silent small-model runner mode, cached failed shell output is diagnostic
580303
+ * evidence, not a substitute for recovery. Asking a small model to "use cached
580304
+ * evidence" repeatedly was itself a loop: it neither changed code nor
580305
+ * selected a new diagnostic. Direct/strict supervisor consumers retain the
580306
+ * legacy cache directive and its hard-block semantics.
580307
+ */
580308
+ shellFailureRequiredNextAction() {
580309
+ return this.silent && this.modelTier === "small" ? "creative_pivot_or_research" : "use_cached_evidence";
580310
+ }
579935
580311
  snapshot() {
579936
580312
  return {
579937
580313
  mode: this.mode,
@@ -580084,11 +580460,12 @@ var init_focusSupervisor = __esm({
580084
580460
  const advisoryOnly = this.repeatGateMax === 0;
580085
580461
  const hitLimit = input.cachedResultFailed ? 1 : Math.max(1, this.repeatGateMax - 1);
580086
580462
  const state = input.cachedResultFailed || duplicateHitCount >= hitLimit ? "cached_evidence" : "warn";
580463
+ const requiredNextAction = input.cachedResultFailed && input.toolName === "shell" ? this.shellFailureRequiredNextAction() : "use_cached_evidence";
580087
580464
  const directive = this.setDirective({
580088
580465
  turn: input.turn,
580089
580466
  state,
580090
580467
  reason: input.cachedResultFailed ? `cached failed ${input.toolName} evidence already exists` : `duplicate ${input.toolName} call has cached evidence`,
580091
- requiredNextAction: "use_cached_evidence",
580468
+ requiredNextAction,
580092
580469
  forbiddenActionFamilies: forbiddenCachedEvidenceFamilies(input, family)
580093
580470
  });
580094
580471
  if (strict && !advisoryOnly && (input.cachedResultFailed || duplicateHitCount >= hitLimit)) {
@@ -580204,7 +580581,7 @@ var init_focusSupervisor = __esm({
580204
580581
  actionFamily(input.toolName, input.args, this.familyCwd),
580205
580582
  input.toolName
580206
580583
  ]) : input.toolName === "shell" ? [actionFamily(input.toolName, input.args, this.familyCwd)] : [actionFamily(input.toolName, input.args, this.familyCwd)];
580207
- const requiredNextAction = ambiguousEditFailure ? "disambiguate_edit_match" : staleEditFailure ? "read_authoritative_target" : input.toolName === "shell" ? "use_cached_evidence" : this.resolveRequiredNextAction("update_todos");
580584
+ const requiredNextAction = ambiguousEditFailure ? "disambiguate_edit_match" : staleEditFailure ? "read_authoritative_target" : input.toolName === "shell" ? this.shellFailureRequiredNextAction() : this.resolveRequiredNextAction("update_todos");
580208
580585
  this.setDirective({
580209
580586
  turn: input.turn,
580210
580587
  state: "forced_replan",
@@ -580216,10 +580593,10 @@ var init_focusSupervisor = __esm({
580216
580593
  const ambiguousEditFailure = isEditTool(input.toolName) && next.errorClass === "stale_ambiguous_target";
580217
580594
  const staleEditFailure = isEditTool(input.toolName) && next.errorClass.startsWith("stale_");
580218
580595
  const shellFailure = input.toolName === "shell";
580219
- const requiredNextAction = ambiguousEditFailure ? "disambiguate_edit_match" : staleEditFailure ? "read_authoritative_target" : shellFailure ? "use_cached_evidence" : this.resolveRequiredNextAction("update_todos");
580596
+ const requiredNextAction = ambiguousEditFailure ? "disambiguate_edit_match" : staleEditFailure ? "read_authoritative_target" : shellFailure ? this.shellFailureRequiredNextAction() : this.resolveRequiredNextAction("update_todos");
580220
580597
  this.setDirective({
580221
580598
  turn: input.turn,
580222
- state: shellFailure ? "cached_evidence" : "warn",
580599
+ state: shellFailure && !this.silent ? "cached_evidence" : "warn",
580223
580600
  reason: `first ${input.toolName} failure (${next.errorClass}): ${next.sample}`,
580224
580601
  requiredNextAction,
580225
580602
  forbiddenActionFamilies: shellFailure ? [actionFamily(input.toolName, input.args, this.familyCwd)] : [actionFamily(input.toolName, input.args, this.familyCwd)]
@@ -581737,10 +582114,10 @@ function compileFixCardToWorkboardInput(card) {
581737
582114
  };
581738
582115
  }
581739
582116
  function compileFixCardId(fingerprint) {
581740
- return `compile-${shortHash5(fingerprint)}`;
582117
+ return `compile-${shortHash6(fingerprint)}`;
581741
582118
  }
581742
582119
  function compileFixVerifierFingerprint(command) {
581743
- return shortHash5(command.trim().replace(/\s+/g, " "));
582120
+ return shortHash6(command.trim().replace(/\s+/g, " "));
581744
582121
  }
581745
582122
  function formatDiagnosticLocation(diag) {
581746
582123
  const parts = [diag.file || "<compiler-output>"];
@@ -581773,7 +582150,7 @@ function normalizeDiagnostic(diag, index, source) {
581773
582150
  message: message2
581774
582151
  });
581775
582152
  return {
581776
- id: `diag-${shortHash5(fingerprint || String(index))}`,
582153
+ id: `diag-${shortHash6(fingerprint || String(index))}`,
581777
582154
  rank: index + 1,
581778
582155
  file,
581779
582156
  line: diag.line,
@@ -581851,7 +582228,7 @@ function uniqueNormalizedPaths(values) {
581851
582228
  function isCompileFixDiagnostic(value2) {
581852
582229
  return Boolean(value2 && typeof value2.fingerprint === "string" && typeof value2.rank === "number");
581853
582230
  }
581854
- function shortHash5(value2) {
582231
+ function shortHash6(value2) {
581855
582232
  return createHash32("sha256").update(value2).digest("hex").slice(0, 10);
581856
582233
  }
581857
582234
  function fence(value2) {
@@ -584530,10 +584907,10 @@ function classifyShellIntent(cmd) {
584530
584907
  return { klass: "verify", verb: "test", tool: first2 };
584531
584908
  }
584532
584909
  }
584533
- const row = VERB_TABLE[verbToken];
584534
- if (!row)
584910
+ const row2 = VERB_TABLE[verbToken];
584911
+ if (!row2)
584535
584912
  return { klass: "other", verb: verbToken, tool: first2 };
584536
- return { klass: row.klass, verb: row.canonical, tool: first2 };
584913
+ return { klass: row2.klass, verb: row2.canonical, tool: first2 };
584537
584914
  }
584538
584915
  function verifyShellOutcome(command, ctx3, result) {
584539
584916
  const cmd = (command ?? "").trim();
@@ -585417,6 +585794,20 @@ function resolvePersistentMemoryMode(options2) {
585417
585794
  }
585418
585795
  return "full";
585419
585796
  }
585797
+ function resolveTrajectoryCheckpointMode(explicit) {
585798
+ if (explicit === "off" || explicit === "shadow" || explicit === "adaptive" || explicit === "always") {
585799
+ return explicit;
585800
+ }
585801
+ const env2 = String(process.env["OMNIUS_TRAJECTORY_CHECKPOINT"] ?? "").trim().toLowerCase();
585802
+ if (env2 === "off" || env2 === "shadow" || env2 === "adaptive" || env2 === "always") {
585803
+ return env2;
585804
+ }
585805
+ return "adaptive";
585806
+ }
585807
+ function resolveTrajectoryCheckpointCadence(explicit) {
585808
+ const candidate = typeof explicit === "number" ? explicit : Number(process.env["OMNIUS_TRAJECTORY_CHECKPOINT_EVERY_TURNS"] ?? 4);
585809
+ return Number.isFinite(candidate) ? Math.max(1, Math.min(32, Math.floor(candidate))) : 4;
585810
+ }
585420
585811
  function upsertContextFrame(messages2, frame, marker = "[ACTIVE CONTEXT FRAME]") {
585421
585812
  for (let i2 = messages2.length - 1; i2 >= 0; i2--) {
585422
585813
  const m2 = messages2[i2];
@@ -586153,6 +586544,7 @@ var init_agenticRunner = __esm({
586153
586544
  init_context_fabric();
586154
586545
  init_context_compiler();
586155
586546
  init_evidenceLedger();
586547
+ init_trajectory_checkpoint();
586156
586548
  init_adversaryStream();
586157
586549
  init_contextWindowDump();
586158
586550
  init_debugArtifactLibrary();
@@ -586272,6 +586664,15 @@ var init_agenticRunner = __esm({
586272
586664
  modifiedFiles: /* @__PURE__ */ new Map(),
586273
586665
  toolCallCount: 0
586274
586666
  };
586667
+ // -- Trajectory Grounding --
586668
+ // A small, sanitized observation tail covers synthetic/preflight blocks that
586669
+ // intentionally do not enter the ordinary tool-failure accumulator.
586670
+ _trajectoryObservations = [];
586671
+ _trajectoryCheckpoint = null;
586672
+ _trajectoryFingerprint = "";
586673
+ _trajectoryRevision = 0;
586674
+ _trajectoryDirtyCauses = /* @__PURE__ */ new Set();
586675
+ _trajectoryLastEmittedToolCall = -1;
586275
586676
  // -- File State Registry (SWE-agent inspired) --
586276
586677
  _fileRegistry = /* @__PURE__ */ new Map();
586277
586678
  // -- Memex Experience Archive (arXiv:2603.04257 inspired) --
@@ -587712,6 +588113,8 @@ ${parts.join("\n")}
587712
588113
  backwardPassReview: options2?.backwardPassReview,
587713
588114
  completionVerifyCommand: options2?.completionVerifyCommand,
587714
588115
  focusSupervisor: resolveFocusSupervisorMode(options2?.focusSupervisor),
588116
+ trajectoryCheckpoint: resolveTrajectoryCheckpointMode(options2?.trajectoryCheckpoint),
588117
+ trajectoryCheckpointEveryTurns: resolveTrajectoryCheckpointCadence(options2?.trajectoryCheckpointEveryTurns),
587715
588118
  supervisorModel: options2?.supervisorModel ?? process.env["OMNIUS_SUPERVISOR_MODEL"] ?? "",
587716
588119
  supervisorTimeoutMs: options2?.supervisorTimeoutMs ?? Number(process.env["OMNIUS_SUPERVISOR_TIMEOUT_MS"] ?? 2e4),
587717
588120
  supervisorMaxTokens: options2?.supervisorMaxTokens ?? 900,
@@ -592886,21 +593289,21 @@ ${sections.join("\n")}` : sections.join("\n");
592886
593289
  sections.push(`Compacted historical entries: ${compactedCount}. They show what was observed earlier, not what is currently on disk. Re-run the narrow read or verifier when freshness matters.`);
592887
593290
  }
592888
593291
  if (filesRead.length > 0) {
592889
- const unique2 = [...new Set(filesRead)].slice(0, 30);
592890
- sections.push(`Files already read (${unique2.length}): ${unique2.join(", ")}`);
593292
+ const unique3 = [...new Set(filesRead)].slice(0, 30);
593293
+ sections.push(`Files already read (${unique3.length}): ${unique3.join(", ")}`);
592891
593294
  }
592892
593295
  if (dirsListed.length > 0) {
592893
- const unique2 = [...new Set(dirsListed)].slice(0, 15);
592894
- sections.push(`Directories already listed (${unique2.length}): ${unique2.join(", ")}`);
593296
+ const unique3 = [...new Set(dirsListed)].slice(0, 15);
593297
+ sections.push(`Directories already listed (${unique3.length}): ${unique3.join(", ")}`);
592895
593298
  sections.push(`Do not call list_directory again on these exact directories unless you changed their contents. Use the listed child paths directly with file_read/edit/delegation.`);
592896
593299
  }
592897
593300
  if (searches.length > 0) {
592898
- const unique2 = [...new Set(searches)].slice(0, 15);
592899
- sections.push(`Searches already run (${unique2.length}): ${unique2.join(", ")}`);
593301
+ const unique3 = [...new Set(searches)].slice(0, 15);
593302
+ sections.push(`Searches already run (${unique3.length}): ${unique3.join(", ")}`);
592900
593303
  }
592901
593304
  if (shells.length > 0) {
592902
- const unique2 = [...new Set(shells)].slice(0, 15);
592903
- sections.push(`Shell commands already executed (${unique2.length}): ${unique2.join(", ")}`);
593305
+ const unique3 = [...new Set(shells)].slice(0, 15);
593306
+ sections.push(`Shell commands already executed (${unique3.length}): ${unique3.join(", ")}`);
592904
593307
  }
592905
593308
  if (sections.length <= 1)
592906
593309
  return null;
@@ -593242,6 +593645,8 @@ ${String(concreteGoal).replace(/\s+/g, " ").trim().slice(0, 1200)}` : null
593242
593645
  const churnBlock = this._renderWriteChurnBlock(turn);
593243
593646
  const focusBlock = this._focusSupervisor?.renderFrame() ?? null;
593244
593647
  const actionContractBlock = this._renderNextActionContract(turn);
593648
+ const trajectoryCheckpoint = this._refreshTrajectoryCheckpoint(turn, focusBlock);
593649
+ const trajectoryBlock = this.options.trajectoryCheckpoint === "shadow" ? null : trajectoryCheckpoint ? renderTrajectoryCheckpoint(trajectoryCheckpoint) : null;
593245
593650
  const toolCacheBlock = recentToolResults ? this._renderKnowledgeBlock(recentToolResults) : null;
593246
593651
  const anchorsBlock = this.surfaceAnchors(messages2);
593247
593652
  const pprMemoryBlock = this._lastPprMemoryLines.length > 0 ? `[Associative Memory - related prior experience]
@@ -593275,6 +593680,20 @@ ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
593275
593680
  priority: 100,
593276
593681
  createdTurn: turn
593277
593682
  }),
593683
+ signalFromBlock("trajectory_checkpoint", "turn.trajectory-checkpoint", trajectoryBlock, {
593684
+ id: "trajectory-checkpoint",
593685
+ dedupeKey: "turn.trajectory-checkpoint",
593686
+ semanticKey: "context.trajectory-checkpoint",
593687
+ conflictGroup: "context.trajectory-checkpoint",
593688
+ priority: PRIORITY.TRAJECTORY,
593689
+ createdTurn: turn,
593690
+ ttlTurns: 1,
593691
+ metadata: trajectoryCheckpoint ? {
593692
+ revision: trajectoryCheckpoint.revision,
593693
+ assessment: trajectoryCheckpoint.assessment,
593694
+ trigger: trajectoryCheckpoint.trigger
593695
+ } : void 0
593696
+ }),
593278
593697
  signalFromBlock("known_files", "turn.files", filesystemBlock, {
593279
593698
  id: "filesystem-state",
593280
593699
  dedupeKey: "turn.files",
@@ -593394,6 +593813,7 @@ ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
593394
593813
  maxChars: 13e3,
593395
593814
  kindCharBudget: {
593396
593815
  known_files: 8500,
593816
+ trajectory_checkpoint: 1200,
593397
593817
  runtime_guidance: 900,
593398
593818
  recent_failure: 1400,
593399
593819
  action_contract: 1400
@@ -594524,6 +594944,7 @@ ${notice}`;
594524
594944
  /** Inject a user message into the running conversation (mid-task steering) */
594525
594945
  injectUserMessage(content) {
594526
594946
  this.pendingUserMessages.push(this.scrubUserInput(content, "injected-user-message"));
594947
+ this._trajectoryDirtyCauses.add("user_steering");
594527
594948
  }
594528
594949
  /** Inject bounded runtime guidance without treating it as user steering. */
594529
594950
  injectRuntimeGuidance(content) {
@@ -594531,8 +594952,14 @@ ${notice}`;
594531
594952
  }
594532
594953
  enqueueRuntimeGuidance(content) {
594533
594954
  const cleaned = this.scrubUserInput(content, "runtime-guidance").trim();
594534
- if (cleaned)
594955
+ if (cleaned) {
594535
594956
  this.pendingRuntimeGuidanceMessages.push(cleaned);
594957
+ this._trajectoryDirtyCauses.add("runtime_guidance");
594958
+ }
594959
+ }
594960
+ /** Current evidence-bound checkpoint for a UI or child-agent projection. */
594961
+ getTrajectoryCheckpoint() {
594962
+ return this._trajectoryCheckpoint;
594536
594963
  }
594537
594964
  /** Retract the last pending user message (Esc cancel).
594538
594965
  * Returns the retracted text, or null if queue is empty or already consumed. */
@@ -594639,7 +595066,124 @@ ${notice}`;
594639
595066
  });
594640
595067
  return !this.aborted;
594641
595068
  }
595069
+ /** Record only bounded, model-safe event summaries for the next checkpoint. */
595070
+ _observeTrajectoryEvent(event) {
595071
+ if (event.type === "trajectory_checkpoint")
595072
+ return;
595073
+ if (event.type !== "tool_call" && event.type !== "tool_result" && event.type !== "status" && event.type !== "compaction" && event.type !== "error" && event.type !== "complete" && event.type !== "user_interrupt") {
595074
+ return;
595075
+ }
595076
+ const content = sanitizeTrajectoryText(sanitizeModelVisibleContextText(String(event.content ?? "")), 360);
595077
+ const targetPath = event.toolArgs ? sanitizeTrajectoryText(this.extractPrimaryToolPath(event.toolArgs), 320) || void 0 : void 0;
595078
+ this._trajectoryObservations.push({
595079
+ type: event.type,
595080
+ turn: event.turn,
595081
+ toolName: event.toolName,
595082
+ targetPath,
595083
+ success: event.success,
595084
+ content,
595085
+ timestamp: event.timestamp
595086
+ });
595087
+ if (this._trajectoryObservations.length > 32) {
595088
+ this._trajectoryObservations.splice(0, this._trajectoryObservations.length - 32);
595089
+ }
595090
+ if (event.type === "tool_result") {
595091
+ this._trajectoryDirtyCauses.add(event.success === false ? "tool_failure" : "tool_result");
595092
+ } else if (event.type === "compaction") {
595093
+ this._trajectoryDirtyCauses.add("compaction");
595094
+ } else if (event.type === "error" || event.type === "user_interrupt") {
595095
+ this._trajectoryDirtyCauses.add(event.type);
595096
+ } else if (event.type === "status" && content) {
595097
+ if (/focus|loop|blocked|verif|mutation|sub-agent|subagent/i.test(content)) {
595098
+ this._trajectoryDirtyCauses.add("status_change");
595099
+ }
595100
+ }
595101
+ }
595102
+ _trajectoryEvidenceFreshness(path16) {
595103
+ const normalized = this._normalizeEvidencePath(path16);
595104
+ const entry = this._evidenceLedger.get(normalized) ?? this._evidenceLedger.get(path16);
595105
+ if (!entry)
595106
+ return "unknown";
595107
+ return entry.stale ? "stale" : "fresh";
595108
+ }
595109
+ /**
595110
+ * Rebuild the one current checkpoint at the context boundary. This shared
595111
+ * method is deliberately used by normal and brute-force loops via
595112
+ * _buildTurnContextFrame(), preventing separate prompt injections from
595113
+ * drifting apart or accumulating in history.
595114
+ */
595115
+ _refreshTrajectoryCheckpoint(turn, focusDirective) {
595116
+ if (this.options.trajectoryCheckpoint === "off")
595117
+ return null;
595118
+ const trigger = [...this._trajectoryDirtyCauses].join(",") || (this._trajectoryCheckpoint ? "cadence" : "task_start");
595119
+ const provisional = buildTrajectoryCheckpoint({
595120
+ turn,
595121
+ revision: Math.max(1, this._trajectoryRevision || 1),
595122
+ trigger,
595123
+ taskState: this._taskState,
595124
+ observations: this._trajectoryObservations,
595125
+ recentFailures: this._recentFailures,
595126
+ focusDirective,
595127
+ lastVerifier: this._worldFacts.lastTest,
595128
+ lastMutationTurn: this._lastFileWriteTurn,
595129
+ evidenceFreshness: (path16) => this._trajectoryEvidenceFreshness(path16)
595130
+ });
595131
+ const { id: _id2, revision: _revision, turn: _turn, ...fingerprintInput } = provisional;
595132
+ const fingerprint = trajectoryCheckpointFingerprint(fingerprintInput);
595133
+ const changed = fingerprint !== this._trajectoryFingerprint;
595134
+ if (changed) {
595135
+ this._trajectoryRevision++;
595136
+ this._trajectoryFingerprint = fingerprint;
595137
+ }
595138
+ const checkpoint = buildTrajectoryCheckpoint({
595139
+ turn,
595140
+ revision: Math.max(1, this._trajectoryRevision),
595141
+ trigger,
595142
+ taskState: this._taskState,
595143
+ observations: this._trajectoryObservations,
595144
+ recentFailures: this._recentFailures,
595145
+ focusDirective,
595146
+ lastVerifier: this._worldFacts.lastTest,
595147
+ lastMutationTurn: this._lastFileWriteTurn,
595148
+ evidenceFreshness: (path16) => this._trajectoryEvidenceFreshness(path16)
595149
+ });
595150
+ this._trajectoryCheckpoint = checkpoint;
595151
+ const cadenceReached = this._taskState.toolCallCount - this._trajectoryLastEmittedToolCall >= this.options.trajectoryCheckpointEveryTurns;
595152
+ const shouldEmit = changed || this.options.trajectoryCheckpoint === "always" || this.options.trajectoryCheckpoint === "adaptive" && cadenceReached;
595153
+ this._trajectoryDirtyCauses.clear();
595154
+ if (shouldEmit) {
595155
+ this._trajectoryLastEmittedToolCall = this._taskState.toolCallCount;
595156
+ this.emit({
595157
+ type: "trajectory_checkpoint",
595158
+ content: renderTrajectoryCheckpoint(checkpoint),
595159
+ trajectory: checkpoint,
595160
+ turn,
595161
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
595162
+ });
595163
+ this._onTypedEvent?.({
595164
+ type: "trajectory_checkpoint",
595165
+ runId: this._sessionId,
595166
+ revision: checkpoint.revision,
595167
+ assessment: checkpoint.assessment,
595168
+ nextAction: checkpoint.nextAction,
595169
+ summary: `Trajectory ${checkpoint.assessment}: ${checkpoint.nextAction}`,
595170
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
595171
+ });
595172
+ try {
595173
+ recordDebugTrajectoryCheckpoint({
595174
+ cwd: this.authoritativeWorkingDirectory(),
595175
+ stateDir: this.omniusStateDir(),
595176
+ runId: this._sessionId,
595177
+ sessionId: this._sessionId,
595178
+ checkpoint
595179
+ });
595180
+ } catch {
595181
+ }
595182
+ }
595183
+ return checkpoint;
595184
+ }
594642
595185
  emit(event) {
595186
+ this._observeTrajectoryEvent(event);
594643
595187
  for (const handler of this.handlers) {
594644
595188
  try {
594645
595189
  handler(event);
@@ -594931,6 +595475,12 @@ Respond with your assessment, then take action.`;
594931
595475
  modifiedFiles: /* @__PURE__ */ new Map(),
594932
595476
  toolCallCount: 0
594933
595477
  };
595478
+ this._trajectoryObservations = [];
595479
+ this._trajectoryCheckpoint = null;
595480
+ this._trajectoryFingerprint = "";
595481
+ this._trajectoryRevision = 0;
595482
+ this._trajectoryDirtyCauses = /* @__PURE__ */ new Set(["task_start"]);
595483
+ this._trajectoryLastEmittedToolCall = -1;
594934
595484
  this._runStartTime = Date.now();
594935
595485
  this._runErrorCount = 0;
594936
595486
  this._runErrorPatterns = [];
@@ -602133,7 +602683,8 @@ ${caveat}` : caveat;
602133
602683
  toolCallLog,
602134
602684
  turns: consolidation.turns,
602135
602685
  transcriptPath,
602136
- artifactMode: this.options.artifactMode
602686
+ artifactMode: this.options.artifactMode,
602687
+ trajectory: this._trajectoryCheckpoint
602137
602688
  });
602138
602689
  if (!shouldPersistTaskHandoff(handoff))
602139
602690
  throw "skip-low-quality-handoff";
@@ -609578,6 +610129,18 @@ function legacyAgenticEventToRunEvent(runId, event) {
609578
610129
  timestamp
609579
610130
  };
609580
610131
  }
610132
+ if (event.type === "trajectory_checkpoint") {
610133
+ const trajectory = event["trajectory"] && typeof event["trajectory"] === "object" ? event["trajectory"] : void 0;
610134
+ return {
610135
+ type: "trajectory_checkpoint",
610136
+ runId,
610137
+ ...typeof trajectory?.["revision"] === "number" ? { revision: trajectory["revision"] } : {},
610138
+ ...typeof trajectory?.["assessment"] === "string" ? { assessment: text(trajectory["assessment"], 80) } : {},
610139
+ ...typeof trajectory?.["nextAction"] === "string" ? { nextAction: text(trajectory["nextAction"], 500) } : {},
610140
+ summary: text(event.content, 900),
610141
+ timestamp
610142
+ };
610143
+ }
609581
610144
  if (event.type === "complete") {
609582
610145
  const success = event.success === true;
609583
610146
  return {
@@ -611716,10 +612279,10 @@ function buildAgentNotification(task) {
611716
612279
  ` <status>${task.status}</status>`
611717
612280
  ];
611718
612281
  if (task.result) {
611719
- lines.push(` <summary>${escapeXml(truncate(task.result, 500))}</summary>`);
612282
+ lines.push(` <summary>${escapeXml(truncate2(task.result, 500))}</summary>`);
611720
612283
  }
611721
612284
  if (task.error) {
611722
- lines.push(` <error>${escapeXml(truncate(task.error, 300))}</error>`);
612285
+ lines.push(` <error>${escapeXml(truncate2(task.error, 300))}</error>`);
611723
612286
  }
611724
612287
  lines.push(` <tool-uses>${task.progress.toolUseCount}</tool-uses>`);
611725
612288
  lines.push(` <turns>${task.progress.turnsCompleted}</turns>`);
@@ -611736,7 +612299,7 @@ function buildAgentNotification(task) {
611736
612299
  function escapeXml(s2) {
611737
612300
  return s2.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
611738
612301
  }
611739
- function truncate(s2, maxLen) {
612302
+ function truncate2(s2, maxLen) {
611740
612303
  if (s2.length <= maxLen)
611741
612304
  return s2;
611742
612305
  return s2.slice(0, maxLen - 3) + "...";
@@ -615092,6 +615655,9 @@ function buildSubAgentSystemPrompt(type, scenario) {
615092
615655
  if (focus.length) {
615093
615656
  out.push(`## Focus`, ...focus, "");
615094
615657
  }
615658
+ const trajectory = renderScopedTrajectoryCheckpoint(scenario.trajectory);
615659
+ if (trajectory)
615660
+ out.push(trajectory, "");
615095
615661
  const exit = scenario.exitCriterion ?? (p2.mutates ? "Your change is verified by a passing build/test observation." : "You have produced the requested read-only result with evidence.");
615096
615662
  out.push(`## Done When`, exit, "");
615097
615663
  out.push(`## Constraints`);
@@ -615104,6 +615670,7 @@ var WORKER_PREAMBLE, PURPOSES;
615104
615670
  var init_subagent_prompt = __esm({
615105
615671
  "packages/orchestrator/dist/subagent-prompt.js"() {
615106
615672
  "use strict";
615673
+ init_trajectory_checkpoint();
615107
615674
  WORKER_PREAMBLE = [
615108
615675
  "You are an isolated sub-agent with a deliberately small context and a single,",
615109
615676
  "bounded purpose. You were spawned by an orchestrator that holds the overall",
@@ -615288,6 +615855,7 @@ __export(dist_exports3, {
615288
615855
  buildSkillDescription: () => buildSkillDescription,
615289
615856
  buildSteeringPacket: () => buildSteeringPacket,
615290
615857
  buildSubAgentSystemPrompt: () => buildSubAgentSystemPrompt,
615858
+ buildTrajectoryCheckpoint: () => buildTrajectoryCheckpoint,
615291
615859
  buildUnitTodos: () => buildUnitTodos,
615292
615860
  checkMilestoneComplete: () => checkMilestoneComplete,
615293
615861
  chooseCheapModelRoute: () => chooseCheapModelRoute,
@@ -615463,6 +616031,7 @@ __export(dist_exports3, {
615463
616031
  recordContextWindowDump: () => recordContextWindowDump,
615464
616032
  recordDebugContextWindowDump: () => recordDebugContextWindowDump,
615465
616033
  recordDebugToolEvent: () => recordDebugToolEvent,
616034
+ recordDebugTrajectoryCheckpoint: () => recordDebugTrajectoryCheckpoint,
615466
616035
  recordHookExecution: () => recordHookExecution,
615467
616036
  recordTokenUsage: () => recordTokenUsage,
615468
616037
  recordToolDecision: () => recordToolDecision,
@@ -615477,6 +616046,8 @@ __export(dist_exports3, {
615477
616046
  reinforcementScore: () => reinforcementScore,
615478
616047
  renderGitProgressActionContract: () => renderGitProgressActionContract,
615479
616048
  renderGitProgressContextBlock: () => renderGitProgressContextBlock,
616049
+ renderScopedTrajectoryCheckpoint: () => renderScopedTrajectoryCheckpoint,
616050
+ renderTrajectoryCheckpoint: () => renderTrajectoryCheckpoint,
615480
616051
  renderValidationContract: () => renderValidationContract,
615481
616052
  renderWorkerSkill: () => renderWorkerSkill,
615482
616053
  requestApproval: () => requestApproval,
@@ -615489,12 +616060,14 @@ __export(dist_exports3, {
615489
616060
  retentionStrength: () => retentionStrength,
615490
616061
  runFeatureNode: () => runFeatureNode,
615491
616062
  sanitizeInvisibleUnicode: () => sanitizeInvisibleUnicode,
616063
+ sanitizeTrajectoryText: () => sanitizeTrajectoryText,
615492
616064
  saveCompletionLedger: () => saveCompletionLedger,
615493
616065
  saveFeatureTree: () => saveFeatureTree,
615494
616066
  saveStabilityIndex: () => saveStabilityIndex,
615495
616067
  scanContextContent: () => scanContextContent,
615496
616068
  scanDuplicateDefinitions: () => scanDuplicateDefinitions,
615497
616069
  scanOllamaProcesses: () => scanOllamaProcesses,
616070
+ scopeTrajectoryCheckpoint: () => scopeTrajectoryCheckpoint,
615498
616071
  scoreHandoff: () => scoreHandoff,
615499
616072
  scoreMemoryItem: () => scoreMemoryItem,
615500
616073
  scoreMemoryItems: () => scoreMemoryItems,
@@ -615516,6 +616089,7 @@ __export(dist_exports3, {
615516
616089
  summarizeGitProgressForTrajectory: () => summarizeGitProgressForTrajectory,
615517
616090
  tierForWeight: () => tierForWeight,
615518
616091
  toSnrDb: () => toSnrDb,
616092
+ trajectoryCheckpointFingerprint: () => trajectoryCheckpointFingerprint,
615519
616093
  truncateContent: () => truncateContent,
615520
616094
  updateAssertionResult: () => updateAssertionResult,
615521
616095
  updateMemoryStability: () => updateMemoryStability,
@@ -615617,6 +616191,7 @@ var init_dist8 = __esm({
615617
616191
  init_domainDetector();
615618
616192
  init_decomposition_orchestrator();
615619
616193
  init_subagent_prompt();
616194
+ init_trajectory_checkpoint();
615620
616195
  init_contextBudget();
615621
616196
  }
615622
616197
  });
@@ -616365,10 +616940,10 @@ function stringifyImageAsciiMatrix(matrix) {
616365
616940
  const displayLines = [];
616366
616941
  const plainLines = [];
616367
616942
  for (const rowUnknown of rows) {
616368
- const row = Array.isArray(rowUnknown) ? rowUnknown : [];
616943
+ const row2 = Array.isArray(rowUnknown) ? rowUnknown : [];
616369
616944
  let displayLine = "";
616370
616945
  let plainLine = "";
616371
- for (const cell of row) {
616946
+ for (const cell of row2) {
616372
616947
  const pixel = matrixPixel(cell);
616373
616948
  displayLine += `\x1B[38;2;${pixel.r};${pixel.g};${pixel.b}m${IMAGE_ASCII_BLOCK}\x1B[0m`;
616374
616949
  const idx = Math.round(pixel.value / 255 * (DEFAULT_PIXELS.length - 1));
@@ -616403,8 +616978,8 @@ function isLowInformationAsciiPreview(ascii2) {
616403
616978
  if (!plain) return true;
616404
616979
  const visible = plain.replace(/\s/g, "");
616405
616980
  if (visible.length < 12) return true;
616406
- const unique2 = new Set(Array.from(visible));
616407
- if (unique2.size <= 2 && /[█▓▒░#@]/u.test(visible)) return true;
616981
+ const unique3 = new Set(Array.from(visible));
616982
+ if (unique3.size <= 2 && /[█▓▒░#@]/u.test(visible)) return true;
616408
616983
  return false;
616409
616984
  }
616410
616985
  function previewFailure(message2, width) {
@@ -620392,8 +620967,8 @@ function formatLiveDashboardFromSnapshot(snapshot, opts = {}) {
620392
620967
  const paneContentWidth = Math.max(10, paneWidth - 2);
620393
620968
  const sourceLines = dashboardPreviewLines(maximized);
620394
620969
  const paneHeight = cameraPaneTargetHeight(maximized, sourceLines, paneContentWidth, { maxHeight: 60 });
620395
- for (const row of formatCameraPane(maximized, paneWidth, paneHeight, now2)) {
620396
- lines.push(`│${truncateAnsiCell(row, innerWidth)}│`);
620970
+ for (const row2 of formatCameraPane(maximized, paneWidth, paneHeight, now2)) {
620971
+ lines.push(`│${truncateAnsiCell(row2, innerWidth)}│`);
620397
620972
  }
620398
620973
  } else {
620399
620974
  const { innerWidth, paneCount, paneWidth } = liveDashboardPaneLayout(width, cameras.length);
@@ -620405,8 +620980,8 @@ function formatLiveDashboardFromSnapshot(snapshot, opts = {}) {
620405
620980
  return formatCameraPane(camera, paneWidth, paneHeight, now2);
620406
620981
  });
620407
620982
  const rowCount = Math.max(...panes.map((pane) => pane.length));
620408
- for (let row = 0; row < rowCount; row++) {
620409
- const body = panes.map((pane) => pane[row] ?? " ".repeat(paneWidth)).join(" ");
620983
+ for (let row2 = 0; row2 < rowCount; row2++) {
620984
+ const body = panes.map((pane) => pane[row2] ?? " ".repeat(paneWidth)).join(" ");
620410
620985
  lines.push(`│${truncateAnsiCell(body, innerWidth)}│`);
620411
620986
  }
620412
620987
  }
@@ -620465,8 +621040,8 @@ function formatLiveDashboardFromSnapshot(snapshot, opts = {}) {
620465
621040
  for (const item of audioBits.slice(0, 11)) pushDashboardWrapped(lines, item, width);
620466
621041
  if (asr.waterfall.length > 0) {
620467
621042
  lines.push(`│${truncateAnsiCell(` ├─ speech waterfall ${dashboardDim("blue quiet → red loud")}`, width - 2)}│`);
620468
- for (const row of asr.waterfall.slice(-8)) {
620469
- lines.push(`│${truncateAnsiCell(` │ ${row}`, width - 2)}│`);
621043
+ for (const row2 of asr.waterfall.slice(-8)) {
621044
+ lines.push(`│${truncateAnsiCell(` │ ${row2}`, width - 2)}│`);
620470
621045
  }
620471
621046
  }
620472
621047
  if (coloredSoundSummary) {
@@ -628812,12 +629387,12 @@ function setUpdateBadgeRegion(active, startCol, length4) {
628812
629387
  _updateBadgeCol = startCol;
628813
629388
  _updateBadgeLen = length4;
628814
629389
  }
628815
- function hitTestHeaderButton(row, col, termWidth) {
628816
- if (_updateBadgeActive && row === 1 && col >= _updateBadgeCol && col < _updateBadgeCol + _updateBadgeLen) {
629390
+ function hitTestHeaderButton(row2, col, termWidth) {
629391
+ if (_updateBadgeActive && row2 === 1 && col >= _updateBadgeCol && col < _updateBadgeCol + _updateBadgeLen) {
628817
629392
  return "/update";
628818
629393
  }
628819
629394
  const hdrRow = layout().headerContent;
628820
- if (row === hdrRow) {
629395
+ if (row2 === hdrRow) {
628821
629396
  if (col <= 3) return "header-prev";
628822
629397
  if (col >= termWidth - 3) return "header-next";
628823
629398
  const btnDefs = [
@@ -628881,12 +629456,12 @@ var init_text_selection = __esm({
628881
629456
  * Handle mouse press (button 0, M suffix in SGR).
628882
629457
  * Starts a new selection from the click position.
628883
629458
  */
628884
- onMousePress(row, col) {
629459
+ onMousePress(row2, col) {
628885
629460
  const mode = this._blockModeArmed ? "block" : "line";
628886
629461
  this._blockModeArmed = false;
628887
629462
  this._selection = {
628888
- anchor: { row, col },
628889
- current: { row, col },
629463
+ anchor: { row: row2, col },
629464
+ current: { row: row2, col },
628890
629465
  mode
628891
629466
  };
628892
629467
  this._active = true;
@@ -628895,17 +629470,17 @@ var init_text_selection = __esm({
628895
629470
  * Handle mouse drag (button 32, M suffix in SGR).
628896
629471
  * Extends the selection to the current cursor position.
628897
629472
  */
628898
- onMouseDrag(row, col) {
629473
+ onMouseDrag(row2, col) {
628899
629474
  if (!this._active || !this._selection) return;
628900
- this._selection.current = { row, col };
629475
+ this._selection.current = { row: row2, col };
628901
629476
  }
628902
629477
  /**
628903
629478
  * Handle mouse release (button 0, m suffix in SGR).
628904
629479
  * Finalizes the selection.
628905
629480
  */
628906
- onMouseRelease(row, col) {
629481
+ onMouseRelease(row2, col) {
628907
629482
  if (!this._active || !this._selection) return;
628908
- this._selection.current = { row, col };
629483
+ this._selection.current = { row: row2, col };
628909
629484
  this._active = false;
628910
629485
  if (this._selection.anchor.row === this._selection.current.row && this._selection.anchor.col === this._selection.current.col) {
628911
629486
  this._selection = null;
@@ -631390,7 +631965,7 @@ function renderToolDynamicBlock(kind, render2, opts, collapse, persistedSpec) {
631390
631965
  function breakTelegramCoalesce() {
631391
631966
  _telegramCoalesce = null;
631392
631967
  }
631393
- function renderTelegramCoalescedRow(row, opts) {
631968
+ function renderTelegramCoalescedRow(row2, opts) {
631394
631969
  const colorCode = opts?.colorCode ?? 45;
631395
631970
  const title = opts?.title ?? "✈ Telegram";
631396
631971
  const redir = _contentWriteHook?.redirect?.();
@@ -631403,7 +631978,7 @@ function renderTelegramCoalescedRow(row, opts) {
631403
631978
  {
631404
631979
  title,
631405
631980
  metrics: "",
631406
- body: [{ text: row, mode: "wrap", kind: "plain" }],
631981
+ body: [{ text: row2, mode: "wrap", kind: "plain" }],
631407
631982
  colorCode
631408
631983
  },
631409
631984
  width
@@ -631413,12 +631988,12 @@ function renderTelegramCoalescedRow(row, opts) {
631413
631988
  return;
631414
631989
  }
631415
631990
  if (_telegramCoalesce) {
631416
- _telegramCoalesce.lines.push(row);
631991
+ _telegramCoalesce.lines.push(row2);
631417
631992
  host.refreshDynamicBlocks();
631418
631993
  return;
631419
631994
  }
631420
631995
  const id2 = `tg-coalesce-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
631421
- const state = { id: id2, lines: [row], colorCode };
631996
+ const state = { id: id2, lines: [row2], colorCode };
631422
631997
  _telegramCoalesce = state;
631423
631998
  host.registerDynamicBlock(
631424
631999
  id2,
@@ -631441,14 +632016,14 @@ function renderTelegramCoalescedRow(row, opts) {
631441
632016
  function breakVoiceChatCoalesce() {
631442
632017
  _voiceChatCoalesce = null;
631443
632018
  }
631444
- function renderVoiceChatCoalescedRow(row, opts) {
632019
+ function renderVoiceChatCoalescedRow(row2, opts) {
631445
632020
  const colorCode = opts?.colorCode ?? 45;
631446
632021
  const title = opts?.title ?? "☏ VoiceChat";
631447
632022
  const redir = _contentWriteHook?.redirect?.();
631448
632023
  const host = _contentWriteHook?.dynamicBlockHost?.() ?? null;
631449
632024
  if (redir || !host || typeof host.refreshDynamicBlocks !== "function") {
631450
632025
  _voiceChatCoalesce = null;
631451
- const text2 = `${row}
632026
+ const text2 = `${row2}
631452
632027
  `;
631453
632028
  if (redir) redir(text2);
631454
632029
  else process.stdout.write(text2);
@@ -631458,15 +632033,15 @@ function renderVoiceChatCoalescedRow(row, opts) {
631458
632033
  const replacePrefix = opts?.replaceLastPrefix;
631459
632034
  const lastIndex = _voiceChatCoalesce.rows.length - 1;
631460
632035
  if (replacePrefix && lastIndex >= 0 && _voiceChatCoalesce.rows[lastIndex]?.startsWith(replacePrefix)) {
631461
- _voiceChatCoalesce.rows[lastIndex] = row;
632036
+ _voiceChatCoalesce.rows[lastIndex] = row2;
631462
632037
  } else {
631463
- _voiceChatCoalesce.rows.push(row);
632038
+ _voiceChatCoalesce.rows.push(row2);
631464
632039
  }
631465
632040
  host.refreshDynamicBlocks();
631466
632041
  return;
631467
632042
  }
631468
632043
  const id2 = `voicechat-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
631469
- const state = { id: id2, rows: [row], expanded: false, colorCode };
632044
+ const state = { id: id2, rows: [row2], expanded: false, colorCode };
631470
632045
  _voiceChatCoalesce = state;
631471
632046
  host.registerDynamicBlock(id2, (width) => {
631472
632047
  const visible = state.expanded ? state.rows : state.rows.slice(-VOICECHAT_VISIBLE_ROWS);
@@ -638972,6 +639547,17 @@ function buildHandoffPrompt(repoRoot) {
638972
639547
  }
638973
639548
  lines.push("");
638974
639549
  }
639550
+ if (handoff.trajectory) {
639551
+ const trajectory = handoff.trajectory;
639552
+ lines.push("### Prior Trajectory (stale orientation — verify before acting):");
639553
+ lines.push(`- Assessment: ${trajectory.assessment}`);
639554
+ lines.push(`- Next: ${trajectory.nextAction}`);
639555
+ lines.push(`- Success evidence: ${trajectory.successEvidence}`);
639556
+ if (trajectory.doNotRepeat.length > 0) {
639557
+ lines.push(`- Guard: ${trajectory.doNotRepeat.slice(0, 3).join("; ")}`);
639558
+ }
639559
+ lines.push("");
639560
+ }
638975
639561
  if (handoff.memories.length > 0) {
638976
639562
  lines.push("### Memories Used:");
638977
639563
  for (const m2 of handoff.memories.slice(0, 3)) {
@@ -639312,6 +639898,17 @@ function renderSessionDiary(entries) {
639312
639898
  const summary = e2.summary.replace(/\s+/g, " ").trim().slice(0, 280);
639313
639899
  lines.push(`- **Summary:** ${summary}`);
639314
639900
  }
639901
+ if (e2.trajectory) {
639902
+ const trajectory = e2.trajectory;
639903
+ lines.push(
639904
+ `- **Trajectory:** ${trajectory.assessment} — next: ${trajectory.nextAction.replace(/\s+/g, " ").trim().slice(0, 220)}`
639905
+ );
639906
+ if (trajectory.doNotRepeat.length > 0) {
639907
+ lines.push(
639908
+ `- **Trajectory guard:** ${trajectory.doNotRepeat[0].replace(/\s+/g, " ").trim().slice(0, 220)}`
639909
+ );
639910
+ }
639911
+ }
639315
639912
  lines.push("");
639316
639913
  }
639317
639914
  while (lines.length > 1 && lines[lines.length - 1] === "") lines.pop();
@@ -640989,6 +641586,28 @@ function stageForAgentEvent(event) {
640989
641586
  return { stage: "compacting" };
640990
641587
  case "debug_adversary":
640991
641588
  return { stage: "adversary_audit" };
641589
+ case "trajectory_checkpoint": {
641590
+ const assessment = event.trajectory?.assessment;
641591
+ if (assessment === "verification_due") {
641592
+ return { stage: "verifying", detail: "trajectory" };
641593
+ }
641594
+ if (assessment === "blocked") {
641595
+ return { stage: "failed", detail: "trajectory" };
641596
+ }
641597
+ if (assessment === "recovery_required") {
641598
+ return { stage: "blocked", detail: "trajectory" };
641599
+ }
641600
+ if (/verification_due/i.test(event.content ?? "")) {
641601
+ return { stage: "verifying", detail: "trajectory" };
641602
+ }
641603
+ if (/recovery_required/i.test(event.content ?? "")) {
641604
+ return { stage: "blocked", detail: "trajectory" };
641605
+ }
641606
+ if (/\bblocked\b/i.test(event.content ?? "")) {
641607
+ return { stage: "failed", detail: "trajectory" };
641608
+ }
641609
+ return { stage: "planning", detail: "trajectory" };
641610
+ }
640992
641611
  case "complete":
640993
641612
  return { stage: "completed", detail: "done" };
640994
641613
  case "error":
@@ -641297,6 +641916,116 @@ var init_sub_agent_live_block = __esm({
641297
641916
  }
641298
641917
  });
641299
641918
 
641919
+ // packages/cli/src/tui/trajectory-live-block.ts
641920
+ function trajectoryStage(checkpoint) {
641921
+ switch (checkpoint.assessment) {
641922
+ case "recovery_required":
641923
+ return "blocked";
641924
+ case "verification_due":
641925
+ return "verifying";
641926
+ case "blocked":
641927
+ return "failed";
641928
+ default:
641929
+ return "planning";
641930
+ }
641931
+ }
641932
+ function buildTrajectoryLiveBlockLines(checkpoint, width, phase, truecolor = supportsTruecolor()) {
641933
+ if (!checkpoint) return [];
641934
+ const w = Math.max(48, Math.floor(width));
641935
+ const inner = Math.max(1, w - 4);
641936
+ const stage2 = trajectoryStage(checkpoint);
641937
+ const title = ` Trajectory · ${checkpoint.assessment.replace(/_/g, " ")} `;
641938
+ const top = `╭─┤${title}├${"─".repeat(Math.max(0, w - 5 - title.length))}╮`;
641939
+ const bottom = `╰${"─".repeat(Math.max(0, w - 2))}╯`;
641940
+ const lines = [paint2(top, stage2, phase, 0, truecolor)];
641941
+ lines.push(row(`Goal: ${checkpoint.goal}`, inner, stage2, phase, truecolor));
641942
+ lines.push(
641943
+ row(
641944
+ `Next: ${checkpoint.nextAction}`,
641945
+ inner,
641946
+ stage2,
641947
+ phase,
641948
+ truecolor
641949
+ )
641950
+ );
641951
+ lines.push(
641952
+ row(
641953
+ `Proof: ${checkpoint.successEvidence}`,
641954
+ inner,
641955
+ stage2,
641956
+ phase,
641957
+ truecolor
641958
+ )
641959
+ );
641960
+ const guard = checkpoint.doNotRepeat[0] ?? checkpoint.openQuestions[0];
641961
+ if (guard) {
641962
+ lines.push(
641963
+ row(
641964
+ `Guard: ${guard}`,
641965
+ inner,
641966
+ stage2,
641967
+ phase,
641968
+ truecolor
641969
+ )
641970
+ );
641971
+ }
641972
+ const fact = checkpoint.groundedFacts[0];
641973
+ if (fact) {
641974
+ lines.push(
641975
+ row(
641976
+ `Evidence: ${fact.statement}`,
641977
+ inner,
641978
+ stage2,
641979
+ phase,
641980
+ truecolor
641981
+ )
641982
+ );
641983
+ }
641984
+ lines.push(paint2(bottom, stage2, phase, 0, truecolor));
641985
+ return lines;
641986
+ }
641987
+ function buildTrajectoryLiveBlockCollapsedLine(checkpoint, width, phase, truecolor = supportsTruecolor()) {
641988
+ if (!checkpoint) return [];
641989
+ const stage2 = trajectoryStage(checkpoint);
641990
+ const w = Math.max(24, Math.floor(width));
641991
+ const text2 = fit3(
641992
+ `▸ Trajectory · ${checkpoint.assessment.replace(/_/g, " ")} · ${checkpoint.nextAction}`,
641993
+ w
641994
+ );
641995
+ return [paint2(text2, stage2, phase, 0, truecolor)];
641996
+ }
641997
+ function row(value2, width, stage2, phase, truecolor) {
641998
+ return `│ ${paint2(fit3(value2, width), stage2, phase, 1, truecolor)} │`;
641999
+ }
642000
+ function paint2(value2, stage2, phase, offset, truecolor) {
642001
+ let out = "";
642002
+ for (const [index, char] of Array.from(value2).entries()) {
642003
+ if (truecolor) {
642004
+ const [r2, g, b] = stageGradientRgb(stage2, index + offset, phase);
642005
+ out += `\x1B[38;2;${r2};${g};${b}m${char}`;
642006
+ } else {
642007
+ out += `\x1B[38;5;${stageFallbackColor(stage2)}m${char}`;
642008
+ }
642009
+ }
642010
+ return `${out}\x1B[0m`;
642011
+ }
642012
+ function fit3(value2, width) {
642013
+ const clean5 = value2.replace(ANSI_RE3, "").replace(/\s+/g, " ").trim();
642014
+ const chars = Array.from(clean5);
642015
+ if (chars.length > width) {
642016
+ return `${chars.slice(0, Math.max(0, width - 1)).join("")}…`;
642017
+ }
642018
+ return clean5 + " ".repeat(Math.max(0, width - chars.length));
642019
+ }
642020
+ var ANSI_RE3;
642021
+ var init_trajectory_live_block = __esm({
642022
+ "packages/cli/src/tui/trajectory-live-block.ts"() {
642023
+ init_stageIndicator();
642024
+ init_sub_agent_live_block();
642025
+ ANSI_RE3 = /\x1B\[[0-?]*[ -/]*[@-~]|\x1B\].*?(?:\x07|\x1B\\)/g;
642026
+ }
642027
+ });
642028
+
641300
642029
  // packages/cli/src/tui/tui-tasks-renderer.ts
641301
642030
  var tui_tasks_renderer_exports = {};
641302
642031
  __export(tui_tasks_renderer_exports, {
@@ -641525,7 +642254,7 @@ function statusToAnsi(status) {
641525
642254
  return { mark: "○", color: PENDING };
641526
642255
  }
641527
642256
  }
641528
- function truncate2(s2, max) {
642257
+ function truncate3(s2, max) {
641529
642258
  if (s2.length <= max) return s2.padEnd(max, " ");
641530
642259
  return s2.slice(0, Math.max(0, max - 1)) + "…";
641531
642260
  }
@@ -641795,7 +642524,7 @@ function render(options2 = {}) {
641795
642524
  const { mark, color } = statusToAnsi(t2.displayStatus);
641796
642525
  const contentWidth = Math.max(4, cols - 8);
641797
642526
  const contentText = formatTodoContent(t2, activeId);
641798
- const truncated = truncate2(contentText, contentWidth);
642527
+ const truncated = truncate3(contentText, contentWidth);
641799
642528
  if (activeId && t2.id === activeId) {
641800
642529
  const grad = paintActiveRowGradient(truncated);
641801
642530
  if (grad) {
@@ -641819,16 +642548,16 @@ function render(options2 = {}) {
641819
642548
  const safeClearTop = L.headerBottom + 1;
641820
642549
  const safeClearBottom = L.contentBottom;
641821
642550
  if (_lastPaintedTop >= 0 && _lastPaintedBottom >= _lastPaintedTop) {
641822
- for (let row = _lastPaintedTop; row <= _lastPaintedBottom; row++) {
641823
- if (row >= newTop && row <= newBottom) continue;
641824
- if (row < safeClearTop || row > safeClearBottom) continue;
641825
- out += `\x1B[${row};1H${CLEAR_LINE}`;
642551
+ for (let row2 = _lastPaintedTop; row2 <= _lastPaintedBottom; row2++) {
642552
+ if (row2 >= newTop && row2 <= newBottom) continue;
642553
+ if (row2 < safeClearTop || row2 > safeClearBottom) continue;
642554
+ out += `\x1B[${row2};1H${CLEAR_LINE}`;
641826
642555
  }
641827
642556
  }
641828
642557
  for (let i2 = 0; i2 < lines.length; i2++) {
641829
- const row = L.tasksTop + i2;
641830
- if (row > L.tasksBottom) break;
641831
- out += `\x1B[${row};1H${CLEAR_LINE}${BG}${" ".repeat(cols)}\x1B[${row};2H${lines[i2]}${RESET3}`;
642558
+ const row2 = L.tasksTop + i2;
642559
+ if (row2 > L.tasksBottom) break;
642560
+ out += `\x1B[${row2};1H${CLEAR_LINE}${BG}${" ".repeat(cols)}\x1B[${row2};2H${lines[i2]}${RESET3}`;
641832
642561
  }
641833
642562
  out += RESTORE + SHOW;
641834
642563
  try {
@@ -641839,9 +642568,9 @@ function render(options2 = {}) {
641839
642568
  _lastPaintedBottom = newBottom;
641840
642569
  _toggleRowAbs = toggleLineIdx >= 0 && L.tasksTop + toggleLineIdx <= L.tasksBottom ? L.tasksTop + toggleLineIdx : -1;
641841
642570
  }
641842
- function handleTuiTasksClick(row) {
642571
+ function handleTuiTasksClick(row2) {
641843
642572
  if (!panelEffectivelyVisible()) return false;
641844
- if (_toggleRowAbs < 0 || row !== _toggleRowAbs) return false;
642573
+ if (_toggleRowAbs < 0 || row2 !== _toggleRowAbs) return false;
641845
642574
  _expanded = !_expanded;
641846
642575
  loadTodos();
641847
642576
  render();
@@ -641856,9 +642585,9 @@ function clearLastPaintedRows() {
641856
642585
  const safeTop = L.headerBottom + 1;
641857
642586
  const safeBottom = Math.max(L.contentBottom, safeTop - 1);
641858
642587
  let out = HIDE + SAVE;
641859
- for (let row = _lastPaintedTop; row <= _lastPaintedBottom; row++) {
641860
- if (row < safeTop || row > safeBottom) continue;
641861
- out += `\x1B[${row};1H${CLEAR_LINE}`;
642588
+ for (let row2 = _lastPaintedTop; row2 <= _lastPaintedBottom; row2++) {
642589
+ if (row2 < safeTop || row2 > safeBottom) continue;
642590
+ out += `\x1B[${row2};1H${CLEAR_LINE}`;
641862
642591
  }
641863
642592
  out += RESTORE + SHOW;
641864
642593
  try {
@@ -642963,14 +643692,14 @@ function loadFailurePatterns(store2) {
642963
643692
  const unresolved = store2.listUnresolved();
642964
643693
  if (unresolved.length === 0) return "";
642965
643694
  const seen = /* @__PURE__ */ new Set();
642966
- const unique2 = unresolved.filter((f2) => {
643695
+ const unique3 = unresolved.filter((f2) => {
642967
643696
  if (seen.has(f2.fingerprint)) return false;
642968
643697
  seen.add(f2.fingerprint);
642969
643698
  return true;
642970
643699
  });
642971
- if (unique2.length === 0) return "";
643700
+ if (unique3.length === 0) return "";
642972
643701
  const lines = ["Known failure patterns (avoid repeating these):"];
642973
- for (const f2 of unique2.slice(0, 8)) {
643702
+ for (const f2 of unique3.slice(0, 8)) {
642974
643703
  const file = f2.filePath ? ` in ${f2.filePath}` : "";
642975
643704
  lines.push(`- [${f2.failureType}]${file}: ${f2.errorMessage.slice(0, 150)}`);
642976
643705
  }
@@ -644059,6 +644788,7 @@ var init_status_bar = __esm({
644059
644788
  init_render();
644060
644789
  init_stageIndicator();
644061
644790
  init_sub_agent_live_block();
644791
+ init_trajectory_live_block();
644062
644792
  init_tui_tasks_renderer();
644063
644793
  init_braille_spinner();
644064
644794
  init_project_context();
@@ -644301,6 +645031,9 @@ var init_status_bar = __esm({
644301
645031
  // toggles sub-agent / scroll info below header
644302
645032
  _subAgentLiveBlockId = "sub-agent-live-preview";
644303
645033
  _subAgentLiveBlockAppended = false;
645034
+ _trajectoryLiveBlockId = "trajectory-grounding-preview";
645035
+ _trajectoryLiveBlockAppended = false;
645036
+ _trajectoryCheckpoint = null;
644304
645037
  // Virtual scrollback buffer — stores content lines for Page Up/Down scrolling.
644305
645038
  // Since we're in alternate screen buffer, there's no native scrollback.
644306
645039
  // NOTE: _contentLines is now a reference to the ACTIVE view's buffer.
@@ -645172,9 +645905,9 @@ var init_status_bar = __esm({
645172
645905
  innerWidth: Math.max(1, termWidth - contentStartCol - rightChrome)
645173
645906
  };
645174
645907
  }
645175
- hitTestCurrentHeaderAction(row, col, termWidth) {
645908
+ hitTestCurrentHeaderAction(row2, col, termWidth) {
645176
645909
  const hdrRow = layout().headerContent;
645177
- if (row !== hdrRow) return null;
645910
+ if (row2 !== hdrRow) return null;
645178
645911
  const chrome = this.getHeaderChromeLayout(termWidth);
645179
645912
  if (chrome.showPrev && col === 2) return "header-prev";
645180
645913
  if (chrome.showNext && col === termWidth - 1) return "header-next";
@@ -646046,6 +646779,7 @@ var init_status_bar = __esm({
646046
646779
  updatedAt: Date.now()
646047
646780
  });
646048
646781
  }
646782
+ this.ensureTrajectoryLiveBlock();
646049
646783
  if (this._agentViews.size > 1) this.ensureSubAgentLiveBlock();
646050
646784
  setTermSize(process.stdout.rows ?? 24, process.stdout.columns ?? 80);
646051
646785
  setFooterMetricsVisible(this._footerMetricsVisible);
@@ -646259,11 +646993,11 @@ var init_status_bar = __esm({
646259
646993
  return false;
646260
646994
  }
646261
646995
  /** Handle mouse click on a suggestion row */
646262
- suggestClickAt(row) {
646996
+ suggestClickAt(row2) {
646263
646997
  const pos = this.rowPositions(termRows());
646264
646998
  if (pos.suggestStartRow <= 0 || this._suggestions.length === 0)
646265
646999
  return false;
646266
- const idx = row - pos.suggestStartRow;
647000
+ const idx = row2 - pos.suggestStartRow;
646267
647001
  if (idx >= 0 && idx < this._suggestions.length) {
646268
647002
  this._suggestIndex = idx;
646269
647003
  return this.suggestAccept();
@@ -646509,18 +647243,18 @@ var init_status_bar = __esm({
646509
647243
  * Routes to header/footer/tab clicks and scroll affordances. Content-area
646510
647244
  * drag selection is deliberately left to the terminal.
646511
647245
  */
646512
- handlePointerEvent(type, col, row) {
647246
+ handlePointerEvent(type, col, row2) {
646513
647247
  if (!this.active) return;
646514
647248
  const w = termCols();
646515
- if (type === "press" && row >= this.scrollRegionTop) {
646516
- if (this.handleContentBlockClick(row, col)) return;
647249
+ if (type === "press" && row2 >= this.scrollRegionTop) {
647250
+ if (this.handleContentBlockClick(row2, col)) return;
646517
647251
  }
646518
647252
  if (type === "press" && this._suggestions.length > 0) {
646519
- if (this.suggestClickAt(row)) return;
647253
+ if (this.suggestClickAt(row2)) return;
646520
647254
  }
646521
- if (row < this.scrollRegionTop) {
647255
+ if (row2 < this.scrollRegionTop) {
646522
647256
  const hdrRow = layout().headerContent;
646523
- if (type === "press" && row === hdrRow && String(this.currentHeaderPanel).startsWith("sys-")) {
647257
+ if (type === "press" && row2 === hdrRow && String(this.currentHeaderPanel).startsWith("sys-")) {
646524
647258
  const zones = this._sysClickZones ?? [];
646525
647259
  const hit = zones.find((z18) => col >= z18.start && col <= z18.end);
646526
647260
  if (hit) {
@@ -646531,12 +647265,12 @@ var init_status_bar = __esm({
646531
647265
  if (type === "press" && this._updateLatest) {
646532
647266
  const hdrRow2 = layout().headerContent;
646533
647267
  const verZone = this._verClickZone;
646534
- if (row === hdrRow2 && verZone && col >= verZone.start && col <= verZone.end) {
647268
+ if (row2 === hdrRow2 && verZone && col >= verZone.start && col <= verZone.end) {
646535
647269
  if (this._headerButtonHandler) this._headerButtonHandler("/update");
646536
647270
  return;
646537
647271
  }
646538
647272
  }
646539
- const cmd = this.hitTestCurrentHeaderAction(row, col, w);
647273
+ const cmd = this.hitTestCurrentHeaderAction(row2, col, w);
646540
647274
  if (type === "press" && cmd) {
646541
647275
  if (cmd === "header-prev") {
646542
647276
  this.prevHeaderPanel();
@@ -646577,44 +647311,44 @@ var init_status_bar = __esm({
646577
647311
  }
646578
647312
  if (type === "press" && this._footerMetricsVisible) {
646579
647313
  const metricsRow = layout().footerMetrics;
646580
- if (row === metricsRow && col >= termCols() - 5) {
647314
+ if (row2 === metricsRow && col >= termCols() - 5) {
646581
647315
  this.cycleDebugPanelPage();
646582
647316
  this.renderFooterAndPositionInput();
646583
647317
  return;
646584
647318
  }
646585
647319
  }
646586
- if (type === "press" && this._scrollBtnRegion && row === this._scrollBtnRegion.row) {
647320
+ if (type === "press" && this._scrollBtnRegion && row2 === this._scrollBtnRegion.row) {
646587
647321
  if (col >= this._scrollBtnRegion.start && col <= this._scrollBtnRegion.end) {
646588
647322
  this.jumpToLive();
646589
647323
  return;
646590
647324
  }
646591
647325
  }
646592
- if (type === "press" && this._copyBtnRegion && row === this._copyBtnRegion.row) {
647326
+ if (type === "press" && this._copyBtnRegion && row2 === this._copyBtnRegion.row) {
646593
647327
  if (col >= this._copyBtnRegion.start && col <= this._copyBtnRegion.end) {
646594
647328
  void this.copySessionToClipboard();
646595
647329
  return;
646596
647330
  }
646597
647331
  }
646598
647332
  const pos = this.rowPositions(termRows());
646599
- if (type === "press" && pos.tabBarRow > 0 && row === pos.tabBarRow) {
647333
+ if (type === "press" && pos.tabBarRow > 0 && row2 === pos.tabBarRow) {
646600
647334
  const viewId = this.hitTestTabBar(col);
646601
647335
  if (viewId) this.switchToView(viewId);
646602
647336
  return;
646603
647337
  }
646604
647338
  if (type === "press") {
646605
647339
  const Lt = layout();
646606
- if (Lt.tasksTop > 0 && row >= Lt.tasksTop && row <= Lt.tasksBottom) {
647340
+ if (Lt.tasksTop > 0 && row2 >= Lt.tasksTop && row2 <= Lt.tasksBottom) {
646607
647341
  let consumed = false;
646608
647342
  try {
646609
- consumed = handleTuiTasksClick(row);
647343
+ consumed = handleTuiTasksClick(row2);
646610
647344
  } catch {
646611
647345
  }
646612
647346
  if (consumed) return;
646613
647347
  }
646614
647348
  }
646615
- if (type === "press" && this.handleFooterInputClick(row, col)) return;
647349
+ if (type === "press" && this.handleFooterInputClick(row2, col)) return;
646616
647350
  const L = layout();
646617
- const inContent = row >= this.scrollRegionTop && row <= L.contentBottom;
647351
+ const inContent = row2 >= this.scrollRegionTop && row2 <= L.contentBottom;
646618
647352
  if (inContent) {
646619
647353
  return;
646620
647354
  }
@@ -646660,6 +647394,34 @@ var init_status_bar = __esm({
646660
647394
  }, 1500);
646661
647395
  }
646662
647396
  // ── Agent View Management (WO-NA1) ────────────────────────────
647397
+ /** Store and render the runner's single evidence-bound trajectory checkpoint. */
647398
+ updateTrajectoryCheckpoint(checkpoint) {
647399
+ this._trajectoryCheckpoint = checkpoint;
647400
+ this.ensureTrajectoryLiveBlock();
647401
+ if (this.active) {
647402
+ this.refreshDynamicBlocks();
647403
+ this.renderFooterPreserveCursor();
647404
+ }
647405
+ }
647406
+ getTrajectoryCheckpoint() {
647407
+ return this._trajectoryCheckpoint;
647408
+ }
647409
+ ensureTrajectoryLiveBlock() {
647410
+ if (!this.active || !this._agentViews.has("main") || !this._trajectoryCheckpoint)
647411
+ return;
647412
+ if (this._trajectoryLiveBlockAppended) return;
647413
+ ensureCollapsible(this._trajectoryLiveBlockId);
647414
+ this.registerDynamicBlock(this._trajectoryLiveBlockId, (width) => {
647415
+ const checkpoint = this._trajectoryCheckpoint;
647416
+ return getCollapseState(this._trajectoryLiveBlockId) === "collapsed" ? buildTrajectoryLiveBlockCollapsedLine(
647417
+ checkpoint,
647418
+ width,
647419
+ this._stagePhase
647420
+ ) : buildTrajectoryLiveBlockLines(checkpoint, width, this._stagePhase);
647421
+ });
647422
+ this.appendDynamicBlockToAgentView("main", this._trajectoryLiveBlockId);
647423
+ this._trajectoryLiveBlockAppended = true;
647424
+ }
646663
647425
  /** Keep one compact, live child-agent preview in the MAIN view. */
646664
647426
  ensureSubAgentLiveBlock() {
646665
647427
  if (!this.active || !this._agentViews.has("main") || this._agentViews.size <= 1)
@@ -647005,17 +647767,17 @@ var init_status_bar = __esm({
647005
647767
  if (this.writeDepth > 0) {
647006
647768
  const inputWrap = this.wrapInput(w);
647007
647769
  let buf = `\x1B[${this.scrollRegionTop};${pos.scrollEnd}r\x1B[?25l\x1B[?7l`;
647008
- for (let row = clearStart; row <= rows; row++) {
647009
- buf += `\x1B[${row};1H\x1B[2K`;
647770
+ for (let row2 = clearStart; row2 <= rows; row2++) {
647771
+ buf += `\x1B[${row2};1H\x1B[2K`;
647010
647772
  }
647011
647773
  buf += `\x1B[${pos.inputStartRow};1H${PANEL_BG_SEQ}\x1B[2K${this.buildInputBoxTop(w)}${PANEL_BG_SEQ}`;
647012
647774
  for (let i2 = 0; i2 < inputWrap.lines.length; i2++) {
647013
- const row = pos.inputStartRow + 1 + i2;
647775
+ const row2 = pos.inputStartRow + 1 + i2;
647014
647776
  const prefix = i2 === 0 ? this.promptText : " ".repeat(this.promptWidth);
647015
647777
  const lineContent = `${prefix}${inputWrap.lines[i2]}`;
647016
- buf += `\x1B[${row};1H${PANEL_BG_SEQ}\x1B[2K`;
647778
+ buf += `\x1B[${row2};1H${PANEL_BG_SEQ}\x1B[2K`;
647017
647779
  buf += `${this.borderVSeq(1)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}${lineContent}`;
647018
- buf += `${PANEL_BG_SEQ}\x1B[K\x1B[${row};${w}H${this.borderVSeq(w)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
647780
+ buf += `${PANEL_BG_SEQ}\x1B[K\x1B[${row2};${w}H${this.borderVSeq(w)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
647019
647781
  }
647020
647782
  buf += this.buildEnhanceSegment(
647021
647783
  w,
@@ -647035,8 +647797,8 @@ var init_status_bar = __esm({
647035
647797
  this.fillContentArea();
647036
647798
  this.repaintContent();
647037
647799
  let clearBuf = "\x1B[?7l";
647038
- for (let row = pos.scrollEnd + 1; row <= rows; row++) {
647039
- clearBuf += `\x1B[${row};1H\x1B[2K`;
647800
+ for (let row2 = pos.scrollEnd + 1; row2 <= rows; row2++) {
647801
+ clearBuf += `\x1B[${row2};1H\x1B[2K`;
647040
647802
  }
647041
647803
  clearBuf += "\x1B[?7h";
647042
647804
  this.termWrite(clearBuf);
@@ -647542,14 +648304,14 @@ ${CONTENT_BG_SEQ}`);
647542
648304
  };
647543
648305
  return this._rowCountCache;
647544
648306
  }
647545
- firstSourceLineForRow(prefix, row) {
648307
+ firstSourceLineForRow(prefix, row2) {
647546
648308
  if (prefix.length <= 1) return 0;
647547
648309
  let lo = 0;
647548
648310
  let hi = Math.max(0, prefix.length - 2);
647549
648311
  let answer = hi;
647550
648312
  while (lo <= hi) {
647551
648313
  const mid = lo + hi >> 1;
647552
- if ((prefix[mid + 1] ?? 0) > row) {
648314
+ if ((prefix[mid + 1] ?? 0) > row2) {
647553
648315
  answer = mid;
647554
648316
  hi = mid - 1;
647555
648317
  } else {
@@ -647908,11 +648670,11 @@ ${CONTENT_BG_SEQ}`);
647908
648670
  buf += "\x1B7";
647909
648671
  buf += "\x1B[?25l";
647910
648672
  const selRanges = this._textSelection.getSelectedRanges();
647911
- for (let row = 0; row < h; row++) {
647912
- const lineIdx = startIdx + row;
648673
+ for (let row2 = 0; row2 < h; row2++) {
648674
+ const lineIdx = startIdx + row2;
647913
648675
  const reflowed = reflowedLines[lineIdx];
647914
648676
  let line = reflowed?.line ?? "";
647915
- const screenRow = this.scrollRegionTop + row;
648677
+ const screenRow = this.scrollRegionTop + row2;
647916
648678
  if (screenRow < headerSafeFloor) continue;
647917
648679
  line = line.replace(/\x1B\[0m/g, `\x1B[0m${CONTENT_BG_SEQ}`);
647918
648680
  const sel = selRanges.find((r2) => r2.bufferIdx === reflowed?.bufferIdx);
@@ -648191,8 +648953,8 @@ ${CONTENT_BG_SEQ}`);
648191
648953
  const end = termRows();
648192
648954
  if (start2 > end) return;
648193
648955
  let buf = "\x1B7\x1B[?25l";
648194
- for (let row = start2; row <= end; row++) {
648195
- buf += `\x1B[${row};1H${CONTENT_BG_SEQ}\x1B[2K`;
648956
+ for (let row2 = start2; row2 <= end; row2++) {
648957
+ buf += `\x1B[${row2};1H${CONTENT_BG_SEQ}\x1B[2K`;
648196
648958
  }
648197
648959
  buf += "\x1B8";
648198
648960
  if (this.writeDepth === 0) buf += "\x1B[?25h";
@@ -648312,10 +649074,10 @@ ${CONTENT_BG_SEQ}`);
648312
649074
  const cellEnd = w - 1;
648313
649075
  let buf = "";
648314
649076
  for (let i2 = 0; i2 < rowCount; i2++) {
648315
- const row = firstInputRow + i2;
648316
- buf += `\x1B[${row};${dividerCol}H${this.borderVSeq(dividerCol)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
649077
+ const row2 = firstInputRow + i2;
649078
+ buf += `\x1B[${row2};${dividerCol}H${this.borderVSeq(dividerCol)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
648317
649079
  if (i2 > 0) {
648318
- buf += `\x1B[${row};${cellStart}H${PANEL_BG_SEQ}${" ".repeat(ENHANCE_SEG_INNER)}`;
649080
+ buf += `\x1B[${row2};${cellStart}H${PANEL_BG_SEQ}${" ".repeat(ENHANCE_SEG_INNER)}`;
648319
649081
  }
648320
649082
  }
648321
649083
  buf += this.buildEnhanceButtonCell(firstInputRow, cellStart);
@@ -648323,8 +649085,8 @@ ${CONTENT_BG_SEQ}`);
648323
649085
  return buf;
648324
649086
  }
648325
649087
  /** Render the button-cell content for the current enhance state (width = ENHANCE_SEG_INNER). */
648326
- buildEnhanceButtonCell(row, cellStart) {
648327
- const cup = `\x1B[${row};${cellStart}H`;
649088
+ buildEnhanceButtonCell(row2, cellStart) {
649089
+ const cup = `\x1B[${row2};${cellStart}H`;
648328
649090
  if (this._enhanceState === "busy") {
648329
649091
  this._enhanceConfirmZones = null;
648330
649092
  const frame = ENHANCE_SPIN_FRAMES[this._enhanceSpinFrame % ENHANCE_SPIN_FRAMES.length] ?? "⠋";
@@ -648486,14 +649248,14 @@ ${CONTENT_BG_SEQ}`);
648486
649248
  * or a click in the text area to reposition the cursor. Returns true when the
648487
649249
  * click was consumed.
648488
649250
  */
648489
- handleFooterInputClick(row, col) {
649251
+ handleFooterInputClick(row2, col) {
648490
649252
  if (!this.inputStateProvider) return false;
648491
649253
  const w = getTermWidth();
648492
649254
  const pos = this.rowPositions(termRows());
648493
649255
  const inputLines = this.computeInputLineCount(w);
648494
649256
  const firstInputRow = pos.inputStartRow + 1;
648495
649257
  const lastInputRow = firstInputRow + inputLines - 1;
648496
- if (row < firstInputRow || row > lastInputRow) return false;
649258
+ if (row2 < firstInputRow || row2 > lastInputRow) return false;
648497
649259
  if (this.enhanceSegEnabled(w)) {
648498
649260
  const dividerCol = this.enhanceDividerCol(w);
648499
649261
  const cellStart = dividerCol + 1;
@@ -648526,7 +649288,7 @@ ${CONTENT_BG_SEQ}`);
648526
649288
  availWidth
648527
649289
  );
648528
649290
  const lineIdx = Math.min(
648529
- Math.max(0, row - firstInputRow),
649291
+ Math.max(0, row2 - firstInputRow),
648530
649292
  rawLines.length - 1
648531
649293
  );
648532
649294
  const rawLine = rawLines[lineIdx] ?? "";
@@ -648778,13 +649540,13 @@ ${CONTENT_BG_SEQ}`);
648778
649540
  buf += `\x1B[${spacerRow};1H${PANEL_BG_SEQ}\x1B[2K${RESET4}`;
648779
649541
  }
648780
649542
  for (let i2 = 0; i2 < inputWrap.lines.length; i2++) {
648781
- const row = pos.inputStartRow + 1 + i2;
649543
+ const row2 = pos.inputStartRow + 1 + i2;
648782
649544
  const prefix = i2 === 0 ? this.promptText : " ".repeat(this.promptWidth);
648783
649545
  const lineContent = `${prefix}${inputWrap.lines[i2]}`;
648784
- buf += `\x1B[${row};1H${PANEL_BG_SEQ}\x1B[2K`;
649546
+ buf += `\x1B[${row2};1H${PANEL_BG_SEQ}\x1B[2K`;
648785
649547
  buf += `${this.borderVSeq(1)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}${lineContent}`;
648786
649548
  buf += `${PANEL_BG_SEQ}\x1B[K`;
648787
- buf += `\x1B[${row};${w}H${this.borderVSeq(w)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
649549
+ buf += `\x1B[${row2};${w}H${this.borderVSeq(w)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
648788
649550
  }
648789
649551
  buf += this.buildEnhanceSegment(
648790
649552
  w,
@@ -648794,17 +649556,17 @@ ${CONTENT_BG_SEQ}`);
648794
649556
  const cursorTermRow = pos.inputStartRow + 1 + inputWrap.cursorRow;
648795
649557
  if (this._suggestions.length > 0 && pos.suggestStartRow > 0) {
648796
649558
  for (let si = 0; si < this._suggestions.length; si++) {
648797
- const row = pos.suggestStartRow + si;
649559
+ const row2 = pos.suggestStartRow + si;
648798
649560
  const cmd = this._suggestions[si];
648799
649561
  const isHighlighted = si === this._suggestIndex;
648800
649562
  const bg = isHighlighted ? `\x1B[48;5;235m` : PANEL_BG_SEQ;
648801
649563
  const fg2 = isHighlighted ? `\x1B[1;38;5;${TEXT_PRIMARY}m` : `\x1B[38;5;${TEXT_PRIMARY}m`;
648802
649564
  const slash = isHighlighted ? `\x1B[38;5;245m` : `\x1B[38;5;${TEXT_DIM}m`;
648803
649565
  const marker = isHighlighted ? `\x1B[38;5;${TEXT_PRIMARY}m› ` : " ";
648804
- buf += `\x1B[${row};1H${PANEL_BG_SEQ}\x1B[2K${this.borderVSeq(1)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
649566
+ buf += `\x1B[${row2};1H${PANEL_BG_SEQ}\x1B[2K${this.borderVSeq(1)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
648805
649567
  buf += `${bg} ${marker}${slash}/${fg2}${cmd}`;
648806
649568
  buf += `${PANEL_BG_SEQ}\x1B[K`;
648807
- buf += `\x1B[${row};${w}H${this.borderVSeq(w)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
649569
+ buf += `\x1B[${row2};${w}H${this.borderVSeq(w)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
648808
649570
  }
648809
649571
  const suggestBottomRow = pos.suggestStartRow + this._suggestions.length;
648810
649572
  buf += `\x1B[${suggestBottomRow};1H${PANEL_BG_SEQ}\x1B[2K${this.buildInputBoxBottom(w)}${PANEL_BG_SEQ}`;
@@ -648852,13 +649614,13 @@ ${CONTENT_BG_SEQ}`);
648852
649614
  }
648853
649615
  buf += `\x1B[${pos.inputStartRow};1H${PANEL_BG_SEQ}\x1B[2K${this.buildInputBoxTop(w)}${PANEL_BG_SEQ}`;
648854
649616
  for (let i2 = 0; i2 < inputWrap.lines.length; i2++) {
648855
- const row = pos.inputStartRow + 1 + i2;
649617
+ const row2 = pos.inputStartRow + 1 + i2;
648856
649618
  const prefix = i2 === 0 ? this.promptText : " ".repeat(this.promptWidth);
648857
649619
  const lineContent = `${prefix}${inputWrap.lines[i2]}`;
648858
- buf += `\x1B[${row};1H${PANEL_BG_SEQ}\x1B[2K`;
649620
+ buf += `\x1B[${row2};1H${PANEL_BG_SEQ}\x1B[2K`;
648859
649621
  buf += `${this.borderVSeq(1)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}${lineContent}`;
648860
649622
  buf += `${PANEL_BG_SEQ}\x1B[K`;
648861
- buf += `\x1B[${row};${w}H${this.borderVSeq(w)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
649623
+ buf += `\x1B[${row2};${w}H${this.borderVSeq(w)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
648862
649624
  }
648863
649625
  buf += this.buildEnhanceSegment(
648864
649626
  w,
@@ -648867,13 +649629,13 @@ ${CONTENT_BG_SEQ}`);
648867
649629
  );
648868
649630
  if (this._suggestions.length > 0 && pos.suggestStartRow > 0) {
648869
649631
  for (let si = 0; si < this._suggestions.length; si++) {
648870
- const row = pos.suggestStartRow + si;
649632
+ const row2 = pos.suggestStartRow + si;
648871
649633
  const cmd = this._suggestions[si];
648872
649634
  const isHl = si === this._suggestIndex;
648873
649635
  const fg2 = isHl ? `\x1B[1;38;5;${TEXT_PRIMARY}m` : `\x1B[38;5;${TEXT_PRIMARY}m`;
648874
649636
  const marker = isHl ? `\x1B[38;5;${TEXT_PRIMARY}m› ` : " ";
648875
- buf += `\x1B[${row};1H${PANEL_BG_SEQ}\x1B[2K${this.borderVSeq(1)}${BOX_V3}${RESET4}${PANEL_BG_SEQ} ${marker}\x1B[38;5;${TEXT_DIM}m/${fg2}${cmd}`;
648876
- buf += `${PANEL_BG_SEQ}\x1B[K\x1B[${row};${w}H${this.borderVSeq(w)}${BOX_V3}${RESET4}`;
649637
+ buf += `\x1B[${row2};1H${PANEL_BG_SEQ}\x1B[2K${this.borderVSeq(1)}${BOX_V3}${RESET4}${PANEL_BG_SEQ} ${marker}\x1B[38;5;${TEXT_DIM}m/${fg2}${cmd}`;
649638
+ buf += `${PANEL_BG_SEQ}\x1B[K\x1B[${row2};${w}H${this.borderVSeq(w)}${BOX_V3}${RESET4}`;
648877
649639
  }
648878
649640
  buf += `\x1B[${pos.bufferRow};1H${PANEL_BG_SEQ}\x1B[2K${this.buildInputBoxBottom(w)}`;
648879
649641
  } else {
@@ -648926,17 +649688,17 @@ ${CONTENT_BG_SEQ}`);
648926
649688
  }
648927
649689
  const releasedEnd = pos.inputStartRow - 1;
648928
649690
  if (oldFooterTop <= releasedEnd) {
648929
- for (let row = oldFooterTop; row <= releasedEnd; row++) {
648930
- buf += `\x1B[${row};1H${CONTENT_BG_SEQ}\x1B[2K`;
649691
+ for (let row2 = oldFooterTop; row2 <= releasedEnd; row2++) {
649692
+ buf += `\x1B[${row2};1H${CONTENT_BG_SEQ}\x1B[2K`;
648931
649693
  }
648932
649694
  }
648933
649695
  buf += "\x1B[?7l";
648934
649696
  buf += `\x1B[${pos.inputStartRow};1H${PANEL_BG_SEQ}\x1B[2K${this.buildInputBoxTop(w)}`;
648935
649697
  for (let i2 = 0; i2 < inputWrap.lines.length; i2++) {
648936
- const row = pos.inputStartRow + 1 + i2;
649698
+ const row2 = pos.inputStartRow + 1 + i2;
648937
649699
  const prefix = i2 === 0 ? this.promptText : " ".repeat(this.promptWidth);
648938
649700
  const lineContent = `${prefix}${inputWrap.lines[i2]}`;
648939
- buf += `\x1B[${row};1H${PANEL_BG_SEQ}\x1B[2K${this.borderVSeq(1)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}${lineContent}${PANEL_BG_SEQ}\x1B[K\x1B[${row};${w}H${this.borderVSeq(w)}${BOX_V3}${RESET4}`;
649701
+ buf += `\x1B[${row2};1H${PANEL_BG_SEQ}\x1B[2K${this.borderVSeq(1)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}${lineContent}${PANEL_BG_SEQ}\x1B[K\x1B[${row2};${w}H${this.borderVSeq(w)}${BOX_V3}${RESET4}`;
648940
649702
  }
648941
649703
  buf += this.buildEnhanceSegment(
648942
649704
  w,
@@ -648945,15 +649707,15 @@ ${CONTENT_BG_SEQ}`);
648945
649707
  );
648946
649708
  if (this._suggestions.length > 0 && pos.suggestStartRow > 0) {
648947
649709
  for (let si = 0; si < this._suggestions.length; si++) {
648948
- const row = pos.suggestStartRow + si;
649710
+ const row2 = pos.suggestStartRow + si;
648949
649711
  const cmd = this._suggestions[si];
648950
649712
  const isHl = si === this._suggestIndex;
648951
649713
  const bg = isHl ? `\x1B[48;5;235m` : PANEL_BG_SEQ;
648952
649714
  const fg2 = isHl ? `\x1B[1;38;5;${TEXT_PRIMARY}m` : `\x1B[38;5;${TEXT_PRIMARY}m`;
648953
649715
  const marker = isHl ? `\x1B[38;5;${TEXT_PRIMARY}m› ` : " ";
648954
- buf += `\x1B[${row};1H${PANEL_BG_SEQ}\x1B[2K${this.borderVSeq(1)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
649716
+ buf += `\x1B[${row2};1H${PANEL_BG_SEQ}\x1B[2K${this.borderVSeq(1)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
648955
649717
  buf += `${bg} ${marker}\x1B[38;5;${TEXT_DIM}m/${fg2}${cmd}`;
648956
- buf += `${PANEL_BG_SEQ}\x1B[K\x1B[${row};${w}H${this.borderVSeq(w)}${BOX_V3}${RESET4}`;
649718
+ buf += `${PANEL_BG_SEQ}\x1B[K\x1B[${row2};${w}H${this.borderVSeq(w)}${BOX_V3}${RESET4}`;
648957
649719
  }
648958
649720
  }
648959
649721
  buf += `\x1B[${pos.bufferRow};1H${PANEL_BG_SEQ}\x1B[2K${this.buildInputBoxBottom(w)}`;
@@ -648975,13 +649737,13 @@ ${CONTENT_BG_SEQ}`);
648975
649737
  let buf = "\x1B7\x1B[?25l\x1B[?7l";
648976
649738
  buf += `\x1B[${pos.inputStartRow};1H${PANEL_BG_SEQ}\x1B[2K${this.buildInputBoxTop(w)}${PANEL_BG_SEQ}`;
648977
649739
  for (let i2 = 0; i2 < inputWrap.lines.length; i2++) {
648978
- const row = pos.inputStartRow + 1 + i2;
649740
+ const row2 = pos.inputStartRow + 1 + i2;
648979
649741
  const prefix = i2 === 0 ? this.promptText : " ".repeat(this.promptWidth);
648980
649742
  const lineContent = `${prefix}${inputWrap.lines[i2]}`;
648981
- buf += `\x1B[${row};1H${PANEL_BG_SEQ}\x1B[2K`;
649743
+ buf += `\x1B[${row2};1H${PANEL_BG_SEQ}\x1B[2K`;
648982
649744
  buf += `${this.borderVSeq(1)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}${lineContent}`;
648983
649745
  buf += `${PANEL_BG_SEQ}\x1B[K`;
648984
- buf += `\x1B[${row};${w}H${this.borderVSeq(w)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
649746
+ buf += `\x1B[${row2};${w}H${this.borderVSeq(w)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
648985
649747
  }
648986
649748
  buf += this.buildEnhanceSegment(
648987
649749
  w,
@@ -648990,15 +649752,15 @@ ${CONTENT_BG_SEQ}`);
648990
649752
  );
648991
649753
  if (this._suggestions.length > 0 && pos.suggestStartRow > 0) {
648992
649754
  for (let si = 0; si < this._suggestions.length; si++) {
648993
- const row = pos.suggestStartRow + si;
649755
+ const row2 = pos.suggestStartRow + si;
648994
649756
  const cmd = this._suggestions[si];
648995
649757
  const isHl = si === this._suggestIndex;
648996
649758
  const bg = isHl ? `\x1B[48;5;235m` : PANEL_BG_SEQ;
648997
649759
  const fg2 = isHl ? `\x1B[1;38;5;${TEXT_PRIMARY}m` : `\x1B[38;5;${TEXT_PRIMARY}m`;
648998
649760
  const marker = isHl ? `\x1B[38;5;${TEXT_PRIMARY}m› ` : " ";
648999
- buf += `\x1B[${row};1H${PANEL_BG_SEQ}\x1B[2K${this.borderVSeq(1)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
649761
+ buf += `\x1B[${row2};1H${PANEL_BG_SEQ}\x1B[2K${this.borderVSeq(1)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
649000
649762
  buf += `${bg} ${marker}\x1B[38;5;${TEXT_DIM}m/${fg2}${cmd}`;
649001
- buf += `${PANEL_BG_SEQ}\x1B[K\x1B[${row};${w}H${this.borderVSeq(w)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
649763
+ buf += `${PANEL_BG_SEQ}\x1B[K\x1B[${row2};${w}H${this.borderVSeq(w)}${BOX_V3}${RESET4}${PANEL_BG_SEQ}`;
649002
649764
  }
649003
649765
  }
649004
649766
  buf += `\x1B[${pos.bufferRow};1H${PANEL_BG_SEQ}\x1B[2K${this.buildInputBoxBottom(w)}${PANEL_BG_SEQ}`;
@@ -653761,9 +654523,9 @@ function formatExpandedContextDiagnostic(specs, math) {
653761
654523
  memBits.push(`RAM ${fmtGB(specs.availableRamGB)}/${fmtGB(specs.totalRamGB)}${specs.unifiedMemory ? " unified" : ""}`);
653762
654524
  const mem = memBits.join(", ");
653763
654525
  const kv = `KV ${fmtKB(math.kvBytesPerToken)}/tok (${math.kvSource})`;
653764
- const fit4 = `fit ${fmtK(math.memoryFit)}, arch ${math.archCtx !== null ? fmtK(math.archCtx) : "n/a"}, floor ${fmtK(math.floor)}`;
654526
+ const fit5 = `fit ${fmtK(math.memoryFit)}, arch ${math.archCtx !== null ? fmtK(math.archCtx) : "n/a"}, floor ${fmtK(math.floor)}`;
653765
654527
  const limit = `→ ${fmtK(math.numCtx)} (${math.limitedBy === "floor" ? "min floor" : math.limitedBy === "arch" ? "arch-capped" : "memory-fit"})`;
653766
- return `[${mem} | model ${fmtGB(math.modelSizeGB)} | ${kv} | ${fit4} ${limit}]`;
654528
+ return `[${mem} | model ${fmtGB(math.modelSizeGB)} | ${kv} | ${fit5} ${limit}]`;
653767
654529
  }
653768
654530
  async function ensureExpandedContext(modelName, backendUrl2) {
653769
654531
  if (modelName.includes("cloud") || modelName.includes(":cloud")) {
@@ -654042,7 +654804,7 @@ export PATH="${binDir}:$PATH" # Added by omnius for nvim
654042
654804
  } catch {
654043
654805
  }
654044
654806
  }
654045
- var execAsync2, OMNIUS_FIRST_RUN_BANNER, ANSI_RE3, visibleLen2, SETUP_MODEL_VARIANTS, _toolSupportCache, EXPANDED_VARIANT_MIN_NUM_CTX, _cloudflaredInstallPromise;
654807
+ var execAsync2, OMNIUS_FIRST_RUN_BANNER, ANSI_RE4, visibleLen2, SETUP_MODEL_VARIANTS, _toolSupportCache, EXPANDED_VARIANT_MIN_NUM_CTX, _cloudflaredInstallPromise;
654046
654808
  var init_setup = __esm({
654047
654809
  "packages/cli/src/tui/setup.ts"() {
654048
654810
  init_model_picker();
@@ -654061,8 +654823,8 @@ var init_setup = __esm({
654061
654823
  "░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░ ░▒▓█▓▒░ ",
654062
654824
  " ░▒▓██████▓▒░░▒▓█▓▒░░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓█▓▒░▒▓█▓▒░░▒▓██████▓▒░░▒▓███████▓▒░ "
654063
654825
  ].join("\n");
654064
- ANSI_RE3 = /\x1B\[[0-?]*[ -/]*[@-~]/g;
654065
- visibleLen2 = (value2) => Array.from(value2.replace(ANSI_RE3, "")).length;
654826
+ ANSI_RE4 = /\x1B\[[0-?]*[ -/]*[@-~]/g;
654827
+ visibleLen2 = (value2) => Array.from(value2.replace(ANSI_RE4, "")).length;
654066
654828
  SETUP_MODEL_VARIANTS = [
654067
654829
  { tag: "robit/ornith:9b", sizeGB: 6.6, label: "9B params (6.6 GB) - recommended minimum", cloud: false },
654068
654830
  { tag: "robit/ornith:35b", sizeGB: 24, label: "35B params (24 GB) - recommended on 32GB+ unified memory/VRAM", cloud: false }
@@ -658198,13 +658960,13 @@ async function startNeovimMode(opts) {
658198
658960
  if (topOffset > 0) {
658199
658961
  filtered = filtered.replace(
658200
658962
  /\x1B\[(\d+);(\d+)H/g,
658201
- (_m, row, col) => `\x1B[${parseInt(row) + topOffset};${col}H`
658963
+ (_m, row2, col) => `\x1B[${parseInt(row2) + topOffset};${col}H`
658202
658964
  ).replace(
658203
658965
  /\x1B\[(\d+)H/g,
658204
- (_m, row) => `\x1B[${parseInt(row) + topOffset}H`
658966
+ (_m, row2) => `\x1B[${parseInt(row2) + topOffset}H`
658205
658967
  ).replace(/\x1B\[H/g, `\x1B[${topOffset + 1}H`).replace(
658206
658968
  /\x1B\[(\d+)d/g,
658207
- (_m, row) => `\x1B[${parseInt(row) + topOffset}d`
658969
+ (_m, row2) => `\x1B[${parseInt(row2) + topOffset}d`
658208
658970
  );
658209
658971
  }
658210
658972
  if (!state.focused) {
@@ -658279,11 +659041,11 @@ async function startNeovimMode(opts) {
658279
659041
  let normalized = seq.replace(/\x1BO([ABCD])/g, "\x1B[$1");
658280
659042
  normalized = normalized.replace(
658281
659043
  /\x1B\[<(\d+);(\d+);(\d+)([Mm])/g,
658282
- (_m, btn, col, row, suffix) => {
659044
+ (_m, btn, col, row2, suffix) => {
658283
659045
  const b = parseInt(btn);
658284
659046
  if (suffix !== "M" || b !== 0) return "";
658285
659047
  const L = layout();
658286
- const hostRow = parseInt(row);
659048
+ const hostRow = parseInt(row2);
658287
659049
  if (hostRow > L.contentBottom) {
658288
659050
  toggleFocus(state);
658289
659051
  return "";
@@ -659126,7 +659888,7 @@ var init_mem_metabolize = __esm({
659126
659888
  });
659127
659889
 
659128
659890
  // packages/cli/src/tui/commands/kg-prune-inference.ts
659129
- function truncate3(text2, max) {
659891
+ function truncate4(text2, max) {
659130
659892
  const clean5 = text2.replace(/\s+/g, " ").trim();
659131
659893
  return clean5.length > max ? clean5.slice(0, max - 1) + "…" : clean5;
659132
659894
  }
@@ -659138,7 +659900,7 @@ async function classifySignalNodes(candidates, cfg) {
659138
659900
  return { reviewed: 0, keepIds: [], ok: false, error: "no model/endpoint" };
659139
659901
  }
659140
659902
  const list = sample.map(
659141
- (n2, i2) => `${i2 + 1}. id=${n2.id} type=${n2.nodeType} mentions=${n2.mentionCount} edges=${n2.degree} :: ${truncate3(n2.text, 160)}`
659903
+ (n2, i2) => `${i2 + 1}. id=${n2.id} type=${n2.nodeType} mentions=${n2.mentionCount} edges=${n2.degree} :: ${truncate4(n2.text, 160)}`
659142
659904
  ).join("\n");
659143
659905
  const system = 'You are the memory-consolidation process of an AI agent, running during idle time (like sleep). You are shown low-activity knowledge-graph nodes that are scheduled to be FORGOTTEN to keep memory bounded. Your job: rescue only the ones that are durable SIGNAL — stable facts, real entities, decisions, identities, or reusable knowledge the agent will likely need again. Let transient, redundant, trivial, or noisy nodes be forgotten. Reply with ONLY a JSON array of the id strings to KEEP, e.g. ["a1","b2"]. Keep the array short and selective. If none are worth keeping, reply []';
659144
659906
  const user = `Nodes scheduled for forgetting:
@@ -674733,12 +675495,12 @@ function cad3dFitIcon(score) {
674733
675495
  if (score >= 40) return c3.yellow("△");
674734
675496
  return c3.red("✖");
674735
675497
  }
674736
- function cad3dModelDetail(spec, fit4) {
675498
+ function cad3dModelDetail(spec, fit5) {
674737
675499
  const download = spec.resources.approxDownloadGB ? `~${spec.resources.approxDownloadGB}GB` : "size unknown";
674738
675500
  const vram = spec.resources.recommendedVramGB ? `${spec.resources.recommendedVramGB}GB VRAM rec` : "VRAM varies";
674739
675501
  const license = spec.hf.license ? `license ${spec.hf.license}` : "license unknown";
674740
675502
  const token = spec.deployment.requiresToken ? "requires HF token" : "no token gate";
674741
- return `${fit4.label} · ${spec.backend} · ${download} · ${vram} · ${license} · ${token}`;
675503
+ return `${fit5.label} · ${spec.backend} · ${download} · ${vram} · ${license} · ${token}`;
674742
675504
  }
674743
675505
  async function startCad3dViewerFromCommand(rawPath) {
674744
675506
  const viewer = await startCadModelViewer(
@@ -674754,11 +675516,11 @@ async function showCad3dModelsMenu(ctx3, hasLocal, mode) {
674754
675516
  const active = mode === "cad" ? settings.cadModel : settings.model3dModel;
674755
675517
  const currentViewer2 = getCurrentCadModelViewer();
674756
675518
  const buildItem = (entry) => {
674757
- const fit4 = rateCad3dModelForHardware(entry.spec, specs);
675519
+ const fit5 = rateCad3dModelForHardware(entry.spec, specs);
674758
675520
  return {
674759
675521
  key: `model:${entry.spec.id}`,
674760
- label: `${cad3dFitIcon(fit4.score)} ${String(fit4.score).padStart(3)}/100 ${entry.spec.label}`,
674761
- detail: cad3dModelDetail(entry.spec, fit4)
675522
+ label: `${cad3dFitIcon(fit5.score)} ${String(fit5.score).padStart(3)}/100 ${entry.spec.label}`,
675523
+ detail: cad3dModelDetail(entry.spec, fit5)
674762
675524
  };
674763
675525
  };
674764
675526
  const items = [
@@ -674793,11 +675555,11 @@ async function showCad3dModelsMenu(ctx3, hasLocal, mode) {
674793
675555
  const patch = mode === "cad" ? { cadModel: id2, cadBackend: entry.spec.backend } : { model3dModel: id2, model3dBackend: entry.spec.backend };
674794
675556
  const save3 = hasLocal ? ctx3.saveLocalSettings : ctx3.saveSettings;
674795
675557
  save3(patch);
674796
- const fit4 = rateCad3dModelForHardware(entry.spec, specs);
675558
+ const fit5 = rateCad3dModelForHardware(entry.spec, specs);
674797
675559
  renderInfo(
674798
675560
  `${mode === "cad" ? "CAD" : "3D"} model: ${id2} (${entry.spec.backend})${hasLocal ? " (project-local)" : ""}`
674799
675561
  );
674800
- renderInfo(`Hardware fit: ${fit4.score}/100 ${fit4.label} - ${fit4.note}`);
675562
+ renderInfo(`Hardware fit: ${fit5.score}/100 ${fit5.label} - ${fit5.note}`);
674801
675563
  if (entry.spec.resources.approxDownloadGB) {
674802
675564
  renderInfo(
674803
675565
  `Download estimate: ~${entry.spec.resources.approxDownloadGB}GB in ${unifiedModelStoreDir()}`
@@ -674948,19 +675710,19 @@ async function renderImageModelList(ctx3) {
674948
675710
  renderInfo("");
674949
675711
  renderInfo(c3.bold(category));
674950
675712
  for (const preset of presets) {
674951
- const fit4 = rateImagePresetForHardware(preset, specs);
675713
+ const fit5 = rateImagePresetForHardware(preset, specs);
674952
675714
  const primary = category === "Primary hyper-realistic baseline" ? c3.cyan(" ★") : "";
674953
675715
  const disk = ctx3 ? imageModelDiskStats(ctx3, preset, ollamaSizes) : { downloaded: false, bytes: 0, paths: [] };
674954
675716
  const diskInfo = disk.downloaded ? ` ${c3.green("✓")} ${formatFileSize(disk.bytes)}` : "";
674955
675717
  renderInfo(
674956
- `${imageFitIcon(fit4.score)} ${String(fit4.score).padStart(3)}/100 ${c3.bold(preset.label)}${primary}${diskInfo}`
675718
+ `${imageFitIcon(fit5.score)} ${String(fit5.score).padStart(3)}/100 ${c3.bold(preset.label)}${primary}${diskInfo}`
674957
675719
  );
674958
675720
  renderInfo(` id: ${preset.id}`);
674959
675721
  renderInfo(
674960
- ` type: ${preset.backend} · ${preset.sizeClass ?? "unknown size"} · ${fit4.label}`
675722
+ ` type: ${preset.backend} · ${preset.sizeClass ?? "unknown size"} · ${fit5.label}`
674961
675723
  );
674962
675724
  renderImagePresetDetail(" quality: ", preset.quality ?? preset.note);
674963
- renderImagePresetDetail(" fit: ", fit4.note);
675725
+ renderImagePresetDetail(" fit: ", fit5.note);
674964
675726
  if (preset.deployment)
674965
675727
  renderImagePresetDetail(" deploy: ", preset.deployment);
674966
675728
  }
@@ -675103,13 +675865,13 @@ async function showImageModelsMenu(ctx3, hasLocal) {
675103
675865
  () => /* @__PURE__ */ new Map()
675104
675866
  );
675105
675867
  const buildModelItem = (preset) => {
675106
- const fit4 = rateImagePresetForHardware(preset, specs);
675868
+ const fit5 = rateImagePresetForHardware(preset, specs);
675107
675869
  const disk = imageModelDiskStats(ctx3, preset, ollamaSizes);
675108
675870
  const downloaded = disk.downloaded ? `${c3.green("✓")} ` : "";
675109
675871
  return {
675110
675872
  key: `model:${preset.id}`,
675111
- label: `${downloaded}${imageFitIcon(fit4.score)} ${String(fit4.score).padStart(3)}/100 ${preset.label}`,
675112
- detail: `${fit4.score}/100 ${fit4.label} · ${preset.category ?? preset.backend} · ${preset.sizeClass ?? preset.id}${downloadedModelSuffix(disk)}`
675873
+ label: `${downloaded}${imageFitIcon(fit5.score)} ${String(fit5.score).padStart(3)}/100 ${preset.label}`,
675874
+ detail: `${fit5.score}/100 ${fit5.label} · ${preset.category ?? preset.backend} · ${preset.sizeClass ?? preset.id}${downloadedModelSuffix(disk)}`
675113
675875
  };
675114
675876
  };
675115
675877
  const items = [
@@ -675194,9 +675956,9 @@ async function showImageModelsMenu(ctx3, hasLocal) {
675194
675956
  renderInfo(
675195
675957
  `Image model: ${model} (${backend})${hasLocal ? " (project-local)" : ""}`
675196
675958
  );
675197
- const fit4 = preset ? rateImagePresetForHardware(preset, specs) : void 0;
675198
- if (fit4)
675199
- renderInfo(`Hardware fit: ${fit4.score}/100 ${fit4.label} — ${fit4.note}`);
675959
+ const fit5 = preset ? rateImagePresetForHardware(preset, specs) : void 0;
675960
+ if (fit5)
675961
+ renderInfo(`Hardware fit: ${fit5.score}/100 ${fit5.label} — ${fit5.note}`);
675200
675962
  if (preset?.install) renderInfo(`Prewarm command: ${preset.install}`);
675201
675963
  await prewarmImageModel(ctx3, model, backend);
675202
675964
  }
@@ -675512,19 +676274,19 @@ async function renderVideoModelList(ctx3) {
675512
676274
  renderInfo("");
675513
676275
  renderInfo(c3.bold(category));
675514
676276
  for (const preset of presets) {
675515
- const fit4 = rateVideoPresetForHardware(preset, specs);
676277
+ const fit5 = rateVideoPresetForHardware(preset, specs);
675516
676278
  const disk = videoModelDiskStats(ctx3, preset);
675517
676279
  const diskInfo = disk.downloaded ? ` ${c3.green("✓")} ${formatFileSize(disk.bytes)}` : "";
675518
676280
  renderInfo(
675519
- `${imageFitIcon(fit4.score)} ${String(fit4.score).padStart(3)}/100 ${c3.bold(preset.label)}${diskInfo}`
676281
+ `${imageFitIcon(fit5.score)} ${String(fit5.score).padStart(3)}/100 ${c3.bold(preset.label)}${diskInfo}`
675520
676282
  );
675521
676283
  renderInfo(` id: ${preset.id}`);
675522
676284
  renderInfo(
675523
- ` type: ${preset.backend} · ${preset.sizeClass} · ${preset.kinds.join("/")} · ${fit4.label}`
676285
+ ` type: ${preset.backend} · ${preset.sizeClass} · ${preset.kinds.join("/")} · ${fit5.label}`
675524
676286
  );
675525
676287
  renderImagePresetDetail(" quality: ", preset.quality);
675526
676288
  renderImagePresetDetail(" output: ", preset.output);
675527
- renderImagePresetDetail(" fit: ", fit4.note);
676289
+ renderImagePresetDetail(" fit: ", fit5.note);
675528
676290
  renderImagePresetDetail(" deploy: ", preset.deployment);
675529
676291
  if (preset.licenseNote)
675530
676292
  renderImagePresetDetail(" license: ", preset.licenseNote);
@@ -675535,13 +676297,13 @@ async function showVideoModelsMenu(ctx3, hasLocal) {
675535
676297
  const settings = resolveSettings(ctx3.repoRoot);
675536
676298
  const specs = await detectSystemSpecsAsync();
675537
676299
  const buildModelItem = (preset) => {
675538
- const fit4 = rateVideoPresetForHardware(preset, specs);
676300
+ const fit5 = rateVideoPresetForHardware(preset, specs);
675539
676301
  const disk = videoModelDiskStats(ctx3, preset);
675540
676302
  const downloaded = disk.downloaded ? `${c3.green("✓")} ` : "";
675541
676303
  return {
675542
676304
  key: `model:${preset.id}`,
675543
- label: `${downloaded}${imageFitIcon(fit4.score)} ${String(fit4.score).padStart(3)}/100 ${preset.label}`,
675544
- detail: `${fit4.label} · ${preset.category} · ${preset.kinds.join("/")}${downloadedModelSuffix(disk)}`
676305
+ label: `${downloaded}${imageFitIcon(fit5.score)} ${String(fit5.score).padStart(3)}/100 ${preset.label}`,
676306
+ detail: `${fit5.label} · ${preset.category} · ${preset.kinds.join("/")}${downloadedModelSuffix(disk)}`
675545
676307
  };
675546
676308
  };
675547
676309
  const items = [
@@ -675620,8 +676382,8 @@ async function showVideoModelsMenu(ctx3, hasLocal) {
675620
676382
  `Video model: ${model} (${backend})${hasLocal ? " (project-local)" : ""}`
675621
676383
  );
675622
676384
  if (preset) {
675623
- const fit4 = rateVideoPresetForHardware(preset, specs);
675624
- renderInfo(`Hardware fit: ${fit4.score}/100 ${fit4.label} — ${fit4.note}`);
676385
+ const fit5 = rateVideoPresetForHardware(preset, specs);
676386
+ renderInfo(`Hardware fit: ${fit5.score}/100 ${fit5.label} — ${fit5.note}`);
675625
676387
  if (preset.licenseNote) renderInfo(`License: ${preset.licenseNote}`);
675626
676388
  if (preset.install) renderInfo(`Prewarm command: ${preset.install}`);
675627
676389
  }
@@ -675883,19 +676645,19 @@ async function renderAudioModelList(ctx3, kind) {
675883
676645
  renderInfo("");
675884
676646
  renderInfo(c3.bold(category));
675885
676647
  for (const preset of presets) {
675886
- const fit4 = rateAudioPresetForHardware(preset, specs);
676648
+ const fit5 = rateAudioPresetForHardware(preset, specs);
675887
676649
  const disk = audioModelDiskStats(ctx3, preset);
675888
676650
  const diskInfo = disk.downloaded ? ` ${c3.green("✓")} ${formatFileSize(disk.bytes)}` : "";
675889
676651
  renderInfo(
675890
- `${audioFitIcon(fit4.score)} ${String(fit4.score).padStart(3)}/100 ${c3.bold(preset.label)}${diskInfo}`
676652
+ `${audioFitIcon(fit5.score)} ${String(fit5.score).padStart(3)}/100 ${c3.bold(preset.label)}${diskInfo}`
675891
676653
  );
675892
676654
  renderInfo(` id: ${preset.id}`);
675893
676655
  renderInfo(
675894
- ` type: ${preset.backend} · ${preset.sizeClass} · ${fit4.label}`
676656
+ ` type: ${preset.backend} · ${preset.sizeClass} · ${fit5.label}`
675895
676657
  );
675896
676658
  renderImagePresetDetail(" quality: ", preset.quality);
675897
676659
  renderImagePresetDetail(" output: ", preset.output);
675898
- renderImagePresetDetail(" fit: ", fit4.note);
676660
+ renderImagePresetDetail(" fit: ", fit5.note);
675899
676661
  renderImagePresetDetail(" deploy: ", preset.deployment);
675900
676662
  }
675901
676663
  }
@@ -675920,13 +676682,13 @@ async function showAudioGenerationMenu(ctx3, hasLocal, kind) {
675920
676682
  const activeModel = activeAudioModel(settings, kind);
675921
676683
  const title = kind === "music" ? "Music Generation" : "Sound Generation";
675922
676684
  const buildModelItem = (preset) => {
675923
- const fit4 = rateAudioPresetForHardware(preset, specs);
676685
+ const fit5 = rateAudioPresetForHardware(preset, specs);
675924
676686
  const disk = audioModelDiskStats(ctx3, preset);
675925
676687
  const downloaded = disk.downloaded ? `${c3.green("✓")} ` : "";
675926
676688
  return {
675927
676689
  key: `model:${preset.id}`,
675928
- label: `${downloaded}${audioFitIcon(fit4.score)} ${String(fit4.score).padStart(3)}/100 ${preset.label}`,
675929
- detail: `${fit4.label} · ${preset.category} · ${preset.sizeClass}${downloadedModelSuffix(disk)}`
676690
+ label: `${downloaded}${audioFitIcon(fit5.score)} ${String(fit5.score).padStart(3)}/100 ${preset.label}`,
676691
+ detail: `${fit5.label} · ${preset.category} · ${preset.sizeClass}${downloadedModelSuffix(disk)}`
675930
676692
  };
675931
676693
  };
675932
676694
  const setupItems = kind === "music" ? [
@@ -676047,8 +676809,8 @@ async function showAudioGenerationMenu(ctx3, hasLocal, kind) {
676047
676809
  `${kind === "music" ? "Music" : "Sound"} model: ${model} (${backend})${hasLocal ? " (project-local)" : ""}`
676048
676810
  );
676049
676811
  if (preset) {
676050
- const fit4 = rateAudioPresetForHardware(preset, specs);
676051
- renderInfo(`Hardware fit: ${fit4.score}/100 ${fit4.label} - ${fit4.note}`);
676812
+ const fit5 = rateAudioPresetForHardware(preset, specs);
676813
+ renderInfo(`Hardware fit: ${fit5.score}/100 ${fit5.label} - ${fit5.note}`);
676052
676814
  renderInfo(`Prewarm command: ${preset.install}`);
676053
676815
  }
676054
676816
  await prewarmAudioModel(ctx3, kind, model, backend);
@@ -685261,8 +686023,8 @@ var init_carousel = __esm({
685261
686023
  this.rebuildRibbons();
685262
686024
  }
685263
686025
  rebuildRibbons() {
685264
- for (const row of this.rows) {
685265
- row.renderedPlain = buildPlainRibbon(row.phrases, this.width);
686026
+ for (const row2 of this.rows) {
686027
+ row2.renderedPlain = buildPlainRibbon(row2.phrases, this.width);
685266
686028
  }
685267
686029
  }
685268
686030
  /**
@@ -685288,10 +686050,10 @@ var init_carousel = __esm({
685288
686050
  process.stdout.on("resize", this.resizeHandler);
685289
686051
  this.renderFrame();
685290
686052
  this.timer = setInterval(() => {
685291
- for (const row of this.rows) {
685292
- row.offset += row.speed * row.direction;
685293
- if (Math.abs(row.offset) > row.renderedPlain.length / 2) {
685294
- row.offset = 0;
686053
+ for (const row2 of this.rows) {
686054
+ row2.offset += row2.speed * row2.direction;
686055
+ if (Math.abs(row2.offset) > row2.renderedPlain.length / 2) {
686056
+ row2.offset = 0;
685295
686057
  }
685296
686058
  }
685297
686059
  this.renderFrame();
@@ -685320,18 +686082,18 @@ var init_carousel = __esm({
685320
686082
  * Extract a terminal-width colored window from a scrolling ribbon.
685321
686083
  * Uses column-aware width to prevent CJK/fullwidth character overflow.
685322
686084
  */
685323
- extractWindow(row) {
686085
+ extractWindow(row2) {
685324
686086
  const maxCols = this.width;
685325
- const plain = row.renderedPlain;
686087
+ const plain = row2.renderedPlain;
685326
686088
  if (!plain) return "";
685327
- let start2 = Math.floor(Math.abs(row.offset)) % plain.length;
686089
+ let start2 = Math.floor(Math.abs(row2.offset)) % plain.length;
685328
686090
  if (start2 < 0) start2 += plain.length;
685329
686091
  const separator = " : ";
685330
686092
  let coloredLine = "";
685331
686093
  let colCount = 0;
685332
686094
  let charInPhrase = 0;
685333
686095
  let skipChars = start2;
685334
- const phrases = row.phrases;
686096
+ const phrases = row2.phrases;
685335
686097
  let fullIdx = 0;
685336
686098
  while (skipChars > 0) {
685337
686099
  const p2 = phrases[fullIdx % phrases.length];
@@ -685491,15 +686253,15 @@ function createCohereBanner() {
685491
686253
  const fgColor = 226;
685492
686254
  const halftone = ["█", "▓", "▒", "░", " "];
685493
686255
  for (let r2 = 0; r2 < rows; r2++) {
685494
- const row = [];
686256
+ const row2 = [];
685495
686257
  for (let c9 = 0; c9 < width; c9++) {
685496
686258
  const distFromCenter = Math.abs(c9 - width / 2) / (width / 2);
685497
686259
  const htIdx = Math.min(halftone.length - 1, Math.floor(distFromCenter * halftone.length));
685498
686260
  const char = r2 === 0 || r2 === 2 ? halftone[htIdx] : " ";
685499
686261
  const charFg = r2 === 1 ? fgColor : 238;
685500
- row.push({ char, fg: charFg, bg: bgColor, bold: false });
686262
+ row2.push({ char, fg: charFg, bg: bgColor, bold: false });
685501
686263
  }
685502
- grid.push(row);
686264
+ grid.push(row2);
685503
686265
  }
685504
686266
  const text2 = "COHERE — Distributed Cognitive Commons";
685505
686267
  const startCol = Math.max(0, Math.floor((width - text2.length) / 2));
@@ -685522,11 +686284,11 @@ function createSponsorBanner(sponsorName, tagline, primaryColor = 214, bgColor =
685522
686284
  const rows = headerHeight();
685523
686285
  const grid = [];
685524
686286
  for (let r2 = 0; r2 < rows; r2++) {
685525
- const row = [];
686287
+ const row2 = [];
685526
686288
  for (let c9 = 0; c9 < width; c9++) {
685527
- row.push({ char: " ", fg: primaryColor, bg: bgColor, bold: false });
686289
+ row2.push({ char: " ", fg: primaryColor, bg: bgColor, bold: false });
685528
686290
  }
685529
- grid.push(row);
686291
+ grid.push(row2);
685530
686292
  }
685531
686293
  const nameText = ` ${sponsorName}`;
685532
686294
  for (let i2 = 0; i2 < nameText.length && i2 < width; i2++) {
@@ -685577,19 +686339,19 @@ function listBannerDesigns(workDir) {
685577
686339
  function createEmptyGrid(width, rows = 3) {
685578
686340
  const grid = [];
685579
686341
  for (let r2 = 0; r2 < rows; r2++) {
685580
- const row = [];
686342
+ const row2 = [];
685581
686343
  for (let c9 = 0; c9 < width; c9++) {
685582
- row.push({ char: " ", fg: -1, bg: -1, bold: false });
686344
+ row2.push({ char: " ", fg: -1, bg: -1, bold: false });
685583
686345
  }
685584
- grid.push(row);
686346
+ grid.push(row2);
685585
686347
  }
685586
686348
  return grid;
685587
686349
  }
685588
- function setGridText(grid, row, col, text2, fg2 = -1, bg = -1, bold = false) {
685589
- if (!grid[row]) return;
686350
+ function setGridText(grid, row2, col, text2, fg2 = -1, bg = -1, bold = false) {
686351
+ if (!grid[row2]) return;
685590
686352
  for (let i2 = 0; i2 < text2.length; i2++) {
685591
- if (col + i2 < grid[row].length) {
685592
- grid[row][col + i2] = { char: text2[i2], fg: fg2, bg, bold };
686353
+ if (col + i2 < grid[row2].length) {
686354
+ grid[row2][col + i2] = { char: text2[i2], fg: fg2, bg, bold };
685593
686355
  }
685594
686356
  }
685595
686357
  }
@@ -685833,11 +686595,11 @@ var init_banner = __esm({
685833
686595
  const L = layout();
685834
686596
  for (let r2 = 0; r2 < this.rows; r2++) {
685835
686597
  buf += `\x1B[${L.headerTop + r2};1H${tuiBg() >= 0 ? `\x1B[48;5;${tuiBg()}m` : "\x1B[49m"}\x1B[2K`;
685836
- const row = frame.grid[r2];
685837
- if (!row) continue;
686598
+ const row2 = frame.grid[r2];
686599
+ if (!row2) continue;
685838
686600
  let prevFg = -1, prevBg = -1, prevBold = false;
685839
- for (let c9 = 0; c9 < Math.min(this.width, row.length); c9++) {
685840
- const cell = row[c9];
686601
+ for (let c9 = 0; c9 < Math.min(this.width, row2.length); c9++) {
686602
+ const cell = row2[c9];
685841
686603
  let char = cell.char;
685842
686604
  if (defaultBoxSeparators?.has(c9 + 1)) {
685843
686605
  if (r2 === 0) char = "┬";
@@ -685989,8 +686751,8 @@ function generateDescriptors(repoRoot) {
685989
686751
  if (repoName2 && !tags.includes(repoName2)) {
685990
686752
  tags.push(repoName2);
685991
686753
  }
685992
- const unique2 = [...new Set(tags.map((t2) => t2.toLowerCase().trim()).filter((t2) => t2.length > 1 && t2.length < 60))];
685993
- const phrases = unique2.map((text2) => ({
686754
+ const unique3 = [...new Set(tags.map((t2) => t2.toLowerCase().trim()).filter((t2) => t2.length > 1 && t2.length < 60))];
686755
+ const phrases = unique3.map((text2) => ({
685994
686756
  text: text2,
685995
686757
  color: weightedColor(profile)
685996
686758
  }));
@@ -686011,7 +686773,7 @@ function generateDescriptors(repoRoot) {
686011
686773
  ];
686012
686774
  for (const fb of fallbacks) {
686013
686775
  if (phrases.length >= 20) break;
686014
- if (!unique2.includes(fb)) {
686776
+ if (!unique3.includes(fb)) {
686015
686777
  phrases.push({ text: fb, color: weightedColor(profile) });
686016
686778
  }
686017
686779
  }
@@ -691938,13 +692700,13 @@ function buildScopedToolList(scope) {
691938
692700
  const commandSigs = commands.flatMap((cmd) => cmd.signatures);
691939
692701
  const allSigs = [...syntheticSigs, ...commandSigs];
691940
692702
  const seen = /* @__PURE__ */ new Set();
691941
- const unique2 = allSigs.filter((sig) => {
692703
+ const unique3 = allSigs.filter((sig) => {
691942
692704
  if (seen.has(sig.signature)) return false;
691943
692705
  seen.add(sig.signature);
691944
692706
  return true;
691945
692707
  });
691946
692708
  const entries = [];
691947
- for (const sig of unique2) {
692709
+ for (const sig of unique3) {
691948
692710
  const matchingCmd = commands.find(
691949
692711
  (cmd) => cmd.signatures.some((s2) => s2.signature === sig.signature)
691950
692712
  );
@@ -697045,14 +697807,14 @@ function parseTelegramReplyPreferenceUpdate(parsed) {
697045
697807
  }
697046
697808
  function uniqueTelegramJsonCandidates(candidates) {
697047
697809
  const seen = /* @__PURE__ */ new Set();
697048
- const unique2 = [];
697810
+ const unique3 = [];
697049
697811
  for (const candidate of candidates) {
697050
697812
  const clean5 = candidate.trim();
697051
697813
  if (!clean5 || seen.has(clean5)) continue;
697052
697814
  seen.add(clean5);
697053
- unique2.push(clean5);
697815
+ unique3.push(clean5);
697054
697816
  }
697055
- return unique2;
697817
+ return unique3;
697056
697818
  }
697057
697819
  function extractBalancedTelegramJsonObjects(text2) {
697058
697820
  const objects = [];
@@ -698051,10 +698813,10 @@ function telegramHistoryTime(entry) {
698051
698813
  });
698052
698814
  }
698053
698815
  function formatTelegramIdentitySignals(signals) {
698054
- const unique2 = [
698816
+ const unique3 = [
698055
698817
  ...new Set(signals.map((signal) => signal.trim()).filter(Boolean))
698056
698818
  ];
698057
- return unique2.length > 0 ? unique2.join(", ") : "none";
698819
+ return unique3.length > 0 ? unique3.join(", ") : "none";
698058
698820
  }
698059
698821
  function summarizeTelegramMessageAttachments(msg) {
698060
698822
  const parts = [];
@@ -698540,12 +699302,12 @@ function buildTelegramHelpHTML(scope, maxPublicCommands = 24) {
698540
699302
  ...commands.flatMap((cmd) => cmd.signatures)
698541
699303
  ];
698542
699304
  const seen = /* @__PURE__ */ new Set();
698543
- const unique2 = signatures.filter((sig) => {
699305
+ const unique3 = signatures.filter((sig) => {
698544
699306
  if (seen.has(sig.signature)) return false;
698545
699307
  seen.add(sig.signature);
698546
699308
  return true;
698547
699309
  });
698548
- const visible = scope === "public" ? unique2.slice(0, maxPublicCommands) : unique2;
699310
+ const visible = scope === "public" ? unique3.slice(0, maxPublicCommands) : unique3;
698549
699311
  const lines = [
698550
699312
  `<b>Commands (${scope === "admin" ? "admin full scope" : "public secure scope"})</b>`,
698551
699313
  "",
@@ -698553,7 +699315,7 @@ function buildTelegramHelpHTML(scope, maxPublicCommands = 24) {
698553
699315
  (sig) => `<code>${escapeTelegramHTML(sig.signature)}</code> - ${escapeTelegramHTML(sig.description)}`
698554
699316
  )
698555
699317
  ];
698556
- if (scope === "public" && unique2.length > visible.length) {
699318
+ if (scope === "public" && unique3.length > visible.length) {
698557
699319
  lines.push("");
698558
699320
  lines.push(
698559
699321
  `Public scope truncated to ${visible.length} safe commands. Authenticate as admin for full command help.`
@@ -701384,10 +702146,10 @@ ${message2}`)
701384
702146
  telegramModelMenuItems(generation) {
701385
702147
  return this.telegramGenerationModelDescriptors(generation).map((model) => {
701386
702148
  const cached = model.cachedBytes > 0 ? `cached ${formatModelBytes(model.cachedBytes)}` : "not downloaded";
701387
- const fit4 = model.recommendedVramGB ? `${model.recommendedVramGB}GB VRAM rec` : model.minVramGB ? `${model.minVramGB}GB VRAM min` : "VRAM n/a";
702149
+ const fit5 = model.recommendedVramGB ? `${model.recommendedVramGB}GB VRAM rec` : model.minVramGB ? `${model.minVramGB}GB VRAM min` : "VRAM n/a";
701388
702150
  return {
701389
702151
  label: model.label,
701390
- description: `${model.backend} - ${model.category} - ${fit4} - ${cached}`,
702152
+ description: `${model.backend} - ${model.category} - ${fit5} - ${cached}`,
701391
702153
  action: {
701392
702154
  type: "model_detail",
701393
702155
  generation,
@@ -703233,13 +703995,13 @@ ${mediaContext}` : ""
703233
703995
  const store2 = new EpisodeStore(paths.episodes, graph);
703234
703996
  let existingTelegramEpisodes = 0;
703235
703997
  try {
703236
- const row = store2.getDb().prepare(
703998
+ const row2 = store2.getDb().prepare(
703237
703999
  `
703238
704000
  SELECT COUNT(*) AS n FROM episodes
703239
704001
  WHERE session_id = ? AND metadata LIKE '%"sourceSurface":"telegram"%'
703240
704002
  `
703241
704003
  ).get(sessionKey);
703242
- existingTelegramEpisodes = row?.n ?? 0;
704004
+ existingTelegramEpisodes = row2?.n ?? 0;
703243
704005
  } finally {
703244
704006
  store2.close();
703245
704007
  graph.close();
@@ -704754,9 +705516,9 @@ ${lines.join("\n")}`;
704754
705516
  if (!db) return "";
704755
705517
  const rows = /* @__PURE__ */ new Map();
704756
705518
  const addRows = (items) => {
704757
- for (const row of items) {
704758
- const key = Number(row.rowid);
704759
- if (Number.isFinite(key)) rows.set(key, row);
705519
+ for (const row2 of items) {
705520
+ const key = Number(row2.rowid);
705521
+ if (Number.isFinite(key)) rows.set(key, row2);
704760
705522
  }
704761
705523
  };
704762
705524
  try {
@@ -704803,11 +705565,11 @@ ${lines.join("\n")}`;
704803
705565
  }
704804
705566
  const selected = [...rows.values()].sort((a2, b) => Number(b.received_at ?? 0) - Number(a2.received_at ?? 0)).slice(0, limit);
704805
705567
  if (selected.length === 0) return "";
704806
- const lines = selected.map((row) => {
704807
- const when = row.received_at ? new Date(Number(row.received_at)).toISOString() : "";
704808
- const speaker = row.role === "assistant" ? `@${this.state.botUsername || "omnius"}` : row.username ? `@${row.username}` : row.from_user_id ? `user:${row.from_user_id}` : "unknown";
704809
- const reply = row.reply_to_message_id ? ` reply_to:${row.reply_to_message_id}` : "";
704810
- return `- ${when} ${speaker}/${row.role || "user"} msg:${row.message_id}${reply}: ${telegramContextJsonString(String(row.text || ""), 260)}`;
705568
+ const lines = selected.map((row2) => {
705569
+ const when = row2.received_at ? new Date(Number(row2.received_at)).toISOString() : "";
705570
+ const speaker = row2.role === "assistant" ? `@${this.state.botUsername || "omnius"}` : row2.username ? `@${row2.username}` : row2.from_user_id ? `user:${row2.from_user_id}` : "unknown";
705571
+ const reply = row2.reply_to_message_id ? ` reply_to:${row2.reply_to_message_id}` : "";
705572
+ return `- ${when} ${speaker}/${row2.role || "user"} msg:${row2.message_id}${reply}: ${telegramContextJsonString(String(row2.text || ""), 260)}`;
704811
705573
  });
704812
705574
  return [
704813
705575
  "### SQLite Telegram Raw Mirror Recall",
@@ -704886,16 +705648,16 @@ ${lines.join("\n")}`;
704886
705648
  LIMIT ?
704887
705649
  `
704888
705650
  ).all(sessionKey, limit);
704889
- return rows.reverse().map((row) => this.telegramSqliteRowToHistoryEntry(row));
705651
+ return rows.reverse().map((row2) => this.telegramSqliteRowToHistoryEntry(row2));
704890
705652
  } catch {
704891
705653
  return [];
704892
705654
  }
704893
705655
  }
704894
- telegramSqliteRowIsBot(row) {
704895
- if (row.role === "assistant") return true;
704896
- if (row.from_is_bot === 1 || row.from_is_bot === true) return true;
705656
+ telegramSqliteRowIsBot(row2) {
705657
+ if (row2.role === "assistant") return true;
705658
+ if (row2.from_is_bot === 1 || row2.from_is_bot === true) return true;
704897
705659
  for (const key of ["normalized_json", "raw_json"]) {
704898
- const raw = row?.[key];
705660
+ const raw = row2?.[key];
704899
705661
  if (typeof raw !== "string" || !raw.trim()) continue;
704900
705662
  try {
704901
705663
  const parsed = JSON.parse(raw);
@@ -704906,31 +705668,31 @@ ${lines.join("\n")}`;
704906
705668
  }
704907
705669
  return false;
704908
705670
  }
704909
- telegramSqliteRowToHistoryEntry(row) {
705671
+ telegramSqliteRowToHistoryEntry(row2) {
704910
705672
  const num3 = (value2) => {
704911
705673
  const n2 = Number(value2);
704912
705674
  return Number.isFinite(n2) ? n2 : void 0;
704913
705675
  };
704914
- const role = row.role === "assistant" ? "assistant" : "user";
704915
- const username = row.username ? String(row.username) : void 0;
704916
- const fromUserId = num3(row.from_user_id);
704917
- const isBot = this.telegramSqliteRowIsBot(row);
705676
+ const role = row2.role === "assistant" ? "assistant" : "user";
705677
+ const username = row2.username ? String(row2.username) : void 0;
705678
+ const fromUserId = num3(row2.from_user_id);
705679
+ const isBot = this.telegramSqliteRowIsBot(row2);
704918
705680
  return {
704919
705681
  role,
704920
- text: String(row.text || ""),
704921
- ts: num3(row.received_at),
704922
- chatId: row.chat_id,
705682
+ text: String(row2.text || ""),
705683
+ ts: num3(row2.received_at),
705684
+ chatId: row2.chat_id,
704923
705685
  speaker: role === "assistant" ? `@${this.state.botUsername || username || "omnius"}` : username ? `@${username}` : fromUserId !== void 0 ? isBot ? `bot:${fromUserId}` : `user:${fromUserId}` : "unknown",
704924
705686
  username,
704925
- firstName: row.first_name ? String(row.first_name) : void 0,
705687
+ firstName: row2.first_name ? String(row2.first_name) : void 0,
704926
705688
  fromUserId,
704927
705689
  isBot,
704928
- messageId: num3(row.message_id),
704929
- messageThreadId: num3(row.message_thread_id),
704930
- replyToMessageId: num3(row.reply_to_message_id),
704931
- chatType: row.chat_type,
704932
- chatTitle: row.chat_title || void 0,
704933
- mediaSummary: row.media_json ? "media attached in raw Telegram SQLite mirror" : void 0
705690
+ messageId: num3(row2.message_id),
705691
+ messageThreadId: num3(row2.message_thread_id),
705692
+ replyToMessageId: num3(row2.reply_to_message_id),
705693
+ chatType: row2.chat_type,
705694
+ chatTitle: row2.chat_title || void 0,
705695
+ mediaSummary: row2.media_json ? "media attached in raw Telegram SQLite mirror" : void 0
704934
705696
  };
704935
705697
  }
704936
705698
  telegramMergedHistoryForSession(sessionKey, limit = TELEGRAM_CHAT_HISTORY_LIMIT) {
@@ -704977,7 +705739,7 @@ ${lines.join("\n")}`;
704977
705739
  if (earliestRows.length > 0 || latestRow) {
704978
705740
  return {
704979
705741
  earliest: earliestRows.map(
704980
- (row) => this.telegramSqliteRowToHistoryEntry(row)
705742
+ (row2) => this.telegramSqliteRowToHistoryEntry(row2)
704981
705743
  ),
704982
705744
  latest: latestRow ? this.telegramSqliteRowToHistoryEntry(latestRow) : void 0
704983
705745
  };
@@ -705044,17 +705806,17 @@ ${lines.join("\n")}`;
705044
705806
  LIMIT ?
705045
705807
  `
705046
705808
  ).all(...params, limit);
705047
- return rows.map((row) => {
705048
- const role = row.role === "assistant" ? "assistant" : "user";
705049
- const fromUserId = Number(row.from_user_id);
705050
- const isBot = role === "assistant" || row.from_is_bot === 1 || row.from_is_bot === true;
705051
- const speaker = role === "assistant" ? `@${this.state.botUsername || row.username || "omnius"}` : row.username ? `@${row.username}` : Number.isFinite(fromUserId) ? isBot ? `bot:${fromUserId}` : `user:${fromUserId}` : row.first_name || "unknown";
705052
- const firstTs = Number(row.first_ts);
705053
- const lastTs = Number(row.last_ts);
705809
+ return rows.map((row2) => {
705810
+ const role = row2.role === "assistant" ? "assistant" : "user";
705811
+ const fromUserId = Number(row2.from_user_id);
705812
+ const isBot = role === "assistant" || row2.from_is_bot === 1 || row2.from_is_bot === true;
705813
+ const speaker = role === "assistant" ? `@${this.state.botUsername || row2.username || "omnius"}` : row2.username ? `@${row2.username}` : Number.isFinite(fromUserId) ? isBot ? `bot:${fromUserId}` : `user:${fromUserId}` : row2.first_name || "unknown";
705814
+ const firstTs = Number(row2.first_ts);
705815
+ const lastTs = Number(row2.last_ts);
705054
705816
  return {
705055
705817
  speaker,
705056
705818
  isBot,
705057
- count: Number(row.n) || 0,
705819
+ count: Number(row2.n) || 0,
705058
705820
  firstTs: Number.isFinite(firstTs) ? firstTs : void 0,
705059
705821
  lastTs: Number.isFinite(lastTs) ? lastTs : void 0
705060
705822
  };
@@ -705110,9 +705872,9 @@ ${lines.join("\n")}`;
705110
705872
  );
705111
705873
  const rows = /* @__PURE__ */ new Map();
705112
705874
  const addRows = (items) => {
705113
- for (const row of items) {
705114
- const key = Number(row.rowid);
705115
- if (Number.isFinite(key)) rows.set(key, row);
705875
+ for (const row2 of items) {
705876
+ const key = Number(row2.rowid);
705877
+ if (Number.isFinite(key)) rows.set(key, row2);
705116
705878
  }
705117
705879
  };
705118
705880
  const baseWhere = (extraClauses = [], extraParams = []) => {
@@ -705191,13 +705953,13 @@ ${lines.join("\n")}`;
705191
705953
  }).slice(0, limit);
705192
705954
  }
705193
705955
  formatTelegramSqliteMirrorRows(rows, maxText = 260) {
705194
- return rows.map((row) => {
705195
- const when = row.received_at ? new Date(Number(row.received_at)).toISOString() : "";
705196
- const speaker = row.role === "assistant" ? `@${this.state.botUsername || "omnius"}` : row.username ? `@${row.username}` : row.from_user_id ? this.telegramSqliteRowIsBot(row) ? `bot:${row.from_user_id}` : `user:${row.from_user_id}` : "unknown";
705197
- const kind = row.role === "assistant" || this.telegramSqliteRowIsBot(row) ? "bot" : "human";
705198
- const reply = row.reply_to_message_id ? ` reply_to:${row.reply_to_message_id}` : "";
705199
- const media = row.media_json ? " media:attached" : "";
705200
- return `- ${when} ${speaker}/${row.role || "user"} [${kind}] msg:${row.message_id}${reply}${media}: ${telegramContextJsonString(String(row.text || ""), maxText)}`;
705956
+ return rows.map((row2) => {
705957
+ const when = row2.received_at ? new Date(Number(row2.received_at)).toISOString() : "";
705958
+ const speaker = row2.role === "assistant" ? `@${this.state.botUsername || "omnius"}` : row2.username ? `@${row2.username}` : row2.from_user_id ? this.telegramSqliteRowIsBot(row2) ? `bot:${row2.from_user_id}` : `user:${row2.from_user_id}` : "unknown";
705959
+ const kind = row2.role === "assistant" || this.telegramSqliteRowIsBot(row2) ? "bot" : "human";
705960
+ const reply = row2.reply_to_message_id ? ` reply_to:${row2.reply_to_message_id}` : "";
705961
+ const media = row2.media_json ? " media:attached" : "";
705962
+ return `- ${when} ${speaker}/${row2.role || "user"} [${kind}] msg:${row2.message_id}${reply}${media}: ${telegramContextJsonString(String(row2.text || ""), maxText)}`;
705201
705963
  }).join("\n");
705202
705964
  }
705203
705965
  searchTelegramEpisodeMemory(sessionKey, query, limit = 8) {
@@ -712613,20 +713375,20 @@ Scoped workspace: ${scopedRoot}`,
712613
713375
  };
712614
713376
  }
712615
713377
  async deleteTelegramMessages(chatId, messageIds, currentMsg) {
712616
- const unique2 = [...new Set(messageIds)].filter((id2) => Number.isFinite(id2));
712617
- if (unique2.length === 0)
713378
+ const unique3 = [...new Set(messageIds)].filter((id2) => Number.isFinite(id2));
713379
+ if (unique3.length === 0)
712618
713380
  throw new Error(
712619
713381
  "deleteTelegramMessages requires at least one message id."
712620
713382
  );
712621
713383
  await this.assertTelegramBotRightsForAction(
712622
713384
  "delete_messages",
712623
713385
  chatId,
712624
- unique2,
713386
+ unique3,
712625
713387
  currentMsg
712626
713388
  );
712627
713389
  const chunks = [];
712628
- for (let idx = 0; idx < unique2.length; idx += 100)
712629
- chunks.push(unique2.slice(idx, idx + 100));
713390
+ for (let idx = 0; idx < unique3.length; idx += 100)
713391
+ chunks.push(unique3.slice(idx, idx + 100));
712630
713392
  const results = [];
712631
713393
  for (const chunk of chunks) {
712632
713394
  const result = await this.apiCall("deleteMessages", {
@@ -712644,9 +713406,9 @@ Scoped workspace: ${scopedRoot}`,
712644
713406
  telegram_method: "deleteMessages",
712645
713407
  ok: true,
712646
713408
  chat_id: chatId,
712647
- message_ids: unique2,
713409
+ message_ids: unique3,
712648
713410
  batches: results,
712649
- bot_rights_checked: !this.telegramTargetLooksPrivate(chatId, currentMsg) && !unique2.every((id2) => this.isKnownAssistantTelegramMessage(chatId, id2)),
713411
+ bot_rights_checked: !this.telegramTargetLooksPrivate(chatId, currentMsg) && !unique3.every((id2) => this.isKnownAssistantTelegramMessage(chatId, id2)),
712650
713412
  policy_scope: this.telegramToolPolicy.chatOverrides?.[String(chatId)] ? "chat" : "global/default"
712651
713413
  };
712652
713414
  }
@@ -715520,9 +716282,9 @@ function pushShellLiveLine(state, line) {
715520
716282
  }
715521
716283
  }
715522
716284
  function contentRow2(value2, inner) {
715523
- return `│ ${fit3(value2, inner)} │`;
716285
+ return `│ ${fit4(value2, inner)} │`;
715524
716286
  }
715525
- function fit3(value2, width) {
716287
+ function fit4(value2, width) {
715526
716288
  const plain = value2.replace(ANSI_OR_OSC_RE, "").replace(/\s+$/g, "");
715527
716289
  const chars = Array.from(plain);
715528
716290
  if (chars.length > width) {
@@ -715595,8 +716357,8 @@ function gibberishTokenPenalty(s2) {
715595
716357
  const tokens = s2.trim().split(/\s+/).filter(Boolean);
715596
716358
  if (tokens.length < 2) return 0;
715597
716359
  let penalty = 0;
715598
- const unique2 = new Set(tokens.map((t2) => t2.toLowerCase()));
715599
- const uniqueRatio = unique2.size / tokens.length;
716360
+ const unique3 = new Set(tokens.map((t2) => t2.toLowerCase()));
716361
+ const uniqueRatio = unique3.size / tokens.length;
715600
716362
  if (tokens.length >= 4 && uniqueRatio <= 0.5) {
715601
716363
  penalty += Math.min(1, (0.5 - uniqueRatio) * 2 + 0.5);
715602
716364
  }
@@ -717291,15 +718053,15 @@ var init_mouse_filter = __esm({
717291
718053
  const hasMarker = Boolean(match[1]);
717292
718054
  const btn = parseInt(match[2], 10);
717293
718055
  const col = parseInt(match[3], 10);
717294
- const row = parseInt(match[4], 10);
718056
+ const row2 = parseInt(match[4], 10);
717295
718057
  const suffix = match[5];
717296
- if (!Number.isFinite(btn) || !Number.isFinite(col) || !Number.isFinite(row))
718058
+ if (!Number.isFinite(btn) || !Number.isFinite(col) || !Number.isFinite(row2))
717297
718059
  return null;
717298
- if (col <= 0 || row <= 0) return null;
718060
+ if (col <= 0 || row2 <= 0) return null;
717299
718061
  if (!hasMarker && Date.now() > this.expectPrefixlessMouseUntil && !this.isKnownMouseButton(btn))
717300
718062
  return null;
717301
718063
  if (btn < 0 || btn > 255) return null;
717302
- return { raw: match[0], btn, col, row, suffix };
718064
+ return { raw: match[0], btn, col, row: row2, suffix };
717303
718065
  }
717304
718066
  looksLikePartialPrefixlessSgrMouse(input) {
717305
718067
  if (input.length < 2) return false;
@@ -717317,21 +718079,21 @@ var init_mouse_filter = __esm({
717317
718079
  return false;
717318
718080
  }
717319
718081
  handleSgrMouse(mouse) {
717320
- const { btn, col, row, suffix } = mouse;
718082
+ const { btn, col, row: row2, suffix } = mouse;
717321
718083
  if ((btn === 64 || btn === 96) && this.onScroll)
717322
- this.onScroll("up", 3, row);
718084
+ this.onScroll("up", 3, row2);
717323
718085
  else if ((btn === 65 || btn === 97) && this.onScroll)
717324
- this.onScroll("down", 3, row);
718086
+ this.onScroll("down", 3, row2);
717325
718087
  else if (this.onPointer) {
717326
718088
  const hasShift = (btn & 4) !== 0 && btn < 32;
717327
718089
  if (btn === 2) {
717328
718090
  } else if (hasShift) {
717329
718091
  } else if ((btn === 0 || btn === 1) && suffix === "M") {
717330
- this.onPointer("press", col, row);
718092
+ this.onPointer("press", col, row2);
717331
718093
  } else if (btn >= 32 && btn <= 35 && suffix === "M") {
717332
- this.onPointer("drag", col, row);
718094
+ this.onPointer("drag", col, row2);
717333
718095
  } else if (suffix === "m") {
717334
- this.onPointer("release", col, row);
718096
+ this.onPointer("release", col, row2);
717335
718097
  }
717336
718098
  }
717337
718099
  if (this.onActivity) this.onActivity();
@@ -717687,10 +718449,10 @@ var init_direct_input = __esm({
717687
718449
  const hasMarker = Boolean(match[1]);
717688
718450
  const btn = parseInt(match[2], 10);
717689
718451
  const col = parseInt(match[3], 10);
717690
- const row = parseInt(match[4], 10);
717691
- if (!Number.isFinite(btn) || !Number.isFinite(col) || !Number.isFinite(row))
718452
+ const row2 = parseInt(match[4], 10);
718453
+ if (!Number.isFinite(btn) || !Number.isFinite(col) || !Number.isFinite(row2))
717692
718454
  return null;
717693
- if (btn < 0 || btn > 255 || col <= 0 || row <= 0) return null;
718455
+ if (btn < 0 || btn > 255 || col <= 0 || row2 <= 0) return null;
717694
718456
  if (!hasMarker && Date.now() > this._expectPrefixlessMouseUntil && !this._isKnownMouseButton(btn))
717695
718457
  return null;
717696
718458
  return { length: match[0].length };
@@ -748773,7 +749535,12 @@ function wireAgentToolMinimal(tool, config, repoRoot) {
748773
749535
  const workerSystem = opts.agentType ? buildSubAgentSystemPrompt(opts.agentType, {
748774
749536
  task: opts.task,
748775
749537
  focusFiles: opts.focusFiles,
748776
- exitCriterion: opts.exitCriterion
749538
+ exitCriterion: opts.exitCriterion,
749539
+ trajectory: scopeTrajectoryCheckpoint(
749540
+ _activeRunnerRef?.getTrajectoryCheckpoint?.() ?? null,
749541
+ opts.task,
749542
+ opts.exitCriterion ?? "Return a compact result with a tool observation that verifies it."
749543
+ )
748777
749544
  }) : opts.systemPromptAddition;
748778
749545
  const systemCtx = workerSystem ? `Working directory: ${repoRoot}
748779
749546
 
@@ -749467,6 +750234,11 @@ function formatSubAgentEventForView(event) {
749467
750234
  const t2 = (event.content ?? "").trim();
749468
750235
  return t2 ? `· ${truncateSubAgentViewText(t2, 300)}` : null;
749469
750236
  }
750237
+ case "trajectory_checkpoint": {
750238
+ const assessment = event.trajectory?.assessment ?? "updated";
750239
+ const next = event.trajectory?.nextAction ?? "";
750240
+ return `↗ trajectory ${assessment}: ${truncateSubAgentViewText(next, 300)}`;
750241
+ }
749470
750242
  case "error": {
749471
750243
  const t2 = (event.content ?? "").trim();
749472
750244
  return t2 ? `✗ ${truncateSubAgentViewText(t2, 400)}` : null;
@@ -751977,6 +752749,9 @@ ${entry.fullContent}`
751977
752749
  }
751978
752750
  case "user_interrupt":
751979
752751
  break;
752752
+ case "trajectory_checkpoint":
752753
+ statusBar?.updateTrajectoryCheckpoint(event.trajectory ?? null);
752754
+ break;
751980
752755
  case "compaction":
751981
752756
  if (isNeovimActive()) {
751982
752757
  writeToNeovimOutput("\x1B[33m⚠ Context compacted\x1B[0m\r\n");
@@ -752204,6 +752979,7 @@ When done, either call task_complete with your answer, or use FINAL_VAR(variable
752204
752979
  }
752205
752980
  }
752206
752981
  resetSessionLock();
752982
+ statusBar?.updateTrajectoryCheckpoint(null);
752207
752983
  const promise = Promise.resolve(
752208
752984
  runWithOmniusContext(
752209
752985
  {
@@ -752481,6 +753257,14 @@ When done, either call task_complete with your answer, or use FINAL_VAR(variable
752481
753257
  cleanForStorage(result.summary)
752482
753258
  );
752483
753259
  }
753260
+ const finalTrajectory = runner.getTrajectoryCheckpoint();
753261
+ const trajectoryOrientation = finalTrajectory ? {
753262
+ revision: finalTrajectory.revision,
753263
+ assessment: finalTrajectory.assessment,
753264
+ nextAction: cleanForStorage(finalTrajectory.nextAction).slice(0, 360),
753265
+ successEvidence: cleanForStorage(finalTrajectory.successEvidence).slice(0, 360),
753266
+ doNotRepeat: finalTrajectory.doNotRepeat.slice(0, 3).map((item) => cleanForStorage(item).slice(0, 220)).filter(Boolean)
753267
+ } : void 0;
752484
753268
  try {
752485
753269
  saveSession(repoRoot, {
752486
753270
  id: sessionId,
@@ -752508,7 +753292,8 @@ When done, either call task_complete with your answer, or use FINAL_VAR(variable
752508
753292
  completed: result.completed,
752509
753293
  model: config.model,
752510
753294
  source: "task_complete",
752511
- sessionId
753295
+ sessionId,
753296
+ ...trajectoryOrientation ? { trajectory: trajectoryOrientation } : {}
752512
753297
  });
752513
753298
  } catch {
752514
753299
  }
@@ -752563,7 +753348,8 @@ When done, either call task_complete with your answer, or use FINAL_VAR(variable
752563
753348
  buildSucceeded: validationStatus.buildSucceeded
752564
753349
  },
752565
753350
  eligible: result.completed,
752566
- handoffAt: (/* @__PURE__ */ new Date()).toISOString()
753351
+ handoffAt: (/* @__PURE__ */ new Date()).toISOString(),
753352
+ ...trajectoryOrientation ? { trajectory: trajectoryOrientation } : {}
752567
753353
  };
752568
753354
  writeTaskHandoff2(repoRoot, handoff);
752569
753355
  } catch {
@@ -753264,7 +754050,12 @@ async function startInteractive(config, repoPath2) {
753264
754050
  const workerSystem = opts.agentType ? buildSubAgentSystemPrompt(opts.agentType, {
753265
754051
  task: opts.task,
753266
754052
  focusFiles: opts.focusFiles,
753267
- exitCriterion: opts.exitCriterion
754053
+ exitCriterion: opts.exitCriterion,
754054
+ trajectory: scopeTrajectoryCheckpoint(
754055
+ _activeRunnerRef?.getTrajectoryCheckpoint?.() ?? null,
754056
+ opts.task,
754057
+ opts.exitCriterion ?? "Return a compact result with a tool observation that verifies it."
754058
+ )
753268
754059
  }) : opts.systemPromptAddition;
753269
754060
  const systemCtx = workerSystem ? `Working directory: ${repoRoot}
753270
754061
 
@@ -754147,10 +754938,10 @@ This is an independent background session started from /background.`
754147
754938
  const { MouseFilterStream: MouseFilterStream2 } = await Promise.resolve().then(() => (init_mouse_filter(), mouse_filter_exports));
754148
754939
  let origTtyWriteRef = null;
754149
754940
  const mouseFilter = new MouseFilterStream2(
754150
- (direction, lines, row) => {
754941
+ (direction, lines, row2) => {
754151
754942
  const fh = statusBar._currentFooterHeight ?? 3;
754152
754943
  const footerStart = termRows() - fh + 1;
754153
- if (row >= footerStart) {
754944
+ if (row2 >= footerStart) {
754154
754945
  const arrowKey = direction === "up" ? { name: "up" } : { name: "down" };
754155
754946
  const arrowSeq = direction === "up" ? "\x1B[A" : "\x1B[B";
754156
754947
  origTtyWriteRef?.(arrowSeq, arrowKey);
@@ -754163,8 +754954,8 @@ This is an independent background session started from /background.`
754163
754954
  statusBar.cancelMouseIdle();
754164
754955
  statusBar.enableMouseTracking();
754165
754956
  },
754166
- (type, col, row) => {
754167
- statusBar.handlePointerEvent(type, col, row);
754957
+ (type, col, row2) => {
754958
+ statusBar.handlePointerEvent(type, col, row2);
754168
754959
  },
754169
754960
  () => {
754170
754961
  }