omnius 1.0.385 → 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
  };
@@ -295326,6 +295326,35 @@ function getTodoSessionId() {
295326
295326
  return envSession;
295327
295327
  return "default";
295328
295328
  }
295329
+ function flattenNestedTodoItems(items, repairNotes, parentId) {
295330
+ const flattened = [];
295331
+ for (const item of items) {
295332
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
295333
+ flattened.push(item);
295334
+ continue;
295335
+ }
295336
+ const record = item;
295337
+ const children2 = Array.isArray(record["children"]) ? record["children"] : Array.isArray(record["subtasks"]) ? record["subtasks"] : [];
295338
+ const parentAware = { ...record };
295339
+ delete parentAware["children"];
295340
+ delete parentAware["subtasks"];
295341
+ if (parentId && typeof parentAware["parentId"] !== "string") {
295342
+ parentAware["parentId"] = parentId;
295343
+ }
295344
+ flattened.push(parentAware);
295345
+ const id = typeof parentAware["id"] === "string" && parentAware["id"].trim() ? parentAware["id"].trim() : void 0;
295346
+ if (children2.length > 0) {
295347
+ if (id) {
295348
+ repairNotes.push("flattened nested children/subtasks into parentId-linked todos");
295349
+ flattened.push(...flattenNestedTodoItems(children2, repairNotes, id));
295350
+ } else {
295351
+ repairNotes.push("left nested children unattached because parent todo had no stable id");
295352
+ flattened.push(...flattenNestedTodoItems(children2, repairNotes, parentId));
295353
+ }
295354
+ }
295355
+ }
295356
+ return flattened;
295357
+ }
295329
295358
  function validateLargeTaskDecomposition(todos) {
295330
295359
  if (todos.length < 20)
295331
295360
  return null;
@@ -295450,6 +295479,16 @@ Mark tasks complete IMMEDIATELY after finishing — don't batch. Never mark comp
295450
295479
  type: "array",
295451
295480
  items: { type: "string" },
295452
295481
  description: `REG-38: optional list of file paths this todo is expected to produce on disk. When you mark the todo 'completed', the supervisor inspects each declared path; missing/empty/stale files trigger a rejection with a specific gap critique. Use whenever a todo has concrete deliverables (e.g. ["src/lib/foo.ts", "tests/unit/foo.test.ts"]). Generic across stacks.`
295482
+ },
295483
+ children: {
295484
+ type: "array",
295485
+ description: "Optional nested child todos. The tool flattens children into parentId-linked todos before storing.",
295486
+ items: { type: "object" }
295487
+ },
295488
+ subtasks: {
295489
+ type: "array",
295490
+ description: "Alias for children. Use this for decomposed child work under a parent objective.",
295491
+ items: { type: "object" }
295453
295492
  }
295454
295493
  }
295455
295494
  }
@@ -295474,8 +295513,9 @@ Mark tasks complete IMMEDIATELY after finishing — don't batch. Never mark comp
295474
295513
  }
295475
295514
  const incoming = [];
295476
295515
  const repairNotes = [...normalized.repairNotes];
