omnius 1.0.386 → 1.0.387

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();
@@ -294005,27 +294005,27 @@ function compactWorkboardSnapshot(snapshot, maxCards = 24) {
294005
294005
  };
294006
294006
  }
294007
294007
  function formatWorkboardCompact(snapshot, maxCards = 24) {
294008
- const compact3 = compactWorkboardSnapshot(snapshot, maxCards);
294008
+ const compact4 = compactWorkboardSnapshot(snapshot, maxCards);
294009
294009
  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}`
294010
+ `Workboard ${compact4.runId} [${compact4.status}] owner=${compact4.owner} updated=${compact4.updatedAt}`,
294011
+ `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
294012
  ];
294013
- if (compact3.cards.length === 0) {
294013
+ if (compact4.cards.length === 0) {
294014
294014
  lines.push("Cards: none");
294015
294015
  } else {
294016
294016
  lines.push("Cards:");
294017
- for (const card of compact3.cards) {
294017
+ for (const card of compact4.cards) {
294018
294018
  const assignee = card.assignee ? ` assignee=${card.assignee}` : "";
294019
294019
  const deps = card.dependencies.length > 0 ? ` deps=${card.dependencies.join(",")}` : "";
294020
294020
  const blocker = card.blocker ? ` blocker=${card.blocker}` : "";
294021
294021
  lines.push(`- ${card.id} [${card.status}/${card.lane}]${assignee} evidence=${card.evidenceCount}${deps}: ${card.title}${blocker}`);
294022
294022
  }
294023
294023
  }
294024
- if (compact3.hiddenCardCount > 0)
294025
- lines.push(`Hidden cards: ${compact3.hiddenCardCount}`);
294026
- if (compact3.diagnostics.length > 0) {
294024
+ if (compact4.hiddenCardCount > 0)
294025
+ lines.push(`Hidden cards: ${compact4.hiddenCardCount}`);
294026
+ if (compact4.diagnostics.length > 0) {
294027
294027
  lines.push("Diagnostics:");
294028
- for (const diagnostic of compact3.diagnostics) {
294028
+ for (const diagnostic of compact4.diagnostics) {
294029
294029
  lines.push(`- ${diagnostic.code} ${diagnostic.severity}${diagnostic.cardId ? ` card=${diagnostic.cardId}` : ""}: ${diagnostic.message}`);
294030
294030
  }
294031
294031
  }
@@ -294857,11 +294857,11 @@ var init_workboard = __esm({
294857
294857
  mutated: false
294858
294858
  };
294859
294859
  }
294860
- const compact3 = formatWorkboardCompact(snapshot, maxCards);
294860
+ const compact4 = formatWorkboardCompact(snapshot, maxCards);
294861
294861
  return {
294862
294862
  success: true,
294863
- output: compact3,
294864
- llmContent: compact3,
294863
+ output: compact4,
294864
+ llmContent: compact4,
294865
294865
  durationMs: performance.now() - start2,
294866
294866
  mutated: false
294867
294867
  };
@@ -298879,7 +298879,7 @@ var require_typescript = __commonJS({
298879
298879
  commandLineOptionOfCustomType: () => commandLineOptionOfCustomType,
298880
298880
  commentPragmas: () => commentPragmas,
298881
298881
  commonOptionsWithBuild: () => commonOptionsWithBuild,
298882
- compact: () => compact3,
298882
+ compact: () => compact4,
298883
298883
  compareBooleans: () => compareBooleans,
298884
298884
  compareComparableValues: () => compareComparableValues,
298885
298885
  compareDataObjects: () => compareDataObjects,
@@ -301394,7 +301394,7 @@ var require_typescript = __commonJS({
301394
301394
  }
301395
301395
  return true;
301396
301396
  }
301397
- function compact3(array) {
301397
+ function compact4(array) {
301398
301398
  let result;
301399
301399
  if (array !== void 0) {
301400
301400
  for (let i2 = 0; i2 < array.length; i2++) {
@@ -407465,7 +407465,7 @@ ${lanes.join("\n")}
407465
407465
  node.operatorToken,
407466
407466
  visitNode(node.right, visitor, isExpression)
407467
407467
  );
407468
- const expr = some(pendingExpressions) ? factory2.inlineExpressions(compact3([...pendingExpressions, node])) : node;
407468
+ const expr = some(pendingExpressions) ? factory2.inlineExpressions(compact4([...pendingExpressions, node])) : node;
407469
407469
  pendingExpressions = savedPendingExpressions;
407470
407470
  return expr;
407471
407471
  }
@@ -427734,7 +427734,7 @@ ${lanes.join("\n")}
427734
427734
  let parameterProperties;
427735
427735
  if (ctor) {
427736
427736
  const oldDiag2 = getSymbolAccessibilityDiagnostic;
427737
- parameterProperties = compact3(flatMap(ctor.parameters, (param) => {
427737
+ parameterProperties = compact4(flatMap(ctor.parameters, (param) => {
427738
427738
  if (!hasSyntacticModifier(
427739
427739
  param,
427740
427740
  31
@@ -464815,7 +464815,7 @@ ${newComment.split("\n").map((c8) => ` * ${c8}`).join("\n")}
464815
464815
  }
464816
464816
  const checker = context2.program.getTypeChecker();
464817
464817
  const trackChanges = (cb) => ts_textChanges_exports.ChangeTracker.with(context2, cb);
464818
- return compact3([
464818
+ return compact4([
464819
464819
  getDeclarationSiteFix(context2, expression, errorCode, checker, trackChanges),
464820
464820
  getUseSiteFix(context2, expression, errorCode, checker, trackChanges)
464821
464821
  ]);
@@ -488406,7 +488406,7 @@ ${content}
488406
488406
  const lastToken = last2(children2);
488407
488407
  const separateLastToken = separateTrailingSemicolon && lastToken.kind === 27;
488408
488408
  const rightChildren = children2.slice(splitTokenIndex + 1, separateLastToken ? children2.length - 1 : void 0);
488409
- const result = compact3([
488409
+ const result = compact4([
488410
488410
  leftChildren.length ? createSyntaxList2(leftChildren) : void 0,
488411
488411
  splitToken,
488412
488412
  rightChildren.length ? createSyntaxList2(rightChildren) : void 0
@@ -495130,7 +495130,7 @@ ${options2.prefix}` : "\n" : options2.prefix
495130
495130
  commandLineOptionOfCustomType: () => commandLineOptionOfCustomType,
495131
495131
  commentPragmas: () => commentPragmas,
495132
495132
  commonOptionsWithBuild: () => commonOptionsWithBuild,
495133
- compact: () => compact3,
495133
+ compact: () => compact4,
495134
495134
  compareBooleans: () => compareBooleans,
495135
495135
  compareComparableValues: () => compareComparableValues,
495136
495136
  compareDataObjects: () => compareDataObjects,
@@ -498681,11 +498681,11 @@ ${options2.prefix}` : "\n" : options2.prefix
498681
498681
  return true;
498682
498682
  }
498683
498683
  const set = /* @__PURE__ */ new Map();
498684
- let unique3 = 0;
498684
+ let unique2 = 0;
498685
498685
  for (const v of arr1) {
498686
498686
  if (set.get(v) !== true) {
498687
498687
  set.set(v, true);
498688
- unique3++;
498688
+ unique2++;
498689
498689
  }
498690
498690
  }
498691
498691
  for (const v of arr2) {
@@ -498695,10 +498695,10 @@ ${options2.prefix}` : "\n" : options2.prefix
498695
498695
  }
498696
498696
  if (isSet === true) {
498697
498697
  set.set(v, false);
498698
- unique3--;
498698
+ unique2--;
498699
498699
  }
498700
498700
  }
498701
- return unique3 === 0;
498701
+ return unique2 === 0;
498702
498702
  }
498703
498703
  function typeAcquisitionChanged(opt1, opt2) {
498704
498704
  return opt1.enable !== opt2.enable || !setIsEqualTo(opt1.include, opt2.include) || !setIsEqualTo(opt1.exclude, opt2.exclude);
@@ -559395,9 +559395,9 @@ function deriveClaimsFromProposedText(input) {
559395
559395
  if (!raw)
559396
559396
  return [];
559397
559397
  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)]));
559398
+ const unique2 = Array.from(new Set(segments.length > 0 ? segments : [cleanText(raw, 300)]));
559399
559399
  const existingIds = new Set((input.existing ?? []).map((claim) => claim.id));
559400
- return unique3.map((text2, index) => {
559400
+ return unique2.map((text2, index) => {
559401
559401
  const base3 = normalizeCompletionKey(text2, `claim_${index + 1}`).slice(0, 64);
559402
559402
  let id = base3 || `claim_${index + 1}`;
559403
559403
  let suffix = 2;
@@ -559751,7 +559751,9 @@ function finalizeCompletionLedgerTruth(ledger) {
559751
559751
  unresolved = appendUnresolved(unresolved, `Stale edit failure remains unresolved: ${entry.summary}`, entry.id);
559752
559752
  }
559753
559753
  });
559754
- if (lastVerification >= 0 && lastVerificationInvalidatingMutation > lastVerification) {
559754
+ if (lastVerificationInvalidatingMutation >= 0 && lastVerification < 0) {
559755
+ unresolved = appendUnresolved(unresolved, "File changes occurred without any successful verification evidence.", "verification_missing");
559756
+ } else if (lastVerification >= 0 && lastVerificationInvalidatingMutation > lastVerification) {
559755
559757
  unresolved = appendUnresolved(unresolved, "File changes occurred after the last successful verification; final verification is stale.", "verification_freshness");
559756
559758
  }
559757
559759
  unresolved = appendTestCountOverclaims(ledger, unresolved);
@@ -569505,7 +569507,7 @@ function resolveFocusSupervisorMode(configured, envValue = process.env["OMNIUS_F
569505
569507
  }
569506
569508
  function violatesDirective(directive, input) {
569507
569509
  if (input.toolName === "task_complete") {
569508
- return directive.state === "terminal_incomplete";
569510
+ return directive.requiredNextAction !== "report_blocked" && directive.requiredNextAction !== "report_incomplete";
569509
569511
  }
569510
569512
  if (input.toolName === "ask_user")
569511
569513
  return false;
@@ -569554,27 +569556,137 @@ function isReportTool(toolName) {
569554
569556
  return toolName === "task_complete" || toolName === "ask_user";
569555
569557
  }
569556
569558
  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"}`;
569559
+ if (isEditTool(toolName)) {
569560
+ const path12 = primaryPath(args);
569561
+ const target2 = editTargetDescriptor(toolName, args);
569562
+ return `${toolName}:${compactTarget(path12 || "no-path", 120)}:${compactTarget(target2 || "no-edit-target", 120)}`;
569563
+ }
569564
+ if (toolName === "shell") {
569565
+ const command = args?.["command"] ?? args?.["cmd"] ?? "";
569566
+ return `${toolName}:${compactTarget(String(command ?? "") || "no-command", 120)}`;
569567
+ }
569568
+ const target = primaryPath(args) ?? "";
569569
+ return `${toolName}:${compactTarget(String(target ?? "")) || "no-target"}`;
569559
569570
  }
569560
569571
  function failureFamilyKey(toolName, args, error, output) {
569561
- const sample = cleanFailureSample(error || output || "");
569562
- return `${actionFamily(toolName, args)}:${sample}`;
569572
+ const errorClass = failureErrorClass(error || output || "");
569573
+ return `${actionFamily(toolName, args)}:${errorClass}`;
569563
569574
  }
569564
569575
  function cleanFailureSample(text2) {
569565
569576
  return String(text2 || "").replace(/\s+/g, " ").trim().slice(0, 180);
569566
569577
  }
569567
- function normalizeTarget(text2) {
569568
- return text2.replace(/\s+/g, " ").trim().slice(0, 220);
569578
+ function failureErrorClass(text2) {
569579
+ const normalized = String(text2 || "").toLowerCase();
569580
+ if (/ambiguous|multiple occurrences|matches more than once/.test(normalized)) {
569581
+ return "stale_ambiguous_target";
569582
+ }
569583
+ if (/expected[_ -]?hash|hash mismatch|stale hash|beforehash|afterhash/.test(normalized)) {
569584
+ return "stale_expected_hash";
569585
+ }
569586
+ if (/expected.*content|content.*did not match|context mismatch|patch failed|hunk failed/.test(normalized)) {
569587
+ return "stale_expected_content";
569588
+ }
569589
+ if (/atomic.*abort|batch.*abort|skipped/.test(normalized)) {
569590
+ return "stale_atomic_batch_abort";
569591
+ }
569592
+ if (/old[_ -]?string|old text|old content|not found|no occurrences|0 occurrences|could not find/.test(normalized)) {
569593
+ return "stale_missing_target";
569594
+ }
569595
+ if (/permission|eacces|denied/.test(normalized))
569596
+ return "permission_denied";
569597
+ if (/timeout|timed out/.test(normalized))
569598
+ return "timeout";
569599
+ if (/exit code|non-zero|failed/.test(normalized))
569600
+ return "tool_failed";
569601
+ return compactTarget(cleanFailureSample(text2) || "unknown_failure", 80);
569569
569602
  }
569570
- function unique2(values) {
569571
- return [...new Set(values.filter((value2) => value2.trim().length > 0))];
569603
+ function primaryPath(args) {
569604
+ if (!args)
569605
+ return "";
569606
+ const direct = args["path"] ?? args["file"] ?? args["filePath"] ?? args["file_path"] ?? "";
569607
+ if (typeof direct === "string" && direct.trim())
569608
+ return direct.trim();
569609
+ const edits = args["edits"];
569610
+ if (Array.isArray(edits)) {
569611
+ for (const edit of edits) {
569612
+ if (!edit || typeof edit !== "object")
569613
+ continue;
569614
+ const rec = edit;
569615
+ const editPath = rec["path"] ?? rec["file"] ?? rec["filePath"] ?? rec["file_path"];
569616
+ if (typeof editPath === "string" && editPath.trim())
569617
+ return editPath.trim();
569618
+ }
569619
+ }
569620
+ return "";
569572
569621
  }
569573
- var directiveCounter, FocusSupervisor;
569622
+ function editTargetDescriptor(toolName, args) {
569623
+ if (!args)
569624
+ return "";
569625
+ const parts = [];
569626
+ for (const key of [
569627
+ "old_string",
569628
+ "oldString",
569629
+ "oldText",
569630
+ "search",
569631
+ "expected_old_string",
569632
+ "expectedHash",
569633
+ "expected_hash",
569634
+ "mode",
569635
+ "offset",
569636
+ "limit",
569637
+ "start_line"
569638
+ ]) {
569639
+ const value2 = args[key];
569640
+ if (typeof value2 === "string" || typeof value2 === "number") {
569641
+ parts.push(`${key}=${String(value2)}`);
569642
+ }
569643
+ }
569644
+ const edits = args["edits"];
569645
+ if (Array.isArray(edits)) {
569646
+ for (const edit of edits.slice(0, 6)) {
569647
+ if (!edit || typeof edit !== "object")
569648
+ continue;
569649
+ const rec = edit;
569650
+ const editPath = rec["path"] ?? rec["file"] ?? rec["filePath"] ?? rec["file_path"];
569651
+ const target = rec["old_string"] ?? rec["oldString"] ?? rec["oldText"] ?? rec["search"] ?? rec["expected_old_string"] ?? rec["offset"] ?? rec["start_line"] ?? "";
569652
+ parts.push(`${String(editPath ?? "")}=${String(target ?? "")}`);
569653
+ }
569654
+ }
569655
+ if (parts.length === 0 && toolName === "file_patch") {
569656
+ const newContent = args["new_content"] ?? args["patch"] ?? "";
569657
+ if (typeof newContent === "string" && newContent.trim()) {
569658
+ parts.push(`patch=${newContent.slice(0, 240)}`);
569659
+ }
569660
+ }
569661
+ return parts.join("\n").replace(/\s+/g, " ").trim();
569662
+ }
569663
+ function compactTarget(text2, max = 220) {
569664
+ const normalized = text2.replace(/\s+/g, " ").trim();
569665
+ if (normalized.length <= max)
569666
+ return normalized;
569667
+ return `${normalized.slice(0, Math.max(24, max - 18))}#${quickHash(normalized)}`;
569668
+ }
569669
+ function quickHash(input) {
569670
+ let hash = 2166136261;
569671
+ for (let index = 0; index < input.length; index++) {
569672
+ hash ^= input.charCodeAt(index);
569673
+ hash = Math.imul(hash, 16777619) >>> 0;
569674
+ }
569675
+ return hash.toString(16).padStart(8, "0");
569676
+ }
569677
+ function uniqueLimited(values) {
569678
+ const uniqueValues = [...new Set(values.filter((value2) => value2.trim().length > 0))];
569679
+ if (uniqueValues.length <= MAX_FORBIDDEN_FAMILIES)
569680
+ return uniqueValues;
569681
+ return uniqueValues.slice(-MAX_FORBIDDEN_FAMILIES);
569682
+ }
569683
+ var directiveCounter, TERMINAL_INCOMPLETE_IGNORE_THRESHOLD, MAX_FORBIDDEN_FAMILIES, FocusSupervisor;
569574
569684
  var init_focusSupervisor = __esm({
569575
569685
  "packages/orchestrator/dist/focusSupervisor.js"() {
569576
569686
  "use strict";
569577
569687
  directiveCounter = 0;
569688
+ TERMINAL_INCOMPLETE_IGNORE_THRESHOLD = 8;
569689
+ MAX_FORBIDDEN_FAMILIES = 12;
569578
569690
  FocusSupervisor = class {
569579
569691
  mode;
569580
569692
  modelTier;
@@ -569637,13 +569749,14 @@ var init_focusSupervisor = __esm({
569637
569749
  this.ignoredDirectiveStreak++;
569638
569750
  const strict = this.shouldStrictlyIntervene(input.context);
569639
569751
  if (strict && prior.ignoredCount >= 1) {
569752
+ const terminal = this.ignoredDirectiveStreak >= TERMINAL_INCOMPLETE_IGNORE_THRESHOLD;
569640
569753
  const ignoredManyTimes = this.ignoredDirectiveStreak >= 3;
569641
569754
  const directive = this.setDirective({
569642
569755
  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([
569756
+ state: terminal ? "terminal_incomplete" : ignoredManyTimes ? "verify_or_block" : "single_next_action",
569757
+ 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}`,
569758
+ requiredNextAction: terminal ? "report_incomplete" : prior.requiredNextAction,
569759
+ forbiddenActionFamilies: uniqueLimited([
569647
569760
  ...prior.forbiddenActionFamilies,
569648
569761
  family
569649
569762
  ])
@@ -569652,7 +569765,7 @@ var init_focusSupervisor = __esm({
569652
569765
  `[FOCUS SUPERVISOR BLOCK] The previous directive was ignored: ${prior.reason}`,
569653
569766
  `Required next action: ${directive.requiredNextAction}.`,
569654
569767
  `Blocked action family: ${family}.`,
569655
- "Take the required next action, or report blocked/incomplete with evidence."
569768
+ 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
569769
  ].join("\n"), false);
569657
569770
  }
569658
569771
  }
@@ -569738,15 +569851,17 @@ var init_focusSupervisor = __esm({
569738
569851
  const next = {
569739
569852
  count: (existing?.count ?? 0) + 1,
569740
569853
  lastTurn: input.turn,
569741
- sample: cleanFailureSample(input.error || input.output || "")
569854
+ sample: cleanFailureSample(input.error || input.output || ""),
569855
+ errorClass: failureErrorClass(input.error || input.output || "")
569742
569856
  };
569743
569857
  this.failureFamilies.set(family, next);
569744
569858
  if (next.count >= 2 && this.shouldStrictlyIntervene(this.lastContext)) {
569859
+ const staleEditFailure = isEditTool(input.toolName) && next.errorClass.startsWith("stale_");
569745
569860
  this.setDirective({
569746
569861
  turn: input.turn,
569747
569862
  state: "forced_replan",
569748
569863
  reason: `same ${input.toolName} failure family repeated ${next.count} times: ${next.sample}`,
569749
- requiredNextAction: input.toolName === "shell" ? "edit_different_target" : "update_todos",
569864
+ requiredNextAction: staleEditFailure ? "read_authoritative_target" : input.toolName === "shell" ? "edit_different_target" : "update_todos",
569750
569865
  forbiddenActionFamilies: [actionFamily(input.toolName, input.args)]
569751
569866
  });
569752
569867
  }
@@ -569770,7 +569885,7 @@ var init_focusSupervisor = __esm({
569770
569885
  state: "terminal_incomplete",
569771
569886
  reason,
569772
569887
  requiredNextAction: "report_incomplete",
569773
- forbiddenActionFamilies: ["brute_force", "task_complete"]
569888
+ forbiddenActionFamilies: ["brute_force"]
569774
569889
  });
569775
569890
  }
569776
569891
  shouldStrictlyIntervene(context2) {
@@ -569802,7 +569917,7 @@ var init_focusSupervisor = __esm({
569802
569917
  const stable = existing && existing.state === input.state && existing.reason === input.reason && existing.requiredNextAction === input.requiredNextAction;
569803
569918
  const directive = stable ? {
569804
569919
  ...existing,
569805
- forbiddenActionFamilies: unique2([
569920
+ forbiddenActionFamilies: uniqueLimited([
569806
569921
  ...existing.forbiddenActionFamilies,
569807
569922
  ...input.forbiddenActionFamilies
569808
569923
  ])
@@ -569811,7 +569926,7 @@ var init_focusSupervisor = __esm({
569811
569926
  state: input.state,
569812
569927
  reason: input.reason,
569813
569928
  requiredNextAction: input.requiredNextAction,
569814
- forbiddenActionFamilies: unique2(input.forbiddenActionFamilies),
569929
+ forbiddenActionFamilies: uniqueLimited(input.forbiddenActionFamilies),
569815
569930
  createdTurn: input.turn,
569816
569931
  ignoredCount: 0
569817
569932
  };
@@ -570589,24 +570704,132 @@ function estimateTokens3(messages2) {
570589
570704
  const chars = messages2.reduce((sum, message2) => sum + message2.content.length + message2.role.length + (message2.name?.length ?? 0), 0);
570590
570705
  return Math.ceil(chars / 4);
570591
570706
  }
570592
- function evidenceMessage(event) {
570707
+ function evidenceMessage(folded) {
570708
+ const event = folded.event;
570593
570709
  const status = event.success === true ? "ok" : event.success === false ? "failed" : "unknown";
570594
570710
  const parts = [
570595
570711
  `tool=${event.name}`,
570596
570712
  `status=${status}`,
570597
- typeof event.turn === "number" ? `turn=${event.turn}` : "",
570713
+ folded.count > 1 ? `turns=${folded.firstTurn ?? "?"}-${folded.lastTurn ?? "?"}` : typeof event.turn === "number" ? `turn=${event.turn}` : "",
570714
+ folded.count > 1 ? `repeats=${folded.count}` : "",
570598
570715
  event.evidenceId ? `evidence=${event.evidenceId}` : "",
570599
- event.outputPreview ? `observed=${event.outputPreview}` : ""
570716
+ event.outputPreview ? `observed=${observedPreview(event, folded.count)}` : ""
570600
570717
  ].filter(Boolean);
570601
570718
  return { role: "system", content: `[RUN EVIDENCE] ${parts.join(" ")}` };
570602
570719
  }
570720
+ function foldToolEvents(events) {
570721
+ const byFamily = /* @__PURE__ */ new Map();
570722
+ let folded = 0;
570723
+ for (const event of events) {
570724
+ const family = evidenceFamily(event);
570725
+ const existing = byFamily.get(family);
570726
+ if (existing) {
570727
+ folded++;
570728
+ existing.count++;
570729
+ existing.event = event;
570730
+ existing.lastTurn = event.turn ?? existing.lastTurn;
570731
+ continue;
570732
+ }
570733
+ byFamily.set(family, {
570734
+ event,
570735
+ count: 1,
570736
+ firstTurn: event.turn,
570737
+ lastTurn: event.turn
570738
+ });
570739
+ }
570740
+ const foldedMessages = [...byFamily.values()].map(evidenceMessage);
570741
+ let dropped = events.length - foldedMessages.length;
570742
+ let selected = foldedMessages;
570743
+ if (selected.length > MAX_EVIDENCE_MESSAGES) {
570744
+ dropped += selected.length - MAX_EVIDENCE_MESSAGES;
570745
+ selected = selected.slice(-MAX_EVIDENCE_MESSAGES);
570746
+ }
570747
+ let usedChars = 0;
570748
+ const budgeted = [];
570749
+ for (const message2 of [...selected].reverse()) {
570750
+ const cost = message2.content.length;
570751
+ if (usedChars + cost > MAX_EVIDENCE_CHARS && budgeted.length > 0) {
570752
+ dropped++;
570753
+ continue;
570754
+ }
570755
+ budgeted.push(message2);
570756
+ usedChars += cost;
570757
+ }
570758
+ return {
570759
+ messages: budgeted.reverse(),
570760
+ retained: budgeted.length,
570761
+ dropped,
570762
+ folded
570763
+ };
570764
+ }
570765
+ function evidenceFamily(event) {
570766
+ const status = event.success === true ? "ok" : event.success === false ? "failed" : "unknown";
570767
+ const preview = normalizePreview(event.outputPreview ?? "");
570768
+ if (preview.includes("[FOCUS SUPERVISOR BLOCK]")) {
570769
+ return `synthetic-focus-block:${event.name}:${status}`;
570770
+ }
570771
+ if (preview.includes("[STALE EDIT LOOP BLOCKED]")) {
570772
+ return `stale-edit-block:${event.name}:${status}`;
570773
+ }
570774
+ if (event.success === false) {
570775
+ return `${event.name}:${status}:${failureClass(preview)}`;
570776
+ }
570777
+ const firstLine = preview.split("\n")[0] ?? preview;
570778
+ return `${event.name}:${status}:${quickHash2(firstLine.slice(0, 500))}`;
570779
+ }
570780
+ function observedPreview(event, repeatCount) {
570781
+ const preview = event.outputPreview ?? "";
570782
+ if (!preview)
570783
+ return "";
570784
+ if (preview.includes("[FOCUS SUPERVISOR BLOCK]")) {
570785
+ return repeatCount > 1 ? `Repeated focus-supervisor block. Latest: ${compact(preview, 700)}` : compact(preview, 700);
570786
+ }
570787
+ if (event.name === "list_directory" || event.name === "find_files") {
570788
+ return compact(preview, 900);
570789
+ }
570790
+ return compact(preview, 1200);
570791
+ }
570792
+ function failureClass(text2) {
570793
+ const normalized = text2.toLowerCase();
570794
+ if (/old[_ -]?string|old text|old content|not found|no occurrences|could not find/.test(normalized)) {
570795
+ return "stale-missing-target";
570796
+ }
570797
+ if (/focus supervisor block/.test(normalized))
570798
+ return "focus-block";
570799
+ if (/permission|eacces|denied/.test(normalized))
570800
+ return "permission";
570801
+ if (/timeout|timed out/.test(normalized))
570802
+ return "timeout";
570803
+ if (/exit code|non-zero|failed/.test(normalized))
570804
+ return "failed";
570805
+ return quickHash2(normalized.slice(0, 500));
570806
+ }
570807
+ function normalizePreview(text2) {
570808
+ return text2.replace(/\s+/g, " ").trim();
570809
+ }
570810
+ function compact(text2, max) {
570811
+ const normalized = text2.replace(/\s+/g, " ").trim();
570812
+ if (normalized.length <= max)
570813
+ return normalized;
570814
+ return `${normalized.slice(0, Math.max(24, max - 18))}#${quickHash2(normalized)}`;
570815
+ }
570816
+ function quickHash2(input) {
570817
+ let hash = 2166136261;
570818
+ for (let index = 0; index < input.length; index++) {
570819
+ hash ^= input.charCodeAt(index);
570820
+ hash = Math.imul(hash, 16777619) >>> 0;
570821
+ }
570822
+ return hash.toString(16).padStart(8, "0");
570823
+ }
570603
570824
  function createDefaultContextEngine() {
570604
570825
  return new DefaultContextEngine();
570605
570826
  }
570606
- var DefaultContextEngine;
570827
+ var MAX_EVIDENCE_MESSAGES, MAX_EVIDENCE_CHARS, DefaultContextEngine;
570607
570828
  var init_contextEngine = __esm({
570608
570829
  "packages/orchestrator/dist/contextEngine.js"() {
570609
570830
  "use strict";
570831
+ MAX_EVIDENCE_MESSAGES = 40;
570832
+ MAX_EVIDENCE_CHARS = 24e3;
570610
570833
  DefaultContextEngine = class {
570611
570834
  async build(input) {
570612
570835
  return this.render(input, false);
@@ -570615,7 +570838,8 @@ var init_contextEngine = __esm({
570615
570838
  return this.render(input, true);
570616
570839
  }
570617
570840
  render(input, allowCompaction) {
570618
- const evidence = (input.toolEvents ?? []).map(evidenceMessage);
570841
+ const foldedEvidence = foldToolEvents(input.toolEvents ?? []);
570842
+ const evidence = foldedEvidence.messages;
570619
570843
  const hints = (input.memoryHints ?? []).filter((hint) => hint.trim().length > 0).slice(-8).map((hint) => ({ role: "system", content: `[MEMORY HINT] ${hint.trim()}` }));
570620
570844
  const contract = input.runState?.completionContract ? [{ role: "system", content: input.runState.completionContract }] : [];
570621
570845
  const beforeMessages = [...evidence, ...hints, ...contract, ...input.messages];
@@ -570642,6 +570866,8 @@ var init_contextEngine = __esm({
570642
570866
  const allMessages = [...evidence, ...hints, ...contract, ...compactedMessages];
570643
570867
  const after = estimateTokens3(allMessages);
570644
570868
  return {
570869
+ messages: allMessages,
570870
+ compactedMessages,
570645
570871
  systemMessages: allMessages.filter((m2) => m2.role === "system"),
570646
570872
  conversationMessages: allMessages.filter((m2) => m2.role !== "system"),
570647
570873
  compacted,
@@ -570651,8 +570877,9 @@ var init_contextEngine = __esm({
570651
570877
  tokenEstimateAfter: after,
570652
570878
  compacted,
570653
570879
  compactionStrategy: compacted ? "drop_oldest_non_evidence" : "none",
570654
- evidenceRetained: evidence.length,
570655
- evidenceDropped
570880
+ evidenceRetained: foldedEvidence.retained,
570881
+ evidenceDropped: evidenceDropped + foldedEvidence.dropped,
570882
+ evidenceFolded: foldedEvidence.folded
570656
570883
  }
570657
570884
  };
570658
570885
  }
@@ -572881,6 +573108,7 @@ var init_agenticRunner = __esm({
572881
573108
  // stale edit loops, completion holds, and context pressure into a single
572882
573109
  // next-action contract injected through the active context frame.
572883
573110
  _focusSupervisor = null;
573111
+ _focusTerminalLedgerRecorded = false;
572884
573112
  // Generic, cross-session failure→resolution learning: learns the token-level
572885
573113
  // change that turned a failed command into a working one (e.g. python→python3)
572886
573114
  // from observed pairs, and surfaces it before a matching command runs — so
@@ -572889,6 +573117,7 @@ var init_agenticRunner = __esm({
572889
573117
  _resolutionMemory = new ResolutionMemory();
572890
573118
  _lastContextFrameDiagnostics = null;
572891
573119
  _lastContextPressureSnapshot = null;
573120
+ _lastFocusContextSnapshot = null;
572892
573121
  _lastActiveForgettingReport = null;
572893
573122
  _lastContextConsolidationTurn = -1e3;
572894
573123
  /** WO-CE-BOUNDARY: Context engine instance for structured context assembly */
@@ -572950,13 +573179,85 @@ var init_agenticRunner = __esm({
572950
573179
  this._workboard = createWorkboard(dir, {
572951
573180
  runId,
572952
573181
  owner: this.options.subAgent ? "sub-agent" : "agent",
572953
- title: (this._taskState.goal || "").slice(0, 120) || void 0
573182
+ goal: this._taskState.originalGoal || this._taskState.goal || void 0,
573183
+ title: (this._taskState.goal || "").slice(0, 120) || void 0,
573184
+ cards: this._initialWorkboardCardsForGoal(this._taskState.originalGoal || this._taskState.goal || "")
572954
573185
  });
572955
573186
  } catch {
572956
573187
  this._workboard = loadWorkboardSnapshot(dir, runId);
572957
573188
  }
572958
573189
  return this._workboard;
572959
573190
  }
573191
+ _initialWorkboardCardsForGoal(goal) {
573192
+ if (!this.writesUserTaskArtifacts())
573193
+ return [];
573194
+ if (this.options.subAgent || this.options.recursionDepth > 0)
573195
+ return [];
573196
+ const normalizedGoal = goal.replace(/\s+/g, " ").trim();
573197
+ if (normalizedGoal.length < 120)
573198
+ return [];
573199
+ return [
573200
+ {
573201
+ id: "discover-current-state",
573202
+ title: "Discover current state",
573203
+ description: "Identify the relevant files, runtime entrypoints, constraints, and current failure evidence before changing behavior.",
573204
+ lane: "worker",
573205
+ status: "in_progress",
573206
+ assignee: "agent",
573207
+ role: "worker",
573208
+ evidenceRequired: true,
573209
+ evidenceRequirements: [
573210
+ "file_read, grep_search, or shell evidence identifying the authoritative targets",
573211
+ "current failure or baseline observation when available"
573212
+ ]
573213
+ },
573214
+ {
573215
+ id: "implement-repair",
573216
+ title: "Implement smallest repair",
573217
+ description: "Apply the narrowest code or asset changes that address the discovered root cause.",
573218
+ lane: "ready",
573219
+ status: "open",
573220
+ assignee: "agent",
573221
+ role: "worker",
573222
+ dependencies: ["discover-current-state"],
573223
+ evidenceRequired: true,
573224
+ evidenceRequirements: [
573225
+ "file_edit, file_patch, batch_edit, or file_write evidence for each changed target",
573226
+ "stale edit failures resolved by fresh current-file evidence"
573227
+ ]
573228
+ },
573229
+ {
573230
+ id: "integrate-and-run",
573231
+ title: "Integrate and run",
573232
+ description: "Exercise the changed system through the intended runtime path rather than only inspecting files.",
573233
+ lane: "verification",
573234
+ status: "open",
573235
+ assignee: "agent",
573236
+ role: "verifier",
573237
+ dependencies: ["implement-repair"],
573238
+ evidenceRequired: true,
573239
+ evidenceRequirements: [
573240
+ "shell evidence showing the configured runtime, training, build, or simulation command was attempted",
573241
+ "captured output sufficient to distinguish progress from setup failure"
573242
+ ]
573243
+ },
573244
+ {
573245
+ id: "verify-observed-outcome",
573246
+ title: "Verify observed outcome",
573247
+ description: "Record objective success, incomplete verification, or a concrete blocker from the runtime evidence.",
573248
+ lane: "verification",
573249
+ status: "open",
573250
+ assignee: "agent",
573251
+ role: "verifier",
573252
+ dependencies: ["integrate-and-run"],
573253
+ evidenceRequired: true,
573254
+ evidenceRequirements: [
573255
+ "successful verification output after the final mutation, or an explicit blocker",
573256
+ "completion summary reconciled with unresolved workboard cards"
573257
+ ]
573258
+ }
573259
+ ];
573260
+ }
572960
573261
  /**
572961
573262
  * Build a compact workboard context string for injection into the
572962
573263
  * system prompt. Returns null when no active board exists or when
@@ -572984,7 +573285,7 @@ var init_agenticRunner = __esm({
572984
573285
  parts.push(`Active: ${activeCards.length}`);
572985
573286
  }
572986
573287
  if (snapshot.cards.length > 0) {
572987
- const compact3 = compactWorkboardSnapshot(snapshot, 12);
573288
+ const compact4 = compactWorkboardSnapshot(snapshot, 12);
572988
573289
  parts.push(`
572989
573290
  ${formatWorkboardCompact(snapshot, 12)}`);
572990
573291
  }
@@ -573162,7 +573463,7 @@ ${parts.join("\n")}
573162
573463
  focusSupervisor: this._focusSupervisor?.snapshot()
573163
573464
  });
573164
573465
  if (record) {
573165
- this._focusSupervisor?.observeContext({
573466
+ const focusSnapshot = {
573166
573467
  estimatedTokens: record.metrics.estimatedTokens,
573167
573468
  rawDiscoveryChars: record.metrics.rawDiscoveryToolChars,
573168
573469
  activeEvidenceChars: record.metrics.activeEvidenceChars,
@@ -573171,7 +573472,9 @@ ${parts.join("\n")}
573171
573472
  pressureRatio: this._lastContextPressureSnapshot?.rawRatio ?? (this.options.contextWindowSize ? record.metrics.estimatedTokens / this.options.contextWindowSize : 0),
573172
573473
  droppedSignals: this._lastContextFrameDiagnostics?.droppedSignals ?? this._lastContextPressureSnapshot?.droppedSignals,
573173
573474
  truncatedSignals: this._lastContextFrameDiagnostics?.truncatedSignals ?? this._lastContextPressureSnapshot?.truncatedSignals
573174
- });
573475
+ };
573476
+ this._lastFocusContextSnapshot = focusSnapshot;
573477
+ this._focusSupervisor?.observeContext(focusSnapshot);
573175
573478
  }
573176
573479
  return record?.id ?? null;
573177
573480
  }
@@ -573191,13 +573494,59 @@ ${parts.join("\n")}
573191
573494
  }
573192
573495
  });
573193
573496
  }
573497
+ _maybeMarkFocusTerminalIncomplete(input) {
573498
+ if (input.decision.kind === "pass")
573499
+ return;
573500
+ const directive = input.decision.directive;
573501
+ if (directive.state !== "terminal_incomplete" || directive.requiredNextAction !== "report_incomplete") {
573502
+ return;
573503
+ }
573504
+ if (!this._completionIncompleteVerification) {
573505
+ const reason = directive.reason;
573506
+ const blocked = input.blockedTool ? `Blocked tool: ${input.blockedTool}.` : "";
573507
+ const details = input.decision.kind === "block_tool_call" ? input.decision.message : input.decision.message;
573508
+ this._completionIncompleteVerification = {
573509
+ reason,
573510
+ summary: [
573511
+ "INCOMPLETE_VERIFICATION: focus supervisor stopped a repeated recovery loop.",
573512
+ blocked,
573513
+ "",
573514
+ "Reason:",
573515
+ reason,
573516
+ "",
573517
+ "Evidence:",
573518
+ details.slice(0, 2e3)
573519
+ ].filter((line) => line.length > 0).join("\n")
573520
+ };
573521
+ this.emit({
573522
+ type: "status",
573523
+ content: `Focus supervisor terminal incomplete: ${reason.slice(0, 220)}`,
573524
+ turn: input.turn,
573525
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
573526
+ });
573527
+ }
573528
+ if (this._completionLedger && !this._focusTerminalLedgerRecorded) {
573529
+ this._completionLedger = recordToolEvidence(this._completionLedger, {
573530
+ name: "focus_supervisor",
573531
+ success: false,
573532
+ outputPreview: this._completionIncompleteVerification.summary.slice(0, 500),
573533
+ argsKey: input.blockedTool ?? ""
573534
+ });
573535
+ this._saveCompletionLedgerSafe();
573536
+ this._focusTerminalLedgerRecorded = true;
573537
+ }
573538
+ }
573194
573539
  _buildFocusContextSnapshot() {
573540
+ const last2 = this._lastFocusContextSnapshot;
573195
573541
  return {
573196
573542
  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
573543
+ estimatedTokens: this._lastContextPressureSnapshot?.rawTokens ?? last2?.estimatedTokens,
573544
+ rawDiscoveryChars: last2?.rawDiscoveryChars,
573545
+ activeEvidenceChars: last2?.activeEvidenceChars,
573546
+ activeFrameChars: this._lastContextFrameDiagnostics?.totalChars ?? last2?.activeFrameChars,
573547
+ signalToNoiseRatio: last2?.signalToNoiseRatio,
573548
+ droppedSignals: this._lastContextFrameDiagnostics?.droppedSignals ?? this._lastContextPressureSnapshot?.droppedSignals ?? last2?.droppedSignals,
573549
+ truncatedSignals: this._lastContextFrameDiagnostics?.truncatedSignals ?? this._lastContextPressureSnapshot?.truncatedSignals ?? last2?.truncatedSignals
573201
573550
  };
573202
573551
  }
573203
573552
  _emitModelResolutionTelemetry(purpose, turn) {
@@ -573475,10 +573824,10 @@ ${parts.join("\n")}
573475
573824
  const afterMarker = tail.slice(marker.length);
573476
573825
  const nextH2 = afterMarker.search(/\n## (?!#)/);
573477
573826
  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()}
573827
+ const compact4 = raw.replace(/\n{3,}/g, "\n\n").trim();
573828
+ if (compact4.length <= limit)
573829
+ return compact4;
573830
+ return `${compact4.slice(0, Math.max(0, limit - 18)).trimEnd()}
573482
573831
  ... [truncated]`;
573483
573832
  }
573484
573833
  /**
@@ -576734,21 +577083,21 @@ ${sections.join("\n")}` : sections.join("\n");
576734
577083
  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
577084
  }
576736
577085
  if (filesRead.length > 0) {
576737
- const unique3 = [...new Set(filesRead)].slice(0, 30);
576738
- sections.push(`Files already read (${unique3.length}): ${unique3.join(", ")}`);
577086
+ const unique2 = [...new Set(filesRead)].slice(0, 30);
577087
+ sections.push(`Files already read (${unique2.length}): ${unique2.join(", ")}`);
576739
577088
  }
576740
577089
  if (dirsListed.length > 0) {
576741
- const unique3 = [...new Set(dirsListed)].slice(0, 15);
576742
- sections.push(`Directories already listed (${unique3.length}): ${unique3.join(", ")}`);
577090
+ const unique2 = [...new Set(dirsListed)].slice(0, 15);
577091
+ sections.push(`Directories already listed (${unique2.length}): ${unique2.join(", ")}`);
576743
577092
  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
577093
  }
576745
577094
  if (searches.length > 0) {
576746
- const unique3 = [...new Set(searches)].slice(0, 15);
576747
- sections.push(`Searches already run (${unique3.length}): ${unique3.join(", ")}`);
577095
+ const unique2 = [...new Set(searches)].slice(0, 15);
577096
+ sections.push(`Searches already run (${unique2.length}): ${unique2.join(", ")}`);
576748
577097
  }
576749
577098
  if (shells.length > 0) {
576750
- const unique3 = [...new Set(shells)].slice(0, 15);
576751
- sections.push(`Shell commands already executed (${unique3.length}): ${unique3.join(", ")}`);
577099
+ const unique2 = [...new Set(shells)].slice(0, 15);
577100
+ sections.push(`Shell commands already executed (${unique2.length}): ${unique2.join(", ")}`);
576752
577101
  }
576753
577102
  if (sections.length <= 1)
576754
577103
  return null;
@@ -578412,6 +578761,7 @@ Respond with your assessment, then take action.`;
578412
578761
  this._completionIncompleteVerification = null;
578413
578762
  this._completionCaveat = null;
578414
578763
  this._completionLedger = null;
578764
+ this._focusTerminalLedgerRecorded = false;
578415
578765
  this._staleEditFamilies.clear();
578416
578766
  this._lastWorldStateTurn = -1;
578417
578767
  this._fileWritesSinceLastWorldState = 0;
@@ -578474,6 +578824,7 @@ Respond with your assessment, then take action.`;
578474
578824
  this._evidenceLedger = new EvidenceLedger();
578475
578825
  this._lastContextFrameDiagnostics = null;
578476
578826
  this._lastContextPressureSnapshot = null;
578827
+ this._lastFocusContextSnapshot = null;
578477
578828
  this._lastActiveForgettingReport = null;
578478
578829
  this._lastContextConsolidationTurn = -1e3;
578479
578830
  this._contextFrameBuilder = new ContextFrameBuilder();
@@ -580683,7 +581034,16 @@ If you're stuck, try a completely different approach. Do NOT repeat what failed
580683
581034
  completionContract: this._completionContract ? formatCompletionContract(this._completionContract) : void 0
580684
581035
  }
580685
581036
  };
580686
- await this._contextEngine.compact(ceCompactInput);
581037
+ const ceCompactOutput = await this._contextEngine.compact(ceCompactInput);
581038
+ if (ceCompactOutput.compacted && ceCompactOutput.compactedMessages.length > 0 && ceCompactOutput.compactedMessages.length < compacted.length) {
581039
+ messages2.length = 0;
581040
+ messages2.push(...ceCompactOutput.compactedMessages.map((m2) => ({
581041
+ role: m2.role,
581042
+ content: m2.content,
581043
+ ...m2.name ? { name: m2.name } : {}
581044
+ })));
581045
+ compacted = messages2;
581046
+ }
580687
581047
  } catch {
580688
581048
  }
580689
581049
  }
@@ -580793,6 +581153,7 @@ ${memoryLines.join("\n")}`
580793
581153
  this.proactivePrune(compacted, turn);
580794
581154
  this.microcompact(compacted, recentToolResults);
580795
581155
  this._insertContextFrame(compacted, await this._buildTurnContextFrame(turn, compacted, recentToolResults, environmentBlock));
581156
+ let requestMessages = compacted;
580796
581157
  {
580797
581158
  const _limits = this.contextLimits();
580798
581159
  const ceInput = {
@@ -580815,10 +581176,13 @@ ${memoryLines.join("\n")}`
580815
581176
  if (ceOutput.diagnostics.evidenceRetained > 0 || ceInput.runState?.completionContract || ceInput.memoryHints?.length) {
580816
581177
  const engineExtra = ceOutput.systemMessages.filter((m2) => !ceInput.messages.some((im) => im.content === m2.content));
580817
581178
  if (engineExtra.length > 0) {
580818
- compacted.unshift(...engineExtra.map((m2) => ({
580819
- role: "system",
580820
- content: m2.content
580821
- })));
581179
+ requestMessages = [
581180
+ ...engineExtra.map((m2) => ({
581181
+ role: "system",
581182
+ content: m2.content
581183
+ })),
581184
+ ...compacted
581185
+ ];
580822
581186
  }
580823
581187
  }
580824
581188
  } catch {
@@ -580826,7 +581190,7 @@ ${memoryLines.join("\n")}`
580826
581190
  }
580827
581191
  const { maxOutputTokens: effectiveMaxTokens } = this.contextLimits();
580828
581192
  const chatRequest = {
580829
- messages: compacted,
581193
+ messages: requestMessages,
580830
581194
  tools: toolDefs,
580831
581195
  temperature: this.options.temperature,
580832
581196
  maxTokens: effectiveMaxTokens,
@@ -581010,6 +581374,10 @@ ${memoryLines.join("\n")}`
581010
581374
  'When done, output: {"tool": "task_complete", "args": {"summary": "what you did"}}'
581011
581375
  ].join("\n");
581012
581376
  messages2.push({ role: "system", content: toolInjectMsg });
581377
+ chatRequest.messages = [
581378
+ ...requestMessages,
581379
+ { role: "system", content: toolInjectMsg }
581380
+ ];
581013
581381
  chatRequest.tools = [];
581014
581382
  try {
581015
581383
  this._recordContextWindowDump("agent_turn_prompt_tool_retry", chatRequest, turn, 1);
@@ -581676,6 +582044,11 @@ Use the saved fact to continue the promised synthesis or next concrete step, or
581676
582044
  blockedTool: tc.name,
581677
582045
  turn
581678
582046
  });
582047
+ this._maybeMarkFocusTerminalIncomplete({
582048
+ decision: focusDecision2,
582049
+ blockedTool: tc.name,
582050
+ turn
582051
+ });
581679
582052
  }
581680
582053
  this.emit({
581681
582054
  type: "tool_call",
@@ -581734,6 +582107,11 @@ Use the saved fact to continue the promised synthesis or next concrete step, or
581734
582107
  blockedTool: tc.name,
581735
582108
  turn
581736
582109
  });
582110
+ this._maybeMarkFocusTerminalIncomplete({
582111
+ decision: focusDecision2,
582112
+ blockedTool: tc.name,
582113
+ turn
582114
+ });
581737
582115
  }
581738
582116
  this.emit({
581739
582117
  type: "tool_call",
@@ -581972,6 +582350,11 @@ ${cachedResult}`,
581972
582350
  blockedTool: focusDecision.kind === "block_tool_call" ? tc.name : void 0,
581973
582351
  turn
581974
582352
  });
582353
+ this._maybeMarkFocusTerminalIncomplete({
582354
+ decision: focusDecision,
582355
+ blockedTool: focusDecision.kind === "block_tool_call" ? tc.name : void 0,
582356
+ turn
582357
+ });
581975
582358
  if (focusDecision.kind === "inject_guidance") {
581976
582359
  pushSoftInjection("system", focusDecision.message);
581977
582360
  } else if (!repeatShortCircuit) {
@@ -587489,8 +587872,8 @@ ${trimmedNew}`;
587489
587872
  buildAdversaryToolOutcomeEvidence(toolName, toolArgs, content, succeeded) {
587490
587873
  const pathValue = toolArgs?.["path"] ?? toolArgs?.["file"] ?? toolArgs?.["filePath"] ?? toolArgs?.["file_path"];
587491
587874
  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);
587875
+ const compact4 = content.replace(/\s+/g, " ").trim();
587876
+ const snippet = compact4.slice(0, 160);
587494
587877
  const digest3 = _createHash("sha256").update(content).digest("hex").slice(0, 16);
587495
587878
  const lineCount = content.length > 0 ? content.split("\n").length : 0;
587496
587879
  if (toolName === "file_read") {
@@ -608950,9 +609333,9 @@ function keywords(text2) {
608950
609333
  return out;
608951
609334
  }
608952
609335
  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()}...`;
609336
+ const compact4 = text2.replace(/\s+/g, " ").trim();
609337
+ if (compact4.length <= limit) return compact4;
609338
+ return `${compact4.slice(0, Math.max(0, limit - 3)).trimEnd()}...`;
608956
609339
  }
608957
609340
  function newDocument(scope) {
608958
609341
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
@@ -609287,9 +609670,9 @@ import { createHash as createHash33 } from "node:crypto";
609287
609670
  import { existsSync as existsSync109, readdirSync as readdirSync36, readFileSync as readFileSync86 } from "node:fs";
609288
609671
  import { basename as basename22, join as join123, resolve as resolve54 } from "node:path";
609289
609672
  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()}...`;
609673
+ const compact4 = text2.replace(/\s+/g, " ").trim();
609674
+ if (compact4.length <= limit) return compact4;
609675
+ return `${compact4.slice(0, Math.max(0, limit - 3)).trimEnd()}...`;
609293
609676
  }
609294
609677
  function blockText(text2, limit) {
609295
609678
  const clean5 = text2.replace(/\r\n/g, "\n").trim();
@@ -620593,10 +620976,10 @@ ${CONTENT_BG_SEQ}`);
620593
620976
  if (this._telegramStatus.active) {
620594
620977
  const suffix = this._telegramStatus.activeSubAgents > 0 ? ` ${_StatusBar.digitBar(this._telegramStatus.activeSubAgents)}` : "";
620595
620978
  const label = `✈ tg${suffix}`;
620596
- const compact3 = `✈${suffix}`;
620979
+ const compact4 = `✈${suffix}`;
620597
620980
  sections.push({
620598
620981
  expanded: `${HEADER_TELEGRAM_FG}${label}\x1B[0m`,
620599
- compact: `${HEADER_TELEGRAM_FG}${compact3}\x1B[0m`,
620982
+ compact: `${HEADER_TELEGRAM_FG}${compact4}\x1B[0m`,
620600
620983
  expandedW: 2 + 3 + suffix.length,
620601
620984
  compactW: 2 + suffix.length,
620602
620985
  empty: false,
@@ -652866,9 +653249,9 @@ async function handleUpdate(subcommand, ctx3) {
652866
653249
  const installOverlay = startInstallOverlay(targetVersion);
652867
653250
  const stripInstallAnsi = (value2) => value2.replace(/\x1B\][^\x07]*(?:\x07|\x1B\\)/g, "").replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "").replace(/\r/g, "\n");
652868
653251
  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() + "…";
653252
+ const compact4 = value2.replace(/\s+/g, " ").trim();
653253
+ if (compact4.length <= max) return compact4;
653254
+ return compact4.slice(0, Math.max(1, max - 1)).trimEnd() + "…";
652872
653255
  };
652873
653256
  const summarizeInstallCommand = (cmd) => {
652874
653257
  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 +655212,14 @@ function loadFailurePatterns(store2) {
654829
655212
  const unresolved = store2.listUnresolved();
654830
655213
  if (unresolved.length === 0) return "";
654831
655214
  const seen = /* @__PURE__ */ new Set();
654832
- const unique3 = unresolved.filter((f2) => {
655215
+ const unique2 = unresolved.filter((f2) => {
654833
655216
  if (seen.has(f2.fingerprint)) return false;
654834
655217
  seen.add(f2.fingerprint);
654835
655218
  return true;
654836
655219
  });
654837
- if (unique3.length === 0) return "";
655220
+ if (unique2.length === 0) return "";
654838
655221
  const lines = ["Known failure patterns (avoid repeating these):"];
654839
- for (const f2 of unique3.slice(0, 8)) {
655222
+ for (const f2 of unique2.slice(0, 8)) {
654840
655223
  const file = f2.filePath ? ` in ${f2.filePath}` : "";
654841
655224
  lines.push(`- [${f2.failureType}]${file}: ${f2.errorMessage.slice(0, 150)}`);
654842
655225
  }
@@ -657620,8 +658003,8 @@ function generateDescriptors(repoRoot) {
657620
658003
  if (repoName2 && !tags.includes(repoName2)) {
657621
658004
  tags.push(repoName2);
657622
658005
  }
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) => ({
658006
+ const unique2 = [...new Set(tags.map((t2) => t2.toLowerCase().trim()).filter((t2) => t2.length > 1 && t2.length < 60))];
658007
+ const phrases = unique2.map((text2) => ({
657625
658008
  text: text2,
657626
658009
  color: weightedColor(profile)
657627
658010
  }));
@@ -657642,7 +658025,7 @@ function generateDescriptors(repoRoot) {
657642
658025
  ];
657643
658026
  for (const fb of fallbacks) {
657644
658027
  if (phrases.length >= 20) break;
657645
- if (!unique3.includes(fb)) {
658028
+ if (!unique2.includes(fb)) {
657646
658029
  phrases.push({ text: fb, color: weightedColor(profile) });
657647
658030
  }
657648
658031
  }
@@ -662634,9 +663017,9 @@ function toolCallBlock(name10, args) {
662634
663017
  if (args == null || typeof args === "object" && Object.keys(args).length === 0) {
662635
663018
  return header;
662636
663019
  }
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>`;
663020
+ const compact4 = typeof args === "string" ? args : safeJson(args, false);
663021
+ if (compact4.length <= 120 && !compact4.includes("\n")) {
663022
+ return `${header} <code>${escapeHtml2(compact4)}</code>`;
662640
663023
  }
662641
663024
  const pretty = typeof args === "string" ? args : safeJson(args, true);
662642
663025
  return `${header}
@@ -662973,13 +663356,13 @@ function buildScopedToolList(scope) {
662973
663356
  const commandSigs = commands.flatMap((cmd) => cmd.signatures);
662974
663357
  const allSigs = [...syntheticSigs, ...commandSigs];
662975
663358
  const seen = /* @__PURE__ */ new Set();
662976
- const unique3 = allSigs.filter((sig) => {
663359
+ const unique2 = allSigs.filter((sig) => {
662977
663360
  if (seen.has(sig.signature)) return false;
662978
663361
  seen.add(sig.signature);
662979
663362
  return true;
662980
663363
  });
662981
663364
  const entries = [];
662982
- for (const sig of unique3) {
663365
+ for (const sig of unique2) {
662983
663366
  const matchingCmd = commands.find(
662984
663367
  (cmd) => cmd.signatures.some((s2) => s2.signature === sig.signature)
662985
663368
  );
@@ -666086,7 +666469,7 @@ function stableHash2(value2, length4 = 16) {
666086
666469
  function clean3(value2) {
666087
666470
  return String(value2 ?? "").replace(/\s+/g, " ").trim();
666088
666471
  }
666089
- function compact(value2, max = 420) {
666472
+ function compact2(value2, max = 420) {
666090
666473
  const text2 = clean3(value2);
666091
666474
  return text2.length > max ? `${text2.slice(0, Math.max(0, max - 3)).trimEnd()}...` : text2;
666092
666475
  }
@@ -666167,7 +666550,7 @@ function contentFor(entry, sessionKey, options2) {
666167
666550
  `identity_boundary: ${identityBoundary(entry)}`,
666168
666551
  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
666552
  entry.mode ? `mode: ${entry.mode}` : "",
666170
- entry.mediaSummary ? `media: ${compact(entry.mediaSummary, 260)}` : "",
666553
+ entry.mediaSummary ? `media: ${compact2(entry.mediaSummary, 260)}` : "",
666171
666554
  "",
666172
666555
  entry.text
666173
666556
  ].filter((line) => line !== "");
@@ -666209,7 +666592,7 @@ function addTextEdges(graph, result, entry) {
666209
666592
  srcId: messageId,
666210
666593
  dstId: senderId,
666211
666594
  relation: "said_by",
666212
- fact: compact(entry.text, 260),
666595
+ fact: compact2(entry.text, 260),
666213
666596
  sourceEpisodeId: result.episodeId,
666214
666597
  modality: entry.role === "user" ? "social" : "text",
666215
666598
  confidence: entry.role === "assistant" ? 0.92 : 0.96
@@ -666221,7 +666604,7 @@ function addTextEdges(graph, result, entry) {
666221
666604
  srcId: messageId,
666222
666605
  dstId: channelTopic,
666223
666606
  relation: "related_to",
666224
- fact: compact(entry.text || entry.mediaSummary || "telegram message", 220),
666607
+ fact: compact2(entry.text || entry.mediaSummary || "telegram message", 220),
666225
666608
  sourceEpisodeId: result.episodeId,
666226
666609
  modality: entry.role === "user" ? "social" : "text",
666227
666610
  confidence: 0.72
@@ -666261,7 +666644,7 @@ function upsertTelegramReflectionMessage(repoRoot, sessionKey, entry, options2)
666261
666644
  }
666262
666645
  function queryFor(options2) {
666263
666646
  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));
666647
+ const recent = options2.history.slice(-12).map((entry) => compact2(`${senderLabel(entry)}: ${entry.text || entry.mediaSummary || ""}`, 180));
666265
666648
  return [
666266
666649
  `Telegram ${options2.chatType} ${options2.chatTitle || options2.chatId} reflection`,
666267
666650
  ...recent
@@ -666819,7 +667202,7 @@ function telegramSocialActorKey(actor) {
666819
667202
  if (typeof actor.userId === "number") return `user:${actor.userId}`;
666820
667203
  const username = cleanUsername(actor.username);
666821
667204
  if (username) return `username:${username.toLowerCase()}`;
666822
- const first2 = compact2(actor.firstName, 80).toLowerCase();
667205
+ const first2 = compact3(actor.firstName, 80).toLowerCase();
666823
667206
  return first2 ? `name:${first2}` : "unknown";
666824
667207
  }
666825
667208
  function telegramSocialActorKind(actor) {
@@ -666854,16 +667237,16 @@ function cleanUsername(value2) {
666854
667237
  return clean5 ? clean5.slice(0, 80) : void 0;
666855
667238
  }
666856
667239
  function compactOptional(value2, max) {
666857
- const clean5 = compact2(value2, max);
667240
+ const clean5 = compact3(value2, max);
666858
667241
  return clean5 || void 0;
666859
667242
  }
666860
- function compact2(value2, max) {
667243
+ function compact3(value2, max) {
666861
667244
  if (value2 === void 0 || value2 === null) return "";
666862
667245
  const clean5 = String(value2).replace(/\s+/g, " ").trim();
666863
667246
  return clean5.length > max ? `${clean5.slice(0, Math.max(0, max - 3)).trimEnd()}...` : clean5;
666864
667247
  }
666865
667248
  function jsonLine(value2, max) {
666866
- return JSON.stringify(compact2(value2, max));
667249
+ return JSON.stringify(compact3(value2, max));
666867
667250
  }
666868
667251
  function numberOr(value2, fallback) {
666869
667252
  return typeof value2 === "number" && Number.isFinite(value2) ? value2 : fallback;
@@ -667109,8 +667492,8 @@ function normalizeReplyPreferenceScope(raw) {
667109
667492
  function normalizeDeliveryCapability(raw) {
667110
667493
  if (!raw || typeof raw !== "object") return null;
667111
667494
  const value2 = raw;
667112
- const key = compact2(value2.key || "", 180);
667113
- const chatId = compact2(value2.chatId || "", 120);
667495
+ const key = compact3(value2.key || "", 180);
667496
+ const chatId = compact3(value2.chatId || "", 120);
667114
667497
  if (!key || !chatId) return null;
667115
667498
  const status = normalizeDeliveryStatus(value2.status);
667116
667499
  return {
@@ -667162,7 +667545,7 @@ function normalizeSalience(raw) {
667162
667545
  senderKey: String(value2.senderKey),
667163
667546
  actorKind: value2.actorKind === "bot" || value2.actorKind === "human" ? value2.actorKind : "unknown",
667164
667547
  signals: Array.isArray(value2.signals) ? value2.signals.map(String).slice(0, 16) : [],
667165
- textPreview: compact2(value2.textPreview || "", 240)
667548
+ textPreview: compact3(value2.textPreview || "", 240)
667166
667549
  };
667167
667550
  }
667168
667551
  function normalizeOutcome2(raw) {
@@ -667180,8 +667563,8 @@ function normalizeOutcome2(raw) {
667180
667563
  route: value2.route === "action" ? "action" : "chat",
667181
667564
  shouldReply: value2.shouldReply === true,
667182
667565
  confidence: clamp0113(numberOr(value2.confidence, 0)),
667183
- reason: compact2(value2.reason || "", 280),
667184
- source: compact2(value2.source || "unknown", 80),
667566
+ reason: compact3(value2.reason || "", 280),
667567
+ source: compact3(value2.source || "unknown", 80),
667185
667568
  silentDisposition: compactOptional(value2.silentDisposition, 280),
667186
667569
  mentalNote: compactOptional(value2.mentalNote, 360),
667187
667570
  memoryNote: compactOptional(value2.memoryNote, 360),
@@ -667208,7 +667591,7 @@ function normalizeDaydreamOpportunity(raw) {
667208
667591
  id,
667209
667592
  artifactId: String(value2.artifactId || "unknown"),
667210
667593
  generatedAt: String(value2.generatedAt || (/* @__PURE__ */ new Date()).toISOString()),
667211
- trigger: compact2(value2.trigger || "", 240),
667594
+ trigger: compact3(value2.trigger || "", 240),
667212
667595
  confidence: clamp0113(numberOr(value2.confidence, 0)),
667213
667596
  lifecycle,
667214
667597
  firstSeenAt: numberOr(value2.firstSeenAt, Date.now()),
@@ -667232,7 +667615,7 @@ function observeTelegramSocialMessage(state, input) {
667232
667615
  state.updatedAt = now2;
667233
667616
  const senderKey3 = upsertParticipant(state, input, now2, true);
667234
667617
  const thread = upsertThread(state, input, senderKey3, now2, true);
667235
- const text2 = compact2(input.text || "", 500);
667618
+ const text2 = compact3(input.text || "", 500);
667236
667619
  const participant = state.participants[senderKey3];
667237
667620
  if (participant) {
667238
667621
  participant.lastText = text2 || participant.lastText;
@@ -667267,8 +667650,8 @@ function commitTelegramSocialDecision(state, input) {
667267
667650
  route: input.route,
667268
667651
  shouldReply: input.shouldReply,
667269
667652
  confidence: clamp0113(input.confidence),
667270
- reason: compact2(input.reason, 280),
667271
- source: compact2(input.source, 80),
667653
+ reason: compact3(input.reason, 280),
667654
+ source: compact3(input.source, 80),
667272
667655
  silentDisposition: compactOptional(input.silentDisposition, 280),
667273
667656
  mentalNote: compactOptional(input.mentalNote, 360),
667274
667657
  memoryNote: compactOptional(input.memoryNote, 360),
@@ -667301,7 +667684,7 @@ function registerDaydreamOpportunities(state, opportunities, now2 = Date.now())
667301
667684
  id,
667302
667685
  artifactId: opportunity.artifactId || "unknown",
667303
667686
  generatedAt: opportunity.generatedAt || new Date(now2).toISOString(),
667304
- trigger: compact2(opportunity.trigger, 240),
667687
+ trigger: compact3(opportunity.trigger, 240),
667305
667688
  confidence: clamp0113(opportunity.confidence),
667306
667689
  lifecycle: "proposed",
667307
667690
  firstSeenAt: now2,
@@ -667311,7 +667694,7 @@ function registerDaydreamOpportunities(state, opportunities, now2 = Date.now())
667311
667694
  suppressedMessageIds: []
667312
667695
  };
667313
667696
  if (existing) {
667314
- item.trigger = compact2(opportunity.trigger, 240) || item.trigger;
667697
+ item.trigger = compact3(opportunity.trigger, 240) || item.trigger;
667315
667698
  item.confidence = clamp0113(opportunity.confidence);
667316
667699
  item.updatedAt = now2;
667317
667700
  }
@@ -667538,7 +667921,7 @@ function addSalience(state, input, senderKey3, now2, text2) {
667538
667921
  senderKey: senderKey3,
667539
667922
  actorKind: telegramSocialActorKind(input),
667540
667923
  signals,
667541
- textPreview: compact2(text2, 240)
667924
+ textPreview: compact3(text2, 240)
667542
667925
  });
667543
667926
  state.salience = state.salience.slice(-TELEGRAM_SOCIAL_LIMITS.salience);
667544
667927
  }
@@ -667921,14 +668304,14 @@ function parseTelegramReplyPreferenceUpdate(parsed) {
667921
668304
  }
667922
668305
  function uniqueTelegramJsonCandidates(candidates) {
667923
668306
  const seen = /* @__PURE__ */ new Set();
667924
- const unique3 = [];
668307
+ const unique2 = [];
667925
668308
  for (const candidate of candidates) {
667926
668309
  const clean5 = candidate.trim();
667927
668310
  if (!clean5 || seen.has(clean5)) continue;
667928
668311
  seen.add(clean5);
667929
- unique3.push(clean5);
668312
+ unique2.push(clean5);
667930
668313
  }
667931
- return unique3;
668314
+ return unique2;
667932
668315
  }
667933
668316
  function extractBalancedTelegramJsonObjects(text2) {
667934
668317
  const objects = [];
@@ -668268,8 +668651,8 @@ function telegramRouterErrorText(err) {
668268
668651
  return err instanceof Error ? err.message : String(err);
668269
668652
  }
668270
668653
  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;
668654
+ const compact4 = text2.replace(/\s+/g, " ").trim();
668655
+ return compact4.length > maxLength ? `${compact4.slice(0, Math.max(0, maxLength - 3))}...` : compact4;
668273
668656
  }
668274
668657
  function telegramRouterErrorLooksLikeTimeout(err) {
668275
668658
  const text2 = telegramRouterErrorText(err);
@@ -668710,8 +669093,8 @@ function stripTelegramHiddenThinking(text2) {
668710
669093
  return withoutClosedThink.replace(/<think>[\s\S]*$/gi, "");
668711
669094
  }
668712
669095
  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;
669096
+ const compact4 = stripTelegramHiddenThinking(text2).replace(/\s+/g, " ").trim();
669097
+ return compact4.length > maxLength ? compact4.slice(0, Math.max(0, maxLength - 3)) + "..." : compact4;
668715
669098
  }
668716
669099
  function isCodebaseMemoryStatus(text2) {
668717
669100
  return /^\s*\[CODEBASE MEMORY\]/i.test(stripTelegramHiddenThinking(text2));
@@ -668763,39 +669146,39 @@ function isTelegramNoReplySentinel(text2) {
668763
669146
  return lower === "no_reply" || lower.startsWith("no_reply");
668764
669147
  }
668765
669148
  function isTelegramInternalStatusText(text2) {
668766
- const compact3 = compactTelegramVisibleText(text2);
668767
- if (!compact3) return false;
668768
- const lower = compact3.toLowerCase();
668769
- if (isTelegramNoReplySentinel(compact3)) return true;
669149
+ const compact4 = compactTelegramVisibleText(text2);
669150
+ if (!compact4) return false;
669151
+ const lower = compact4.toLowerCase();
669152
+ if (isTelegramNoReplySentinel(compact4)) return true;
668770
669153
  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;
669154
+ if (/^memory stage:/i.test(compact4)) return true;
669155
+ if (/^\[ppr[-_\s]?skip\]/i.test(compact4)) return true;
668773
669156
  if (/^(casual|ambient|group)\b.{0,180}\b(skipping|skipped|not directed|no action needed|no reply)\b/i.test(
668774
- compact3
669157
+ compact4
668775
669158
  ))
668776
669159
  return true;
668777
- if (/^no further action needed\b/i.test(compact3)) return true;
669160
+ if (/^no further action needed\b/i.test(compact4)) return true;
668778
669161
  if (/^no action needed\b.{0,120}\b(task|complete|completed|done)\b/i.test(
668779
- compact3
669162
+ compact4
668780
669163
  ))
668781
669164
  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))
669165
+ if (/^(there'?s|there is) no active task\b/i.test(compact4)) return true;
669166
+ if (/^everything'?s (done|complete|completed|wrapped up)\b/i.test(compact4))
668784
669167
  return true;
668785
669168
  if (/\balready (been )?(provided|answered|handled|delivered) above\b/i.test(
668786
- compact3
669169
+ compact4
668787
669170
  ))
668788
669171
  return true;
668789
669172
  if (/\b(no remaining work|nothing left to do|task is complete|task has been completed)\b/i.test(
668790
- compact3
669173
+ compact4
668791
669174
  ))
668792
669175
  return true;
668793
669176
  return false;
668794
669177
  }
668795
669178
  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));
669179
+ const compact4 = text2.trim();
669180
+ if (!compact4) return false;
669181
+ return TELEGRAM_STUCK_SELF_TALK_PREFIXES.some((re) => re.test(compact4));
668799
669182
  }
668800
669183
  function stripTelegramStuckSelfTalk(text2) {
668801
669184
  if (!text2) return "";
@@ -668868,11 +669251,11 @@ function truncateTelegramContext(text2, maxLength) {
668868
669251
  );
668869
669252
  }
668870
669253
  function truncateTelegramContextLine(text2, maxLength = TELEGRAM_CONTEXT_LINE_LIMIT) {
668871
- const compact3 = normalizeTelegramOutboundLinks(
669254
+ const compact4 = normalizeTelegramOutboundLinks(
668872
669255
  stripTelegramHiddenThinking(text2)
668873
669256
  ).replace(/\s+/g, " ").trim();
668874
- if (compact3.length <= maxLength) return compact3;
668875
- return truncateTelegramUrlSafe(compact3, maxLength);
669257
+ if (compact4.length <= maxLength) return compact4;
669258
+ return truncateTelegramUrlSafe(compact4, maxLength);
668876
669259
  }
668877
669260
  function redactTelegramLocalPaths(text2) {
668878
669261
  return text2.replace(
@@ -668927,10 +669310,10 @@ function telegramHistoryTime(entry) {
668927
669310
  });
668928
669311
  }
668929
669312
  function formatTelegramIdentitySignals(signals) {
668930
- const unique3 = [
669313
+ const unique2 = [
668931
669314
  ...new Set(signals.map((signal) => signal.trim()).filter(Boolean))
668932
669315
  ];
668933
- return unique3.length > 0 ? unique3.join(", ") : "none";
669316
+ return unique2.length > 0 ? unique2.join(", ") : "none";
668934
669317
  }
668935
669318
  function summarizeTelegramMessageAttachments(msg) {
668936
669319
  const parts = [];
@@ -669451,12 +669834,12 @@ function buildTelegramHelpHTML(scope, maxPublicCommands = 24) {
669451
669834
  ...commands.flatMap((cmd) => cmd.signatures)
669452
669835
  ];
669453
669836
  const seen = /* @__PURE__ */ new Set();
669454
- const unique3 = signatures.filter((sig) => {
669837
+ const unique2 = signatures.filter((sig) => {
669455
669838
  if (seen.has(sig.signature)) return false;
669456
669839
  seen.add(sig.signature);
669457
669840
  return true;
669458
669841
  });
669459
- const visible = scope === "public" ? unique3.slice(0, maxPublicCommands) : unique3;
669842
+ const visible = scope === "public" ? unique2.slice(0, maxPublicCommands) : unique2;
669460
669843
  const lines = [
669461
669844
  `<b>Commands (${scope === "admin" ? "admin full scope" : "public secure scope"})</b>`,
669462
669845
  "",
@@ -669464,7 +669847,7 @@ function buildTelegramHelpHTML(scope, maxPublicCommands = 24) {
669464
669847
  (sig) => `<code>${escapeTelegramHTML(sig.signature)}</code> - ${escapeTelegramHTML(sig.description)}`
669465
669848
  )
669466
669849
  ];
669467
- if (scope === "public" && unique3.length > visible.length) {
669850
+ if (scope === "public" && unique2.length > visible.length) {
669468
669851
  lines.push("");
669469
669852
  lines.push(
669470
669853
  `Public scope truncated to ${visible.length} safe commands. Authenticate as admin for full command help.`
@@ -675301,9 +675684,9 @@ ${mediaContext}` : ""
675301
675684
  if (!userMemory.toneTags.includes(tag)) userMemory.toneTags.push(tag);
675302
675685
  }
675303
675686
  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);
675687
+ const compact4 = stripTelegramHiddenThinking(entry.text || "").replace(/\s+/g, " ").trim();
675688
+ if (compact4) {
675689
+ userMemory.lastMessages.push(compact4);
675307
675690
  userMemory.lastMessages = userMemory.lastMessages.slice(-40);
675308
675691
  }
675309
675692
  for (const topic of telegramMemoryTags(
@@ -683697,20 +684080,20 @@ Scoped workspace: ${scopedRoot}`,
683697
684080
  };
683698
684081
  }
683699
684082
  async deleteTelegramMessages(chatId, messageIds, currentMsg) {
683700
- const unique3 = [...new Set(messageIds)].filter((id) => Number.isFinite(id));
683701
- if (unique3.length === 0)
684083
+ const unique2 = [...new Set(messageIds)].filter((id) => Number.isFinite(id));
684084
+ if (unique2.length === 0)
683702
684085
  throw new Error(
683703
684086
  "deleteTelegramMessages requires at least one message id."
683704
684087
  );
683705
684088
  await this.assertTelegramBotRightsForAction(
683706
684089
  "delete_messages",
683707
684090
  chatId,
683708
- unique3,
684091
+ unique2,
683709
684092
  currentMsg
683710
684093
  );
683711
684094
  const chunks = [];
683712
- for (let idx = 0; idx < unique3.length; idx += 100)
683713
- chunks.push(unique3.slice(idx, idx + 100));
684095
+ for (let idx = 0; idx < unique2.length; idx += 100)
684096
+ chunks.push(unique2.slice(idx, idx + 100));
683714
684097
  const results = [];
683715
684098
  for (const chunk of chunks) {
683716
684099
  const result = await this.apiCall("deleteMessages", {
@@ -683728,9 +684111,9 @@ Scoped workspace: ${scopedRoot}`,
683728
684111
  telegram_method: "deleteMessages",
683729
684112
  ok: true,
683730
684113
  chat_id: chatId,
683731
- message_ids: unique3,
684114
+ message_ids: unique2,
683732
684115
  batches: results,
683733
- bot_rights_checked: !this.telegramTargetLooksPrivate(chatId, currentMsg) && !unique3.every((id) => this.isKnownAssistantTelegramMessage(chatId, id)),
684116
+ bot_rights_checked: !this.telegramTargetLooksPrivate(chatId, currentMsg) && !unique2.every((id) => this.isKnownAssistantTelegramMessage(chatId, id)),
683734
684117
  policy_scope: this.telegramToolPolicy.chatOverrides?.[String(chatId)] ? "chat" : "global/default"
683735
684118
  };
683736
684119
  }