omnius 1.0.386 → 1.0.388

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
@@ -1033,8 +1033,8 @@ var init_model_broker = __esm({
1033
1033
  }
1034
1034
  /** Restore a set of previously evicted Ollama models, oldest first. */
1035
1035
  async restoreOllamaModels(models, options2 = {}) {
1036
- const unique3 = dedupeLoadedModels(models.filter((m2) => m2.host === "ollama")).sort((a2, b) => a2.lastUsedAt - b.lastUsedAt);
1037
- for (const model of unique3) {
1036
+ const unique2 = dedupeLoadedModels(models.filter((m2) => m2.host === "ollama")).sort((a2, b) => a2.lastUsedAt - b.lastUsedAt);
1037
+ for (const model of unique2) {
1038
1038
  await this.warmOllamaModel(model.name, options2.keepAlive ?? "30m").catch(() => false);
1039
1039
  }
1040
1040
  }
@@ -6389,22 +6389,22 @@ function firstString(args, keys) {
6389
6389
  return null;
6390
6390
  }
6391
6391
  function decodeBase64Text(raw, source) {
6392
- const compact3 = raw.replace(/\s+/g, "").replace(/-/g, "+").replace(/_/g, "/");
6393
- if (compact3.length > 0 && /[^A-Za-z0-9+/=]/.test(compact3)) {
6392
+ const compact4 = raw.replace(/\s+/g, "").replace(/-/g, "+").replace(/_/g, "/");
6393
+ if (compact4.length > 0 && /[^A-Za-z0-9+/=]/.test(compact4)) {
6394
6394
  return {
6395
6395
  ok: false,
6396
6396
  reason: "invalid",
6397
6397
  error: `${source} is not valid base64: contains characters outside the base64 alphabet.`
6398
6398
  };
6399
6399
  }
6400
- if (compact3.length % 4 === 1) {
6400
+ if (compact4.length % 4 === 1) {
6401
6401
  return {
6402
6402
  ok: false,
6403
6403
  reason: "invalid",
6404
6404
  error: `${source} is not valid base64: invalid length.`
6405
6405
  };
6406
6406
  }
6407
- const padded = compact3.padEnd(Math.ceil(compact3.length / 4) * 4, "=");
6407
+ const padded = compact4.padEnd(Math.ceil(compact4.length / 4) * 4, "=");
6408
6408
  let bytes;
6409
6409
  try {
6410
6410
  bytes = Buffer.from(padded, "base64");
@@ -6416,7 +6416,7 @@ function decodeBase64Text(raw, source) {
6416
6416
  };
6417
6417
  }
6418
6418
  const canonical = bytes.toString("base64").replace(/=+$/g, "");
6419
- if (compact3.replace(/=+$/g, "") !== canonical) {
6419
+ if (compact4.replace(/=+$/g, "") !== canonical) {
6420
6420
  return {
6421
6421
  ok: false,
6422
6422
  reason: "invalid",
@@ -14274,8 +14274,8 @@ var init_unifiedMemoryStore = __esm({
14274
14274
  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 }));
14275
14275
  }
14276
14276
  recordAccess(itemIds) {
14277
- const unique3 = [...new Set(itemIds)].filter(Boolean);
14278
- if (unique3.length === 0)
14277
+ const unique2 = [...new Set(itemIds)].filter(Boolean);
14278
+ if (unique2.length === 0)
14279
14279
  return;
14280
14280
  const update2 = this.db.prepare(`
14281
14281
  UPDATE memory_item
@@ -14285,7 +14285,7 @@ var init_unifiedMemoryStore = __esm({
14285
14285
  `);
14286
14286
  const now2 = this.nowIso();
14287
14287
  const txn = this.db.transaction(() => {
14288
- for (const id of unique3)
14288
+ for (const id of unique2)
14289
14289
  update2.run(now2, id);
14290
14290
  });
14291
14291
  txn();
@@ -25024,7 +25024,7 @@ var init_list_directory = __esm({
25024
25024
  ListDirectoryTool = class {
25025
25025
  name = "list_directory";
25026
25026
  aliases = ["ls", "dir"];
25027
- description = "List files and directories at a given path. Shows file sizes and types. Output includes full relative paths you can use directly in subsequent tool calls.";
25027
+ description = "List files and directories at a given path. Shows file sizes and types. Output includes full relative paths.";
25028
25028
  parameters = {
25029
25029
  type: "object",
25030
25030
  properties: {
@@ -25075,20 +25075,12 @@ var init_list_directory = __esm({
25075
25075
  }
25076
25076
  if (dirs.length > 0 || files.length > 0) {
25077
25077
  lines.push("");
25078
- lines.push("Next steps use these exact paths:");
25078
+ lines.push("Discovered child paths (data only):");
25079
25079
  if (dirs.length > 0) {
25080
- for (const d2 of dirs.slice(0, 8)) {
25081
- lines.push(` list_directory("${d2}")`);
25082
- }
25083
- if (dirs.length > 8)
25084
- lines.push(` ... and ${dirs.length - 8} more directories`);
25080
+ lines.push(` directories: ${dirs.slice(0, 8).join(", ")}${dirs.length > 8 ? ` (+${dirs.length - 8} more)` : ""}`);
25085
25081
  }
25086
25082
  if (files.length > 0) {
25087
- for (const f2 of files.slice(0, 5)) {
25088
- lines.push(` file_read("${f2}")`);
25089
- }
25090
- if (files.length > 5)
25091
- lines.push(` ... and ${files.length - 5} more files`);
25083
+ lines.push(` files: ${files.slice(0, 8).join(", ")}${files.length > 8 ? ` (+${files.length - 8} more)` : ""}`);
25092
25084
  }
25093
25085
  }
25094
25086
  return {
@@ -25126,7 +25118,7 @@ var init_list_directory = __esm({
25126
25118
  const remaining = entries.filter((entry) => !kgSummaries.includes(entry));
25127
25119
  const syntheticLines = [
25128
25120
  `g ${dirPath}/kg-summary-*.md ${kgSummaries.length} generated summaries collapsed, ${totalBytes} bytes`,
25129
- ` latest generated summary: file_read("${latestPath}")`
25121
+ ` latest generated summary path: ${latestPath}`
25130
25122
  ];
25131
25123
  return { entries: remaining, syntheticLines };
25132
25124
  }
@@ -294005,27 +293997,27 @@ function compactWorkboardSnapshot(snapshot, maxCards = 24) {
294005
293997
  };
294006
293998
  }
294007
293999
  function formatWorkboardCompact(snapshot, maxCards = 24) {
294008
- const compact3 = compactWorkboardSnapshot(snapshot, maxCards);
294000
+ const compact4 = compactWorkboardSnapshot(snapshot, maxCards);
294009
294001
  const lines = [
294010
- `Workboard ${compact3.runId} [${compact3.status}] owner=${compact3.owner} updated=${compact3.updatedAt}`,
294011
- `Counts: open=${compact3.counts.open}, in_progress=${compact3.counts.in_progress}, needs_changes=${compact3.counts.needs_changes}, blocked=${compact3.counts.blocked}, completed=${compact3.counts.completed}, verified=${compact3.counts.verified}`
294002
+ `Workboard ${compact4.runId} [${compact4.status}] owner=${compact4.owner} updated=${compact4.updatedAt}`,
294003
+ `Counts: open=${compact4.counts.open}, in_progress=${compact4.counts.in_progress}, needs_changes=${compact4.counts.needs_changes}, blocked=${compact4.counts.blocked}, completed=${compact4.counts.completed}, verified=${compact4.counts.verified}`
294012
294004
  ];
294013
- if (compact3.cards.length === 0) {
294005
+ if (compact4.cards.length === 0) {
294014
294006
  lines.push("Cards: none");
294015
294007
  } else {
294016
294008
  lines.push("Cards:");
294017
- for (const card of compact3.cards) {
294009
+ for (const card of compact4.cards) {
294018
294010
  const assignee = card.assignee ? ` assignee=${card.assignee}` : "";
294019
294011
  const deps = card.dependencies.length > 0 ? ` deps=${card.dependencies.join(",")}` : "";
294020
294012
  const blocker = card.blocker ? ` blocker=${card.blocker}` : "";
294021
294013
  lines.push(`- ${card.id} [${card.status}/${card.lane}]${assignee} evidence=${card.evidenceCount}${deps}: ${card.title}${blocker}`);
294022
294014
  }
294023
294015
  }
294024
- if (compact3.hiddenCardCount > 0)
294025
- lines.push(`Hidden cards: ${compact3.hiddenCardCount}`);
294026
- if (compact3.diagnostics.length > 0) {
294016
+ if (compact4.hiddenCardCount > 0)
294017
+ lines.push(`Hidden cards: ${compact4.hiddenCardCount}`);
294018
+ if (compact4.diagnostics.length > 0) {
294027
294019
  lines.push("Diagnostics:");
294028
- for (const diagnostic of compact3.diagnostics) {
294020
+ for (const diagnostic of compact4.diagnostics) {
294029
294021
  lines.push(`- ${diagnostic.code} ${diagnostic.severity}${diagnostic.cardId ? ` card=${diagnostic.cardId}` : ""}: ${diagnostic.message}`);
294030
294022
  }
294031
294023
  }
@@ -294857,11 +294849,11 @@ var init_workboard = __esm({
294857
294849
  mutated: false
294858
294850
  };
294859
294851
  }
294860
- const compact3 = formatWorkboardCompact(snapshot, maxCards);
294852
+ const compact4 = formatWorkboardCompact(snapshot, maxCards);
294861
294853
  return {
294862
294854
  success: true,
294863
- output: compact3,
294864
- llmContent: compact3,
294855
+ output: compact4,
294856
+ llmContent: compact4,
294865
294857
  durationMs: performance.now() - start2,
294866
294858
  mutated: false
294867
294859
  };
@@ -298879,7 +298871,7 @@ var require_typescript = __commonJS({
298879
298871
  commandLineOptionOfCustomType: () => commandLineOptionOfCustomType,
298880
298872
  commentPragmas: () => commentPragmas,
298881
298873
  commonOptionsWithBuild: () => commonOptionsWithBuild,
298882
- compact: () => compact3,
298874
+ compact: () => compact4,
298883
298875
  compareBooleans: () => compareBooleans,
298884
298876
  compareComparableValues: () => compareComparableValues,
298885
298877
  compareDataObjects: () => compareDataObjects,
@@ -301394,7 +301386,7 @@ var require_typescript = __commonJS({
301394
301386
  }
301395
301387
  return true;
301396
301388
  }
301397
- function compact3(array) {
301389
+ function compact4(array) {
301398
301390
  let result;
301399
301391
  if (array !== void 0) {
301400
301392
  for (let i2 = 0; i2 < array.length; i2++) {
@@ -407465,7 +407457,7 @@ ${lanes.join("\n")}
407465
407457
  node.operatorToken,
407466
407458
  visitNode(node.right, visitor, isExpression)
407467
407459
  );
407468
- const expr = some(pendingExpressions) ? factory2.inlineExpressions(compact3([...pendingExpressions, node])) : node;
407460
+ const expr = some(pendingExpressions) ? factory2.inlineExpressions(compact4([...pendingExpressions, node])) : node;
407469
407461
  pendingExpressions = savedPendingExpressions;
407470
407462
  return expr;
407471
407463
  }
@@ -427734,7 +427726,7 @@ ${lanes.join("\n")}
427734
427726
  let parameterProperties;
427735
427727
  if (ctor) {
427736
427728
  const oldDiag2 = getSymbolAccessibilityDiagnostic;
427737
- parameterProperties = compact3(flatMap(ctor.parameters, (param) => {
427729
+ parameterProperties = compact4(flatMap(ctor.parameters, (param) => {
427738
427730
  if (!hasSyntacticModifier(
427739
427731
  param,
427740
427732
  31
@@ -464815,7 +464807,7 @@ ${newComment.split("\n").map((c8) => ` * ${c8}`).join("\n")}
464815
464807
  }
464816
464808
  const checker = context2.program.getTypeChecker();
464817
464809
  const trackChanges = (cb) => ts_textChanges_exports.ChangeTracker.with(context2, cb);
464818
- return compact3([
464810
+ return compact4([
464819
464811
  getDeclarationSiteFix(context2, expression, errorCode, checker, trackChanges),
464820
464812
  getUseSiteFix(context2, expression, errorCode, checker, trackChanges)
464821
464813
  ]);
@@ -488406,7 +488398,7 @@ ${content}
488406
488398
  const lastToken = last2(children2);
488407
488399
  const separateLastToken = separateTrailingSemicolon && lastToken.kind === 27;
488408
488400
  const rightChildren = children2.slice(splitTokenIndex + 1, separateLastToken ? children2.length - 1 : void 0);
488409
- const result = compact3([
488401
+ const result = compact4([
488410
488402
  leftChildren.length ? createSyntaxList2(leftChildren) : void 0,
488411
488403
  splitToken,
488412
488404
  rightChildren.length ? createSyntaxList2(rightChildren) : void 0
@@ -495130,7 +495122,7 @@ ${options2.prefix}` : "\n" : options2.prefix
495130
495122
  commandLineOptionOfCustomType: () => commandLineOptionOfCustomType,
495131
495123
  commentPragmas: () => commentPragmas,
495132
495124
  commonOptionsWithBuild: () => commonOptionsWithBuild,
495133
- compact: () => compact3,
495125
+ compact: () => compact4,
495134
495126
  compareBooleans: () => compareBooleans,
495135
495127
  compareComparableValues: () => compareComparableValues,
495136
495128
  compareDataObjects: () => compareDataObjects,
@@ -498681,11 +498673,11 @@ ${options2.prefix}` : "\n" : options2.prefix
498681
498673
  return true;
498682
498674
  }
498683
498675
  const set = /* @__PURE__ */ new Map();
498684
- let unique3 = 0;
498676
+ let unique2 = 0;
498685
498677
  for (const v of arr1) {
498686
498678
  if (set.get(v) !== true) {
498687
498679
  set.set(v, true);
498688
- unique3++;
498680
+ unique2++;
498689
498681
  }
498690
498682
  }
498691
498683
  for (const v of arr2) {
@@ -498695,10 +498687,10 @@ ${options2.prefix}` : "\n" : options2.prefix
498695
498687
  }
498696
498688
  if (isSet === true) {
498697
498689
  set.set(v, false);
498698
- unique3--;
498690
+ unique2--;
498699
498691
  }
498700
498692
  }
498701
- return unique3 === 0;
498693
+ return unique2 === 0;
498702
498694
  }
498703
498695
  function typeAcquisitionChanged(opt1, opt2) {
498704
498696
  return opt1.enable !== opt2.enable || !setIsEqualTo(opt1.include, opt2.include) || !setIsEqualTo(opt1.exclude, opt2.exclude);
@@ -559395,9 +559387,9 @@ function deriveClaimsFromProposedText(input) {
559395
559387
  if (!raw)
559396
559388
  return [];
559397
559389
  const segments = raw.replace(/\b(?:done|completed|verified)\s*:\s*/gi, "").split(/(?:\n+|;\s+|,\s+(?=(?:and\s+)?(?:sent|built|created|updated|published|verified|tested|fixed|added|removed|deployed|wrote)\b)|\.\s+)/i).map((part) => cleanText(part, 300)).filter((part) => part.length > 0);
559398
- const unique3 = Array.from(new Set(segments.length > 0 ? segments : [cleanText(raw, 300)]));
559390
+ const unique2 = Array.from(new Set(segments.length > 0 ? segments : [cleanText(raw, 300)]));
559399
559391
  const existingIds = new Set((input.existing ?? []).map((claim) => claim.id));
559400
- return unique3.map((text2, index) => {
559392
+ return unique2.map((text2, index) => {
559401
559393
  const base3 = normalizeCompletionKey(text2, `claim_${index + 1}`).slice(0, 64);
559402
559394
  let id = base3 || `claim_${index + 1}`;
559403
559395
  let suffix = 2;
@@ -559751,7 +559743,9 @@ function finalizeCompletionLedgerTruth(ledger) {
559751
559743
  unresolved = appendUnresolved(unresolved, `Stale edit failure remains unresolved: ${entry.summary}`, entry.id);
559752
559744
  }
559753
559745
  });
559754
- if (lastVerification >= 0 && lastVerificationInvalidatingMutation > lastVerification) {
559746
+ if (lastVerificationInvalidatingMutation >= 0 && lastVerification < 0) {
559747
+ unresolved = appendUnresolved(unresolved, "File changes occurred without any successful verification evidence.", "verification_missing");
559748
+ } else if (lastVerification >= 0 && lastVerificationInvalidatingMutation > lastVerification) {
559755
559749
  unresolved = appendUnresolved(unresolved, "File changes occurred after the last successful verification; final verification is stale.", "verification_freshness");
559756
559750
  }
559757
559751
  unresolved = appendTestCountOverclaims(ledger, unresolved);
@@ -569505,7 +569499,7 @@ function resolveFocusSupervisorMode(configured, envValue = process.env["OMNIUS_F
569505
569499
  }
569506
569500
  function violatesDirective(directive, input) {
569507
569501
  if (input.toolName === "task_complete") {
569508
- return directive.state === "terminal_incomplete";
569502
+ return directive.requiredNextAction !== "report_blocked" && directive.requiredNextAction !== "report_incomplete";
569509
569503
  }
569510
569504
  if (input.toolName === "ask_user")
569511
569505
  return false;
@@ -569554,27 +569548,137 @@ function isReportTool(toolName) {
569554
569548
  return toolName === "task_complete" || toolName === "ask_user";
569555
569549
  }
569556
569550
  function actionFamily(toolName, args) {
569557
- const target = args?.["path"] ?? args?.["file"] ?? args?.["filePath"] ?? args?.["file_path"] ?? args?.["command"] ?? args?.["cmd"] ?? "";
569558
- return `${toolName}:${normalizeTarget(String(target ?? "")) || "no-target"}`;
569551
+ if (isEditTool(toolName)) {
569552
+ const path12 = primaryPath(args);
569553
+ const target2 = editTargetDescriptor(toolName, args);
569554
+ return `${toolName}:${compactTarget(path12 || "no-path", 120)}:${compactTarget(target2 || "no-edit-target", 120)}`;
569555
+ }
569556
+ if (toolName === "shell") {
569557
+ const command = args?.["command"] ?? args?.["cmd"] ?? "";
569558
+ return `${toolName}:${compactTarget(String(command ?? "") || "no-command", 120)}`;
569559
+ }
569560
+ const target = primaryPath(args) ?? "";
569561
+ return `${toolName}:${compactTarget(String(target ?? "")) || "no-target"}`;
569559
569562
  }
569560
569563
  function failureFamilyKey(toolName, args, error, output) {
569561
- const sample = cleanFailureSample(error || output || "");
569562
- return `${actionFamily(toolName, args)}:${sample}`;
569564
+ const errorClass = failureErrorClass(error || output || "");
569565
+ return `${actionFamily(toolName, args)}:${errorClass}`;
569563
569566
  }
569564
569567
  function cleanFailureSample(text2) {
569565
569568
  return String(text2 || "").replace(/\s+/g, " ").trim().slice(0, 180);
569566
569569
  }
569567
- function normalizeTarget(text2) {
569568
- return text2.replace(/\s+/g, " ").trim().slice(0, 220);
569570
+ function failureErrorClass(text2) {
569571
+ const normalized = String(text2 || "").toLowerCase();
569572
+ if (/ambiguous|multiple occurrences|matches more than once/.test(normalized)) {
569573
+ return "stale_ambiguous_target";
569574
+ }
569575
+ if (/expected[_ -]?hash|hash mismatch|stale hash|beforehash|afterhash/.test(normalized)) {
569576
+ return "stale_expected_hash";
569577
+ }
569578
+ if (/expected.*content|content.*did not match|context mismatch|patch failed|hunk failed/.test(normalized)) {
569579
+ return "stale_expected_content";
569580
+ }
569581
+ if (/atomic.*abort|batch.*abort|skipped/.test(normalized)) {
569582
+ return "stale_atomic_batch_abort";
569583
+ }
569584
+ if (/old[_ -]?string|old text|old content|not found|no occurrences|0 occurrences|could not find/.test(normalized)) {
569585
+ return "stale_missing_target";
569586
+ }
569587
+ if (/permission|eacces|denied/.test(normalized))
569588
+ return "permission_denied";
569589
+ if (/timeout|timed out/.test(normalized))
569590
+ return "timeout";
569591
+ if (/exit code|non-zero|failed/.test(normalized))
569592
+ return "tool_failed";
569593
+ return compactTarget(cleanFailureSample(text2) || "unknown_failure", 80);
569569
569594
  }
569570
- function unique2(values) {
569571
- return [...new Set(values.filter((value2) => value2.trim().length > 0))];
569595
+ function primaryPath(args) {
569596
+ if (!args)
569597
+ return "";
569598
+ const direct = args["path"] ?? args["file"] ?? args["filePath"] ?? args["file_path"] ?? "";
569599
+ if (typeof direct === "string" && direct.trim())
569600
+ return direct.trim();
569601
+ const edits = args["edits"];
569602
+ if (Array.isArray(edits)) {
569603
+ for (const edit of edits) {
569604
+ if (!edit || typeof edit !== "object")
569605
+ continue;
569606
+ const rec = edit;
569607
+ const editPath = rec["path"] ?? rec["file"] ?? rec["filePath"] ?? rec["file_path"];
569608
+ if (typeof editPath === "string" && editPath.trim())
569609
+ return editPath.trim();
569610
+ }
569611
+ }
569612
+ return "";
569572
569613
  }
569573
- var directiveCounter, FocusSupervisor;
569614
+ function editTargetDescriptor(toolName, args) {
569615
+ if (!args)
569616
+ return "";
569617
+ const parts = [];
569618
+ for (const key of [
569619
+ "old_string",
569620
+ "oldString",
569621
+ "oldText",
569622
+ "search",
569623
+ "expected_old_string",
569624
+ "expectedHash",
569625
+ "expected_hash",
569626
+ "mode",
569627
+ "offset",
569628
+ "limit",
569629
+ "start_line"
569630
+ ]) {
569631
+ const value2 = args[key];
569632
+ if (typeof value2 === "string" || typeof value2 === "number") {
569633
+ parts.push(`${key}=${String(value2)}`);
569634
+ }
569635
+ }
569636
+ const edits = args["edits"];
569637
+ if (Array.isArray(edits)) {
569638
+ for (const edit of edits.slice(0, 6)) {
569639
+ if (!edit || typeof edit !== "object")
569640
+ continue;
569641
+ const rec = edit;
569642
+ const editPath = rec["path"] ?? rec["file"] ?? rec["filePath"] ?? rec["file_path"];
569643
+ const target = rec["old_string"] ?? rec["oldString"] ?? rec["oldText"] ?? rec["search"] ?? rec["expected_old_string"] ?? rec["offset"] ?? rec["start_line"] ?? "";
569644
+ parts.push(`${String(editPath ?? "")}=${String(target ?? "")}`);
569645
+ }
569646
+ }
569647
+ if (parts.length === 0 && toolName === "file_patch") {
569648
+ const newContent = args["new_content"] ?? args["patch"] ?? "";
569649
+ if (typeof newContent === "string" && newContent.trim()) {
569650
+ parts.push(`patch=${newContent.slice(0, 240)}`);
569651
+ }
569652
+ }
569653
+ return parts.join("\n").replace(/\s+/g, " ").trim();
569654
+ }
569655
+ function compactTarget(text2, max = 220) {
569656
+ const normalized = text2.replace(/\s+/g, " ").trim();
569657
+ if (normalized.length <= max)
569658
+ return normalized;
569659
+ return `${normalized.slice(0, Math.max(24, max - 18))}#${quickHash(normalized)}`;
569660
+ }
569661
+ function quickHash(input) {
569662
+ let hash = 2166136261;
569663
+ for (let index = 0; index < input.length; index++) {
569664
+ hash ^= input.charCodeAt(index);
569665
+ hash = Math.imul(hash, 16777619) >>> 0;
569666
+ }
569667
+ return hash.toString(16).padStart(8, "0");
569668
+ }
569669
+ function uniqueLimited(values) {
569670
+ const uniqueValues = [...new Set(values.filter((value2) => value2.trim().length > 0))];
569671
+ if (uniqueValues.length <= MAX_FORBIDDEN_FAMILIES)
569672
+ return uniqueValues;
569673
+ return uniqueValues.slice(-MAX_FORBIDDEN_FAMILIES);
569674
+ }
569675
+ var directiveCounter, TERMINAL_INCOMPLETE_IGNORE_THRESHOLD, MAX_FORBIDDEN_FAMILIES, FocusSupervisor;
569574
569676
  var init_focusSupervisor = __esm({
569575
569677
  "packages/orchestrator/dist/focusSupervisor.js"() {
569576
569678
  "use strict";
569577
569679
  directiveCounter = 0;
569680
+ TERMINAL_INCOMPLETE_IGNORE_THRESHOLD = 8;
569681
+ MAX_FORBIDDEN_FAMILIES = 12;
569578
569682
  FocusSupervisor = class {
569579
569683
  mode;
569580
569684
  modelTier;
@@ -569637,13 +569741,14 @@ var init_focusSupervisor = __esm({
569637
569741
  this.ignoredDirectiveStreak++;
569638
569742
  const strict = this.shouldStrictlyIntervene(input.context);
569639
569743
  if (strict && prior.ignoredCount >= 1) {
569744
+ const terminal = this.ignoredDirectiveStreak >= TERMINAL_INCOMPLETE_IGNORE_THRESHOLD;
569640
569745
  const ignoredManyTimes = this.ignoredDirectiveStreak >= 3;
569641
569746
  const directive = this.setDirective({
569642
569747
  turn: input.turn,
569643
- state: ignoredManyTimes ? "verify_or_block" : "single_next_action",
569644
- reason: ignoredManyTimes ? `model ignored ${this.ignoredDirectiveStreak} focus directives; take the required recovery action before trying another variant` : `model ignored prior directive ${prior.id}; ${prior.reason}`,
569645
- requiredNextAction: prior.requiredNextAction,
569646
- forbiddenActionFamilies: unique2([
569748
+ state: terminal ? "terminal_incomplete" : ignoredManyTimes ? "verify_or_block" : "single_next_action",
569749
+ reason: terminal ? `model ignored ${this.ignoredDirectiveStreak} focus directives with no satisfying recovery action; report incomplete with the blocker and evidence` : ignoredManyTimes ? `model ignored ${this.ignoredDirectiveStreak} focus directives; take the required recovery action before trying another variant` : `model ignored prior directive ${prior.id}; ${prior.reason}`,
569750
+ requiredNextAction: terminal ? "report_incomplete" : prior.requiredNextAction,
569751
+ forbiddenActionFamilies: uniqueLimited([
569647
569752
  ...prior.forbiddenActionFamilies,
569648
569753
  family
569649
569754
  ])
@@ -569652,7 +569757,7 @@ var init_focusSupervisor = __esm({
569652
569757
  `[FOCUS SUPERVISOR BLOCK] The previous directive was ignored: ${prior.reason}`,
569653
569758
  `Required next action: ${directive.requiredNextAction}.`,
569654
569759
  `Blocked action family: ${family}.`,
569655
- "Take the required next action, or report blocked/incomplete with evidence."
569760
+ directive.requiredNextAction === "report_incomplete" ? "Stop trying tool variants. Report incomplete/blocked with the concrete evidence." : "Take the required next action before trying another variant."
569656
569761
  ].join("\n"), false);
569657
569762
  }
569658
569763
  }
@@ -569738,15 +569843,17 @@ var init_focusSupervisor = __esm({
569738
569843
  const next = {
569739
569844
  count: (existing?.count ?? 0) + 1,
569740
569845
  lastTurn: input.turn,
569741
- sample: cleanFailureSample(input.error || input.output || "")
569846
+ sample: cleanFailureSample(input.error || input.output || ""),
569847
+ errorClass: failureErrorClass(input.error || input.output || "")
569742
569848
  };
569743
569849
  this.failureFamilies.set(family, next);
569744
569850
  if (next.count >= 2 && this.shouldStrictlyIntervene(this.lastContext)) {
569851
+ const staleEditFailure = isEditTool(input.toolName) && next.errorClass.startsWith("stale_");
569745
569852
  this.setDirective({
569746
569853
  turn: input.turn,
569747
569854
  state: "forced_replan",
569748
569855
  reason: `same ${input.toolName} failure family repeated ${next.count} times: ${next.sample}`,
569749
- requiredNextAction: input.toolName === "shell" ? "edit_different_target" : "update_todos",
569856
+ requiredNextAction: staleEditFailure ? "read_authoritative_target" : input.toolName === "shell" ? "edit_different_target" : "update_todos",
569750
569857
  forbiddenActionFamilies: [actionFamily(input.toolName, input.args)]
569751
569858
  });
569752
569859
  }
@@ -569770,7 +569877,7 @@ var init_focusSupervisor = __esm({
569770
569877
  state: "terminal_incomplete",
569771
569878
  reason,
569772
569879
  requiredNextAction: "report_incomplete",
569773
- forbiddenActionFamilies: ["brute_force", "task_complete"]
569880
+ forbiddenActionFamilies: ["brute_force"]
569774
569881
  });
569775
569882
  }
569776
569883
  shouldStrictlyIntervene(context2) {
@@ -569802,7 +569909,7 @@ var init_focusSupervisor = __esm({
569802
569909
  const stable = existing && existing.state === input.state && existing.reason === input.reason && existing.requiredNextAction === input.requiredNextAction;
569803
569910
  const directive = stable ? {
569804
569911
  ...existing,
569805
- forbiddenActionFamilies: unique2([
569912
+ forbiddenActionFamilies: uniqueLimited([
569806
569913
  ...existing.forbiddenActionFamilies,
569807
569914
  ...input.forbiddenActionFamilies
569808
569915
  ])
@@ -569811,7 +569918,7 @@ var init_focusSupervisor = __esm({
569811
569918
  state: input.state,
569812
569919
  reason: input.reason,
569813
569920
  requiredNextAction: input.requiredNextAction,
569814
- forbiddenActionFamilies: unique2(input.forbiddenActionFamilies),
569921
+ forbiddenActionFamilies: uniqueLimited(input.forbiddenActionFamilies),
569815
569922
  createdTurn: input.turn,
569816
569923
  ignoredCount: 0
569817
569924
  };
@@ -570589,24 +570696,132 @@ function estimateTokens3(messages2) {
570589
570696
  const chars = messages2.reduce((sum, message2) => sum + message2.content.length + message2.role.length + (message2.name?.length ?? 0), 0);
570590
570697
  return Math.ceil(chars / 4);
570591
570698
  }
570592
- function evidenceMessage(event) {
570699
+ function evidenceMessage(folded) {
570700
+ const event = folded.event;
570593
570701
  const status = event.success === true ? "ok" : event.success === false ? "failed" : "unknown";
570594
570702
  const parts = [
570595
570703
  `tool=${event.name}`,
570596
570704
  `status=${status}`,
570597
- typeof event.turn === "number" ? `turn=${event.turn}` : "",
570705
+ folded.count > 1 ? `turns=${folded.firstTurn ?? "?"}-${folded.lastTurn ?? "?"}` : typeof event.turn === "number" ? `turn=${event.turn}` : "",
570706
+ folded.count > 1 ? `repeats=${folded.count}` : "",
570598
570707
  event.evidenceId ? `evidence=${event.evidenceId}` : "",
570599
- event.outputPreview ? `observed=${event.outputPreview}` : ""
570708
+ event.outputPreview ? `observed=${observedPreview(event, folded.count)}` : ""
570600
570709
  ].filter(Boolean);
570601
570710
  return { role: "system", content: `[RUN EVIDENCE] ${parts.join(" ")}` };
570602
570711
  }
570712
+ function foldToolEvents(events) {
570713
+ const byFamily = /* @__PURE__ */ new Map();
570714
+ let folded = 0;
570715
+ for (const event of events) {
570716
+ const family = evidenceFamily(event);
570717
+ const existing = byFamily.get(family);
570718
+ if (existing) {
570719
+ folded++;
570720
+ existing.count++;
570721
+ existing.event = event;
570722
+ existing.lastTurn = event.turn ?? existing.lastTurn;
570723
+ continue;
570724
+ }
570725
+ byFamily.set(family, {
570726
+ event,
570727
+ count: 1,
570728
+ firstTurn: event.turn,
570729
+ lastTurn: event.turn
570730
+ });
570731
+ }
570732
+ const foldedMessages = [...byFamily.values()].map(evidenceMessage);
570733
+ let dropped = events.length - foldedMessages.length;
570734
+ let selected = foldedMessages;
570735
+ if (selected.length > MAX_EVIDENCE_MESSAGES) {
570736
+ dropped += selected.length - MAX_EVIDENCE_MESSAGES;
570737
+ selected = selected.slice(-MAX_EVIDENCE_MESSAGES);
570738
+ }
570739
+ let usedChars = 0;
570740
+ const budgeted = [];
570741
+ for (const message2 of [...selected].reverse()) {
570742
+ const cost = message2.content.length;
570743
+ if (usedChars + cost > MAX_EVIDENCE_CHARS && budgeted.length > 0) {
570744
+ dropped++;
570745
+ continue;
570746
+ }
570747
+ budgeted.push(message2);
570748
+ usedChars += cost;
570749
+ }
570750
+ return {
570751
+ messages: budgeted.reverse(),
570752
+ retained: budgeted.length,
570753
+ dropped,
570754
+ folded
570755
+ };
570756
+ }
570757
+ function evidenceFamily(event) {
570758
+ const status = event.success === true ? "ok" : event.success === false ? "failed" : "unknown";
570759
+ const preview = normalizePreview(event.outputPreview ?? "");
570760
+ if (preview.includes("[FOCUS SUPERVISOR BLOCK]")) {
570761
+ return `synthetic-focus-block:${event.name}:${status}`;
570762
+ }
570763
+ if (preview.includes("[STALE EDIT LOOP BLOCKED]")) {
570764
+ return `stale-edit-block:${event.name}:${status}`;
570765
+ }
570766
+ if (event.success === false) {
570767
+ return `${event.name}:${status}:${failureClass(preview)}`;
570768
+ }
570769
+ const firstLine = preview.split("\n")[0] ?? preview;
570770
+ return `${event.name}:${status}:${quickHash2(firstLine.slice(0, 500))}`;
570771
+ }
570772
+ function observedPreview(event, repeatCount) {
570773
+ const preview = event.outputPreview ?? "";
570774
+ if (!preview)
570775
+ return "";
570776
+ if (preview.includes("[FOCUS SUPERVISOR BLOCK]")) {
570777
+ return repeatCount > 1 ? `Repeated focus-supervisor block. Latest: ${compact(preview, 700)}` : compact(preview, 700);
570778
+ }
570779
+ if (event.name === "list_directory" || event.name === "find_files") {
570780
+ return compact(preview, 900);
570781
+ }
570782
+ return compact(preview, 1200);
570783
+ }
570784
+ function failureClass(text2) {
570785
+ const normalized = text2.toLowerCase();
570786
+ if (/old[_ -]?string|old text|old content|not found|no occurrences|could not find/.test(normalized)) {
570787
+ return "stale-missing-target";
570788
+ }
570789
+ if (/focus supervisor block/.test(normalized))
570790
+ return "focus-block";
570791
+ if (/permission|eacces|denied/.test(normalized))
570792
+ return "permission";
570793
+ if (/timeout|timed out/.test(normalized))
570794
+ return "timeout";
570795
+ if (/exit code|non-zero|failed/.test(normalized))
570796
+ return "failed";
570797
+ return quickHash2(normalized.slice(0, 500));
570798
+ }
570799
+ function normalizePreview(text2) {
570800
+ return text2.replace(/\s+/g, " ").trim();
570801
+ }
570802
+ function compact(text2, max) {
570803
+ const normalized = text2.replace(/\s+/g, " ").trim();
570804
+ if (normalized.length <= max)
570805
+ return normalized;
570806
+ return `${normalized.slice(0, Math.max(24, max - 18))}#${quickHash2(normalized)}`;
570807
+ }
570808
+ function quickHash2(input) {
570809
+ let hash = 2166136261;
570810
+ for (let index = 0; index < input.length; index++) {
570811
+ hash ^= input.charCodeAt(index);
570812
+ hash = Math.imul(hash, 16777619) >>> 0;
570813
+ }
570814
+ return hash.toString(16).padStart(8, "0");
570815
+ }
570603
570816
  function createDefaultContextEngine() {
570604
570817
  return new DefaultContextEngine();
570605
570818
  }
570606
- var DefaultContextEngine;
570819
+ var MAX_EVIDENCE_MESSAGES, MAX_EVIDENCE_CHARS, DefaultContextEngine;
570607
570820
  var init_contextEngine = __esm({
570608
570821
  "packages/orchestrator/dist/contextEngine.js"() {
570609
570822
  "use strict";
570823
+ MAX_EVIDENCE_MESSAGES = 40;
570824
+ MAX_EVIDENCE_CHARS = 24e3;
570610
570825
  DefaultContextEngine = class {
570611
570826
  async build(input) {
570612
570827
  return this.render(input, false);
@@ -570615,7 +570830,8 @@ var init_contextEngine = __esm({
570615
570830
  return this.render(input, true);
570616
570831
  }
570617
570832
  render(input, allowCompaction) {
570618
- const evidence = (input.toolEvents ?? []).map(evidenceMessage);
570833
+ const foldedEvidence = foldToolEvents(input.toolEvents ?? []);
570834
+ const evidence = foldedEvidence.messages;
570619
570835
  const hints = (input.memoryHints ?? []).filter((hint) => hint.trim().length > 0).slice(-8).map((hint) => ({ role: "system", content: `[MEMORY HINT] ${hint.trim()}` }));
570620
570836
  const contract = input.runState?.completionContract ? [{ role: "system", content: input.runState.completionContract }] : [];
570621
570837
  const beforeMessages = [...evidence, ...hints, ...contract, ...input.messages];
@@ -570642,6 +570858,8 @@ var init_contextEngine = __esm({
570642
570858
  const allMessages = [...evidence, ...hints, ...contract, ...compactedMessages];
570643
570859
  const after = estimateTokens3(allMessages);
570644
570860
  return {
570861
+ messages: allMessages,
570862
+ compactedMessages,
570645
570863
  systemMessages: allMessages.filter((m2) => m2.role === "system"),
570646
570864
  conversationMessages: allMessages.filter((m2) => m2.role !== "system"),
570647
570865
  compacted,
@@ -570651,8 +570869,9 @@ var init_contextEngine = __esm({
570651
570869
  tokenEstimateAfter: after,
570652
570870
  compacted,
570653
570871
  compactionStrategy: compacted ? "drop_oldest_non_evidence" : "none",
570654
- evidenceRetained: evidence.length,
570655
- evidenceDropped
570872
+ evidenceRetained: foldedEvidence.retained,
570873
+ evidenceDropped: evidenceDropped + foldedEvidence.dropped,
570874
+ evidenceFolded: foldedEvidence.folded
570656
570875
  }
570657
570876
  };
570658
570877
  }
@@ -572881,6 +573100,7 @@ var init_agenticRunner = __esm({
572881
573100
  // stale edit loops, completion holds, and context pressure into a single
572882
573101
  // next-action contract injected through the active context frame.
572883
573102
  _focusSupervisor = null;
573103
+ _focusTerminalLedgerRecorded = false;
572884
573104
  // Generic, cross-session failure→resolution learning: learns the token-level
572885
573105
  // change that turned a failed command into a working one (e.g. python→python3)
572886
573106
  // from observed pairs, and surfaces it before a matching command runs — so
@@ -572889,6 +573109,7 @@ var init_agenticRunner = __esm({
572889
573109
  _resolutionMemory = new ResolutionMemory();
572890
573110
  _lastContextFrameDiagnostics = null;
572891
573111
  _lastContextPressureSnapshot = null;
573112
+ _lastFocusContextSnapshot = null;
572892
573113
  _lastActiveForgettingReport = null;
572893
573114
  _lastContextConsolidationTurn = -1e3;
572894
573115
  /** WO-CE-BOUNDARY: Context engine instance for structured context assembly */
@@ -572950,13 +573171,123 @@ var init_agenticRunner = __esm({
572950
573171
  this._workboard = createWorkboard(dir, {
572951
573172
  runId,
572952
573173
  owner: this.options.subAgent ? "sub-agent" : "agent",
572953
- title: (this._taskState.goal || "").slice(0, 120) || void 0
573174
+ goal: this._taskState.originalGoal || this._taskState.goal || void 0,
573175
+ title: (this._taskState.goal || "").slice(0, 120) || void 0,
573176
+ cards: this._initialWorkboardCardsForGoal(this._taskState.originalGoal || this._taskState.goal || "")
572954
573177
  });
572955
573178
  } catch {
572956
573179
  this._workboard = loadWorkboardSnapshot(dir, runId);
572957
573180
  }
572958
573181
  return this._workboard;
572959
573182
  }
573183
+ _initialWorkboardCardsForGoal(goal) {
573184
+ if (!this.writesUserTaskArtifacts())
573185
+ return [];
573186
+ if (this.options.subAgent || this.options.recursionDepth > 0)
573187
+ return [];
573188
+ const normalizedGoal = goal.replace(/\s+/g, " ").trim();
573189
+ if (normalizedGoal.length < 120 && !this._isContinuationResumeGoal(normalizedGoal))
573190
+ return [];
573191
+ return [
573192
+ {
573193
+ id: "discover-current-state",
573194
+ title: "Discover current state",
573195
+ description: "Identify the relevant files, runtime entrypoints, constraints, and current failure evidence before changing behavior.",
573196
+ lane: "worker",
573197
+ status: "in_progress",
573198
+ assignee: "agent",
573199
+ role: "worker",
573200
+ evidenceRequired: true,
573201
+ evidenceRequirements: [
573202
+ "file_read, grep_search, or shell evidence identifying the authoritative targets",
573203
+ "current failure or baseline observation when available"
573204
+ ]
573205
+ },
573206
+ {
573207
+ id: "implement-repair",
573208
+ title: "Implement smallest repair",
573209
+ description: "Apply the narrowest code or asset changes that address the discovered root cause.",
573210
+ lane: "ready",
573211
+ status: "open",
573212
+ assignee: "agent",
573213
+ role: "worker",
573214
+ dependencies: ["discover-current-state"],
573215
+ evidenceRequired: true,
573216
+ evidenceRequirements: [
573217
+ "file_edit, file_patch, batch_edit, or file_write evidence for each changed target",
573218
+ "stale edit failures resolved by fresh current-file evidence"
573219
+ ]
573220
+ },
573221
+ {
573222
+ id: "integrate-and-run",
573223
+ title: "Integrate and run",
573224
+ description: "Exercise the changed system through the intended runtime path rather than only inspecting files.",
573225
+ lane: "verification",
573226
+ status: "open",
573227
+ assignee: "agent",
573228
+ role: "verifier",
573229
+ dependencies: ["implement-repair"],
573230
+ evidenceRequired: true,
573231
+ evidenceRequirements: [
573232
+ "shell evidence showing the configured runtime, training, build, or simulation command was attempted",
573233
+ "captured output sufficient to distinguish progress from setup failure"
573234
+ ]
573235
+ },
573236
+ {
573237
+ id: "verify-observed-outcome",
573238
+ title: "Verify observed outcome",
573239
+ description: "Record objective success, incomplete verification, or a concrete blocker from the runtime evidence.",
573240
+ lane: "verification",
573241
+ status: "open",
573242
+ assignee: "agent",
573243
+ role: "verifier",
573244
+ dependencies: ["integrate-and-run"],
573245
+ evidenceRequired: true,
573246
+ evidenceRequirements: [
573247
+ "successful verification output after the final mutation, or an explicit blocker",
573248
+ "completion summary reconciled with unresolved workboard cards"
573249
+ ]
573250
+ }
573251
+ ];
573252
+ }
573253
+ _isContinuationResumeGoal(goal) {
573254
+ const tokens = goal.toLowerCase().replace(/[^a-z0-9]+/g, " ").split(/\s+/).filter(Boolean);
573255
+ if (tokens.length === 0 || tokens.length > 14)
573256
+ return false;
573257
+ const continuationTerms = /* @__PURE__ */ new Set([
573258
+ "again",
573259
+ "and",
573260
+ "back",
573261
+ "carry",
573262
+ "complete",
573263
+ "continue",
573264
+ "finish",
573265
+ "from",
573266
+ "last",
573267
+ "latest",
573268
+ "left",
573269
+ "my",
573270
+ "off",
573271
+ "please",
573272
+ "previous",
573273
+ "prior",
573274
+ "proceed",
573275
+ "request",
573276
+ "resume",
573277
+ "task",
573278
+ "that",
573279
+ "the",
573280
+ "this",
573281
+ "to",
573282
+ "try",
573283
+ "work"
573284
+ ]);
573285
+ const hasResumeVerb = tokens.some((token) => token === "continue" || token === "resume" || token === "proceed" || token === "complete" || token === "finish");
573286
+ if (!hasResumeVerb)
573287
+ return false;
573288
+ const continuationTokenCount = tokens.filter((token) => continuationTerms.has(token)).length;
573289
+ return continuationTokenCount / tokens.length >= 0.7;
573290
+ }
572960
573291
  /**
572961
573292
  * Build a compact workboard context string for injection into the
572962
573293
  * system prompt. Returns null when no active board exists or when
@@ -572984,7 +573315,7 @@ var init_agenticRunner = __esm({
572984
573315
  parts.push(`Active: ${activeCards.length}`);
572985
573316
  }
572986
573317
  if (snapshot.cards.length > 0) {
572987
- const compact3 = compactWorkboardSnapshot(snapshot, 12);
573318
+ const compact4 = compactWorkboardSnapshot(snapshot, 12);
572988
573319
  parts.push(`
572989
573320
  ${formatWorkboardCompact(snapshot, 12)}`);
572990
573321
  }
@@ -573162,7 +573493,7 @@ ${parts.join("\n")}
573162
573493
  focusSupervisor: this._focusSupervisor?.snapshot()
573163
573494
  });
573164
573495
  if (record) {
573165
- this._focusSupervisor?.observeContext({
573496
+ const focusSnapshot = {
573166
573497
  estimatedTokens: record.metrics.estimatedTokens,
573167
573498
  rawDiscoveryChars: record.metrics.rawDiscoveryToolChars,
573168
573499
  activeEvidenceChars: record.metrics.activeEvidenceChars,
@@ -573171,7 +573502,9 @@ ${parts.join("\n")}
573171
573502
  pressureRatio: this._lastContextPressureSnapshot?.rawRatio ?? (this.options.contextWindowSize ? record.metrics.estimatedTokens / this.options.contextWindowSize : 0),
573172
573503
  droppedSignals: this._lastContextFrameDiagnostics?.droppedSignals ?? this._lastContextPressureSnapshot?.droppedSignals,
573173
573504
  truncatedSignals: this._lastContextFrameDiagnostics?.truncatedSignals ?? this._lastContextPressureSnapshot?.truncatedSignals
573174
- });
573505
+ };
573506
+ this._lastFocusContextSnapshot = focusSnapshot;
573507
+ this._focusSupervisor?.observeContext(focusSnapshot);
573175
573508
  }
573176
573509
  return record?.id ?? null;
573177
573510
  }
@@ -573191,13 +573524,59 @@ ${parts.join("\n")}
573191
573524
  }
573192
573525
  });
573193
573526
  }
573527
+ _maybeMarkFocusTerminalIncomplete(input) {
573528
+ if (input.decision.kind === "pass")
573529
+ return;
573530
+ const directive = input.decision.directive;
573531
+ if (directive.state !== "terminal_incomplete" || directive.requiredNextAction !== "report_incomplete") {
573532
+ return;
573533
+ }
573534
+ if (!this._completionIncompleteVerification) {
573535
+ const reason = directive.reason;
573536
+ const blocked = input.blockedTool ? `Blocked tool: ${input.blockedTool}.` : "";
573537
+ const details = input.decision.kind === "block_tool_call" ? input.decision.message : input.decision.message;
573538
+ this._completionIncompleteVerification = {
573539
+ reason,
573540
+ summary: [
573541
+ "INCOMPLETE_VERIFICATION: focus supervisor stopped a repeated recovery loop.",
573542
+ blocked,
573543
+ "",
573544
+ "Reason:",
573545
+ reason,
573546
+ "",
573547
+ "Evidence:",
573548
+ details.slice(0, 2e3)
573549
+ ].filter((line) => line.length > 0).join("\n")
573550
+ };
573551
+ this.emit({
573552
+ type: "status",
573553
+ content: `Focus supervisor terminal incomplete: ${reason.slice(0, 220)}`,
573554
+ turn: input.turn,
573555
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
573556
+ });
573557
+ }
573558
+ if (this._completionLedger && !this._focusTerminalLedgerRecorded) {
573559
+ this._completionLedger = recordToolEvidence(this._completionLedger, {
573560
+ name: "focus_supervisor",
573561
+ success: false,
573562
+ outputPreview: this._completionIncompleteVerification.summary.slice(0, 500),
573563
+ argsKey: input.blockedTool ?? ""
573564
+ });
573565
+ this._saveCompletionLedgerSafe();
573566
+ this._focusTerminalLedgerRecorded = true;
573567
+ }
573568
+ }
573194
573569
  _buildFocusContextSnapshot() {
573570
+ const last2 = this._lastFocusContextSnapshot;
573195
573571
  return {
573196
573572
  pressureRatio: this._lastContextPressureSnapshot?.rawRatio ?? 0,
573197
- estimatedTokens: this._lastContextPressureSnapshot?.rawTokens,
573198
- activeFrameChars: this._lastContextFrameDiagnostics?.totalChars,
573199
- droppedSignals: this._lastContextFrameDiagnostics?.droppedSignals ?? this._lastContextPressureSnapshot?.droppedSignals,
573200
- truncatedSignals: this._lastContextFrameDiagnostics?.truncatedSignals ?? this._lastContextPressureSnapshot?.truncatedSignals
573573
+ estimatedTokens: this._lastContextPressureSnapshot?.rawTokens ?? last2?.estimatedTokens,
573574
+ rawDiscoveryChars: last2?.rawDiscoveryChars,
573575
+ activeEvidenceChars: last2?.activeEvidenceChars,
573576
+ activeFrameChars: this._lastContextFrameDiagnostics?.totalChars ?? last2?.activeFrameChars,
573577
+ signalToNoiseRatio: last2?.signalToNoiseRatio,
573578
+ droppedSignals: this._lastContextFrameDiagnostics?.droppedSignals ?? this._lastContextPressureSnapshot?.droppedSignals ?? last2?.droppedSignals,
573579
+ truncatedSignals: this._lastContextFrameDiagnostics?.truncatedSignals ?? this._lastContextPressureSnapshot?.truncatedSignals ?? last2?.truncatedSignals
573201
573580
  };
573202
573581
  }
573203
573582
  _emitModelResolutionTelemetry(purpose, turn) {
@@ -573475,10 +573854,10 @@ ${parts.join("\n")}
573475
573854
  const afterMarker = tail.slice(marker.length);
573476
573855
  const nextH2 = afterMarker.search(/\n## (?!#)/);
573477
573856
  const raw = nextH2 >= 0 ? tail.slice(0, marker.length + nextH2) : tail;
573478
- const compact3 = raw.replace(/\n{3,}/g, "\n\n").trim();
573479
- if (compact3.length <= limit)
573480
- return compact3;
573481
- return `${compact3.slice(0, Math.max(0, limit - 18)).trimEnd()}
573857
+ const compact4 = raw.replace(/\n{3,}/g, "\n\n").trim();
573858
+ if (compact4.length <= limit)
573859
+ return compact4;
573860
+ return `${compact4.slice(0, Math.max(0, limit - 18)).trimEnd()}
573482
573861
  ... [truncated]`;
573483
573862
  }
573484
573863
  /**
@@ -576734,21 +577113,21 @@ ${sections.join("\n")}` : sections.join("\n");
576734
577113
  sections.push(`Compacted cached entries still count as already-known results (${compactedCount}); an exact repeat will be served from cache or skipped, not produce new information.`);
576735
577114
  }
576736
577115
  if (filesRead.length > 0) {
576737
- const unique3 = [...new Set(filesRead)].slice(0, 30);
576738
- sections.push(`Files already read (${unique3.length}): ${unique3.join(", ")}`);
577116
+ const unique2 = [...new Set(filesRead)].slice(0, 30);
577117
+ sections.push(`Files already read (${unique2.length}): ${unique2.join(", ")}`);
576739
577118
  }
576740
577119
  if (dirsListed.length > 0) {
576741
- const unique3 = [...new Set(dirsListed)].slice(0, 15);
576742
- sections.push(`Directories already listed (${unique3.length}): ${unique3.join(", ")}`);
577120
+ const unique2 = [...new Set(dirsListed)].slice(0, 15);
577121
+ sections.push(`Directories already listed (${unique2.length}): ${unique2.join(", ")}`);
576743
577122
  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.`);
576744
577123
  }
576745
577124
  if (searches.length > 0) {
576746
- const unique3 = [...new Set(searches)].slice(0, 15);
576747
- sections.push(`Searches already run (${unique3.length}): ${unique3.join(", ")}`);
577125
+ const unique2 = [...new Set(searches)].slice(0, 15);
577126
+ sections.push(`Searches already run (${unique2.length}): ${unique2.join(", ")}`);
576748
577127
  }
576749
577128
  if (shells.length > 0) {
576750
- const unique3 = [...new Set(shells)].slice(0, 15);
576751
- sections.push(`Shell commands already executed (${unique3.length}): ${unique3.join(", ")}`);
577129
+ const unique2 = [...new Set(shells)].slice(0, 15);
577130
+ sections.push(`Shell commands already executed (${unique2.length}): ${unique2.join(", ")}`);
576752
577131
  }
576753
577132
  if (sections.length <= 1)
576754
577133
  return null;
@@ -578412,6 +578791,7 @@ Respond with your assessment, then take action.`;
578412
578791
  this._completionIncompleteVerification = null;
578413
578792
  this._completionCaveat = null;
578414
578793
  this._completionLedger = null;
578794
+ this._focusTerminalLedgerRecorded = false;
578415
578795
  this._staleEditFamilies.clear();
578416
578796
  this._lastWorldStateTurn = -1;
578417
578797
  this._fileWritesSinceLastWorldState = 0;
@@ -578474,6 +578854,7 @@ Respond with your assessment, then take action.`;
578474
578854
  this._evidenceLedger = new EvidenceLedger();
578475
578855
  this._lastContextFrameDiagnostics = null;
578476
578856
  this._lastContextPressureSnapshot = null;
578857
+ this._lastFocusContextSnapshot = null;
578477
578858
  this._lastActiveForgettingReport = null;
578478
578859
  this._lastContextConsolidationTurn = -1e3;
578479
578860
  this._contextFrameBuilder = new ContextFrameBuilder();
@@ -580683,7 +581064,16 @@ If you're stuck, try a completely different approach. Do NOT repeat what failed
580683
581064
  completionContract: this._completionContract ? formatCompletionContract(this._completionContract) : void 0
580684
581065
  }
580685
581066
  };
580686
- await this._contextEngine.compact(ceCompactInput);
581067
+ const ceCompactOutput = await this._contextEngine.compact(ceCompactInput);
581068
+ if (ceCompactOutput.compacted && ceCompactOutput.compactedMessages.length > 0 && ceCompactOutput.compactedMessages.length < compacted.length) {
581069
+ messages2.length = 0;
581070
+ messages2.push(...ceCompactOutput.compactedMessages.map((m2) => ({
581071
+ role: m2.role,
581072
+ content: m2.content,
581073
+ ...m2.name ? { name: m2.name } : {}
581074
+ })));
581075
+ compacted = messages2;
581076
+ }
580687
581077
  } catch {
580688
581078
  }
580689
581079
  }
@@ -580793,6 +581183,7 @@ ${memoryLines.join("\n")}`
580793
581183
  this.proactivePrune(compacted, turn);
580794
581184
  this.microcompact(compacted, recentToolResults);
580795
581185
  this._insertContextFrame(compacted, await this._buildTurnContextFrame(turn, compacted, recentToolResults, environmentBlock));
581186
+ let requestMessages = compacted;
580796
581187
  {
580797
581188
  const _limits = this.contextLimits();
580798
581189
  const ceInput = {
@@ -580815,10 +581206,13 @@ ${memoryLines.join("\n")}`
580815
581206
  if (ceOutput.diagnostics.evidenceRetained > 0 || ceInput.runState?.completionContract || ceInput.memoryHints?.length) {
580816
581207
  const engineExtra = ceOutput.systemMessages.filter((m2) => !ceInput.messages.some((im) => im.content === m2.content));
580817
581208
  if (engineExtra.length > 0) {
580818
- compacted.unshift(...engineExtra.map((m2) => ({
580819
- role: "system",
580820
- content: m2.content
580821
- })));
581209
+ requestMessages = [
581210
+ ...engineExtra.map((m2) => ({
581211
+ role: "system",
581212
+ content: m2.content
581213
+ })),
581214
+ ...compacted
581215
+ ];
580822
581216
  }
580823
581217
  }
580824
581218
  } catch {
@@ -580826,7 +581220,7 @@ ${memoryLines.join("\n")}`
580826
581220
  }
580827
581221
  const { maxOutputTokens: effectiveMaxTokens } = this.contextLimits();
580828
581222
  const chatRequest = {
580829
- messages: compacted,
581223
+ messages: requestMessages,
580830
581224
  tools: toolDefs,
580831
581225
  temperature: this.options.temperature,
580832
581226
  maxTokens: effectiveMaxTokens,
@@ -581010,6 +581404,10 @@ ${memoryLines.join("\n")}`
581010
581404
  'When done, output: {"tool": "task_complete", "args": {"summary": "what you did"}}'
581011
581405
  ].join("\n");
581012
581406
  messages2.push({ role: "system", content: toolInjectMsg });
581407
+ chatRequest.messages = [
581408
+ ...requestMessages,
581409
+ { role: "system", content: toolInjectMsg }
581410
+ ];
581013
581411
  chatRequest.tools = [];
581014
581412
  try {
581015
581413
  this._recordContextWindowDump("agent_turn_prompt_tool_retry", chatRequest, turn, 1);
@@ -581676,6 +582074,11 @@ Use the saved fact to continue the promised synthesis or next concrete step, or
581676
582074
  blockedTool: tc.name,
581677
582075
  turn
581678
582076
  });
582077
+ this._maybeMarkFocusTerminalIncomplete({
582078
+ decision: focusDecision2,
582079
+ blockedTool: tc.name,
582080
+ turn
582081
+ });
581679
582082
  }
581680
582083
  this.emit({
581681
582084
  type: "tool_call",
@@ -581734,6 +582137,11 @@ Use the saved fact to continue the promised synthesis or next concrete step, or
581734
582137
  blockedTool: tc.name,
581735
582138
  turn
581736
582139
  });
582140
+ this._maybeMarkFocusTerminalIncomplete({
582141
+ decision: focusDecision2,
582142
+ blockedTool: tc.name,
582143
+ turn
582144
+ });
581737
582145
  }
581738
582146
  this.emit({
581739
582147
  type: "tool_call",
@@ -581972,6 +582380,11 @@ ${cachedResult}`,
581972
582380
  blockedTool: focusDecision.kind === "block_tool_call" ? tc.name : void 0,
581973
582381
  turn
581974
582382
  });
582383
+ this._maybeMarkFocusTerminalIncomplete({
582384
+ decision: focusDecision,
582385
+ blockedTool: focusDecision.kind === "block_tool_call" ? tc.name : void 0,
582386
+ turn
582387
+ });
581975
582388
  if (focusDecision.kind === "inject_guidance") {
581976
582389
  pushSoftInjection("system", focusDecision.message);
581977
582390
  } else if (!repeatShortCircuit) {
@@ -587489,8 +587902,8 @@ ${trimmedNew}`;
587489
587902
  buildAdversaryToolOutcomeEvidence(toolName, toolArgs, content, succeeded) {
587490
587903
  const pathValue = toolArgs?.["path"] ?? toolArgs?.["file"] ?? toolArgs?.["filePath"] ?? toolArgs?.["file_path"];
587491
587904
  const path12 = typeof pathValue === "string" && pathValue.trim() ? pathValue.trim() : void 0;
587492
- const compact3 = content.replace(/\s+/g, " ").trim();
587493
- const snippet = compact3.slice(0, 160);
587905
+ const compact4 = content.replace(/\s+/g, " ").trim();
587906
+ const snippet = compact4.slice(0, 160);
587494
587907
  const digest3 = _createHash("sha256").update(content).digest("hex").slice(0, 16);
587495
587908
  const lineCount = content.length > 0 ? content.split("\n").length : 0;
587496
587909
  if (toolName === "file_read") {
@@ -608950,9 +609363,9 @@ function keywords(text2) {
608950
609363
  return out;
608951
609364
  }
608952
609365
  function compactLine(text2, limit = 220) {
608953
- const compact3 = text2.replace(/\s+/g, " ").trim();
608954
- if (compact3.length <= limit) return compact3;
608955
- return `${compact3.slice(0, Math.max(0, limit - 3)).trimEnd()}...`;
609366
+ const compact4 = text2.replace(/\s+/g, " ").trim();
609367
+ if (compact4.length <= limit) return compact4;
609368
+ return `${compact4.slice(0, Math.max(0, limit - 3)).trimEnd()}...`;
608956
609369
  }
608957
609370
  function newDocument(scope) {
608958
609371
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
@@ -609287,9 +609700,9 @@ import { createHash as createHash33 } from "node:crypto";
609287
609700
  import { existsSync as existsSync109, readdirSync as readdirSync36, readFileSync as readFileSync86 } from "node:fs";
609288
609701
  import { basename as basename22, join as join123, resolve as resolve54 } from "node:path";
609289
609702
  function compactText(text2, limit) {
609290
- const compact3 = text2.replace(/\s+/g, " ").trim();
609291
- if (compact3.length <= limit) return compact3;
609292
- return `${compact3.slice(0, Math.max(0, limit - 3)).trimEnd()}...`;
609703
+ const compact4 = text2.replace(/\s+/g, " ").trim();
609704
+ if (compact4.length <= limit) return compact4;
609705
+ return `${compact4.slice(0, Math.max(0, limit - 3)).trimEnd()}...`;
609293
609706
  }
609294
609707
  function blockText(text2, limit) {
609295
609708
  const clean5 = text2.replace(/\r\n/g, "\n").trim();
@@ -614399,6 +614812,129 @@ function loadSessionContext(repoRoot) {
614399
614812
  return null;
614400
614813
  }
614401
614814
  }
614815
+ function readJsonOrNull(filePath) {
614816
+ try {
614817
+ if (!existsSync113(filePath)) return null;
614818
+ return JSON.parse(readFileSync90(filePath, "utf-8"));
614819
+ } catch {
614820
+ return null;
614821
+ }
614822
+ }
614823
+ function isManualSessionEntry(entry) {
614824
+ const task = cleanPromptForDiary(entry.task).toLowerCase();
614825
+ const summary = normalizeSessionText(entry.summary || entry.assistantResponse, 160).toLowerCase();
614826
+ return entry.source === "manual" || task === "(manual save)" || entry.toolCalls === 0 && summary.startsWith("manual context save");
614827
+ }
614828
+ function isDeicticContinuationGoal(goal) {
614829
+ const tokens = normalizeSessionText(cleanPromptForDiary(goal), 180).toLowerCase().replace(/[^a-z0-9]+/g, " ").split(/\s+/).filter(Boolean);
614830
+ if (tokens.length === 0 || tokens.length > 14) return false;
614831
+ const hasResumeVerb = tokens.some(
614832
+ (token) => token === "continue" || token === "resume" || token === "proceed" || token === "complete" || token === "finish"
614833
+ );
614834
+ if (!hasResumeVerb) return false;
614835
+ const deicticCount = tokens.filter((token) => DEICTIC_CONTINUATION_TERMS.has(token)).length;
614836
+ return deicticCount / tokens.length >= 0.7;
614837
+ }
614838
+ function readRestoreWorkboard(repoRoot, runId) {
614839
+ if (!runId) return null;
614840
+ return readJsonOrNull(
614841
+ join127(repoRoot, OMNIUS_DIR, "workboards", runId, "active.json")
614842
+ );
614843
+ }
614844
+ function scoreRestoreLedger(ledger, workboard) {
614845
+ const status = ledger.status || "open";
614846
+ if (status === "approved") return -1e3;
614847
+ const evidence = ledger.evidence ?? [];
614848
+ const unresolvedCount = ledger.unresolved?.length ?? 0;
614849
+ const activeCards = (workboard?.cards ?? []).filter(
614850
+ (card) => card.status === "open" || card.status === "in_progress" || card.status === "needs_changes" || card.status === "blocked"
614851
+ ).length;
614852
+ const mutationTools = /* @__PURE__ */ new Set(["file_edit", "file_patch", "batch_edit", "file_write"]);
614853
+ const mutationEvidence = evidence.filter((item) => mutationTools.has(item.toolName || "")).length;
614854
+ const failedMutationEvidence = evidence.filter(
614855
+ (item) => mutationTools.has(item.toolName || "") && item.success === false
614856
+ ).length;
614857
+ const targetPathEvidence = evidence.filter((item) => (item.targetPaths?.length ?? 0) > 0).length;
614858
+ const blockedEvidence = evidence.filter((item) => {
614859
+ const summary = String(item.summary ?? "").toLowerCase();
614860
+ return summary.includes("[focus supervisor block]") || summary.includes("stale") || summary.includes("blocked");
614861
+ }).length;
614862
+ let score = 0;
614863
+ if (status === "open") score += 10;
614864
+ else if (status === "incomplete_verification") score += 18;
614865
+ else if (status === "request_changes" || status === "blocked") score += 16;
614866
+ else score += 4;
614867
+ score += Math.min(evidence.length, 20);
614868
+ score += Math.min(unresolvedCount, 10) * 4;
614869
+ score += Math.min(activeCards, 8) * 3;
614870
+ score += Math.min(mutationEvidence, 8) * 5;
614871
+ score += Math.min(failedMutationEvidence, 8) * 3;
614872
+ score += Math.min(targetPathEvidence, 6) * 2;
614873
+ score += Math.min(blockedEvidence, 6) * 2;
614874
+ const goal = normalizeSessionText(ledger.goal, 260);
614875
+ if (goal.length >= 80) score += 5;
614876
+ if (isDeicticContinuationGoal(goal) && mutationEvidence === 0 && unresolvedCount === 0 && activeCards === 0) {
614877
+ score -= 25;
614878
+ }
614879
+ return score;
614880
+ }
614881
+ function selectActiveTaskAnchor(repoRoot) {
614882
+ const ledgerDir = join127(repoRoot, OMNIUS_DIR, "completion-ledgers");
614883
+ try {
614884
+ if (!existsSync113(ledgerDir)) return null;
614885
+ const candidates = readdirSync39(ledgerDir).filter((name10) => name10.endsWith(".json")).map((name10) => {
614886
+ const filePath = join127(ledgerDir, name10);
614887
+ const ledger = readJsonOrNull(filePath);
614888
+ if (!ledger || !ledger.goal) return null;
614889
+ const runId = ledger.runId || name10.replace(/\.json$/, "");
614890
+ const workboard = readRestoreWorkboard(repoRoot, runId);
614891
+ const score = scoreRestoreLedger(ledger, workboard);
614892
+ const mtimeMs = statSync42(filePath).mtimeMs;
614893
+ return { ledger: { ...ledger, runId }, workboard, score, mtimeMs };
614894
+ }).filter((item) => Boolean(item));
614895
+ candidates.sort((a2, b) => b.score - a2.score || b.mtimeMs - a2.mtimeMs);
614896
+ const selected = candidates.find((candidate) => candidate.score >= 18);
614897
+ return selected ?? null;
614898
+ } catch {
614899
+ return null;
614900
+ }
614901
+ }
614902
+ function buildActiveTaskAnchor(repoRoot) {
614903
+ const selected = selectActiveTaskAnchor(repoRoot);
614904
+ if (!selected) return null;
614905
+ const ledger = selected.ledger;
614906
+ const evidence = ledger.evidence ?? [];
614907
+ const selectedEvidence = [...evidence.slice(0, 2), ...evidence.slice(-4)];
614908
+ const seenEvidence = /* @__PURE__ */ new Set();
614909
+ const evidenceLines = selectedEvidence.flatMap((item) => {
614910
+ const summary = normalizeSessionText(item.summary, 240);
614911
+ if (!summary || seenEvidence.has(summary)) return [];
614912
+ seenEvidence.add(summary);
614913
+ const status = item.success === false ? "failed" : item.success === true ? "ok" : "observed";
614914
+ const tool = item.toolName || "evidence";
614915
+ return [`- ${tool} ${status}: ${summary}`];
614916
+ });
614917
+ const unresolvedLines = (ledger.unresolved ?? []).slice(0, 4).map((item) => `- ${normalizeSessionText(item.text, 180)}`).filter((line) => line !== "- ");
614918
+ const boardCards = (selected.workboard?.cards ?? []).filter((card) => card.status !== "completed" && card.status !== "verified").slice(0, 5).map((card) => {
614919
+ const title = normalizeSessionText(card.title || card.id, 120);
614920
+ const status = card.status || "open";
614921
+ const lane = card.lane ? `/${card.lane}` : "";
614922
+ const evidenceCount = Array.isArray(card.evidence) ? card.evidence.length : 0;
614923
+ return `- ${title} (${status}${lane}, evidence=${evidenceCount})`;
614924
+ });
614925
+ return `<active-task-anchor>
614926
+ Source: completion ledger ${ledger.runId || "(unknown run)"}; status=${ledger.status || "open"}
614927
+ Goal: ${normalizeSessionText(ledger.goal, 420)}
614928
+ Recorded evidence: ${evidence.length}; unresolved items: ${ledger.unresolved?.length ?? 0}
614929
+ ` + (evidenceLines.length > 0 ? `Material evidence:
614930
+ ${evidenceLines.join("\n")}
614931
+ ` : "") + (unresolvedLines.length > 0 ? `Unresolved:
614932
+ ${unresolvedLines.join("\n")}
614933
+ ` : "") + (boardCards.length > 0 ? `Active workboard cards:
614934
+ ${boardCards.join("\n")}
614935
+ ` : "") + `Continuation rule: when the user asks to continue, resume this active task unless the new prompt names a different target.
614936
+ </active-task-anchor>`;
614937
+ }
614402
614938
  function formatSessionHistoryDisplay(ctx3) {
614403
614939
  return buildSessionHistoryBoxLines(
614404
614940
  sessionContextToHistoryBoxData(ctx3),
@@ -614427,18 +614963,23 @@ function sessionContextToHistoryBoxData(ctx3, title = "Session History") {
614427
614963
  function buildContextRestorePrompt(repoRoot) {
614428
614964
  const ctx3 = loadSessionContext(repoRoot);
614429
614965
  const handoffPrompt = buildHandoffPrompt(repoRoot);
614966
+ const activeTaskAnchor = buildActiveTaskAnchor(repoRoot);
614430
614967
  if (handoffPrompt) {
614968
+ const usefulEntries2 = (ctx3?.entries ?? []).filter((entry) => !isManualSessionEntry(entry));
614431
614969
  const baseCtx = ctx3 && ctx3.entries.length > 0 ? `
614432
614970
 
614433
614971
  <session-recap>
614434
- Recent tasks: ${ctx3.entries.slice(-3).map(
614972
+ Recent tasks: ${(usefulEntries2.length > 0 ? usefulEntries2 : ctx3.entries).slice(-3).map(
614435
614973
  (e2) => `[${e2.completed ? "done" : "partial"}] ${normalizeSessionText(e2.summary || e2.task, 80)}`
614436
614974
  ).join(", ")}
614437
614975
  </session-recap>` : "";
614438
- return handoffPrompt + baseCtx;
614976
+ return handoffPrompt + (activeTaskAnchor ? `
614977
+
614978
+ ${activeTaskAnchor}` : "") + baseCtx;
614439
614979
  }
614440
- if (!ctx3 || ctx3.entries.length === 0) return null;
614441
- const recent = ctx3.entries.slice(-5);
614980
+ if (!ctx3 || ctx3.entries.length === 0) return activeTaskAnchor;
614981
+ const usefulEntries = ctx3.entries.filter((entry) => !isManualSessionEntry(entry));
614982
+ const recent = (usefulEntries.length > 0 ? usefulEntries : ctx3.entries).slice(-5);
614442
614983
  const chronology = recent.map((e2) => {
614443
614984
  const status = e2.completed ? "done" : "partial";
614444
614985
  const summary = normalizeSessionText(e2.assistantResponse || e2.summary || e2.task, 140);
@@ -614446,8 +614987,8 @@ Recent tasks: ${ctx3.entries.slice(-3).map(
614446
614987
  const files = e2.filesModified && e2.filesModified.length > 0 ? ` | files: ${e2.filesModified.slice(0, 3).join(", ")}` : "";
614447
614988
  return `[${status}] ${summary}${tools}${files}`;
614448
614989
  });
614449
- const last2 = ctx3.entries[ctx3.entries.length - 1];
614450
- const lastCompleted = [...ctx3.entries].reverse().find((entry) => entry.completed);
614990
+ const last2 = recent[recent.length - 1] ?? ctx3.entries[ctx3.entries.length - 1];
614991
+ const lastCompleted = [...usefulEntries].reverse().find((entry) => entry.completed);
614451
614992
  const latestCompleted = lastCompleted ? `Latest completed task: ${normalizeSessionText(lastCompleted.assistantResponse || lastCompleted.summary || lastCompleted.task, 180)}` : "";
614452
614993
  const recentDialogue = recent.slice(-3).map((entry) => {
614453
614994
  const assistant = normalizeSessionText(entry.assistantResponse || entry.summary, 320) || "(no assistant reply captured)";
@@ -614460,15 +615001,18 @@ Provenance: ${last2.provenance} (file_read to expand)` : "";
614460
615001
  const kg = `
614461
615002
  KG summary: .omnius/context/kg-summary/latest.md (file_read to expand; legacy pointer: .omnius/context/kg-summary-latest.md)`;
614462
615003
  return `<session-recap>
614463
- Project chronology (older to newer):
615004
+ ` + (activeTaskAnchor ? `${activeTaskAnchor}
615005
+
615006
+ ` : "") + `Project chronology (older to newer):
614464
615007
  ${chronology.join("\n")}
614465
615008
  ` + (latestCompleted ? `
614466
615009
  ${latestCompleted}
614467
615010
  ` : "\n") + `
614468
615011
  Most recent exchanges (older to newer):
614469
615012
  ${recentDialogue}
614470
- Continue from the latest exchange and do not repeat completed work.${prov}${kg}
614471
- </session-recap>`;
615013
+ ` + (activeTaskAnchor ? `For continuation prompts, resume the active task anchor above; use chronology only to avoid repeating completed work.${prov}${kg}
615014
+ ` : `Continue from the latest exchange and do not repeat completed work.${prov}${kg}
615015
+ `) + `</session-recap>`;
614472
615016
  }
614473
615017
  function getLastTaskSummary(repoRoot) {
614474
615018
  const ctx3 = loadSessionContext(repoRoot);
@@ -614791,7 +615335,7 @@ function deleteUsageRecord(kind, value2, repoRoot) {
614791
615335
  remove(join127(repoRoot, OMNIUS_DIR, USAGE_HISTORY_FILE));
614792
615336
  }
614793
615337
  }
614794
- var OMNIUS_DIR, LEGACY_DIRS, SUBDIRS, gitignoreWatchers, gitignoreRetryTimers, CONTEXT_FILES, PENDING_TASK_FILE, HANDOFF_FILE, CONTEXT_SAVE_FILE, CONTEXT_LEDGER_FILE, MAX_CONTEXT_ENTRIES, MAX_SESSION_DIARY_ENTRIES, MAX_SESSION_DIARY_DETAILED_ENTRIES, MAX_CONTEXT_LEDGER_LINES, MAX_CONTEXT_LEDGER_BYTES, SAME_TASK_REPLACE_WINDOW_MS, LOCK_TIMEOUT_MS, LOCK_RETRY_MS, LOCK_RETRY_MAX, SESSIONS_DIR, SESSIONS_INDEX, SKIP_DIRS3, HOME_SKIP_DIRS, USAGE_HISTORY_FILE, MAX_HISTORY_RECORDS;
615338
+ var OMNIUS_DIR, LEGACY_DIRS, SUBDIRS, gitignoreWatchers, gitignoreRetryTimers, CONTEXT_FILES, PENDING_TASK_FILE, HANDOFF_FILE, CONTEXT_SAVE_FILE, CONTEXT_LEDGER_FILE, MAX_CONTEXT_ENTRIES, MAX_SESSION_DIARY_ENTRIES, MAX_SESSION_DIARY_DETAILED_ENTRIES, MAX_CONTEXT_LEDGER_LINES, MAX_CONTEXT_LEDGER_BYTES, SAME_TASK_REPLACE_WINDOW_MS, LOCK_TIMEOUT_MS, LOCK_RETRY_MS, LOCK_RETRY_MAX, DEICTIC_CONTINUATION_TERMS, SESSIONS_DIR, SESSIONS_INDEX, SKIP_DIRS3, HOME_SKIP_DIRS, USAGE_HISTORY_FILE, MAX_HISTORY_RECORDS;
614795
615339
  var init_omnius_directory = __esm({
614796
615340
  "packages/cli/src/tui/omnius-directory.ts"() {
614797
615341
  "use strict";
@@ -614824,6 +615368,34 @@ var init_omnius_directory = __esm({
614824
615368
  LOCK_TIMEOUT_MS = 5e3;
614825
615369
  LOCK_RETRY_MS = 50;
614826
615370
  LOCK_RETRY_MAX = 100;
615371
+ DEICTIC_CONTINUATION_TERMS = /* @__PURE__ */ new Set([
615372
+ "again",
615373
+ "and",
615374
+ "back",
615375
+ "carry",
615376
+ "complete",
615377
+ "continue",
615378
+ "finish",
615379
+ "from",
615380
+ "last",
615381
+ "latest",
615382
+ "left",
615383
+ "my",
615384
+ "off",
615385
+ "please",
615386
+ "previous",
615387
+ "prior",
615388
+ "proceed",
615389
+ "request",
615390
+ "resume",
615391
+ "task",
615392
+ "that",
615393
+ "the",
615394
+ "this",
615395
+ "to",
615396
+ "try",
615397
+ "work"
615398
+ ]);
614827
615399
  SESSIONS_DIR = "sessions";
614828
615400
  SESSIONS_INDEX = "sessions-index.json";
614829
615401
  SKIP_DIRS3 = /* @__PURE__ */ new Set([
@@ -620593,10 +621165,10 @@ ${CONTENT_BG_SEQ}`);
620593
621165
  if (this._telegramStatus.active) {
620594
621166
  const suffix = this._telegramStatus.activeSubAgents > 0 ? ` ${_StatusBar.digitBar(this._telegramStatus.activeSubAgents)}` : "";
620595
621167
  const label = `✈ tg${suffix}`;
620596
- const compact3 = `✈${suffix}`;
621168
+ const compact4 = `✈${suffix}`;
620597
621169
  sections.push({
620598
621170
  expanded: `${HEADER_TELEGRAM_FG}${label}\x1B[0m`,
620599
- compact: `${HEADER_TELEGRAM_FG}${compact3}\x1B[0m`,
621171
+ compact: `${HEADER_TELEGRAM_FG}${compact4}\x1B[0m`,
620600
621172
  expandedW: 2 + 3 + suffix.length,
620601
621173
  compactW: 2 + suffix.length,
620602
621174
  empty: false,
@@ -652866,9 +653438,9 @@ async function handleUpdate(subcommand, ctx3) {
652866
653438
  const installOverlay = startInstallOverlay(targetVersion);
652867
653439
  const stripInstallAnsi = (value2) => value2.replace(/\x1B\][^\x07]*(?:\x07|\x1B\\)/g, "").replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "").replace(/\r/g, "\n");
652868
653440
  const truncateInstallStatus = (value2, max = 88) => {
652869
- const compact3 = value2.replace(/\s+/g, " ").trim();
652870
- if (compact3.length <= max) return compact3;
652871
- return compact3.slice(0, Math.max(1, max - 1)).trimEnd() + "…";
653441
+ const compact4 = value2.replace(/\s+/g, " ").trim();
653442
+ if (compact4.length <= max) return compact4;
653443
+ return compact4.slice(0, Math.max(1, max - 1)).trimEnd() + "…";
652872
653444
  };
652873
653445
  const summarizeInstallCommand = (cmd) => {
652874
653446
  const cleaned = cmd.replace(/^\s*sudo(?:\s+-n)?\s+/, "").replace(/\s+2>\/dev\/null/g, "").replace(/\s+\|\|\s+true\s*$/g, "").replace(/\s+/g, " ").trim();
@@ -654829,14 +655401,14 @@ function loadFailurePatterns(store2) {
654829
655401
  const unresolved = store2.listUnresolved();
654830
655402
  if (unresolved.length === 0) return "";
654831
655403
  const seen = /* @__PURE__ */ new Set();
654832
- const unique3 = unresolved.filter((f2) => {
655404
+ const unique2 = unresolved.filter((f2) => {
654833
655405
  if (seen.has(f2.fingerprint)) return false;
654834
655406
  seen.add(f2.fingerprint);
654835
655407
  return true;
654836
655408
  });
654837
- if (unique3.length === 0) return "";
655409
+ if (unique2.length === 0) return "";
654838
655410
  const lines = ["Known failure patterns (avoid repeating these):"];
654839
- for (const f2 of unique3.slice(0, 8)) {
655411
+ for (const f2 of unique2.slice(0, 8)) {
654840
655412
  const file = f2.filePath ? ` in ${f2.filePath}` : "";
654841
655413
  lines.push(`- [${f2.failureType}]${file}: ${f2.errorMessage.slice(0, 150)}`);
654842
655414
  }
@@ -657620,8 +658192,8 @@ function generateDescriptors(repoRoot) {
657620
658192
  if (repoName2 && !tags.includes(repoName2)) {
657621
658193
  tags.push(repoName2);
657622
658194
  }
657623
- const unique3 = [...new Set(tags.map((t2) => t2.toLowerCase().trim()).filter((t2) => t2.length > 1 && t2.length < 60))];
657624
- const phrases = unique3.map((text2) => ({
658195
+ const unique2 = [...new Set(tags.map((t2) => t2.toLowerCase().trim()).filter((t2) => t2.length > 1 && t2.length < 60))];
658196
+ const phrases = unique2.map((text2) => ({
657625
658197
  text: text2,
657626
658198
  color: weightedColor(profile)
657627
658199
  }));
@@ -657642,7 +658214,7 @@ function generateDescriptors(repoRoot) {
657642
658214
  ];
657643
658215
  for (const fb of fallbacks) {
657644
658216
  if (phrases.length >= 20) break;
657645
- if (!unique3.includes(fb)) {
658217
+ if (!unique2.includes(fb)) {
657646
658218
  phrases.push({ text: fb, color: weightedColor(profile) });
657647
658219
  }
657648
658220
  }
@@ -662634,9 +663206,9 @@ function toolCallBlock(name10, args) {
662634
663206
  if (args == null || typeof args === "object" && Object.keys(args).length === 0) {
662635
663207
  return header;
662636
663208
  }
662637
- const compact3 = typeof args === "string" ? args : safeJson(args, false);
662638
- if (compact3.length <= 120 && !compact3.includes("\n")) {
662639
- return `${header} <code>${escapeHtml2(compact3)}</code>`;
663209
+ const compact4 = typeof args === "string" ? args : safeJson(args, false);
663210
+ if (compact4.length <= 120 && !compact4.includes("\n")) {
663211
+ return `${header} <code>${escapeHtml2(compact4)}</code>`;
662640
663212
  }
662641
663213
  const pretty = typeof args === "string" ? args : safeJson(args, true);
662642
663214
  return `${header}
@@ -662973,13 +663545,13 @@ function buildScopedToolList(scope) {
662973
663545
  const commandSigs = commands.flatMap((cmd) => cmd.signatures);
662974
663546
  const allSigs = [...syntheticSigs, ...commandSigs];
662975
663547
  const seen = /* @__PURE__ */ new Set();
662976
- const unique3 = allSigs.filter((sig) => {
663548
+ const unique2 = allSigs.filter((sig) => {
662977
663549
  if (seen.has(sig.signature)) return false;
662978
663550
  seen.add(sig.signature);
662979
663551
  return true;
662980
663552
  });
662981
663553
  const entries = [];
662982
- for (const sig of unique3) {
663554
+ for (const sig of unique2) {
662983
663555
  const matchingCmd = commands.find(
662984
663556
  (cmd) => cmd.signatures.some((s2) => s2.signature === sig.signature)
662985
663557
  );
@@ -666086,7 +666658,7 @@ function stableHash2(value2, length4 = 16) {
666086
666658
  function clean3(value2) {
666087
666659
  return String(value2 ?? "").replace(/\s+/g, " ").trim();
666088
666660
  }
666089
- function compact(value2, max = 420) {
666661
+ function compact2(value2, max = 420) {
666090
666662
  const text2 = clean3(value2);
666091
666663
  return text2.length > max ? `${text2.slice(0, Math.max(0, max - 3)).trimEnd()}...` : text2;
666092
666664
  }
@@ -666167,7 +666739,7 @@ function contentFor(entry, sessionKey, options2) {
666167
666739
  `identity_boundary: ${identityBoundary(entry)}`,
666168
666740
  entry.replyContext?.sender ? `reply_sender: ${entry.replyContext.sender.username || entry.replyContext.sender.firstName || entry.replyContext.sender.id || "unknown"} [${entry.replyContext.sender.isBot ? "participant_bot" : "participant_human"}]` : "",
666169
666741
  entry.mode ? `mode: ${entry.mode}` : "",
666170
- entry.mediaSummary ? `media: ${compact(entry.mediaSummary, 260)}` : "",
666742
+ entry.mediaSummary ? `media: ${compact2(entry.mediaSummary, 260)}` : "",
666171
666743
  "",
666172
666744
  entry.text
666173
666745
  ].filter((line) => line !== "");
@@ -666209,7 +666781,7 @@ function addTextEdges(graph, result, entry) {
666209
666781
  srcId: messageId,
666210
666782
  dstId: senderId,
666211
666783
  relation: "said_by",
666212
- fact: compact(entry.text, 260),
666784
+ fact: compact2(entry.text, 260),
666213
666785
  sourceEpisodeId: result.episodeId,
666214
666786
  modality: entry.role === "user" ? "social" : "text",
666215
666787
  confidence: entry.role === "assistant" ? 0.92 : 0.96
@@ -666221,7 +666793,7 @@ function addTextEdges(graph, result, entry) {
666221
666793
  srcId: messageId,
666222
666794
  dstId: channelTopic,
666223
666795
  relation: "related_to",
666224
- fact: compact(entry.text || entry.mediaSummary || "telegram message", 220),
666796
+ fact: compact2(entry.text || entry.mediaSummary || "telegram message", 220),
666225
666797
  sourceEpisodeId: result.episodeId,
666226
666798
  modality: entry.role === "user" ? "social" : "text",
666227
666799
  confidence: 0.72
@@ -666261,7 +666833,7 @@ function upsertTelegramReflectionMessage(repoRoot, sessionKey, entry, options2)
666261
666833
  }
666262
666834
  function queryFor(options2) {
666263
666835
  if (options2.query?.trim()) return options2.query.trim();
666264
- const recent = options2.history.slice(-12).map((entry) => compact(`${senderLabel(entry)}: ${entry.text || entry.mediaSummary || ""}`, 180));
666836
+ const recent = options2.history.slice(-12).map((entry) => compact2(`${senderLabel(entry)}: ${entry.text || entry.mediaSummary || ""}`, 180));
666265
666837
  return [
666266
666838
  `Telegram ${options2.chatType} ${options2.chatTitle || options2.chatId} reflection`,
666267
666839
  ...recent
@@ -666819,7 +667391,7 @@ function telegramSocialActorKey(actor) {
666819
667391
  if (typeof actor.userId === "number") return `user:${actor.userId}`;
666820
667392
  const username = cleanUsername(actor.username);
666821
667393
  if (username) return `username:${username.toLowerCase()}`;
666822
- const first2 = compact2(actor.firstName, 80).toLowerCase();
667394
+ const first2 = compact3(actor.firstName, 80).toLowerCase();
666823
667395
  return first2 ? `name:${first2}` : "unknown";
666824
667396
  }
666825
667397
  function telegramSocialActorKind(actor) {
@@ -666854,16 +667426,16 @@ function cleanUsername(value2) {
666854
667426
  return clean5 ? clean5.slice(0, 80) : void 0;
666855
667427
  }
666856
667428
  function compactOptional(value2, max) {
666857
- const clean5 = compact2(value2, max);
667429
+ const clean5 = compact3(value2, max);
666858
667430
  return clean5 || void 0;
666859
667431
  }
666860
- function compact2(value2, max) {
667432
+ function compact3(value2, max) {
666861
667433
  if (value2 === void 0 || value2 === null) return "";
666862
667434
  const clean5 = String(value2).replace(/\s+/g, " ").trim();
666863
667435
  return clean5.length > max ? `${clean5.slice(0, Math.max(0, max - 3)).trimEnd()}...` : clean5;
666864
667436
  }
666865
667437
  function jsonLine(value2, max) {
666866
- return JSON.stringify(compact2(value2, max));
667438
+ return JSON.stringify(compact3(value2, max));
666867
667439
  }
666868
667440
  function numberOr(value2, fallback) {
666869
667441
  return typeof value2 === "number" && Number.isFinite(value2) ? value2 : fallback;
@@ -667109,8 +667681,8 @@ function normalizeReplyPreferenceScope(raw) {
667109
667681
  function normalizeDeliveryCapability(raw) {
667110
667682
  if (!raw || typeof raw !== "object") return null;
667111
667683
  const value2 = raw;
667112
- const key = compact2(value2.key || "", 180);
667113
- const chatId = compact2(value2.chatId || "", 120);
667684
+ const key = compact3(value2.key || "", 180);
667685
+ const chatId = compact3(value2.chatId || "", 120);
667114
667686
  if (!key || !chatId) return null;
667115
667687
  const status = normalizeDeliveryStatus(value2.status);
667116
667688
  return {
@@ -667162,7 +667734,7 @@ function normalizeSalience(raw) {
667162
667734
  senderKey: String(value2.senderKey),
667163
667735
  actorKind: value2.actorKind === "bot" || value2.actorKind === "human" ? value2.actorKind : "unknown",
667164
667736
  signals: Array.isArray(value2.signals) ? value2.signals.map(String).slice(0, 16) : [],
667165
- textPreview: compact2(value2.textPreview || "", 240)
667737
+ textPreview: compact3(value2.textPreview || "", 240)
667166
667738
  };
667167
667739
  }
667168
667740
  function normalizeOutcome2(raw) {
@@ -667180,8 +667752,8 @@ function normalizeOutcome2(raw) {
667180
667752
  route: value2.route === "action" ? "action" : "chat",
667181
667753
  shouldReply: value2.shouldReply === true,
667182
667754
  confidence: clamp0113(numberOr(value2.confidence, 0)),
667183
- reason: compact2(value2.reason || "", 280),
667184
- source: compact2(value2.source || "unknown", 80),
667755
+ reason: compact3(value2.reason || "", 280),
667756
+ source: compact3(value2.source || "unknown", 80),
667185
667757
  silentDisposition: compactOptional(value2.silentDisposition, 280),
667186
667758
  mentalNote: compactOptional(value2.mentalNote, 360),
667187
667759
  memoryNote: compactOptional(value2.memoryNote, 360),
@@ -667208,7 +667780,7 @@ function normalizeDaydreamOpportunity(raw) {
667208
667780
  id,
667209
667781
  artifactId: String(value2.artifactId || "unknown"),
667210
667782
  generatedAt: String(value2.generatedAt || (/* @__PURE__ */ new Date()).toISOString()),
667211
- trigger: compact2(value2.trigger || "", 240),
667783
+ trigger: compact3(value2.trigger || "", 240),
667212
667784
  confidence: clamp0113(numberOr(value2.confidence, 0)),
667213
667785
  lifecycle,
667214
667786
  firstSeenAt: numberOr(value2.firstSeenAt, Date.now()),
@@ -667232,7 +667804,7 @@ function observeTelegramSocialMessage(state, input) {
667232
667804
  state.updatedAt = now2;
667233
667805
  const senderKey3 = upsertParticipant(state, input, now2, true);
667234
667806
  const thread = upsertThread(state, input, senderKey3, now2, true);
667235
- const text2 = compact2(input.text || "", 500);
667807
+ const text2 = compact3(input.text || "", 500);
667236
667808
  const participant = state.participants[senderKey3];
667237
667809
  if (participant) {
667238
667810
  participant.lastText = text2 || participant.lastText;
@@ -667267,8 +667839,8 @@ function commitTelegramSocialDecision(state, input) {
667267
667839
  route: input.route,
667268
667840
  shouldReply: input.shouldReply,
667269
667841
  confidence: clamp0113(input.confidence),
667270
- reason: compact2(input.reason, 280),
667271
- source: compact2(input.source, 80),
667842
+ reason: compact3(input.reason, 280),
667843
+ source: compact3(input.source, 80),
667272
667844
  silentDisposition: compactOptional(input.silentDisposition, 280),
667273
667845
  mentalNote: compactOptional(input.mentalNote, 360),
667274
667846
  memoryNote: compactOptional(input.memoryNote, 360),
@@ -667301,7 +667873,7 @@ function registerDaydreamOpportunities(state, opportunities, now2 = Date.now())
667301
667873
  id,
667302
667874
  artifactId: opportunity.artifactId || "unknown",
667303
667875
  generatedAt: opportunity.generatedAt || new Date(now2).toISOString(),
667304
- trigger: compact2(opportunity.trigger, 240),
667876
+ trigger: compact3(opportunity.trigger, 240),
667305
667877
  confidence: clamp0113(opportunity.confidence),
667306
667878
  lifecycle: "proposed",
667307
667879
  firstSeenAt: now2,
@@ -667311,7 +667883,7 @@ function registerDaydreamOpportunities(state, opportunities, now2 = Date.now())
667311
667883
  suppressedMessageIds: []
667312
667884
  };
667313
667885
  if (existing) {
667314
- item.trigger = compact2(opportunity.trigger, 240) || item.trigger;
667886
+ item.trigger = compact3(opportunity.trigger, 240) || item.trigger;
667315
667887
  item.confidence = clamp0113(opportunity.confidence);
667316
667888
  item.updatedAt = now2;
667317
667889
  }
@@ -667538,7 +668110,7 @@ function addSalience(state, input, senderKey3, now2, text2) {
667538
668110
  senderKey: senderKey3,
667539
668111
  actorKind: telegramSocialActorKind(input),
667540
668112
  signals,
667541
- textPreview: compact2(text2, 240)
668113
+ textPreview: compact3(text2, 240)
667542
668114
  });
667543
668115
  state.salience = state.salience.slice(-TELEGRAM_SOCIAL_LIMITS.salience);
667544
668116
  }
@@ -667921,14 +668493,14 @@ function parseTelegramReplyPreferenceUpdate(parsed) {
667921
668493
  }
667922
668494
  function uniqueTelegramJsonCandidates(candidates) {
667923
668495
  const seen = /* @__PURE__ */ new Set();
667924
- const unique3 = [];
668496
+ const unique2 = [];
667925
668497
  for (const candidate of candidates) {
667926
668498
  const clean5 = candidate.trim();
667927
668499
  if (!clean5 || seen.has(clean5)) continue;
667928
668500
  seen.add(clean5);
667929
- unique3.push(clean5);
668501
+ unique2.push(clean5);
667930
668502
  }
667931
- return unique3;
668503
+ return unique2;
667932
668504
  }
667933
668505
  function extractBalancedTelegramJsonObjects(text2) {
667934
668506
  const objects = [];
@@ -668268,8 +668840,8 @@ function telegramRouterErrorText(err) {
668268
668840
  return err instanceof Error ? err.message : String(err);
668269
668841
  }
668270
668842
  function compactTelegramRouterDiagnosticText(text2, maxLength = 220) {
668271
- const compact3 = text2.replace(/\s+/g, " ").trim();
668272
- return compact3.length > maxLength ? `${compact3.slice(0, Math.max(0, maxLength - 3))}...` : compact3;
668843
+ const compact4 = text2.replace(/\s+/g, " ").trim();
668844
+ return compact4.length > maxLength ? `${compact4.slice(0, Math.max(0, maxLength - 3))}...` : compact4;
668273
668845
  }
668274
668846
  function telegramRouterErrorLooksLikeTimeout(err) {
668275
668847
  const text2 = telegramRouterErrorText(err);
@@ -668710,8 +669282,8 @@ function stripTelegramHiddenThinking(text2) {
668710
669282
  return withoutClosedThink.replace(/<think>[\s\S]*$/gi, "");
668711
669283
  }
668712
669284
  function sanitizeTelegramProgressText(text2, maxLength) {
668713
- const compact3 = stripTelegramHiddenThinking(text2).replace(/\s+/g, " ").trim();
668714
- return compact3.length > maxLength ? compact3.slice(0, Math.max(0, maxLength - 3)) + "..." : compact3;
669285
+ const compact4 = stripTelegramHiddenThinking(text2).replace(/\s+/g, " ").trim();
669286
+ return compact4.length > maxLength ? compact4.slice(0, Math.max(0, maxLength - 3)) + "..." : compact4;
668715
669287
  }
668716
669288
  function isCodebaseMemoryStatus(text2) {
668717
669289
  return /^\s*\[CODEBASE MEMORY\]/i.test(stripTelegramHiddenThinking(text2));
@@ -668763,39 +669335,39 @@ function isTelegramNoReplySentinel(text2) {
668763
669335
  return lower === "no_reply" || lower.startsWith("no_reply");
668764
669336
  }
668765
669337
  function isTelegramInternalStatusText(text2) {
668766
- const compact3 = compactTelegramVisibleText(text2);
668767
- if (!compact3) return false;
668768
- const lower = compact3.toLowerCase();
668769
- if (isTelegramNoReplySentinel(compact3)) return true;
669338
+ const compact4 = compactTelegramVisibleText(text2);
669339
+ if (!compact4) return false;
669340
+ const lower = compact4.toLowerCase();
669341
+ if (isTelegramNoReplySentinel(compact4)) return true;
668770
669342
  if (lower === "complete" || lower === "completed") return true;
668771
- if (/^memory stage:/i.test(compact3)) return true;
668772
- if (/^\[ppr[-_\s]?skip\]/i.test(compact3)) return true;
669343
+ if (/^memory stage:/i.test(compact4)) return true;
669344
+ if (/^\[ppr[-_\s]?skip\]/i.test(compact4)) return true;
668773
669345
  if (/^(casual|ambient|group)\b.{0,180}\b(skipping|skipped|not directed|no action needed|no reply)\b/i.test(
668774
- compact3
669346
+ compact4
668775
669347
  ))
668776
669348
  return true;
668777
- if (/^no further action needed\b/i.test(compact3)) return true;
669349
+ if (/^no further action needed\b/i.test(compact4)) return true;
668778
669350
  if (/^no action needed\b.{0,120}\b(task|complete|completed|done)\b/i.test(
668779
- compact3
669351
+ compact4
668780
669352
  ))
668781
669353
  return true;
668782
- if (/^(there'?s|there is) no active task\b/i.test(compact3)) return true;
668783
- if (/^everything'?s (done|complete|completed|wrapped up)\b/i.test(compact3))
669354
+ if (/^(there'?s|there is) no active task\b/i.test(compact4)) return true;
669355
+ if (/^everything'?s (done|complete|completed|wrapped up)\b/i.test(compact4))
668784
669356
  return true;
668785
669357
  if (/\balready (been )?(provided|answered|handled|delivered) above\b/i.test(
668786
- compact3
669358
+ compact4
668787
669359
  ))
668788
669360
  return true;
668789
669361
  if (/\b(no remaining work|nothing left to do|task is complete|task has been completed)\b/i.test(
668790
- compact3
669362
+ compact4
668791
669363
  ))
668792
669364
  return true;
668793
669365
  return false;
668794
669366
  }
668795
669367
  function isTelegramStuckSelfTalkSegment(text2) {
668796
- const compact3 = text2.trim();
668797
- if (!compact3) return false;
668798
- return TELEGRAM_STUCK_SELF_TALK_PREFIXES.some((re) => re.test(compact3));
669368
+ const compact4 = text2.trim();
669369
+ if (!compact4) return false;
669370
+ return TELEGRAM_STUCK_SELF_TALK_PREFIXES.some((re) => re.test(compact4));
668799
669371
  }
668800
669372
  function stripTelegramStuckSelfTalk(text2) {
668801
669373
  if (!text2) return "";
@@ -668868,11 +669440,11 @@ function truncateTelegramContext(text2, maxLength) {
668868
669440
  );
668869
669441
  }
668870
669442
  function truncateTelegramContextLine(text2, maxLength = TELEGRAM_CONTEXT_LINE_LIMIT) {
668871
- const compact3 = normalizeTelegramOutboundLinks(
669443
+ const compact4 = normalizeTelegramOutboundLinks(
668872
669444
  stripTelegramHiddenThinking(text2)
668873
669445
  ).replace(/\s+/g, " ").trim();
668874
- if (compact3.length <= maxLength) return compact3;
668875
- return truncateTelegramUrlSafe(compact3, maxLength);
669446
+ if (compact4.length <= maxLength) return compact4;
669447
+ return truncateTelegramUrlSafe(compact4, maxLength);
668876
669448
  }
668877
669449
  function redactTelegramLocalPaths(text2) {
668878
669450
  return text2.replace(
@@ -668927,10 +669499,10 @@ function telegramHistoryTime(entry) {
668927
669499
  });
668928
669500
  }
668929
669501
  function formatTelegramIdentitySignals(signals) {
668930
- const unique3 = [
669502
+ const unique2 = [
668931
669503
  ...new Set(signals.map((signal) => signal.trim()).filter(Boolean))
668932
669504
  ];
668933
- return unique3.length > 0 ? unique3.join(", ") : "none";
669505
+ return unique2.length > 0 ? unique2.join(", ") : "none";
668934
669506
  }
668935
669507
  function summarizeTelegramMessageAttachments(msg) {
668936
669508
  const parts = [];
@@ -669451,12 +670023,12 @@ function buildTelegramHelpHTML(scope, maxPublicCommands = 24) {
669451
670023
  ...commands.flatMap((cmd) => cmd.signatures)
669452
670024
  ];
669453
670025
  const seen = /* @__PURE__ */ new Set();
669454
- const unique3 = signatures.filter((sig) => {
670026
+ const unique2 = signatures.filter((sig) => {
669455
670027
  if (seen.has(sig.signature)) return false;
669456
670028
  seen.add(sig.signature);
669457
670029
  return true;
669458
670030
  });
669459
- const visible = scope === "public" ? unique3.slice(0, maxPublicCommands) : unique3;
670031
+ const visible = scope === "public" ? unique2.slice(0, maxPublicCommands) : unique2;
669460
670032
  const lines = [
669461
670033
  `<b>Commands (${scope === "admin" ? "admin full scope" : "public secure scope"})</b>`,
669462
670034
  "",
@@ -669464,7 +670036,7 @@ function buildTelegramHelpHTML(scope, maxPublicCommands = 24) {
669464
670036
  (sig) => `<code>${escapeTelegramHTML(sig.signature)}</code> - ${escapeTelegramHTML(sig.description)}`
669465
670037
  )
669466
670038
  ];
669467
- if (scope === "public" && unique3.length > visible.length) {
670039
+ if (scope === "public" && unique2.length > visible.length) {
669468
670040
  lines.push("");
669469
670041
  lines.push(
669470
670042
  `Public scope truncated to ${visible.length} safe commands. Authenticate as admin for full command help.`
@@ -675301,9 +675873,9 @@ ${mediaContext}` : ""
675301
675873
  if (!userMemory.toneTags.includes(tag)) userMemory.toneTags.push(tag);
675302
675874
  }
675303
675875
  userMemory.toneTags = userMemory.toneTags.slice(0, 20);
675304
- const compact3 = stripTelegramHiddenThinking(entry.text || "").replace(/\s+/g, " ").trim();
675305
- if (compact3) {
675306
- userMemory.lastMessages.push(compact3);
675876
+ const compact4 = stripTelegramHiddenThinking(entry.text || "").replace(/\s+/g, " ").trim();
675877
+ if (compact4) {
675878
+ userMemory.lastMessages.push(compact4);
675307
675879
  userMemory.lastMessages = userMemory.lastMessages.slice(-40);
675308
675880
  }
675309
675881
  for (const topic of telegramMemoryTags(
@@ -683697,20 +684269,20 @@ Scoped workspace: ${scopedRoot}`,
683697
684269
  };
683698
684270
  }
683699
684271
  async deleteTelegramMessages(chatId, messageIds, currentMsg) {
683700
- const unique3 = [...new Set(messageIds)].filter((id) => Number.isFinite(id));
683701
- if (unique3.length === 0)
684272
+ const unique2 = [...new Set(messageIds)].filter((id) => Number.isFinite(id));
684273
+ if (unique2.length === 0)
683702
684274
  throw new Error(
683703
684275
  "deleteTelegramMessages requires at least one message id."
683704
684276
  );
683705
684277
  await this.assertTelegramBotRightsForAction(
683706
684278
  "delete_messages",
683707
684279
  chatId,
683708
- unique3,
684280
+ unique2,
683709
684281
  currentMsg
683710
684282
  );
683711
684283
  const chunks = [];
683712
- for (let idx = 0; idx < unique3.length; idx += 100)
683713
- chunks.push(unique3.slice(idx, idx + 100));
684284
+ for (let idx = 0; idx < unique2.length; idx += 100)
684285
+ chunks.push(unique2.slice(idx, idx + 100));
683714
684286
  const results = [];
683715
684287
  for (const chunk of chunks) {
683716
684288
  const result = await this.apiCall("deleteMessages", {
@@ -683728,9 +684300,9 @@ Scoped workspace: ${scopedRoot}`,
683728
684300
  telegram_method: "deleteMessages",
683729
684301
  ok: true,
683730
684302
  chat_id: chatId,
683731
- message_ids: unique3,
684303
+ message_ids: unique2,
683732
684304
  batches: results,
683733
- bot_rights_checked: !this.telegramTargetLooksPrivate(chatId, currentMsg) && !unique3.every((id) => this.isKnownAssistantTelegramMessage(chatId, id)),
684305
+ bot_rights_checked: !this.telegramTargetLooksPrivate(chatId, currentMsg) && !unique2.every((id) => this.isKnownAssistantTelegramMessage(chatId, id)),
683734
684306
  policy_scope: this.telegramToolPolicy.chatOverrides?.[String(chatId)] ? "chat" : "global/default"
683735
684307
  };
683736
684308
  }