295477
- for (let index = 0; index < normalized.todos.length; index++) {
295478
- const raw = normalized.todos[index];
295516
+ const flattenedTodos = flattenNestedTodoItems(normalized.todos, repairNotes);
295517
+ for (let index = 0; index < flattenedTodos.length; index++) {
295518
+ const raw = flattenedTodos[index];
295479
295519
  if (!raw || typeof raw !== "object") {
295480
295520
  if (typeof raw === "string" && raw.trim()) {
295481
295521
  incoming.push({
@@ -298839,7 +298879,7 @@ var require_typescript = __commonJS({
298839
298879
  commandLineOptionOfCustomType: () => commandLineOptionOfCustomType,
298840
298880
  commentPragmas: () => commentPragmas,
298841
298881
  commonOptionsWithBuild: () => commonOptionsWithBuild,
298842
- compact: () => compact3,
298882
+ compact: () => compact4,
298843
298883
  compareBooleans: () => compareBooleans,
298844
298884
  compareComparableValues: () => compareComparableValues,
298845
298885
  compareDataObjects: () => compareDataObjects,
@@ -301354,7 +301394,7 @@ var require_typescript = __commonJS({
301354
301394
  }
301355
301395
  return true;
301356
301396
  }
301357
- function compact3(array) {
301397
+ function compact4(array) {
301358
301398
  let result;
301359
301399
  if (array !== void 0) {
301360
301400
  for (let i2 = 0; i2 < array.length; i2++) {
@@ -407425,7 +407465,7 @@ ${lanes.join("\n")}
407425
407465
  node.operatorToken,
407426
407466
  visitNode(node.right, visitor, isExpression)
407427
407467
  );
407428
- const expr = some(pendingExpressions) ? factory2.inlineExpressions(compact3([...pendingExpressions, node])) : node;
407468
+ const expr = some(pendingExpressions) ? factory2.inlineExpressions(compact4([...pendingExpressions, node])) : node;
407429
407469
  pendingExpressions = savedPendingExpressions;
407430
407470
  return expr;
407431
407471
  }
@@ -427694,7 +427734,7 @@ ${lanes.join("\n")}
427694
427734
  let parameterProperties;
427695
427735
  if (ctor) {
427696
427736
  const oldDiag2 = getSymbolAccessibilityDiagnostic;
427697
- parameterProperties = compact3(flatMap(ctor.parameters, (param) => {
427737
+ parameterProperties = compact4(flatMap(ctor.parameters, (param) => {
427698
427738
  if (!hasSyntacticModifier(
427699
427739
  param,
427700
427740
  31
@@ -464775,7 +464815,7 @@ ${newComment.split("\n").map((c8) => ` * ${c8}`).join("\n")}
464775
464815
  }
464776
464816
  const checker = context2.program.getTypeChecker();
464777
464817
  const trackChanges = (cb) => ts_textChanges_exports.ChangeTracker.with(context2, cb);
464778
- return compact3([
464818
+ return compact4([
464779
464819
  getDeclarationSiteFix(context2, expression, errorCode, checker, trackChanges),
464780
464820
  getUseSiteFix(context2, expression, errorCode, checker, trackChanges)
464781
464821
  ]);
@@ -488366,7 +488406,7 @@ ${content}
488366
488406
  const lastToken = last2(children2);
488367
488407
  const separateLastToken = separateTrailingSemicolon && lastToken.kind === 27;
488368
488408
  const rightChildren = children2.slice(splitTokenIndex + 1, separateLastToken ? children2.length - 1 : void 0);
488369
- const result = compact3([
488409
+ const result = compact4([
488370
488410
  leftChildren.length ? createSyntaxList2(leftChildren) : void 0,
488371
488411
  splitToken,
488372
488412
  rightChildren.length ? createSyntaxList2(rightChildren) : void 0
@@ -495090,7 +495130,7 @@ ${options2.prefix}` : "\n" : options2.prefix
495090
495130
  commandLineOptionOfCustomType: () => commandLineOptionOfCustomType,
495091
495131
  commentPragmas: () => commentPragmas,
495092
495132
  commonOptionsWithBuild: () => commonOptionsWithBuild,
495093
- compact: () => compact3,
495133
+ compact: () => compact4,
495094
495134
  compareBooleans: () => compareBooleans,
495095
495135
  compareComparableValues: () => compareComparableValues,
495096
495136
  compareDataObjects: () => compareDataObjects,
@@ -498641,11 +498681,11 @@ ${options2.prefix}` : "\n" : options2.prefix
498641
498681
  return true;
498642
498682
  }
498643
498683
  const set = /* @__PURE__ */ new Map();
498644
- let unique3 = 0;
498684
+ let unique2 = 0;
498645
498685
  for (const v of arr1) {
498646
498686
  if (set.get(v) !== true) {
498647
498687
  set.set(v, true);
498648
- unique3++;
498688
+ unique2++;
498649
498689
  }
498650
498690
  }
498651
498691
  for (const v of arr2) {
@@ -498655,10 +498695,10 @@ ${options2.prefix}` : "\n" : options2.prefix
498655
498695
  }
498656
498696
  if (isSet === true) {
498657
498697
  set.set(v, false);
498658
- unique3--;
498698
+ unique2--;
498659
498699
  }
498660
498700
  }
498661
- return unique3 === 0;
498701
+ return unique2 === 0;
498662
498702
  }
498663
498703
  function typeAcquisitionChanged(opt1, opt2) {
498664
498704
  return opt1.enable !== opt2.enable || !setIsEqualTo(opt1.include, opt2.include) || !setIsEqualTo(opt1.exclude, opt2.exclude);
@@ -559355,9 +559395,9 @@ function deriveClaimsFromProposedText(input) {
559355
559395
  if (!raw)
559356
559396
  return [];
559357
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);
559358
- 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)]));
559359
559399
  const existingIds = new Set((input.existing ?? []).map((claim) => claim.id));
559360
- return unique3.map((text2, index) => {
559400
+ return unique2.map((text2, index) => {
559361
559401
  const base3 = normalizeCompletionKey(text2, `claim_${index + 1}`).slice(0, 64);
559362
559402
  let id = base3 || `claim_${index + 1}`;
559363
559403
  let suffix = 2;
@@ -559711,7 +559751,9 @@ function finalizeCompletionLedgerTruth(ledger) {
559711
559751
  unresolved = appendUnresolved(unresolved, `Stale edit failure remains unresolved: ${entry.summary}`, entry.id);
559712
559752
  }
559713
559753
  });
559714
- 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) {
559715
559757
  unresolved = appendUnresolved(unresolved, "File changes occurred after the last successful verification; final verification is stale.", "verification_freshness");
559716
559758
  }
559717
559759
  unresolved = appendTestCountOverclaims(ledger, unresolved);
@@ -569465,7 +569507,7 @@ function resolveFocusSupervisorMode(configured, envValue = process.env["OMNIUS_F
569465
569507
  }
569466
569508
  function violatesDirective(directive, input) {
569467
569509
  if (input.toolName === "task_complete") {
569468
- return directive.state === "terminal_incomplete";
569510
+ return directive.requiredNextAction !== "report_blocked" && directive.requiredNextAction !== "report_incomplete";
569469
569511
  }
569470
569512
  if (input.toolName === "ask_user")
569471
569513
  return false;
@@ -569514,27 +569556,137 @@ function isReportTool(toolName) {
569514
569556
  return toolName === "task_complete" || toolName === "ask_user";
569515
569557
  }
569516
569558
  function actionFamily(toolName, args) {
569517
- const target = args?.["path"] ?? args?.["file"] ?? args?.["filePath"] ?? args?.["file_path"] ?? args?.["command"] ?? args?.["cmd"] ?? "";
569518
- 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"}`;
569519
569570
  }
569520
569571
  function failureFamilyKey(toolName, args, error, output) {
569521
- const sample = cleanFailureSample(error || output || "");
569522
- return `${actionFamily(toolName, args)}:${sample}`;
569572
+ const errorClass = failureErrorClass(error || output || "");
569573
+ return `${actionFamily(toolName, args)}:${errorClass}`;
569523
569574
  }
569524
569575
  function cleanFailureSample(text2) {
569525
569576
  return String(text2 || "").replace(/\s+/g, " ").trim().slice(0, 180);
569526
569577
  }
569527
- function normalizeTarget(text2) {
569528
- 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);
569602
+ }
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 "";
569621
+ }
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");
569529
569676
  }
569530
- function unique2(values) {
569531
- return [...new Set(values.filter((value2) => value2.trim().length > 0))];
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);
569532
569682
  }
569533
- var directiveCounter, FocusSupervisor;
569683
+ var directiveCounter, TERMINAL_INCOMPLETE_IGNORE_THRESHOLD, MAX_FORBIDDEN_FAMILIES, FocusSupervisor;
569534
569684
  var init_focusSupervisor = __esm({
569535
569685
  "packages/orchestrator/dist/focusSupervisor.js"() {
569536
569686
  "use strict";
569537
569687
  directiveCounter = 0;
569688
+ TERMINAL_INCOMPLETE_IGNORE_THRESHOLD = 8;
569689
+ MAX_FORBIDDEN_FAMILIES = 12;
569538
569690
  FocusSupervisor = class {
569539
569691
  mode;
569540
569692
  modelTier;
@@ -569597,13 +569749,14 @@ var init_focusSupervisor = __esm({
569597
569749
  this.ignoredDirectiveStreak++;
569598
569750
  const strict = this.shouldStrictlyIntervene(input.context);
569599
569751
  if (strict && prior.ignoredCount >= 1) {
569752
+ const terminal = this.ignoredDirectiveStreak >= TERMINAL_INCOMPLETE_IGNORE_THRESHOLD;
569600
569753
  const ignoredManyTimes = this.ignoredDirectiveStreak >= 3;
569601
569754
  const directive = this.setDirective({
569602
569755
  turn: input.turn,
569603
- state: ignoredManyTimes ? "verify_or_block" : "single_next_action",
569604
- 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}`,
569605
- requiredNextAction: prior.requiredNextAction,
569606
- 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([
569607
569760
  ...prior.forbiddenActionFamilies,
569608
569761
  family
569609
569762
  ])
@@ -569612,7 +569765,7 @@ var init_focusSupervisor = __esm({
569612
569765
  `[FOCUS SUPERVISOR BLOCK] The previous directive was ignored: ${prior.reason}`,
569613
569766
  `Required next action: ${directive.requiredNextAction}.`,
569614
569767
  `Blocked action family: ${family}.`,
569615
- "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."
569616
569769
  ].join("\n"), false);
569617
569770
  }
569618
569771
  }
@@ -569698,15 +569851,17 @@ var init_focusSupervisor = __esm({
569698
569851
  const next = {
569699
569852
  count: (existing?.count ?? 0) + 1,
569700
569853
  lastTurn: input.turn,
569701
- sample: cleanFailureSample(input.error || input.output || "")
569854
+ sample: cleanFailureSample(input.error || input.output || ""),
569855
+ errorClass: failureErrorClass(input.error || input.output || "")
569702
569856
  };
569703
569857
  this.failureFamilies.set(family, next);
569704
569858
  if (next.count >= 2 && this.shouldStrictlyIntervene(this.lastContext)) {
569859
+ const staleEditFailure = isEditTool(input.toolName) && next.errorClass.startsWith("stale_");
569705
569860
  this.setDirective({
569706
569861
  turn: input.turn,
569707
569862
  state: "forced_replan",
569708
569863
  reason: `same ${input.toolName} failure family repeated ${next.count} times: ${next.sample}`,
569709
- requiredNextAction: input.toolName === "shell" ? "edit_different_target" : "update_todos",
569864
+ requiredNextAction: staleEditFailure ? "read_authoritative_target" : input.toolName === "shell" ? "edit_different_target" : "update_todos",
569710
569865
  forbiddenActionFamilies: [actionFamily(input.toolName, input.args)]
569711
569866
  });
569712
569867
  }
@@ -569730,7 +569885,7 @@ var init_focusSupervisor = __esm({
569730
569885
  state: "terminal_incomplete",
569731
569886
  reason,
569732
569887
  requiredNextAction: "report_incomplete",
569733
- forbiddenActionFamilies: ["brute_force", "task_complete"]
569888
+ forbiddenActionFamilies: ["brute_force"]
569734
569889
  });
569735
569890
  }
569736
569891
  shouldStrictlyIntervene(context2) {
@@ -569762,7 +569917,7 @@ var init_focusSupervisor = __esm({
569762
569917
  const stable = existing && existing.state === input.state && existing.reason === input.reason && existing.requiredNextAction === input.requiredNextAction;
569763
569918
  const directive = stable ? {
569764
569919
  ...existing,
569765
- forbiddenActionFamilies: unique2([
569920
+ forbiddenActionFamilies: uniqueLimited([
569766
569921
  ...existing.forbiddenActionFamilies,
569767
569922
  ...input.forbiddenActionFamilies
569768
569923
  ])
@@ -569771,7 +569926,7 @@ var init_focusSupervisor = __esm({
569771
569926
  state: input.state,
569772
569927
  reason: input.reason,
569773
569928
  requiredNextAction: input.requiredNextAction,
569774
- forbiddenActionFamilies: unique2(input.forbiddenActionFamilies),
569929
+ forbiddenActionFamilies: uniqueLimited(input.forbiddenActionFamilies),
569775
569930
  createdTurn: input.turn,
569776
569931
  ignoredCount: 0
569777
569932
  };
@@ -570549,24 +570704,132 @@ function estimateTokens3(messages2) {
570549
570704
  const chars = messages2.reduce((sum, message2) => sum + message2.content.length + message2.role.length + (message2.name?.length ?? 0), 0);
570550
570705
  return Math.ceil(chars / 4);
570551
570706
  }
570552
- function evidenceMessage(event) {
570707
+ function evidenceMessage(folded) {
570708
+ const event = folded.event;
570553
570709
  const status = event.success === true ? "ok" : event.success === false ? "failed" : "unknown";
570554
570710
  const parts = [
570555
570711
  `tool=${event.name}`,
570556
570712
  `status=${status}`,
570557
- 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}` : "",
570558
570715
  event.evidenceId ? `evidence=${event.evidenceId}` : "",
570559
- event.outputPreview ? `observed=${event.outputPreview}` : ""
570716
+ event.outputPreview ? `observed=${observedPreview(event, folded.count)}` : ""
570560
570717
  ].filter(Boolean);
570561
570718
  return { role: "system", content: `[RUN EVIDENCE] ${parts.join(" ")}` };
570562
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
+ }
570563
570824
  function createDefaultContextEngine() {
570564
570825
  return new DefaultContextEngine();
570565
570826
  }
570566
- var DefaultContextEngine;
570827
+ var MAX_EVIDENCE_MESSAGES, MAX_EVIDENCE_CHARS, DefaultContextEngine;
570567
570828
  var init_contextEngine = __esm({
570568
570829
  "packages/orchestrator/dist/contextEngine.js"() {
570569
570830
  "use strict";
570831
+ MAX_EVIDENCE_MESSAGES = 40;
570832
+ MAX_EVIDENCE_CHARS = 24e3;
570570
570833
  DefaultContextEngine = class {
570571
570834
  async build(input) {
570572
570835
  return this.render(input, false);
@@ -570575,7 +570838,8 @@ var init_contextEngine = __esm({
570575
570838
  return this.render(input, true);
570576
570839
  }
570577
570840
  render(input, allowCompaction) {
570578
- const evidence = (input.toolEvents ?? []).map(evidenceMessage);
570841
+ const foldedEvidence = foldToolEvents(input.toolEvents ?? []);
570842
+ const evidence = foldedEvidence.messages;
570579
570843
  const hints = (input.memoryHints ?? []).filter((hint) => hint.trim().length > 0).slice(-8).map((hint) => ({ role: "system", content: `[MEMORY HINT] ${hint.trim()}` }));
570580
570844
  const contract = input.runState?.completionContract ? [{ role: "system", content: input.runState.completionContract }] : [];
570581
570845
  const beforeMessages = [...evidence, ...hints, ...contract, ...input.messages];
@@ -570602,6 +570866,8 @@ var init_contextEngine = __esm({
570602
570866
  const allMessages = [...evidence, ...hints, ...contract, ...compactedMessages];
570603
570867
  const after = estimateTokens3(allMessages);
570604
570868
  return {
570869
+ messages: allMessages,
570870
+ compactedMessages,
570605
570871
  systemMessages: allMessages.filter((m2) => m2.role === "system"),
570606
570872
  conversationMessages: allMessages.filter((m2) => m2.role !== "system"),
570607
570873
  compacted,
@@ -570611,8 +570877,9 @@ var init_contextEngine = __esm({
570611
570877
  tokenEstimateAfter: after,
570612
570878
  compacted,
570613
570879
  compactionStrategy: compacted ? "drop_oldest_non_evidence" : "none",
570614
- evidenceRetained: evidence.length,
570615
- evidenceDropped
570880
+ evidenceRetained: foldedEvidence.retained,
570881
+ evidenceDropped: evidenceDropped + foldedEvidence.dropped,
570882
+ evidenceFolded: foldedEvidence.folded
570616
570883
  }
570617
570884
  };
570618
570885
  }
@@ -572841,6 +573108,7 @@ var init_agenticRunner = __esm({
572841
573108
  // stale edit loops, completion holds, and context pressure into a single
572842
573109
  // next-action contract injected through the active context frame.
572843
573110
  _focusSupervisor = null;
573111
+ _focusTerminalLedgerRecorded = false;
572844
573112
  // Generic, cross-session failure→resolution learning: learns the token-level
572845
573113
  // change that turned a failed command into a working one (e.g. python→python3)
572846
573114
  // from observed pairs, and surfaces it before a matching command runs — so
@@ -572849,6 +573117,7 @@ var init_agenticRunner = __esm({
572849
573117
  _resolutionMemory = new ResolutionMemory();
572850
573118
  _lastContextFrameDiagnostics = null;
572851
573119
  _lastContextPressureSnapshot = null;
573120
+ _lastFocusContextSnapshot = null;
572852
573121
  _lastActiveForgettingReport = null;
572853
573122
  _lastContextConsolidationTurn = -1e3;
572854
573123
  /** WO-CE-BOUNDARY: Context engine instance for structured context assembly */
@@ -572910,13 +573179,85 @@ var init_agenticRunner = __esm({
572910
573179
  this._workboard = createWorkboard(dir, {
572911
573180
  runId,
572912
573181
  owner: this.options.subAgent ? "sub-agent" : "agent",
572913
- 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 || "")
572914
573185
  });
572915
573186
  } catch {
572916
573187
  this._workboard = loadWorkboardSnapshot(dir, runId);
572917
573188
  }
572918
573189
  return this._workboard;
572919
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
+ }
572920
573261
  /**
572921
573262
  * Build a compact workboard context string for injection into the
572922
573263
  * system prompt. Returns null when no active board exists or when
@@ -572944,7 +573285,7 @@ var init_agenticRunner = __esm({
572944
573285
  parts.push(`Active: ${activeCards.length}`);
572945
573286
  }
572946
573287
  if (snapshot.cards.length > 0) {
572947
- const compact3 = compactWorkboardSnapshot(snapshot, 12);
573288
+ const compact4 = compactWorkboardSnapshot(snapshot, 12);
572948
573289
  parts.push(`
572949
573290
  ${formatWorkboardCompact(snapshot, 12)}`);
572950
573291
  }
@@ -573122,7 +573463,7 @@ ${parts.join("\n")}
573122
573463
  focusSupervisor: this._focusSupervisor?.snapshot()
573123
573464
  });
573124
573465
  if (record) {
573125
- this._focusSupervisor?.observeContext({
573466
+ const focusSnapshot = {
573126
573467
  estimatedTokens: record.metrics.estimatedTokens,
573127
573468
  rawDiscoveryChars: record.metrics.rawDiscoveryToolChars,
573128
573469
  activeEvidenceChars: record.metrics.activeEvidenceChars,
@@ -573131,7 +573472,9 @@ ${parts.join("\n")}
573131
573472
  pressureRatio: this._lastContextPressureSnapshot?.rawRatio ?? (this.options.contextWindowSize ? record.metrics.estimatedTokens / this.options.contextWindowSize : 0),
573132
573473
  droppedSignals: this._lastContextFrameDiagnostics?.droppedSignals ?? this._lastContextPressureSnapshot?.droppedSignals,
573133
573474
  truncatedSignals: this._lastContextFrameDiagnostics?.truncatedSignals ?? this._lastContextPressureSnapshot?.truncatedSignals
573134
- });
573475
+ };
573476
+ this._lastFocusContextSnapshot = focusSnapshot;
573477
+ this._focusSupervisor?.observeContext(focusSnapshot);
573135
573478
  }
573136
573479
  return record?.id ?? null;
573137
573480
  }
@@ -573151,13 +573494,59 @@ ${parts.join("\n")}
573151
573494
  }
573152
573495
  });
573153
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
+ }
573154
573539
  _buildFocusContextSnapshot() {
573540
+ const last2 = this._lastFocusContextSnapshot;
573155
573541
  return {
573156
573542
  pressureRatio: this._lastContextPressureSnapshot?.rawRatio ?? 0,
573157
- estimatedTokens: this._lastContextPressureSnapshot?.rawTokens,
573158
- activeFrameChars: this._lastContextFrameDiagnostics?.totalChars,
573159
- droppedSignals: this._lastContextFrameDiagnostics?.droppedSignals ?? this._lastContextPressureSnapshot?.droppedSignals,
573160
- 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
573161
573550
  };
573162
573551
  }
573163
573552
  _emitModelResolutionTelemetry(purpose, turn) {
@@ -573435,10 +573824,10 @@ ${parts.join("\n")}
573435
573824
  const afterMarker = tail.slice(marker.length);
573436
573825
  const nextH2 = afterMarker.search(/\n## (?!#)/);
573437
573826
  const raw = nextH2 >= 0 ? tail.slice(0, marker.length + nextH2) : tail;
573438
- const compact3 = raw.replace(/\n{3,}/g, "\n\n").trim();
573439
- if (compact3.length <= limit)
573440
- return compact3;
573441
- 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()}
573442
573831
  ... [truncated]`;
573443
573832
  }
573444
573833
  /**
@@ -576377,6 +576766,26 @@ ${contentPreview}
576377
576766
  }
576378
576767
  return true;
576379
576768
  }
576769
+ _shellCommandLikelyMutatesFilesystem(rawCmd) {
576770
+ if (!rawCmd || typeof rawCmd !== "string")
576771
+ return false;
576772
+ const cmd = rawCmd.trim();
576773
+ if (!cmd)
576774
+ return false;
576775
+ if (/(^|[^&\d])(>|>>)\s*\S/.test(cmd))
576776
+ return true;
576777
+ if (/\|\s*(?:tee|dd)\b/i.test(cmd))
576778
+ return true;
576779
+ if (/\b(?:sed|gsed)\s+(?:[^\n;&|]*\s)?(?:-i|--in-place)\b/i.test(cmd))
576780
+ return true;
576781
+ if (/\bperl\s+-[A-Za-z]*i[A-Za-z]*\b/.test(cmd))
576782
+ return true;
576783
+ if (/\b(?:cp|mv|rm|mkdir|rmdir|touch|truncate|ln|install)\b/i.test(cmd))
576784
+ return true;
576785
+ if (/\b(?:python3?|node|ruby|deno|bun)\b[\s\S]{0,240}\b(?:writeFile|writeFileSync|openSync|mkdirSync|renameSync|unlinkSync|rmSync)\b/i.test(cmd))
576786
+ return true;
576787
+ return false;
576788
+ }
576380
576789
  /**
576381
576790
  * REG-5: Render the recent-failures block so the agent SEES its own error
576382
576791
  * output before deciding what to do next. Detects same-fingerprint failure
@@ -576674,21 +577083,21 @@ ${sections.join("\n")}` : sections.join("\n");
576674
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.`);
576675
577084
  }
576676
577085
  if (filesRead.length > 0) {
576677
- const unique3 = [...new Set(filesRead)].slice(0, 30);
576678
- 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(", ")}`);
576679
577088
  }
576680
577089
  if (dirsListed.length > 0) {
576681
- const unique3 = [...new Set(dirsListed)].slice(0, 15);
576682
- 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(", ")}`);
576683
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.`);
576684
577093
  }
576685
577094
  if (searches.length > 0) {
576686
- const unique3 = [...new Set(searches)].slice(0, 15);
576687
- 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(", ")}`);
576688
577097
  }
576689
577098
  if (shells.length > 0) {
576690
- const unique3 = [...new Set(shells)].slice(0, 15);
576691
- 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(", ")}`);
576692
577101
  }
576693
577102
  if (sections.length <= 1)
576694
577103
  return null;
@@ -578352,6 +578761,7 @@ Respond with your assessment, then take action.`;
578352
578761
  this._completionIncompleteVerification = null;
578353
578762
  this._completionCaveat = null;
578354
578763
  this._completionLedger = null;
578764
+ this._focusTerminalLedgerRecorded = false;
578355
578765
  this._staleEditFamilies.clear();
578356
578766
  this._lastWorldStateTurn = -1;
578357
578767
  this._fileWritesSinceLastWorldState = 0;
@@ -578414,6 +578824,7 @@ Respond with your assessment, then take action.`;
578414
578824
  this._evidenceLedger = new EvidenceLedger();
578415
578825
  this._lastContextFrameDiagnostics = null;
578416
578826
  this._lastContextPressureSnapshot = null;
578827
+ this._lastFocusContextSnapshot = null;
578417
578828
  this._lastActiveForgettingReport = null;
578418
578829
  this._lastContextConsolidationTurn = -1e3;
578419
578830
  this._contextFrameBuilder = new ContextFrameBuilder();
@@ -580623,7 +581034,16 @@ If you're stuck, try a completely different approach. Do NOT repeat what failed
580623
581034
  completionContract: this._completionContract ? formatCompletionContract(this._completionContract) : void 0
580624
581035
  }
580625
581036
  };
580626
- 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
+ }
580627
581047
  } catch {
580628
581048
  }
580629
581049
  }
@@ -580733,6 +581153,7 @@ ${memoryLines.join("\n")}`
580733
581153
  this.proactivePrune(compacted, turn);
580734
581154
  this.microcompact(compacted, recentToolResults);
580735
581155
  this._insertContextFrame(compacted, await this._buildTurnContextFrame(turn, compacted, recentToolResults, environmentBlock));
581156
+ let requestMessages = compacted;
580736
581157
  {
580737
581158
  const _limits = this.contextLimits();
580738
581159
  const ceInput = {
@@ -580755,10 +581176,13 @@ ${memoryLines.join("\n")}`
580755
581176
  if (ceOutput.diagnostics.evidenceRetained > 0 || ceInput.runState?.completionContract || ceInput.memoryHints?.length) {
580756
581177
  const engineExtra = ceOutput.systemMessages.filter((m2) => !ceInput.messages.some((im) => im.content === m2.content));
580757
581178
  if (engineExtra.length > 0) {
580758
- compacted.unshift(...engineExtra.map((m2) => ({
580759
- role: "system",
580760
- content: m2.content
580761
- })));
581179
+ requestMessages = [
581180
+ ...engineExtra.map((m2) => ({
581181
+ role: "system",
581182
+ content: m2.content
581183
+ })),
581184
+ ...compacted
581185
+ ];
580762
581186
  }
580763
581187
  }
580764
581188
  } catch {
@@ -580766,7 +581190,7 @@ ${memoryLines.join("\n")}`
580766
581190
  }
580767
581191
  const { maxOutputTokens: effectiveMaxTokens } = this.contextLimits();
580768
581192
  const chatRequest = {
580769
- messages: compacted,
581193
+ messages: requestMessages,
580770
581194
  tools: toolDefs,
580771
581195
  temperature: this.options.temperature,
580772
581196
  maxTokens: effectiveMaxTokens,
@@ -580950,6 +581374,10 @@ ${memoryLines.join("\n")}`
580950
581374
  'When done, output: {"tool": "task_complete", "args": {"summary": "what you did"}}'
580951
581375
  ].join("\n");
580952
581376
  messages2.push({ role: "system", content: toolInjectMsg });
581377
+ chatRequest.messages = [
581378
+ ...requestMessages,
581379
+ { role: "system", content: toolInjectMsg }
581380
+ ];
580953
581381
  chatRequest.tools = [];
580954
581382
  try {
580955
581383
  this._recordContextWindowDump("agent_turn_prompt_tool_retry", chatRequest, turn, 1);
@@ -581616,6 +582044,11 @@ Use the saved fact to continue the promised synthesis or next concrete step, or
581616
582044
  blockedTool: tc.name,
581617
582045
  turn
581618
582046
  });
582047
+ this._maybeMarkFocusTerminalIncomplete({
582048
+ decision: focusDecision2,
582049
+ blockedTool: tc.name,
582050
+ turn
582051
+ });
581619
582052
  }
581620
582053
  this.emit({
581621
582054
  type: "tool_call",
@@ -581674,6 +582107,11 @@ Use the saved fact to continue the promised synthesis or next concrete step, or
581674
582107
  blockedTool: tc.name,
581675
582108
  turn
581676
582109
  });
582110
+ this._maybeMarkFocusTerminalIncomplete({
582111
+ decision: focusDecision2,
582112
+ blockedTool: tc.name,
582113
+ turn
582114
+ });
581677
582115
  }
581678
582116
  this.emit({
581679
582117
  type: "tool_call",
@@ -581912,6 +582350,11 @@ ${cachedResult}`,
581912
582350
  blockedTool: focusDecision.kind === "block_tool_call" ? tc.name : void 0,
581913
582351
  turn
581914
582352
  });
582353
+ this._maybeMarkFocusTerminalIncomplete({
582354
+ decision: focusDecision,
582355
+ blockedTool: focusDecision.kind === "block_tool_call" ? tc.name : void 0,
582356
+ turn
582357
+ });
581915
582358
  if (focusDecision.kind === "inject_guidance") {
581916
582359
  pushSoftInjection("system", focusDecision.message);
581917
582360
  } else if (!repeatShortCircuit) {
@@ -582156,6 +582599,7 @@ Respond with EXACTLY this structure before your next tool call:
582156
582599
  }
582157
582600
  }
582158
582601
  }
582602
+ const shellFilesystemMutation = tc.name === "shell" && result.success === true && this._shellCommandLikelyMutatesFilesystem(String(tc.arguments?.["command"] ?? tc.arguments?.["cmd"] ?? ""));
582159
582603
  const realFileMutation = this._isRealProjectMutation(tc.name, result);
582160
582604
  const realMutationPaths = realFileMutation ? this._extractToolTargetPaths(tc.name, tc.arguments, result) : [];
582161
582605
  if (realFileMutation && this._reg61PerpetualGateActive) {
@@ -582937,6 +583381,20 @@ Respond with EXACTLY this structure before your next tool call:
582937
583381
  dedupHitCount.clear();
582938
583382
  }
582939
583383
  }
583384
+ if (shellFilesystemMutation && recentToolResults.size > 0) {
583385
+ for (const key of Array.from(recentToolResults.keys())) {
583386
+ if (key.startsWith("shell:") || key.startsWith("file_read:") || key.startsWith("list_directory:") || key.startsWith("grep_search:") || key.startsWith("find_files:")) {
583387
+ recentToolResults.delete(key);
583388
+ dedupHitCount.delete(key);
583389
+ }
583390
+ }
583391
+ this._readCoverage.clear();
583392
+ this.emit({
583393
+ type: "status",
583394
+ content: "Shell filesystem mutation invalidated cached read/shell evidence",
583395
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
583396
+ });
583397
+ }
582940
583398
  if (isFileMutation && recentToolResults.size > 0) {
582941
583399
  for (const key of Array.from(recentToolResults.keys())) {
582942
583400
  if (key.startsWith("shell:"))
@@ -583334,7 +583792,7 @@ Evidence: ${evidencePreview}`.slice(0, 500);
583334
583792
  success: result.success,
583335
583793
  output: result.output ?? result.llmContent ?? "",
583336
583794
  error: result.error ?? "",
583337
- mutated: realFileMutation,
583795
+ mutated: realFileMutation || shellFilesystemMutation,
583338
583796
  isReadLike
583339
583797
  });
583340
583798
  const afterDirective = this._focusSupervisor?.snapshot().directive ?? null;
@@ -587414,8 +587872,8 @@ ${trimmedNew}`;
587414
587872
  buildAdversaryToolOutcomeEvidence(toolName, toolArgs, content, succeeded) {
587415
587873
  const pathValue = toolArgs?.["path"] ?? toolArgs?.["file"] ?? toolArgs?.["filePath"] ?? toolArgs?.["file_path"];
587416
587874
  const path12 = typeof pathValue === "string" && pathValue.trim() ? pathValue.trim() : void 0;
587417
- const compact3 = content.replace(/\s+/g, " ").trim();
587418
- const snippet = compact3.slice(0, 160);
587875
+ const compact4 = content.replace(/\s+/g, " ").trim();
587876
+ const snippet = compact4.slice(0, 160);
587419
587877
  const digest3 = _createHash("sha256").update(content).digest("hex").slice(0, 16);
587420
587878
  const lineCount = content.length > 0 ? content.split("\n").length : 0;
587421
587879
  if (toolName === "file_read") {
@@ -608875,9 +609333,9 @@ function keywords(text2) {
608875
609333
  return out;
608876
609334
  }
608877
609335
  function compactLine(text2, limit = 220) {
608878
- const compact3 = text2.replace(/\s+/g, " ").trim();
608879
- if (compact3.length <= limit) return compact3;
608880
- 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()}...`;
608881
609339
  }
608882
609340
  function newDocument(scope) {
608883
609341
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
@@ -609212,9 +609670,9 @@ import { createHash as createHash33 } from "node:crypto";
609212
609670
  import { existsSync as existsSync109, readdirSync as readdirSync36, readFileSync as readFileSync86 } from "node:fs";
609213
609671
  import { basename as basename22, join as join123, resolve as resolve54 } from "node:path";
609214
609672
  function compactText(text2, limit) {
609215
- const compact3 = text2.replace(/\s+/g, " ").trim();
609216
- if (compact3.length <= limit) return compact3;
609217
- 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()}...`;
609218
609676
  }
609219
609677
  function blockText(text2, limit) {
609220
609678
  const clean5 = text2.replace(/\r\n/g, "\n").trim();
@@ -620518,10 +620976,10 @@ ${CONTENT_BG_SEQ}`);
620518
620976
  if (this._telegramStatus.active) {
620519
620977
  const suffix = this._telegramStatus.activeSubAgents > 0 ? ` ${_StatusBar.digitBar(this._telegramStatus.activeSubAgents)}` : "";
620520
620978
  const label = `✈ tg${suffix}`;
620521
- const compact3 = `✈${suffix}`;
620979
+ const compact4 = `✈${suffix}`;
620522
620980
  sections.push({
620523
620981
  expanded: `${HEADER_TELEGRAM_FG}${label}\x1B[0m`,
620524
- compact: `${HEADER_TELEGRAM_FG}${compact3}\x1B[0m`,
620982
+ compact: `${HEADER_TELEGRAM_FG}${compact4}\x1B[0m`,
620525
620983
  expandedW: 2 + 3 + suffix.length,
620526
620984
  compactW: 2 + suffix.length,
620527
620985
  empty: false,
@@ -652791,9 +653249,9 @@ async function handleUpdate(subcommand, ctx3) {
652791
653249
  const installOverlay = startInstallOverlay(targetVersion);
652792
653250
  const stripInstallAnsi = (value2) => value2.replace(/\x1B\][^\x07]*(?:\x07|\x1B\\)/g, "").replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "").replace(/\r/g, "\n");
652793
653251
  const truncateInstallStatus = (value2, max = 88) => {
652794
- const compact3 = value2.replace(/\s+/g, " ").trim();
652795
- if (compact3.length <= max) return compact3;
652796
- 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() + "…";
652797
653255
  };
652798
653256
  const summarizeInstallCommand = (cmd) => {
652799
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();
@@ -654754,14 +655212,14 @@ function loadFailurePatterns(store2) {
654754
655212
  const unresolved = store2.listUnresolved();
654755
655213
  if (unresolved.length === 0) return "";
654756
655214
  const seen = /* @__PURE__ */ new Set();
654757
- const unique3 = unresolved.filter((f2) => {
655215
+ const unique2 = unresolved.filter((f2) => {
654758
655216
  if (seen.has(f2.fingerprint)) return false;
654759
655217
  seen.add(f2.fingerprint);
654760
655218
  return true;
654761
655219
  });
654762
- if (unique3.length === 0) return "";
655220
+ if (unique2.length === 0) return "";
654763
655221
  const lines = ["Known failure patterns (avoid repeating these):"];
654764
- for (const f2 of unique3.slice(0, 8)) {
655222
+ for (const f2 of unique2.slice(0, 8)) {
654765
655223
  const file = f2.filePath ? ` in ${f2.filePath}` : "";
654766
655224
  lines.push(`- [${f2.failureType}]${file}: ${f2.errorMessage.slice(0, 150)}`);
654767
655225
  }
@@ -657545,8 +658003,8 @@ function generateDescriptors(repoRoot) {
657545
658003
  if (repoName2 && !tags.includes(repoName2)) {
657546
658004
  tags.push(repoName2);
657547
658005
  }
657548
- const unique3 = [...new Set(tags.map((t2) => t2.toLowerCase().trim()).filter((t2) => t2.length > 1 && t2.length < 60))];
657549
- 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) => ({
657550
658008
  text: text2,
657551
658009
  color: weightedColor(profile)
657552
658010
  }));
@@ -657567,7 +658025,7 @@ function generateDescriptors(repoRoot) {
657567
658025
  ];
657568
658026
  for (const fb of fallbacks) {
657569
658027
  if (phrases.length >= 20) break;
657570
- if (!unique3.includes(fb)) {
658028
+ if (!unique2.includes(fb)) {
657571
658029
  phrases.push({ text: fb, color: weightedColor(profile) });
657572
658030
  }
657573
658031
  }
@@ -662559,9 +663017,9 @@ function toolCallBlock(name10, args) {
662559
663017
  if (args == null || typeof args === "object" && Object.keys(args).length === 0) {
662560
663018
  return header;
662561
663019
  }
662562
- const compact3 = typeof args === "string" ? args : safeJson(args, false);
662563
- if (compact3.length <= 120 && !compact3.includes("\n")) {
662564
- 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>`;
662565
663023
  }
662566
663024
  const pretty = typeof args === "string" ? args : safeJson(args, true);
662567
663025
  return `${header}
@@ -662898,13 +663356,13 @@ function buildScopedToolList(scope) {
662898
663356
  const commandSigs = commands.flatMap((cmd) => cmd.signatures);
662899
663357
  const allSigs = [...syntheticSigs, ...commandSigs];
662900
663358
  const seen = /* @__PURE__ */ new Set();
662901
- const unique3 = allSigs.filter((sig) => {
663359
+ const unique2 = allSigs.filter((sig) => {
662902
663360
  if (seen.has(sig.signature)) return false;
662903
663361
  seen.add(sig.signature);
662904
663362
  return true;
662905
663363
  });
662906
663364
  const entries = [];
662907
- for (const sig of unique3) {
663365
+ for (const sig of unique2) {
662908
663366
  const matchingCmd = commands.find(
662909
663367
  (cmd) => cmd.signatures.some((s2) => s2.signature === sig.signature)
662910
663368
  );
@@ -666011,7 +666469,7 @@ function stableHash2(value2, length4 = 16) {
666011
666469
  function clean3(value2) {
666012
666470
  return String(value2 ?? "").replace(/\s+/g, " ").trim();
666013
666471
  }
666014
- function compact(value2, max = 420) {
666472
+ function compact2(value2, max = 420) {
666015
666473
  const text2 = clean3(value2);
666016
666474
  return text2.length > max ? `${text2.slice(0, Math.max(0, max - 3)).trimEnd()}...` : text2;
666017
666475
  }
@@ -666092,7 +666550,7 @@ function contentFor(entry, sessionKey, options2) {
666092
666550
  `identity_boundary: ${identityBoundary(entry)}`,
666093
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"}]` : "",
666094
666552
  entry.mode ? `mode: ${entry.mode}` : "",
666095
- entry.mediaSummary ? `media: ${compact(entry.mediaSummary, 260)}` : "",
666553
+ entry.mediaSummary ? `media: ${compact2(entry.mediaSummary, 260)}` : "",
666096
666554
  "",
666097
666555
  entry.text
666098
666556
  ].filter((line) => line !== "");
@@ -666134,7 +666592,7 @@ function addTextEdges(graph, result, entry) {
666134
666592
  srcId: messageId,
666135
666593
  dstId: senderId,
666136
666594
  relation: "said_by",
666137
- fact: compact(entry.text, 260),
666595
+ fact: compact2(entry.text, 260),
666138
666596
  sourceEpisodeId: result.episodeId,
666139
666597
  modality: entry.role === "user" ? "social" : "text",
666140
666598
  confidence: entry.role === "assistant" ? 0.92 : 0.96
@@ -666146,7 +666604,7 @@ function addTextEdges(graph, result, entry) {
666146
666604
  srcId: messageId,
666147
666605
  dstId: channelTopic,
666148
666606
  relation: "related_to",
666149
- fact: compact(entry.text || entry.mediaSummary || "telegram message", 220),
666607
+ fact: compact2(entry.text || entry.mediaSummary || "telegram message", 220),
666150
666608
  sourceEpisodeId: result.episodeId,
666151
666609
  modality: entry.role === "user" ? "social" : "text",
666152
666610
  confidence: 0.72
@@ -666186,7 +666644,7 @@ function upsertTelegramReflectionMessage(repoRoot, sessionKey, entry, options2)
666186
666644
  }
666187
666645
  function queryFor(options2) {
666188
666646
  if (options2.query?.trim()) return options2.query.trim();
666189
- 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));
666190
666648
  return [
666191
666649
  `Telegram ${options2.chatType} ${options2.chatTitle || options2.chatId} reflection`,
666192
666650
  ...recent
@@ -666744,7 +667202,7 @@ function telegramSocialActorKey(actor) {
666744
667202
  if (typeof actor.userId === "number") return `user:${actor.userId}`;
666745
667203
  const username = cleanUsername(actor.username);
666746
667204
  if (username) return `username:${username.toLowerCase()}`;
666747
- const first2 = compact2(actor.firstName, 80).toLowerCase();
667205
+ const first2 = compact3(actor.firstName, 80).toLowerCase();
666748
667206
  return first2 ? `name:${first2}` : "unknown";
666749
667207
  }
666750
667208
  function telegramSocialActorKind(actor) {
@@ -666779,16 +667237,16 @@ function cleanUsername(value2) {
666779
667237
  return clean5 ? clean5.slice(0, 80) : void 0;
666780
667238
  }
666781
667239
  function compactOptional(value2, max) {
666782
- const clean5 = compact2(value2, max);
667240
+ const clean5 = compact3(value2, max);
666783
667241
  return clean5 || void 0;
666784
667242
  }
666785
- function compact2(value2, max) {
667243
+ function compact3(value2, max) {
666786
667244
  if (value2 === void 0 || value2 === null) return "";
666787
667245
  const clean5 = String(value2).replace(/\s+/g, " ").trim();
666788
667246
  return clean5.length > max ? `${clean5.slice(0, Math.max(0, max - 3)).trimEnd()}...` : clean5;
666789
667247
  }
666790
667248
  function jsonLine(value2, max) {
666791
- return JSON.stringify(compact2(value2, max));
667249
+ return JSON.stringify(compact3(value2, max));
666792
667250
  }
666793
667251
  function numberOr(value2, fallback) {
666794
667252
  return typeof value2 === "number" && Number.isFinite(value2) ? value2 : fallback;
@@ -667034,8 +667492,8 @@ function normalizeReplyPreferenceScope(raw) {
667034
667492
  function normalizeDeliveryCapability(raw) {
667035
667493
  if (!raw || typeof raw !== "object") return null;
667036
667494
  const value2 = raw;
667037
- const key = compact2(value2.key || "", 180);
667038
- const chatId = compact2(value2.chatId || "", 120);
667495
+ const key = compact3(value2.key || "", 180);
667496
+ const chatId = compact3(value2.chatId || "", 120);
667039
667497
  if (!key || !chatId) return null;
667040
667498
  const status = normalizeDeliveryStatus(value2.status);
667041
667499
  return {
@@ -667087,7 +667545,7 @@ function normalizeSalience(raw) {
667087
667545
  senderKey: String(value2.senderKey),
667088
667546
  actorKind: value2.actorKind === "bot" || value2.actorKind === "human" ? value2.actorKind : "unknown",
667089
667547
  signals: Array.isArray(value2.signals) ? value2.signals.map(String).slice(0, 16) : [],
667090
- textPreview: compact2(value2.textPreview || "", 240)
667548
+ textPreview: compact3(value2.textPreview || "", 240)
667091
667549
  };
667092
667550
  }
667093
667551
  function normalizeOutcome2(raw) {
@@ -667105,8 +667563,8 @@ function normalizeOutcome2(raw) {
667105
667563
  route: value2.route === "action" ? "action" : "chat",
667106
667564
  shouldReply: value2.shouldReply === true,
667107
667565
  confidence: clamp0113(numberOr(value2.confidence, 0)),
667108
- reason: compact2(value2.reason || "", 280),
667109
- source: compact2(value2.source || "unknown", 80),
667566
+ reason: compact3(value2.reason || "", 280),
667567
+ source: compact3(value2.source || "unknown", 80),
667110
667568
  silentDisposition: compactOptional(value2.silentDisposition, 280),
667111
667569
  mentalNote: compactOptional(value2.mentalNote, 360),
667112
667570
  memoryNote: compactOptional(value2.memoryNote, 360),
@@ -667133,7 +667591,7 @@ function normalizeDaydreamOpportunity(raw) {
667133
667591
  id,
667134
667592
  artifactId: String(value2.artifactId || "unknown"),
667135
667593
  generatedAt: String(value2.generatedAt || (/* @__PURE__ */ new Date()).toISOString()),
667136
- trigger: compact2(value2.trigger || "", 240),
667594
+ trigger: compact3(value2.trigger || "", 240),
667137
667595
  confidence: clamp0113(numberOr(value2.confidence, 0)),
667138
667596
  lifecycle,
667139
667597
  firstSeenAt: numberOr(value2.firstSeenAt, Date.now()),
@@ -667157,7 +667615,7 @@ function observeTelegramSocialMessage(state, input) {
667157
667615
  state.updatedAt = now2;
667158
667616
  const senderKey3 = upsertParticipant(state, input, now2, true);
667159
667617
  const thread = upsertThread(state, input, senderKey3, now2, true);
667160
- const text2 = compact2(input.text || "", 500);
667618
+ const text2 = compact3(input.text || "", 500);
667161
667619
  const participant = state.participants[senderKey3];
667162
667620
  if (participant) {
667163
667621
  participant.lastText = text2 || participant.lastText;
@@ -667192,8 +667650,8 @@ function commitTelegramSocialDecision(state, input) {
667192
667650
  route: input.route,
667193
667651
  shouldReply: input.shouldReply,
667194
667652
  confidence: clamp0113(input.confidence),
667195
- reason: compact2(input.reason, 280),
667196
- source: compact2(input.source, 80),
667653
+ reason: compact3(input.reason, 280),
667654
+ source: compact3(input.source, 80),
667197
667655
  silentDisposition: compactOptional(input.silentDisposition, 280),
667198
667656
  mentalNote: compactOptional(input.mentalNote, 360),
667199
667657
  memoryNote: compactOptional(input.memoryNote, 360),
@@ -667226,7 +667684,7 @@ function registerDaydreamOpportunities(state, opportunities, now2 = Date.now())
667226
667684
  id,
667227
667685
  artifactId: opportunity.artifactId || "unknown",
667228
667686
  generatedAt: opportunity.generatedAt || new Date(now2).toISOString(),
667229
- trigger: compact2(opportunity.trigger, 240),
667687
+ trigger: compact3(opportunity.trigger, 240),
667230
667688
  confidence: clamp0113(opportunity.confidence),
667231
667689
  lifecycle: "proposed",
667232
667690
  firstSeenAt: now2,
@@ -667236,7 +667694,7 @@ function registerDaydreamOpportunities(state, opportunities, now2 = Date.now())
667236
667694
  suppressedMessageIds: []
667237
667695
  };
667238
667696
  if (existing) {
667239
- item.trigger = compact2(opportunity.trigger, 240) || item.trigger;
667697
+ item.trigger = compact3(opportunity.trigger, 240) || item.trigger;
667240
667698
  item.confidence = clamp0113(opportunity.confidence);
667241
667699
  item.updatedAt = now2;
667242
667700
  }
@@ -667463,7 +667921,7 @@ function addSalience(state, input, senderKey3, now2, text2) {
667463
667921
  senderKey: senderKey3,
667464
667922
  actorKind: telegramSocialActorKind(input),
667465
667923
  signals,
667466
- textPreview: compact2(text2, 240)
667924
+ textPreview: compact3(text2, 240)
667467
667925
  });
667468
667926
  state.salience = state.salience.slice(-TELEGRAM_SOCIAL_LIMITS.salience);
667469
667927
  }
@@ -667846,14 +668304,14 @@ function parseTelegramReplyPreferenceUpdate(parsed) {
667846
668304
  }
667847
668305
  function uniqueTelegramJsonCandidates(candidates) {
667848
668306
  const seen = /* @__PURE__ */ new Set();
667849
- const unique3 = [];
668307
+ const unique2 = [];
667850
668308
  for (const candidate of candidates) {
667851
668309
  const clean5 = candidate.trim();
667852
668310
  if (!clean5 || seen.has(clean5)) continue;
667853
668311
  seen.add(clean5);
667854
- unique3.push(clean5);
668312
+ unique2.push(clean5);
667855
668313
  }
667856
- return unique3;
668314
+ return unique2;
667857
668315
  }
667858
668316
  function extractBalancedTelegramJsonObjects(text2) {
667859
668317
  const objects = [];
@@ -668193,8 +668651,8 @@ function telegramRouterErrorText(err) {
668193
668651
  return err instanceof Error ? err.message : String(err);
668194
668652
  }
668195
668653
  function compactTelegramRouterDiagnosticText(text2, maxLength = 220) {
668196
- const compact3 = text2.replace(/\s+/g, " ").trim();
668197
- 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;
668198
668656
  }
668199
668657
  function telegramRouterErrorLooksLikeTimeout(err) {
668200
668658
  const text2 = telegramRouterErrorText(err);
@@ -668635,8 +669093,8 @@ function stripTelegramHiddenThinking(text2) {
668635
669093
  return withoutClosedThink.replace(/<think>[\s\S]*$/gi, "");
668636
669094
  }
668637
669095
  function sanitizeTelegramProgressText(text2, maxLength) {
668638
- const compact3 = stripTelegramHiddenThinking(text2).replace(/\s+/g, " ").trim();
668639
- 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;
668640
669098
  }
668641
669099
  function isCodebaseMemoryStatus(text2) {
668642
669100
  return /^\s*\[CODEBASE MEMORY\]/i.test(stripTelegramHiddenThinking(text2));
@@ -668688,39 +669146,39 @@ function isTelegramNoReplySentinel(text2) {
668688
669146
  return lower === "no_reply" || lower.startsWith("no_reply");
668689
669147
  }
668690
669148
  function isTelegramInternalStatusText(text2) {
668691
- const compact3 = compactTelegramVisibleText(text2);
668692
- if (!compact3) return false;
668693
- const lower = compact3.toLowerCase();
668694
- 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;
668695
669153
  if (lower === "complete" || lower === "completed") return true;
668696
- if (/^memory stage:/i.test(compact3)) return true;
668697
- 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;
668698
669156
  if (/^(casual|ambient|group)\b.{0,180}\b(skipping|skipped|not directed|no action needed|no reply)\b/i.test(
668699
- compact3
669157
+ compact4
668700
669158
  ))
668701
669159
  return true;
668702
- if (/^no further action needed\b/i.test(compact3)) return true;
669160
+ if (/^no further action needed\b/i.test(compact4)) return true;
668703
669161
  if (/^no action needed\b.{0,120}\b(task|complete|completed|done)\b/i.test(
668704
- compact3
669162
+ compact4
668705
669163
  ))
668706
669164
  return true;
668707
- if (/^(there'?s|there is) no active task\b/i.test(compact3)) return true;
668708
- 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))
668709
669167
  return true;
668710
669168
  if (/\balready (been )?(provided|answered|handled|delivered) above\b/i.test(
668711
- compact3
669169
+ compact4
668712
669170
  ))
668713
669171
  return true;
668714
669172
  if (/\b(no remaining work|nothing left to do|task is complete|task has been completed)\b/i.test(
668715
- compact3
669173
+ compact4
668716
669174
  ))
668717
669175
  return true;
668718
669176
  return false;
668719
669177
  }
668720
669178
  function isTelegramStuckSelfTalkSegment(text2) {
668721
- const compact3 = text2.trim();
668722
- if (!compact3) return false;
668723
- 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));
668724
669182
  }
668725
669183
  function stripTelegramStuckSelfTalk(text2) {
668726
669184
  if (!text2) return "";
@@ -668793,11 +669251,11 @@ function truncateTelegramContext(text2, maxLength) {
668793
669251
  );
668794
669252
  }
668795
669253
  function truncateTelegramContextLine(text2, maxLength = TELEGRAM_CONTEXT_LINE_LIMIT) {
668796
- const compact3 = normalizeTelegramOutboundLinks(
669254
+ const compact4 = normalizeTelegramOutboundLinks(
668797
669255
  stripTelegramHiddenThinking(text2)
668798
669256
  ).replace(/\s+/g, " ").trim();
668799
- if (compact3.length <= maxLength) return compact3;
668800
- return truncateTelegramUrlSafe(compact3, maxLength);
669257
+ if (compact4.length <= maxLength) return compact4;
669258
+ return truncateTelegramUrlSafe(compact4, maxLength);
668801
669259
  }
668802
669260
  function redactTelegramLocalPaths(text2) {
668803
669261
  return text2.replace(
@@ -668852,10 +669310,10 @@ function telegramHistoryTime(entry) {
668852
669310
  });
668853
669311
  }
668854
669312
  function formatTelegramIdentitySignals(signals) {
668855
- const unique3 = [
669313
+ const unique2 = [
668856
669314
  ...new Set(signals.map((signal) => signal.trim()).filter(Boolean))
668857
669315
  ];
668858
- return unique3.length > 0 ? unique3.join(", ") : "none";
669316
+ return unique2.length > 0 ? unique2.join(", ") : "none";
668859
669317
  }
668860
669318
  function summarizeTelegramMessageAttachments(msg) {
668861
669319
  const parts = [];
@@ -669376,12 +669834,12 @@ function buildTelegramHelpHTML(scope, maxPublicCommands = 24) {
669376
669834
  ...commands.flatMap((cmd) => cmd.signatures)
669377
669835
  ];
669378
669836
  const seen = /* @__PURE__ */ new Set();
669379
- const unique3 = signatures.filter((sig) => {
669837
+ const unique2 = signatures.filter((sig) => {
669380
669838
  if (seen.has(sig.signature)) return false;
669381
669839
  seen.add(sig.signature);
669382
669840
  return true;
669383
669841
  });
669384
- const visible = scope === "public" ? unique3.slice(0, maxPublicCommands) : unique3;
669842
+ const visible = scope === "public" ? unique2.slice(0, maxPublicCommands) : unique2;
669385
669843
  const lines = [
669386
669844
  `<b>Commands (${scope === "admin" ? "admin full scope" : "public secure scope"})</b>`,
669387
669845
  "",
@@ -669389,7 +669847,7 @@ function buildTelegramHelpHTML(scope, maxPublicCommands = 24) {
669389
669847
  (sig) => `<code>${escapeTelegramHTML(sig.signature)}</code> - ${escapeTelegramHTML(sig.description)}`
669390
669848
  )
669391
669849
  ];
669392
- if (scope === "public" && unique3.length > visible.length) {
669850
+ if (scope === "public" && unique2.length > visible.length) {
669393
669851
  lines.push("");
669394
669852
  lines.push(
669395
669853
  `Public scope truncated to ${visible.length} safe commands. Authenticate as admin for full command help.`
@@ -675226,9 +675684,9 @@ ${mediaContext}` : ""
675226
675684
  if (!userMemory.toneTags.includes(tag)) userMemory.toneTags.push(tag);
675227
675685
  }
675228
675686
  userMemory.toneTags = userMemory.toneTags.slice(0, 20);
675229
- const compact3 = stripTelegramHiddenThinking(entry.text || "").replace(/\s+/g, " ").trim();
675230
- if (compact3) {
675231
- userMemory.lastMessages.push(compact3);
675687
+ const compact4 = stripTelegramHiddenThinking(entry.text || "").replace(/\s+/g, " ").trim();
675688
+ if (compact4) {
675689
+ userMemory.lastMessages.push(compact4);
675232
675690
  userMemory.lastMessages = userMemory.lastMessages.slice(-40);
675233
675691
  }
675234
675692
  for (const topic of telegramMemoryTags(
@@ -683622,20 +684080,20 @@ Scoped workspace: ${scopedRoot}`,
683622
684080
  };
683623
684081
  }
683624
684082
  async deleteTelegramMessages(chatId, messageIds, currentMsg) {
683625
- const unique3 = [...new Set(messageIds)].filter((id) => Number.isFinite(id));
683626
- if (unique3.length === 0)
684083
+ const unique2 = [...new Set(messageIds)].filter((id) => Number.isFinite(id));
684084
+ if (unique2.length === 0)
683627
684085
  throw new Error(
683628
684086
  "deleteTelegramMessages requires at least one message id."
683629
684087
  );
683630
684088
  await this.assertTelegramBotRightsForAction(
683631
684089
  "delete_messages",
683632
684090
  chatId,
683633
- unique3,
684091
+ unique2,
683634
684092
  currentMsg
683635
684093
  );
683636
684094
  const chunks = [];
683637
- for (let idx = 0; idx < unique3.length; idx += 100)
683638
- 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));
683639
684097
  const results = [];
683640
684098
  for (const chunk of chunks) {
683641
684099
  const result = await this.apiCall("deleteMessages", {
@@ -683653,9 +684111,9 @@ Scoped workspace: ${scopedRoot}`,
683653
684111
  telegram_method: "deleteMessages",
683654
684112
  ok: true,
683655
684113
  chat_id: chatId,
683656
- message_ids: unique3,
684114
+ message_ids: unique2,
683657
684115
  batches: results,
683658
- 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)),
683659
684117
  policy_scope: this.telegramToolPolicy.chatOverrides?.[String(chatId)] ? "chat" : "global/default"
683660
684118
  };
683661
684119
  }