omnius 1.0.553 → 1.0.554

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
@@ -7256,6 +7256,22 @@ var init_file_write = __esm({
7256
7256
  import { execFile as execFile2 } from "node:child_process";
7257
7257
  import { promisify } from "node:util";
7258
7258
  import { resolve as resolve6 } from "node:path";
7259
+ function partialGrepOutput(input) {
7260
+ const raw = input.stdout ?? "";
7261
+ const lines = raw.split("\n").filter(Boolean);
7262
+ const sample = lines.slice(0, MAX_OUTPUT_LINES).join("\n");
7263
+ const narrowing = JSON.stringify({
7264
+ pattern: input.pattern,
7265
+ path: input.searchPath,
7266
+ ...input.include ? { include: input.include } : {}
7267
+ });
7268
+ return [
7269
+ `[GREP_PARTIAL] output reached the ${input.capBytes}-byte capture cap; matching succeeded but this is only a prefix (${lines.length} captured lines).`,
7270
+ `provenance=tool:grep_search cap_bytes=${input.capBytes} path=${input.searchPath}${input.include ? ` include=${input.include}` : ""}`,
7271
+ `narrow_next=add an include/path or a more specific pattern, e.g. grep_search(${narrowing})`,
7272
+ sample
7273
+ ].filter(Boolean).join("\n");
7274
+ }
7259
7275
  var _a, execFileAsync, MAX_OUTPUT_LINES, DEFAULT_SEARCH_TIMEOUT_MS, RG_EXCLUDED_GLOBS, GREP_EXCLUDED_DIRS, GrepSearchTool;
7260
7276
  var init_grep_search = __esm({
7261
7277
  "packages/execution/dist/tools/grep-search.js"() {
@@ -7374,10 +7390,25 @@ var init_grep_search = __esm({
7374
7390
  output: truncated ? `${output}
7375
7391
 
7376
7392
  [Output truncated to ${MAX_OUTPUT_LINES} lines. ${lines.length - MAX_OUTPUT_LINES} more matches exist.]` : output,
7393
+ partial: truncated,
7377
7394
  durationMs: performance.now() - start2
7378
7395
  };
7379
7396
  } catch (error) {
7380
7397
  const err = error;
7398
+ if (err.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" || /maxbuffer|max buffer/i.test(err.message)) {
7399
+ return {
7400
+ success: true,
7401
+ partial: true,
7402
+ output: partialGrepOutput({
7403
+ stdout: err.stdout,
7404
+ pattern,
7405
+ searchPath,
7406
+ include,
7407
+ capBytes: 1024 * 1024
7408
+ }),
7409
+ durationMs: performance.now() - start2
7410
+ };
7411
+ }
7381
7412
  if (err.code === 1) {
7382
7413
  return {
7383
7414
  success: true,
@@ -274007,11 +274038,11 @@ var require_out = __commonJS({
274007
274038
  async.read(path16, getSettings(optionsOrSettingsOrCallback), callback);
274008
274039
  }
274009
274040
  exports.stat = stat9;
274010
- function statSync70(path16, optionsOrSettings) {
274041
+ function statSync71(path16, optionsOrSettings) {
274011
274042
  const settings = getSettings(optionsOrSettings);
274012
274043
  return sync.read(path16, settings);
274013
274044
  }
274014
- exports.statSync = statSync70;
274045
+ exports.statSync = statSync71;
274015
274046
  function getSettings(settingsOrOptions = {}) {
274016
274047
  if (settingsOrOptions instanceof settings_1.default) {
274017
274048
  return settingsOrOptions;
@@ -297514,6 +297545,10 @@ function replayWorkboardEvents(events) {
297514
297545
  goal: event.payload.goal,
297515
297546
  scope: event.payload.scope,
297516
297547
  title: event.payload.title,
297548
+ taskEpoch: event.payload.taskEpoch,
297549
+ rawUserIntent: event.payload.rawUserIntent,
297550
+ artifactEvidence: event.payload.artifactEvidence,
297551
+ lastSubstantiveProgress: event.payload.lastSubstantiveProgress,
297517
297552
  createdAt: event.createdAt,
297518
297553
  updatedAt: event.createdAt,
297519
297554
  eventCount: 0,
@@ -297538,7 +297573,11 @@ function replayWorkboardEvents(events) {
297538
297573
  status: event.payload.status,
297539
297574
  goal: event.payload.goal,
297540
297575
  scope: event.payload.scope,
297541
- title: event.payload.title
297576
+ title: event.payload.title,
297577
+ taskEpoch: event.payload.taskEpoch,
297578
+ rawUserIntent: event.payload.rawUserIntent,
297579
+ artifactEvidence: event.payload.artifactEvidence,
297580
+ lastSubstantiveProgress: event.payload.lastSubstantiveProgress
297542
297581
  })
297543
297582
  };
297544
297583
  break;
@@ -297705,7 +297744,11 @@ function createWorkboard(workingDir, input = {}) {
297705
297744
  status: "active",
297706
297745
  goal: cleanString(input.goal),
297707
297746
  scope: cleanString(input.scope),
297708
- title: cleanString(input.title)
297747
+ title: cleanString(input.title),
297748
+ taskEpoch: typeof input.taskEpoch === "number" && Number.isFinite(input.taskEpoch) ? input.taskEpoch : void 0,
297749
+ rawUserIntent: cleanString(input.rawUserIntent),
297750
+ artifactEvidence: input.artifactEvidence ? normalizeEvidenceCollection(input.artifactEvidence, input.actor).slice(-12) : void 0,
297751
+ lastSubstantiveProgress: input.lastSubstantiveProgress
297709
297752
  }
297710
297753
  }
297711
297754
  ];
@@ -297777,6 +297820,25 @@ function addWorkboardCard(workingDir, input) {
297777
297820
  }
297778
297821
  return appendWorkboardEvents(workingDir, runId, events);
297779
297822
  }
297823
+ function updateWorkboardMetadata(workingDir, input) {
297824
+ const runId = normalizeWorkboardRunId(input.runId);
297825
+ const snapshot = requireWorkboard(workingDir, runId);
297826
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
297827
+ return appendWorkboardEvents(workingDir, runId, [{
297828
+ schemaVersion: WORKBOARD_SCHEMA_VERSION,
297829
+ id: newEventId("board"),
297830
+ runId,
297831
+ type: "board.updated",
297832
+ createdAt: now2,
297833
+ actor: cleanString(input.actor),
297834
+ payload: {
297835
+ taskEpoch: typeof input.taskEpoch === "number" && Number.isFinite(input.taskEpoch) ? input.taskEpoch : void 0,
297836
+ rawUserIntent: cleanString(input.rawUserIntent),
297837
+ artifactEvidence: input.artifactEvidence ? appendUniqueEvidence(snapshot.artifactEvidence ?? [], normalizeEvidenceCollection(input.artifactEvidence, input.actor)).slice(-12) : void 0,
297838
+ lastSubstantiveProgress: input.lastSubstantiveProgress
297839
+ }
297840
+ }]);
297841
+ }
297780
297842
  function updateWorkboardCard(workingDir, input) {
297781
297843
  const runId = normalizeWorkboardRunId(input.runId);
297782
297844
  const snapshot = requireWorkboard(workingDir, runId);
@@ -297881,9 +297943,9 @@ function completeWorkboardCard(workingDir, input) {
297881
297943
  if (outcome === "request_changes") {
297882
297944
  const evidence2 = input.evidence === void 0 ? [] : normalizeEvidenceCollection(input.evidence, input.actor);
297883
297945
  const uniqueEvidence2 = evidence2.length > 0 ? filterNewEvidence(card.evidence, evidence2) : [];
297884
- const events = [];
297946
+ const events2 = [];
297885
297947
  if (uniqueEvidence2.length > 0) {
297886
- events.push({
297948
+ events2.push({
297887
297949
  schemaVersion: WORKBOARD_SCHEMA_VERSION,
297888
297950
  id: newEventId("evidence"),
297889
297951
  runId,
@@ -297895,7 +297957,7 @@ function completeWorkboardCard(workingDir, input) {
297895
297957
  }
297896
297958
  const missingEvidence = normalizeStringArray(input.missingEvidence);
297897
297959
  const reason2 = cleanString(input.reason) || cleanString(input.notes) || "Verifier requested changes.";
297898
- events.push({
297960
+ events2.push({
297899
297961
  schemaVersion: WORKBOARD_SCHEMA_VERSION,
297900
297962
  id: newEventId("changes"),
297901
297963
  runId,
@@ -297909,7 +297971,7 @@ function completeWorkboardCard(workingDir, input) {
297909
297971
  decision: makeDecision("needs_changes", reason2, { cardId: card.id, actor: input.actor, createdAt: now2 })
297910
297972
  }
297911
297973
  });
297912
- snapshot = appendWorkboardEvents(workingDir, runId, events);
297974
+ snapshot = appendWorkboardEvents(workingDir, runId, events2);
297913
297975
  return {
297914
297976
  accepted: true,
297915
297977
  snapshot,
@@ -297954,20 +298016,8 @@ function completeWorkboardCard(workingDir, input) {
297954
298016
  };
297955
298017
  }
297956
298018
  const evidence = input.evidence === void 0 ? [] : normalizeEvidenceCollection(input.evidence, input.actor);
297957
- let evidenceSnapshot = snapshot;
297958
298019
  const uniqueEvidence = evidence.length > 0 ? filterNewEvidence(card.evidence, evidence) : [];
297959
- if (uniqueEvidence.length > 0) {
297960
- evidenceSnapshot = appendWorkboardEvents(workingDir, runId, [{
297961
- schemaVersion: WORKBOARD_SCHEMA_VERSION,
297962
- id: newEventId("evidence"),
297963
- runId,
297964
- type: "evidence.attached",
297965
- createdAt: now2,
297966
- actor: cleanString(input.actor),
297967
- payload: { cardId: card.id, evidence: uniqueEvidence }
297968
- }]);
297969
- }
297970
- const currentCard = evidenceSnapshot.cards.find((existing) => existing.id === card.id) ?? card;
298020
+ const currentCard = uniqueEvidence.length > 0 ? { ...card, evidence: appendUniqueEvidence(card.evidence, uniqueEvidence) } : card;
297971
298021
  const evidenceCheck = verifyCardEvidence(currentCard);
297972
298022
  if (!evidenceCheck.valid) {
297973
298023
  const diagnostic = makeDiagnostic("completion_without_evidence", "error", `card '${card.id}' cannot be ${outcome} without required evidence`, {
@@ -298012,7 +298062,20 @@ function completeWorkboardCard(workingDir, input) {
298012
298062
  decision: makeDecision("completed", reason, { cardId: card.id, actor: input.actor, createdAt: now2 })
298013
298063
  }
298014
298064
  };
298015
- snapshot = appendWorkboardEvents(workingDir, runId, [event]);
298065
+ const events = [];
298066
+ if (uniqueEvidence.length > 0) {
298067
+ events.push({
298068
+ schemaVersion: WORKBOARD_SCHEMA_VERSION,
298069
+ id: newEventId("evidence"),
298070
+ runId,
298071
+ type: "evidence.attached",
298072
+ createdAt: now2,
298073
+ actor: cleanString(input.actor),
298074
+ payload: { cardId: card.id, evidence: uniqueEvidence }
298075
+ });
298076
+ }
298077
+ events.push(event);
298078
+ snapshot = appendWorkboardEvents(workingDir, runId, events);
298016
298079
  return {
298017
298080
  accepted: true,
298018
298081
  snapshot,
@@ -298267,7 +298330,9 @@ function normalizeCardInput(input, timestamp) {
298267
298330
  diagnosticFingerprint: cleanString(input.diagnosticFingerprint),
298268
298331
  ownedFiles: normalizeStringArray(input.ownedFiles),
298269
298332
  verifierCommand: cleanString(input.verifierCommand),
298270
- rank: typeof input.rank === "number" && Number.isFinite(input.rank) ? input.rank : void 0
298333
+ rank: typeof input.rank === "number" && Number.isFinite(input.rank) ? input.rank : void 0,
298334
+ canonicalKey: cleanString(input.canonicalKey),
298335
+ sourceTodoIds: normalizeStringArray(input.sourceTodoIds)
298271
298336
  };
298272
298337
  validateSpecialCardAdmission(card);
298273
298338
  return card;
@@ -298308,6 +298373,12 @@ function normalizeCardUpdates(input) {
298308
298373
  updates.verifierCommand = cleanString(input.verifierCommand);
298309
298374
  if (input.rank !== void 0 && Number.isFinite(input.rank))
298310
298375
  updates.rank = input.rank;
298376
+ if (input.canonicalKey !== void 0)
298377
+ updates.canonicalKey = cleanString(input.canonicalKey);
298378
+ if (input.sourceTodoIds !== void 0)
298379
+ updates.sourceTodoIds = normalizeStringArray(input.sourceTodoIds);
298380
+ if (input.supersededBy !== void 0)
298381
+ updates.supersededBy = cleanString(input.supersededBy);
298311
298382
  if (Object.keys(updates).length === 0)
298312
298383
  throw new WorkboardError("empty_update", "at least one card field must be updated");
298313
298384
  return updates;
@@ -311942,7 +312013,7 @@ ${lanes.join("\n")}
311942
312013
  return process.memoryUsage().heapUsed;
311943
312014
  },
311944
312015
  getFileSize(path16) {
311945
- const stat9 = statSync70(path16);
312016
+ const stat9 = statSync71(path16);
311946
312017
  if (stat9 == null ? void 0 : stat9.isFile()) {
311947
312018
  return stat9.size;
311948
312019
  }
@@ -311986,7 +312057,7 @@ ${lanes.join("\n")}
311986
312057
  }
311987
312058
  };
311988
312059
  return nodeSystem;
311989
- function statSync70(path16) {
312060
+ function statSync71(path16) {
311990
312061
  try {
311991
312062
  return _fs.statSync(path16, statSyncOptions);
311992
312063
  } catch {
@@ -312045,7 +312116,7 @@ ${lanes.join("\n")}
312045
312116
  activeSession.post("Profiler.stop", (err, { profile }) => {
312046
312117
  var _a2;
312047
312118
  if (!err) {
312048
- if ((_a2 = statSync70(profilePath)) == null ? void 0 : _a2.isDirectory()) {
312119
+ if ((_a2 = statSync71(profilePath)) == null ? void 0 : _a2.isDirectory()) {
312049
312120
  profilePath = _path.join(profilePath, `${(/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-")}+P${process.pid}.cpuprofile`);
312050
312121
  }
312051
312122
  try {
@@ -312165,7 +312236,7 @@ ${lanes.join("\n")}
312165
312236
  let stat9;
312166
312237
  if (typeof dirent === "string" || dirent.isSymbolicLink()) {
312167
312238
  const name10 = combinePaths(path16, entry);
312168
- stat9 = statSync70(name10);
312239
+ stat9 = statSync71(name10);
312169
312240
  if (!stat9) {
312170
312241
  continue;
312171
312242
  }
@@ -312189,7 +312260,7 @@ ${lanes.join("\n")}
312189
312260
  return matchFiles(path16, extensions, excludes, includes, useCaseSensitiveFileNames2, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
312190
312261
  }
312191
312262
  function fileSystemEntryExists(path16, entryKind) {
312192
- const stat9 = statSync70(path16);
312263
+ const stat9 = statSync71(path16);
312193
312264
  if (!stat9) {
312194
312265
  return false;
312195
312266
  }
@@ -312231,7 +312302,7 @@ ${lanes.join("\n")}
312231
312302
  }
312232
312303
  function getModifiedTime3(path16) {
312233
312304
  var _a2;
312234
- return (_a2 = statSync70(path16)) == null ? void 0 : _a2.mtime;
312305
+ return (_a2 = statSync71(path16)) == null ? void 0 : _a2.mtime;
312235
312306
  }
312236
312307
  function setModifiedTime(path16, time) {
312237
312308
  try {
@@ -562249,6 +562320,7 @@ __export(dist_exports2, {
562249
562320
  unifiedPythonEnv: () => unifiedPythonEnv,
562250
562321
  unifiedRuntimeDir: () => unifiedRuntimeDir,
562251
562322
  updateWorkboardCard: () => updateWorkboardCard,
562323
+ updateWorkboardMetadata: () => updateWorkboardMetadata,
562252
562324
  validateCustomToolDefinition: () => validateCustomToolDefinition,
562253
562325
  validateMediaModelAdapter: () => validateMediaModelAdapter,
562254
562326
  validateMutationWorkerContract: () => validateMutationWorkerContract,
@@ -572353,14 +572425,17 @@ function collectDiff(opts) {
572353
572425
  }
572354
572426
  return { files, strategy: "explicit" };
572355
572427
  }
572428
+ if (opts.explicitFilesOnly)
572429
+ return { files: [], strategy: "explicit" };
572356
572430
  const since = Date.now() - opts.mtimeWindowMs;
572357
572431
  const scan = scanWorkspace({ root: opts.workingDir, maxFiles: cap * 4 });
572358
572432
  const recent = scan.files.filter((f2) => f2.mtimeMs >= since).sort((a2, b) => b.mtimeMs - a2.mtimeMs).slice(0, cap).map((f2) => ({ path: f2.rel, bytes: f2.bytes, status: "modified" }));
572359
572433
  return { files: recent, strategy: "mtime" };
572360
572434
  }
572361
572435
  async function collectDiffAsync(opts) {
572362
- if (opts.explicitFiles && opts.explicitFiles.length > 0)
572436
+ if (opts.explicitFilesOnly || opts.explicitFiles && opts.explicitFiles.length > 0) {
572363
572437
  return collectDiff(opts);
572438
+ }
572364
572439
  const cap = Math.max(1, opts.maxFiles);
572365
572440
  if (existsSync96(join106(opts.workingDir, ".git"))) {
572366
572441
  try {
@@ -572423,7 +572498,8 @@ async function runBackwardPass(opts) {
572423
572498
  workingDir: opts.workingDir,
572424
572499
  maxFiles,
572425
572500
  mtimeWindowMs,
572426
- explicitFiles: opts.explicitFiles
572501
+ explicitFiles: opts.explicitFiles,
572502
+ explicitFilesOnly: opts.explicitFilesOnly
572427
572503
  });
572428
572504
  const diff = collected.files.map((f2) => {
572429
572505
  const abs = isAbsolute14(f2.path) ? f2.path : join106(opts.workingDir, f2.path);
@@ -578836,7 +578912,10 @@ function retireDuplicateToolFailures(messages2) {
578836
578912
  }
578837
578913
  out[index] = {
578838
578914
  ...message2,
578839
- content: "[retired_duplicate_tool_failure] a newer matching result appears later. Use that latest diagnostic; retry only after refreshing prerequisite evidence or correcting the arguments."
578915
+ // Keep the protocol message (some providers require every tool call to
578916
+ // retain a response) but make retired duplicate failures token-empty.
578917
+ // The newest result is the sole model-visible recovery record.
578918
+ content: ""
578840
578919
  };
578841
578920
  }
578842
578921
  return out;
@@ -578877,10 +578956,22 @@ function prepareModelFacingApiMessages(input) {
578877
578956
  }
578878
578957
  sanitized.push({ ...message2 });
578879
578958
  }
578880
- const keep = new Array(sanitized.length).fill(true);
578959
+ const activeUserEpoch = sanitized.reduce((latest, message2) => {
578960
+ if (message2.role !== "user")
578961
+ return latest;
578962
+ const epoch = Number(message2["taskEpoch"]);
578963
+ return Number.isInteger(epoch) && epoch >= 0 && (latest === null || epoch > latest) ? epoch : latest;
578964
+ }, null);
578965
+ const epochScoped = activeUserEpoch === null ? sanitized : sanitized.filter((message2) => {
578966
+ if (message2.role !== "user")
578967
+ return true;
578968
+ const epoch = Number(message2["taskEpoch"]);
578969
+ return Number.isInteger(epoch) && epoch === activeUserEpoch;
578970
+ });
578971
+ const keep = new Array(epochScoped.length).fill(true);
578881
578972
  const seenSystemKeys = /* @__PURE__ */ new Set();
578882
- for (let index = sanitized.length - 1; index >= 0; index--) {
578883
- const message2 = sanitized[index];
578973
+ for (let index = epochScoped.length - 1; index >= 0; index--) {
578974
+ const message2 = epochScoped[index];
578884
578975
  if (message2.role !== "system" || typeof message2.content !== "string")
578885
578976
  continue;
578886
578977
  if (preserveFirstSystem && index === 0)
@@ -578894,7 +578985,7 @@ function prepareModelFacingApiMessages(input) {
578894
578985
  }
578895
578986
  seenSystemKeys.add(key);
578896
578987
  }
578897
- const deduped = retireDuplicateToolFailures(sanitized.filter((_message, index) => keep[index]));
578988
+ const deduped = retireDuplicateToolFailures(epochScoped.filter((_message, index) => keep[index]));
578898
578989
  if (!hasUserMessage(deduped) && !hasConcreteGoalMessage(deduped)) {
578899
578990
  const goal = deriveCurrentGoal({
578900
578991
  explicitGoal: input.currentGoal,
@@ -579026,7 +579117,7 @@ var init_context_compiler = __esm({
579026
579117
  MODEL_FACING_ACTION_GROUND_TRUTH_CHAR_CAP = 5500;
579027
579118
  CONTROLLER_STATE_MARKER = "[CONTROLLER STATE v1]";
579028
579119
  ACTION_GROUND_TRUTH_MARKER = "[RECENT ACTION GROUND TRUTH]";
579029
- LEGACY_RUNTIME_CONTROL_FRAGMENT_RE = /(?:\bREG-\d+\b|\bfocus supervisor\b|\bworld[ -]state\b|\brecent tool failures\b|\bstop\s*[—-]\s*retry loop\b|\bstagnation replan\b|\bfirst-edit nudge\b|\bintra-run lesson\b|\blocal error-informed nudge\b|\b(?:failure|failing)\s+(?:recovery|replan|loop)\b|\bdoom-loop\b|\b(?:prior\s+)?failure reflection\b|\breflexion\b|\b(?:cross-session|prior)\s+lessons?\b|\bprogress gate\b|\bforecast\b)/i;
579120
+ LEGACY_RUNTIME_CONTROL_FRAGMENT_RE = /(?:\bREG-\d+\b|\bfocus supervisor\b|\bworld[ -]state\b|\brecent tool failures\b|\bstop\s*[—-]\s*retry loop\b|\bstagnation replan\b|\bfirst-edit nudge\b|\bintra-run lesson\b|\blocal error-informed nudge\b|\b(?:failure|failing)\s+(?:recovery|replan|loop|recap)\b|\b(?:controller|admin)\s+(?:summary|recap|reflection)\b|\bdoom-loop\b|\b(?:prior\s+)?failure reflection\b|\breflexion\b|\b(?:cross-session|prior)\s+lessons?\b|\bprogress gate\b|\bforecast\b)/i;
579030
579121
  LEGACY_RUNTIME_CONTROL_BLOCK_START_RE = /(?:\[(?:REG-\d+|FOCUS SUPERVISOR[^\]]*|WORLD[ -]STATE[^\]]*|RECENT TOOL FAILURES|STOP\s*[—-]\s*RETRY LOOP|STAGNATION REPLAN[^\]]*|FIRST-EDIT NUDGE[^\]]*|INTRA-RUN LESSON[^\]]*|LOCAL ERROR-INFORMED NUDGE[^\]]*|FORECAST[^\]]*|PROGRESS GATE[^\]]*|FAIL(?:URE|ING)[^\]]*(?:RECOVERY|REPLAN|LOOP)[^\]]*|DOOM-LOOP[^\]]*)\]|<(?:world-state|focus-supervisor|failure-recovery|reflection|lessons?)[^>]*>)/i;
579031
579122
  ASSISTANT_READ_INTENT_RETIRED_MARKER = "[assistant read intent retired: the linked tool result is already available; decide from that evidence instead of restating a read plan]";
579032
579123
  RESTORE_NOISE_LINE_RE = /^\s*(?:🔊|E Task timeout reached|E Incomplete:|⚠ Task incomplete|Tokens:\s*[\d,]+|▹\s*continue\b|·\s*(?:Starting fresh|Context (?:auto-)?restored|Nexus P2P network connected|REST API:|Voice feedback enabled|Memory maintenance:)|.*\bSHELL TRANSCRIPT\b.*|.*speaker emoji.*).*$/i;
@@ -579459,6 +579550,7 @@ function recordContextWindowDump(input) {
579459
579550
  ...input.note ? { note: input.note } : {},
579460
579551
  ...input.focusSupervisor ? { focusSupervisor: compactFocusSupervisor(input.focusSupervisor) } : {},
579461
579552
  metrics: metrics2,
579553
+ contextAccounting: buildContextAccounting(input.request, metrics2),
579462
579554
  apiView: summarizeApiView(input.request, metrics2),
579463
579555
  request: input.request
579464
579556
  };
@@ -579634,6 +579726,57 @@ function analyzeContextWindowDumpRequest(request) {
579634
579726
  }
579635
579727
  };
579636
579728
  }
579729
+ function contextSourceForMessage(role, text2) {
579730
+ if (/\[ACTIVE USER INTENT\]|\[CURRENT USER GOAL\]/.test(text2)) {
579731
+ return "current_user_intent";
579732
+ }
579733
+ if (/\[CONTROLLER STATE v1\]|\[RECENT ACTION GROUND TRUTH\]/.test(text2)) {
579734
+ return "current_controller_state";
579735
+ }
579736
+ if (/\[ACTIVE CONTEXT FRAME\]|Evidence already gathered this run/.test(text2)) {
579737
+ return "active_evidence";
579738
+ }
579739
+ if (role === "tool")
579740
+ return "tool_result";
579741
+ if (role === "system")
579742
+ return "system_instruction";
579743
+ if (role === "user")
579744
+ return "user_history";
579745
+ if (role === "assistant")
579746
+ return "assistant_history";
579747
+ return `role:${role}`;
579748
+ }
579749
+ function buildContextAccounting(request, metrics2) {
579750
+ const buckets = /* @__PURE__ */ new Map();
579751
+ const add3 = (source, chars) => {
579752
+ const bucket = buckets.get(source) ?? { messageCount: 0, chars: 0 };
579753
+ bucket.messageCount++;
579754
+ bucket.chars += chars;
579755
+ buckets.set(source, bucket);
579756
+ };
579757
+ const messages2 = Array.isArray(request["messages"]) ? request["messages"] : [];
579758
+ for (const message2 of messages2) {
579759
+ const record = message2 && typeof message2 === "object" ? message2 : {};
579760
+ const role = typeof record["role"] === "string" ? record["role"] : "unknown";
579761
+ const extracted = textAndImagesFromContent(record["content"]);
579762
+ const toolCallChars = Array.isArray(record["tool_calls"]) ? JSON.stringify(record["tool_calls"]).length : 0;
579763
+ add3(contextSourceForMessage(role, extracted.textWithoutImages), extracted.textWithoutImages.length + toolCallChars);
579764
+ }
579765
+ if (metrics2.toolSchemaChars > 0)
579766
+ add3("tool_schema", metrics2.toolSchemaChars);
579767
+ const sources = [...buckets.entries()].map(([source, bucket]) => ({
579768
+ source,
579769
+ ...bucket,
579770
+ estimatedTokens: Math.ceil(bucket.chars / 4)
579771
+ })).sort((a2, b) => a2.source.localeCompare(b.source));
579772
+ return {
579773
+ schemaVersion: 1,
579774
+ totalMessageChars: metrics2.totalChars,
579775
+ toolSchemaChars: metrics2.toolSchemaChars,
579776
+ estimatedTokens: metrics2.estimatedTokens,
579777
+ sources
579778
+ };
579779
+ }
579637
579780
  function summarizeApiView(request, metrics2) {
579638
579781
  const messages2 = Array.isArray(request["messages"]) ? request["messages"] : [];
579639
579782
  const previews = [];
@@ -581453,6 +581596,9 @@ var init_focusSupervisor = __esm({
581453
581596
  }
581454
581597
  this.taskEpoch = next;
581455
581598
  this.state = "observe";
581599
+ this.failureFamilies.clear();
581600
+ this.convergenceFamilyCounts.clear();
581601
+ this.sawMutationSinceFailure = false;
581456
581602
  this.ignoredDirectiveStreak = 0;
581457
581603
  this.lastIgnoredDirectiveTurn = null;
581458
581604
  this.repeatedViolationCounts.clear();
@@ -581746,6 +581892,8 @@ var init_focusSupervisor = __esm({
581746
581892
  }
581747
581893
  observeToolResult(input) {
581748
581894
  this.lastObservedTurn = Math.max(this.lastObservedTurn, input.turn);
581895
+ if (input.taskEpoch !== void 0)
581896
+ this.setTaskEpoch(input.taskEpoch, input.turn);
581749
581897
  this.expireDirectiveIfNeeded(input.turn);
581750
581898
  if (!this.enabled)
581751
581899
  return;
@@ -581767,7 +581915,7 @@ var init_focusSupervisor = __esm({
581767
581915
  if (input.toolName === "shell" && input.success) {
581768
581916
  if (this.convergenceBreaker) {
581769
581917
  const fam = actionFamily(input.toolName, input.args, this.familyCwd);
581770
- this.convergenceBreaker.resolve(fam);
581918
+ this.convergenceBreaker.resolve(`${this.taskEpoch}:${fam}`);
581771
581919
  this.convergenceFamilyCounts.delete(fam);
581772
581920
  }
581773
581921
  if (this.directive?.requiredNextAction === "run_verification") {
@@ -581855,7 +582003,7 @@ var init_focusSupervisor = __esm({
581855
582003
  const convCount = (this.convergenceFamilyCounts.get(convergenceFamily) ?? 0) + 1;
581856
582004
  this.convergenceFamilyCounts.set(convergenceFamily, convCount);
581857
582005
  const verdict = this.convergenceBreaker.observe({
581858
- family: convergenceFamily,
582006
+ family: `${this.taskEpoch}:${convergenceFamily}`,
581859
582007
  sessionCount: convCount,
581860
582008
  turn: input.turn,
581861
582009
  sample: next.sample,
@@ -581882,7 +582030,15 @@ var init_focusSupervisor = __esm({
581882
582030
  ]
581883
582031
  });
581884
582032
  } else if (verdict.tier === "abandon") {
581885
- this.markTerminalIncomplete(verdict.reason, input.turn);
582033
+ this.setDirective({
582034
+ turn: input.turn,
582035
+ state: "forced_replan",
582036
+ reason: verdict.reason,
582037
+ requiredNextAction: this.resolveRequiredNextAction("creative_pivot_or_research"),
582038
+ forbiddenActionFamilies: [
582039
+ actionFamily(input.toolName, input.args, this.familyCwd)
582040
+ ]
582041
+ });
581886
582042
  } else if (verdict.tier === "stalled") {
581887
582043
  this.setDirective({
581888
582044
  turn: input.turn,
@@ -588446,6 +588602,8 @@ var init_agenticRunner = __esm({
588446
588602
  pendingSteeringInputs = [];
588447
588603
  _steeringSequence = 0;
588448
588604
  _taskEpoch = 0;
588605
+ /** First tool-log turn belonging to the active task epoch. */
588606
+ _taskEpochStartTurn = 0;
588449
588607
  _activeRunId = "";
588450
588608
  /** Session storage is retained for compatibility; superseded task leaves are hidden from active guards. */
588451
588609
  _supersededTodoIds = /* @__PURE__ */ new Set();
@@ -589044,6 +589202,10 @@ var init_agenticRunner = __esm({
589044
589202
  _workboardDir() {
589045
589203
  return this.options.workboardDir || this._workingDirectory || process.cwd();
589046
589204
  }
589205
+ /** One immutable execution run owns every workboard read and mutation. */
589206
+ _workboardRunId() {
589207
+ return this.currentArtifactRunId();
589208
+ }
589047
589209
  _todoWriteAvailable() {
589048
589210
  return this.tools.has("todo_write");
589049
589211
  }
@@ -589065,7 +589227,7 @@ var init_agenticRunner = __esm({
589065
589227
  return this._workboard;
589066
589228
  }
589067
589229
  const dir = this._workboardDir();
589068
- const runId = this.currentArtifactRunId();
589230
+ const runId = this._workboardRunId();
589069
589231
  const existing = loadWorkboardSnapshot(dir, runId);
589070
589232
  if (existing) {
589071
589233
  this._workboard = this._seedWorkboardCardsIfNeeded(existing, goal);
@@ -589082,6 +589244,8 @@ var init_agenticRunner = __esm({
589082
589244
  runId,
589083
589245
  owner: this.options.subAgent ? "sub-agent" : "agent",
589084
589246
  goal: goal || void 0,
589247
+ rawUserIntent: goal || void 0,
589248
+ taskEpoch: this._taskEpoch,
589085
589249
  title: (this._taskState.goal || "").slice(0, 120) || void 0,
589086
589250
  cards: initialCards
589087
589251
  });
@@ -589186,6 +589350,8 @@ var init_agenticRunner = __esm({
589186
589350
  runId,
589187
589351
  owner: actor,
589188
589352
  goal: this._taskState.originalGoal || this._taskState.goal || void 0,
589353
+ rawUserIntent: this._taskState.originalGoal || this._taskState.goal || void 0,
589354
+ taskEpoch: this._taskEpoch,
589189
589355
  title: (this._taskState.goal || diagnosis.workboardTitle).slice(0, 120) || void 0,
589190
589356
  actor,
589191
589357
  cards: [cardInput]
@@ -589244,6 +589410,52 @@ var init_agenticRunner = __esm({
589244
589410
  const safe = todoId.replace(/[^a-zA-Z0-9_.-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80);
589245
589411
  return `todo-${safe || "item"}`;
589246
589412
  }
589413
+ /**
589414
+ * Todo ids are transport identifiers, not task identity. Prefer declared
589415
+ * artifacts, then an explicit verifier, and only then a normalized title so
589416
+ * repeated todo_write calls cannot fork semantic workboard cards.
589417
+ */
589418
+ _todoWorkboardCanonicalKey(todo) {
589419
+ const artifacts = (todo.declaredArtifacts ?? []).filter((path16) => typeof path16 === "string").map((path16) => this._normalizeEvidencePath(path16)).filter(Boolean).sort();
589420
+ if (artifacts.length > 0)
589421
+ return `artifacts:${[...new Set(artifacts)].join("|")}`;
589422
+ const verifier = normalizeShellCommand(String(todo.verifyCommand ?? ""));
589423
+ if (verifier)
589424
+ return `verifier:${verifier}`;
589425
+ const words = todo.content.toLowerCase().replace(/[^a-z0-9]+/g, " ").split(/\s+/).filter((word2) => word2.length > 2).filter((word2) => !(/* @__PURE__ */ new Set(["the", "and", "for", "with", "from", "that", "this", "then", "into", "todo"])).has(word2));
589426
+ return `text:${[...new Set(words)].sort().join("|")}`;
589427
+ }
589428
+ _todoCardsSemanticallyMatch(existing, input) {
589429
+ if (existing.canonicalKey && input.canonicalKey) {
589430
+ return existing.canonicalKey === input.canonicalKey;
589431
+ }
589432
+ const existingVerifier = normalizeShellCommand(existing.verifierCommand ?? "");
589433
+ const inputVerifier = normalizeShellCommand(input.verifierCommand ?? "");
589434
+ if (existingVerifier && inputVerifier)
589435
+ return existingVerifier === inputVerifier;
589436
+ const existingFiles = new Set((existing.ownedFiles ?? []).map((path16) => this._normalizeEvidencePath(path16)));
589437
+ const inputFiles = (input.ownedFiles ?? []).map((path16) => this._normalizeEvidencePath(path16));
589438
+ if (existingFiles.size > 0 && inputFiles.length > 0) {
589439
+ return inputFiles.some((path16) => existingFiles.has(path16));
589440
+ }
589441
+ const words = (value2) => new Set(value2.toLowerCase().replace(/[^a-z0-9]+/g, " ").split(/\s+/).filter((word2) => word2.length > 3));
589442
+ const left = words(`${existing.title} ${existing.description}`);
589443
+ const right = words(`${input.title} ${input.description ?? ""}`);
589444
+ let shared = 0;
589445
+ for (const word2 of left)
589446
+ if (right.has(word2))
589447
+ shared++;
589448
+ return shared >= 5 && shared / Math.max(left.size, right.size, 1) >= 0.62;
589449
+ }
589450
+ _mergeTodoCardInputs(target, incoming) {
589451
+ target.sourceTodoIds = [.../* @__PURE__ */ new Set([...target.sourceTodoIds ?? [], ...incoming.sourceTodoIds ?? []])];
589452
+ target.ownedFiles = [.../* @__PURE__ */ new Set([...target.ownedFiles ?? [], ...incoming.ownedFiles ?? []])];
589453
+ target.evidenceRequirements = [.../* @__PURE__ */ new Set([...target.evidenceRequirements ?? [], ...incoming.evidenceRequirements ?? []])];
589454
+ if (incoming.status === "in_progress") {
589455
+ target.status = "in_progress";
589456
+ target.lane = "worker";
589457
+ }
589458
+ }
589247
589459
  _todoWorkboardCardInput(todo, path16) {
589248
589460
  const requirements = [];
589249
589461
  if (todo.verifyCommand) {
@@ -589268,6 +589480,8 @@ var init_agenticRunner = __esm({
589268
589480
  const status = todo.status === "blocked" ? "blocked" : todo.status === "pending" ? "open" : "in_progress";
589269
589481
  return {
589270
589482
  id: this._todoWorkboardCardId(todo.id),
589483
+ canonicalKey: this._todoWorkboardCanonicalKey(todo),
589484
+ sourceTodoIds: [todo.id],
589271
589485
  title: todo.content.slice(0, 120),
589272
589486
  description: path16.map((item) => item.content).join(" > ").slice(0, 800),
589273
589487
  lane,
@@ -589275,7 +589489,9 @@ var init_agenticRunner = __esm({
589275
589489
  assignee: todo.owner || "any",
589276
589490
  role: "worker",
589277
589491
  evidenceRequired: true,
589278
- evidenceRequirements: requirements
589492
+ evidenceRequirements: requirements,
589493
+ ownedFiles: (todo.declaredArtifacts ?? []).filter((path17) => typeof path17 === "string").map((path17) => this._normalizeEvidencePath(path17)).filter(Boolean),
589494
+ verifierCommand: todo.verifyCommand
589279
589495
  };
589280
589496
  }
589281
589497
  _mirrorTodosToWorkboard(todos) {
@@ -589286,7 +589502,15 @@ var init_agenticRunner = __esm({
589286
589502
  const activeLeaves = this._todoLeaves(normalized, index).filter((todo) => todo.status !== "completed").slice(0, 20);
589287
589503
  if (activeLeaves.length === 0)
589288
589504
  return;
589289
- const cards = activeLeaves.map((todo) => this._todoWorkboardCardInput(todo, this._todoPath(todo, index)));
589505
+ const cards = [];
589506
+ for (const todo of activeLeaves) {
589507
+ const incoming = this._todoWorkboardCardInput(todo, this._todoPath(todo, index));
589508
+ const equivalent = cards.find((card) => this._todoCardsSemanticallyMatch(card, incoming));
589509
+ if (equivalent)
589510
+ this._mergeTodoCardInputs(equivalent, incoming);
589511
+ else
589512
+ cards.push(incoming);
589513
+ }
589290
589514
  const dir = this._workboardDir();
589291
589515
  const runId = this.currentArtifactRunId();
589292
589516
  const actor = this.options.subAgent ? "sub-agent" : "agent";
@@ -589297,6 +589521,8 @@ var init_agenticRunner = __esm({
589297
589521
  runId,
589298
589522
  owner: actor,
589299
589523
  goal: this._taskState.originalGoal || this._taskState.goal || void 0,
589524
+ rawUserIntent: this._taskState.originalGoal || this._taskState.goal || void 0,
589525
+ taskEpoch: this._taskEpoch,
589300
589526
  title: (this._taskState.goal || "Active todo work").slice(0, 120),
589301
589527
  actor,
589302
589528
  cards
@@ -589305,7 +589531,7 @@ var init_agenticRunner = __esm({
589305
589531
  return;
589306
589532
  }
589307
589533
  for (const cardInput of cards) {
589308
- const existing = board.cards.find((card) => card.id === cardInput.id);
589534
+ let existing = board.cards.find((card) => card.id === cardInput.id) ?? board.cards.find((card) => !card.supersededBy && this._todoCardsSemanticallyMatch(card, cardInput));
589309
589535
  if (!existing) {
589310
589536
  board = addWorkboardCard(dir, {
589311
589537
  ...cardInput,
@@ -589315,6 +589541,28 @@ var init_agenticRunner = __esm({
589315
589541
  });
589316
589542
  continue;
589317
589543
  }
589544
+ const duplicates = board.cards.filter((card) => card.id !== existing.id && !card.supersededBy && this._todoCardsSemanticallyMatch(card, cardInput));
589545
+ for (const duplicate of duplicates) {
589546
+ if (duplicate.evidence.length > 0) {
589547
+ attachWorkboardEvidence(dir, {
589548
+ runId,
589549
+ cardId: existing.id,
589550
+ actor,
589551
+ evidence: duplicate.evidence
589552
+ });
589553
+ }
589554
+ board = updateWorkboardCard(dir, {
589555
+ runId,
589556
+ cardId: duplicate.id,
589557
+ actor,
589558
+ updates: {
589559
+ supersededBy: existing.id,
589560
+ blocker: `Superseded by canonical card '${existing.id}'.`
589561
+ },
589562
+ decisionReason: `Merged duplicate todo card into canonical '${existing.id}'.`
589563
+ });
589564
+ existing = board.cards.find((card) => card.id === existing.id) ?? existing;
589565
+ }
589318
589566
  if (existing.status === "verified")
589319
589567
  continue;
589320
589568
  board = updateWorkboardCard(dir, {
@@ -589326,7 +589574,11 @@ var init_agenticRunner = __esm({
589326
589574
  description: cardInput.description,
589327
589575
  lane: cardInput.lane,
589328
589576
  status: existing.status === "completed" ? "needs_changes" : cardInput.status,
589329
- evidenceRequirements: cardInput.evidenceRequirements
589577
+ evidenceRequirements: cardInput.evidenceRequirements,
589578
+ canonicalKey: cardInput.canonicalKey,
589579
+ sourceTodoIds: [.../* @__PURE__ */ new Set([...existing.sourceTodoIds ?? [], ...cardInput.sourceTodoIds ?? []])],
589580
+ ownedFiles: cardInput.ownedFiles,
589581
+ verifierCommand: cardInput.verifierCommand
589330
589582
  },
589331
589583
  decisionReason: "Synchronized workboard card from current todo state."
589332
589584
  });
@@ -589452,12 +589704,12 @@ var init_agenticRunner = __esm({
589452
589704
  injectWorkboardContext() {
589453
589705
  if (this._workboard || this.options.subAgent) {
589454
589706
  const dir = this._workboardDir();
589455
- let snapshot = readActiveWorkboardSnapshot(dir, this._sessionId);
589707
+ let snapshot = readActiveWorkboardSnapshot(dir, this._workboardRunId());
589456
589708
  if (!snapshot)
589457
589709
  return null;
589458
589710
  snapshot = this._seedWorkboardCardsIfNeeded(snapshot, this._taskState.originalGoal || this._taskState.goal || "");
589459
589711
  this._workboard = snapshot;
589460
- const activeCards = snapshot.cards.filter((c9) => c9.status === "in_progress" || c9.status === "open" || c9.status === "needs_changes");
589712
+ const activeCards = snapshot.cards.filter((c9) => !c9.supersededBy && (c9.status === "in_progress" || c9.status === "open" || c9.status === "needs_changes"));
589461
589713
  if (activeCards.length === 0 && snapshot.cards.every((c9) => c9.status === "verified" || c9.status === "completed"))
589462
589714
  return null;
589463
589715
  const synthesis = buildWorkboardSynthesisContext(snapshot);
@@ -589558,7 +589810,7 @@ ${parts.join("\n")}
589558
589810
  _deriveWorkboardActionContract(snapshot) {
589559
589811
  if (snapshot.cards.length === 0)
589560
589812
  return null;
589561
- const byId = new Map(snapshot.cards.map((card) => [card.id, card]));
589813
+ const byId = new Map(snapshot.cards.filter((card) => !card.supersededBy).map((card) => [card.id, card]));
589562
589814
  const discovery = byId.get("discover-current-state");
589563
589815
  const implementation2 = byId.get("implement-repair");
589564
589816
  const integration = byId.get("integrate-and-run");
@@ -589598,7 +589850,7 @@ ${parts.join("\n")}
589598
589850
  ])
589599
589851
  };
589600
589852
  }
589601
- const active = snapshot.cards.find((card) => card.status === "in_progress") ?? snapshot.cards.find((card) => card.status === "needs_changes") ?? snapshot.cards.find((card) => card.status === "open") ?? discovery;
589853
+ const active = snapshot.cards.find((card) => !card.supersededBy && card.status === "in_progress") ?? snapshot.cards.find((card) => !card.supersededBy && card.status === "needs_changes") ?? snapshot.cards.find((card) => !card.supersededBy && card.status === "open") ?? discovery;
589602
589854
  if (!active)
589603
589855
  return null;
589604
589856
  return {
@@ -589738,6 +589990,8 @@ ${parts.join("\n")}
589738
589990
  for (const card of snapshot.cards) {
589739
589991
  if (!card.id.startsWith("todo-"))
589740
589992
  continue;
589993
+ if (card.supersededBy)
589994
+ continue;
589741
589995
  if (card.status === "completed" || card.status === "verified")
589742
589996
  continue;
589743
589997
  const text2 = [
@@ -589760,6 +590014,19 @@ ${parts.join("\n")}
589760
590014
  }
589761
590015
  return best?.card ?? null;
589762
590016
  }
590017
+ _workboardTodoCardForVerifier(snapshot, args) {
590018
+ const command = String(args["command"] ?? args["cmd"] ?? "").trim();
590019
+ if (!command)
590020
+ return null;
590021
+ return snapshot.cards.find((card) => {
590022
+ if (!card.id.startsWith("todo-") || card.supersededBy)
590023
+ return false;
590024
+ if (card.status === "completed" || card.status === "verified")
590025
+ return false;
590026
+ const verifier = card.verifierCommand || card.evidenceRequirements.find((item) => item.startsWith("verifyCommand:"))?.replace(/^verifyCommand:\s*/, "") || "";
590027
+ return verifier.length > 0 && commandReliablySatisfiesVerifyCommand(command, verifier);
590028
+ }) ?? null;
590029
+ }
589763
590030
  _workboardTargetCardId(snapshot, toolName, args, result, meta = {}) {
589764
590031
  const byId = new Map(snapshot.cards.map((card) => [card.id, card]));
589765
590032
  const targetPaths = this._extractToolTargetPaths(toolName, args, result);
@@ -589771,6 +590038,9 @@ ${parts.join("\n")}
589771
590038
  return matchingTodo?.id ?? (byId.has("implement-repair") ? "implement-repair" : null);
589772
590039
  }
589773
590040
  if (toolName === "shell" || toolName === "background_run") {
590041
+ const verifierTodo = this._workboardTodoCardForVerifier(snapshot, args);
590042
+ if (verifierTodo)
590043
+ return verifierTodo.id;
589774
590044
  const implementation2 = byId.get("implement-repair");
589775
590045
  const target = this._workboardHasEditEvidence(implementation2) ? "integrate-and-run" : "discover-current-state";
589776
590046
  return byId.has(target) ? target : null;
@@ -589784,7 +590054,7 @@ ${parts.join("\n")}
589784
590054
  return active?.id ?? null;
589785
590055
  }
589786
590056
  _refreshWorkboardSnapshot(snapshot) {
589787
- const refreshed = readActiveWorkboardSnapshot(this._workboardDir(), this._sessionId) ?? snapshot;
590057
+ const refreshed = readActiveWorkboardSnapshot(this._workboardDir(), this._workboardRunId()) ?? snapshot;
589788
590058
  this._workboard = refreshed;
589789
590059
  return refreshed;
589790
590060
  }
@@ -589855,7 +590125,7 @@ ${parts.join("\n")}
589855
590125
  * Non-fatal: failures to attach evidence are silently caught.
589856
590126
  */
589857
590127
  recordWorkboardToolCall(toolName, args, success, output, result, meta = {}) {
589858
- const board = this._workboard ?? this.getOrCreateWorkboard();
590128
+ const board = this._currentWorkboardSnapshotForFrame() ?? this.getOrCreateWorkboard();
589859
590129
  if (!board)
589860
590130
  return;
589861
590131
  if (toolName === "task_complete" || toolName === "workboard_create")
@@ -589891,13 +590161,26 @@ ${parts.join("\n")}
589891
590161
  if (targetCard.assignee && targetCard.assignee !== actor && targetCard.assignee !== "any") {
589892
590162
  return;
589893
590163
  }
589894
- attachWorkboardEvidence(dir, {
590164
+ const evidenced = attachWorkboardEvidence(dir, {
589895
590165
  runId: this.currentArtifactRunId(),
589896
590166
  cardId: targetCard.id,
589897
590167
  actor,
589898
590168
  evidence
589899
590169
  });
589900
- this._refreshWorkboardSnapshot(advanced);
590170
+ const persistedEvidence = evidenced.cards.find((card) => card.id === targetCard.id)?.evidence.find((item) => item.summary === evidence.summary && item.content === evidence.content);
590171
+ const substantive = success === true && result?.runtimeAuthored !== true;
590172
+ this._workboard = updateWorkboardMetadata(dir, {
590173
+ runId: this.currentArtifactRunId(),
590174
+ actor,
590175
+ taskEpoch: this._taskEpoch,
590176
+ artifactEvidence: persistedEvidence ? [persistedEvidence] : [evidence],
590177
+ lastSubstantiveProgress: substantive ? {
590178
+ turn: this._taskState.toolCallCount,
590179
+ signature: this._buildToolFingerprint(toolName, args),
590180
+ evidenceIds: persistedEvidence ? [persistedEvidence.id] : [],
590181
+ occurredAt: (/* @__PURE__ */ new Date()).toISOString()
590182
+ } : void 0
590183
+ });
589901
590184
  } catch {
589902
590185
  }
589903
590186
  }
@@ -590362,7 +590645,12 @@ ${parts.join("\n")}
590362
590645
  try {
590363
590646
  const dir = _pathJoin(this.omniusStateDir(), "completion-ledgers");
590364
590647
  _fsMkdirSync(dir, { recursive: true });
590365
- saveCompletionLedger(_pathJoin(dir, `${this._sessionId}.json`), this._completionLedger);
590648
+ saveCompletionLedger(
590649
+ // A session can contain several steering epochs. Persist by immutable
590650
+ // artifact run so recovery never hydrates evidence from a retired goal.
590651
+ _pathJoin(dir, `${this.currentArtifactRunId()}.json`),
590652
+ this._completionLedger
590653
+ );
590366
590654
  } catch {
590367
590655
  }
590368
590656
  }
@@ -590807,7 +591095,20 @@ Your hypotheses MUST address this specific error, not generic causes.
590807
591095
  messages: messages2,
590808
591096
  currentGoal: this._taskState.originalGoal || this._taskState.goal || this._taskState.currentStep || this._taskState.nextAction || ""
590809
591097
  });
590810
- return sanitizeHistoryThink(prepared);
591098
+ const withCurrentUserIntent = sanitizeHistoryThink(prepared);
591099
+ if (!withCurrentUserIntent.some((message2) => message2.role === "user")) {
591100
+ const currentIntent = this._taskState.originalGoal || this._taskState.goal || this._taskState.currentStep || this._taskState.nextAction || "";
591101
+ if (currentIntent.trim()) {
591102
+ const insertAt = withCurrentUserIntent[0]?.role === "system" ? 1 : 0;
591103
+ withCurrentUserIntent.splice(insertAt, 0, {
591104
+ role: "user",
591105
+ content: `[ACTIVE USER INTENT]
591106
+ ${currentIntent.trim().slice(0, 6e3)}`,
591107
+ taskEpoch: this._taskEpoch
591108
+ });
591109
+ }
591110
+ }
591111
+ return withCurrentUserIntent;
590811
591112
  }
590812
591113
  // ── Failing-approach detector (the "stop retrying variants" reflex) ───────
590813
591114
  // Encodes the behavior an effective agent uses and the dropbear 27× loop
@@ -590875,7 +591176,7 @@ Your hypotheses MUST address this specific error, not generic causes.
590875
591176
  stage: opts?.dumpStage ?? "aux_inference",
590876
591177
  agentType: "internal",
590877
591178
  sessionId: this._sessionId,
590878
- runId: this.currentArtifactRunId(),
591179
+ runId: this._workboardRunId(),
590879
591180
  model: this._backendModelLabel(this.backend),
590880
591181
  cwd: this._workingDirectory || process.cwd(),
590881
591182
  request: r2
@@ -591769,6 +592070,13 @@ ${extras.join("\n")}`;
591769
592070
  existingCards
591770
592071
  }) : existingCards;
591771
592072
  const delta = diffDiagnosticSets(previousDiagnostics, diagnostics);
592073
+ const verifierActionSignature = normalizeShellCommand(verifierCommand);
592074
+ const verifierResultSignature = [
592075
+ input.success ? "success" : "failure",
592076
+ ...diagnostics.map((diagnostic) => diagnostic.fingerprint).sort()
592077
+ ].join("|");
592078
+ const unchangedVerifierRound = this._compileFixLoop?.verifierActionSignature === verifierActionSignature && this._compileFixLoop?.verifierResultSignature === verifierResultSignature;
592079
+ const verifierStasisCount = unchangedVerifierRound ? (this._compileFixLoop?.verifierStasisCount ?? 0) + 1 : 0;
591772
592080
  const nextCards = this._mergeCompileFixCardsAfterVerifier({
591773
592081
  existingCards,
591774
592082
  observedCards: cards,
@@ -591788,8 +592096,21 @@ ${extras.join("\n")}`;
591788
592096
  cards: nextCards,
591789
592097
  // A live verifier run resolves the gate's demand — the block streak
591790
592098
  // is over regardless of pass/fail.
591791
- preflightBlockStreak: 0
591792
- };
592099
+ preflightBlockStreak: 0,
592100
+ verifierActionSignature,
592101
+ verifierResultSignature,
592102
+ verifierStasisCount,
592103
+ verifierStasisBlocked: verifierStasisCount >= 3 && !(input.success && diagnostics.length === 0),
592104
+ prerequisiteRecoverySignature: void 0
592105
+ };
592106
+ if (this._compileFixLoop.verifierStasisBlocked) {
592107
+ this.emit({
592108
+ type: "status",
592109
+ content: `compile_error_verifier_stasis: action/result unchanged for ${verifierStasisCount} rounds; block unchanged verifier/read retries until a scoped fix or fresh prerequisite evidence changes state`,
592110
+ turn: input.turn,
592111
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
592112
+ });
592113
+ }
591793
592114
  this._mirrorCompileFixCardsToWorkboard(nextCards, {
591794
592115
  command: verifierCommand,
591795
592116
  success: input.success && diagnostics.length === 0,
@@ -591918,7 +592239,7 @@ ${extras.join("\n")}`;
591918
592239
  const dir = this._workboardDir();
591919
592240
  const actor = this.options.subAgent ? "sub-agent" : "agent";
591920
592241
  for (const card of cards) {
591921
- const existing = (readActiveWorkboardSnapshot(dir, this._sessionId) ?? this._workboard)?.cards.find((item) => item.id === card.id);
592242
+ const existing = (readActiveWorkboardSnapshot(dir, this._workboardRunId()) ?? this._workboard)?.cards.find((item) => item.id === card.id);
591922
592243
  if (!existing) {
591923
592244
  this._workboard = addWorkboardCard(dir, {
591924
592245
  ...compileFixCardToWorkboardInput(card),
@@ -591967,7 +592288,7 @@ ${extras.join("\n")}`;
591967
592288
  }
591968
592289
  });
591969
592290
  if (card.status === "dismissed" || card.status === "verified") {
591970
- const active = readActiveWorkboardSnapshot(dir, this._sessionId);
592291
+ const active = readActiveWorkboardSnapshot(dir, this._workboardRunId());
591971
592292
  const wbCard = active?.cards.find((item) => item.id === card.id);
591972
592293
  if (wbCard && wbCard.status !== "completed" && wbCard.status !== "verified") {
591973
592294
  this._workboard = completeWorkboardCard(dir, {
@@ -591979,7 +592300,7 @@ ${extras.join("\n")}`;
591979
592300
  }).snapshot;
591980
592301
  }
591981
592302
  if (card.status === "verified") {
591982
- const latest = readActiveWorkboardSnapshot(dir, this._sessionId);
592303
+ const latest = readActiveWorkboardSnapshot(dir, this._workboardRunId());
591983
592304
  const latestCard = latest?.cards.find((item) => item.id === card.id);
591984
592305
  if (latestCard?.status === "completed") {
591985
592306
  this._workboard = completeWorkboardCard(dir, {
@@ -591999,7 +592320,7 @@ ${extras.join("\n")}`;
591999
592320
  _mirrorCompileFixCardAssigned(card, turn) {
592000
592321
  try {
592001
592322
  const dir = this._workboardDir();
592002
- const active = readActiveWorkboardSnapshot(dir, this._sessionId);
592323
+ const active = readActiveWorkboardSnapshot(dir, this._workboardRunId());
592003
592324
  const existing = active?.cards.find((item) => item.id === card.id);
592004
592325
  if (!existing || existing.status !== "open")
592005
592326
  return;
@@ -592028,6 +592349,9 @@ ${extras.join("\n")}`;
592028
592349
  state.verifierDirtySinceTurn = turn;
592029
592350
  state.lastVerifierPassedTurn = null;
592030
592351
  state.lastMutationTurn = turn;
592352
+ state.verifierStasisCount = 0;
592353
+ state.verifierStasisBlocked = false;
592354
+ state.prerequisiteRecoverySignature = void 0;
592031
592355
  this._focusSupervisor?.markCompletionBlocked({
592032
592356
  turn,
592033
592357
  reason: "A source mutation invalidated the declared verifier; verifier evidence now owns the active focus.",
@@ -592077,68 +592401,67 @@ ${extras.join("\n")}`;
592077
592401
  if (!state?.active)
592078
592402
  return null;
592079
592403
  const action = compileFixLoopNextRequiredAction(state);
592080
- if (action !== "run_declared_verifier")
592404
+ const verifierLocked = action === "run_declared_verifier" || state.verifierStasisBlocked === true;
592405
+ if (!verifierLocked)
592081
592406
  return null;
592407
+ const blocked = (reason) => {
592408
+ const streak = (state.preflightBlockStreak ?? 0) + 1;
592409
+ state.preflightBlockStreak = streak;
592410
+ return {
592411
+ kind: "block",
592412
+ message: [
592413
+ `[COMPILE ERROR FIX LOOP BLOCKED — verifier action locked]`,
592414
+ reason,
592415
+ `declared_verifier=${state.verifierCommand}`,
592416
+ `dirtySinceTurn=${state.verifierDirtySinceTurn}`,
592417
+ `lastVerifierRunTurn=${state.lastVerifierRunTurn}`,
592418
+ `stasisRounds=${state.verifierStasisCount ?? 0}`,
592419
+ `blockedTool=${toolName} consecutiveBlocks=${streak}`,
592420
+ `Allowed next actions: the declared verifier; one narrow prerequisite read of an owned file; or a scoped source fix that changes verifier inputs.`
592421
+ ].join("\n")
592422
+ };
592423
+ };
592082
592424
  if (toolName === "shell") {
592083
592425
  const command = String(args["command"] ?? args["cmd"] ?? "").trim();
592084
592426
  if (commandReliablySatisfiesVerifyCommand(command, state.verifierCommand)) {
592427
+ if (state.verifierStasisBlocked) {
592428
+ return blocked("The same verifier action/result is in stasis. Change the owned source or obtain fresh prerequisite evidence before rerunning this unchanged verifier.");
592429
+ }
592085
592430
  state.preflightBlockStreak = 0;
592086
592431
  return null;
592087
592432
  }
592088
- if (!shellLikelyMutatesFilesystem) {
592433
+ void shellLikelyMutatesFilesystem;
592434
+ return blocked("Only the declared verifier shell command is admitted while verifier evidence is locked.");
592435
+ }
592436
+ const readLike = /* @__PURE__ */ new Set([
592437
+ "file_read",
592438
+ "grep_search",
592439
+ "find_files",
592440
+ "list_directory",
592441
+ "file_explore"
592442
+ ]);
592443
+ if (readLike.has(toolName)) {
592444
+ const target = String(args["path"] ?? args["file"] ?? args["file_path"] ?? "");
592445
+ const owned = state.cards.flatMap((card) => card.ownedFiles);
592446
+ const scoped = target.length > 0 && owned.some((path16) => this._pathsOverlapForVerifier(target, path16));
592447
+ const signature = `${toolName}:${this._buildExactArgsKey(args)}`;
592448
+ if (scoped && state.prerequisiteRecoverySignature !== signature) {
592449
+ state.prerequisiteRecoverySignature = signature;
592450
+ state.preflightBlockStreak = 0;
592089
592451
  return null;
592090
592452
  }
592091
- const extraction = extractShellMutationPaths(command, {
592092
- workingDir: this.authoritativeWorkingDirectory()
592093
- });
592094
- const mutationPaths = extraction.paths.map((p2) => this._normalizeEvidencePath(p2)).filter(Boolean);
592095
- if (mutationPaths.length === 0 || !this._compileFixPathsTouchProjectSources(mutationPaths, state)) {
592453
+ return blocked(scoped ? "The one prerequisite-recovery read has already been used; act on its evidence instead of reading again." : "Prerequisite recovery must be a narrow read of a compile-card owned file.");
592454
+ }
592455
+ if (this._isProjectEditTool(toolName)) {
592456
+ const targetPaths = this._extractToolTargetPaths(toolName, args);
592457
+ const scoped = targetPaths.some((path16) => this._compileFixPathsTouchProjectSources([this._normalizeEvidencePath(path16)], state));
592458
+ if (scoped) {
592459
+ state.preflightBlockStreak = 0;
592096
592460
  return null;
592097
592461
  }
592098
- } else if (!this._isProjectEditTool(toolName)) {
592099
- return null;
592100
- }
592101
- const yieldAfter = Number.MAX_SAFE_INTEGER;
592102
- const streak = (state.preflightBlockStreak ?? 0) + 1;
592103
- if (streak > yieldAfter) {
592104
- state.preflightBlockStreak = 0;
592105
- this.emit({
592106
- type: "status",
592107
- content: `compile_error_verifier_dirty: gate yielded to ${toolName} after ${yieldAfter} consecutive blocks at turn ${turn}`,
592108
- turn,
592109
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
592110
- });
592111
- return {
592112
- kind: "yield",
592113
- notice: [
592114
- `[COMPILE FIX GATE YIELDED — verifier still required]`,
592115
- `The verifier-required gate blocked ${yieldAfter} consecutive tool calls and is yielding so work can continue.`,
592116
- `Verifier evidence is still stale. Run the verifier as your next evidence step:`,
592117
- ` ${state.verifierCommand}`,
592118
- `Any real build/test command whose output shows current compiler diagnostics is also accepted as the live verifier.`,
592119
- `task_complete remains blocked until a verifier run passes after the last mutation.`
592120
- ].join("\n")
592121
- };
592462
+ return blocked("A repair mutation must target a file owned by the active compile-fix card.");
592122
592463
  }
592123
- state.preflightBlockStreak = streak;
592124
- const message2 = [
592125
- `[COMPILE ERROR FIX LOOP BLOCKED — declared verifier required]`,
592126
- `A compile-fix card was patched, so the next mutation/evidence step must be the live verifier.`,
592127
- `Run this now: ${state.verifierCommand}`,
592128
- `Any real build/test command whose output shows current compiler diagnostics is also accepted.`,
592129
- `dirtySinceTurn: ${state.verifierDirtySinceTurn}`,
592130
- `lastMutationTurn: ${state.lastMutationTurn}`,
592131
- `lastVerifierRunTurn: ${state.lastVerifierRunTurn}`,
592132
- `blockedTool: ${toolName}`,
592133
- `consecutiveBlocks: ${streak} (verifier focus is retained until a live verifier settles)`
592134
- ].join("\n");
592135
- this.emit({
592136
- type: "status",
592137
- content: `compile_error_verifier_dirty: blocked ${toolName} at turn ${turn} (${streak}/${yieldAfter})`,
592138
- turn,
592139
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
592140
- });
592141
- return { kind: "block", message: message2 };
592464
+ return blocked("This tool is unrelated to the locked verifier action.");
592142
592465
  }
592143
592466
  _compileFixLoopCompletionBlocker(turn) {
592144
592467
  const state = this._compileFixLoop;
@@ -593350,8 +593673,8 @@ ${_checks}`
593350
593673
  return { proceed: true };
593351
593674
  const maxCycles = parseInt(process.env["OMNIUS_BACKWARD_PASS_MAX_CYCLES"] || "2", 10) || 2;
593352
593675
  if (this._backwardPassCyclesUsed >= maxCycles) {
593353
- const lastCritique2 = this._lastBackwardPassCritique;
593354
- const evidenceAfterCritique = lastCritique2 ? toolCallLog.slice(lastCritique2.toolLogLength) : [];
593676
+ const lastCritique = this._lastBackwardPassCritique;
593677
+ const evidenceAfterCritique = lastCritique ? toolCallLog.slice(lastCritique.toolLogLength) : [];
593355
593678
  const freshVerification = evidenceAfterCritique.filter((entry) => {
593356
593679
  if (entry.success !== true)
593357
593680
  return false;
@@ -593361,7 +593684,7 @@ ${_checks}`
593361
593684
  const concern = freshVerification.length > 0 ? [
593362
593685
  "Prior reviewer concern may be stale; fresh verification evidence was recorded after that critique.",
593363
593686
  ...freshVerification.map((entry) => `${entry.name}: ${(entry.outputPreview ?? entry.argsKey).slice(0, 220)}`)
593364
- ].join(" ") : lastCritique2?.rationale?.trim() || this._lastBackwardPassVerdict || "unspecified";
593687
+ ].join(" ") : lastCritique?.rationale?.trim() || this._lastBackwardPassVerdict || "unspecified";
593365
593688
  this._completionCaveat = [
593366
593689
  `[COMPLETION CAVEAT] Backward-pass review did not fully approve after ${this._backwardPassCyclesUsed}/${maxCycles} cycle(s).`,
593367
593690
  `${freshVerification.length > 0 ? "Reviewer reconciliation note" : "Unresolved reviewer concern"}: ${concern.slice(0, 600)}`,
@@ -593413,7 +593736,7 @@ ${_checks}`
593413
593736
  });
593414
593737
  }
593415
593738
  };
593416
- const todos = (() => {
593739
+ const allTodos = (() => {
593417
593740
  try {
593418
593741
  const _t = this.readSessionTodos();
593419
593742
  return Array.isArray(_t) ? _t : [];
@@ -593421,17 +593744,15 @@ ${_checks}`
593421
593744
  return [];
593422
593745
  }
593423
593746
  })();
593747
+ const todos = allTodos.filter((todo) => !this._supersededTodoIds.has(todo.id));
593424
593748
  const wd = this._workingDirectory || process.cwd();
593425
593749
  let reconciled = [];
593426
593750
  try {
593427
593751
  reconciled = reconcilePlan(todos, [], { workingDir: wd });
593428
593752
  } catch {
593429
593753
  }
593430
- const recentFailures = Array.from(this._failureReflections.entries()).map(([stem, entry]) => ({
593431
- stem,
593432
- attempts: entry.attempts,
593433
- preview: (entry.wentWrong || "").slice(0, 200)
593434
- })).sort((a2, b) => b.attempts - a2.attempts).slice(0, 5);
593754
+ const recentFailures = [];
593755
+ const activeEpochToolLog = toolCallLog.filter((entry) => typeof entry.turn === "number" && entry.turn >= this._taskEpochStartTurn);
593435
593756
  const toCriticEvidence = (entries, limit) => entries.filter((entry) => entry.name !== "task_complete").slice(-limit).map((entry) => ({
593436
593757
  name: entry.name,
593437
593758
  argsKey: entry.argsKey.slice(0, 300),
@@ -593440,9 +593761,7 @@ ${_checks}`
593440
593761
  turn: entry.turn,
593441
593762
  mutated: entry.mutated === true
593442
593763
  }));
593443
- const criticToolEvidence = toCriticEvidence(toolCallLog, 40);
593444
- const lastCritique = this._lastBackwardPassCritique;
593445
- const evidenceSincePriorCritique = lastCritique ? toCriticEvidence(toolCallLog.slice(lastCritique.toolLogLength), 20) : [];
593764
+ const criticToolEvidence = toCriticEvidence(activeEpochToolLog, 40);
593446
593765
  const completionContract = this._completionContractForClaims(proposedSummary);
593447
593766
  const openLoops = [
593448
593767
  ...todos.filter((todo) => todo.status !== "completed" && todo.status !== "blocked").slice(0, 12).map((todo) => `todo still ${todo.status}: ${todo.content}`),
@@ -593451,7 +593770,7 @@ ${_checks}`
593451
593770
  const modifiedFileDigest = (() => {
593452
593771
  const seen = /* @__PURE__ */ new Set();
593453
593772
  const files = [];
593454
- for (const entry of toolCallLog) {
593773
+ for (const entry of activeEpochToolLog) {
593455
593774
  if (!Array.isArray(entry.mutatedFiles))
593456
593775
  continue;
593457
593776
  for (const filePath of entry.mutatedFiles) {
@@ -593492,20 +593811,13 @@ ${_checks}`
593492
593811
  ].join("\n\n");
593493
593812
  }
593494
593813
  }
593495
- const reviewReconciliation = lastCritique ? {
593496
- previousVerdict: lastCritique.verdict,
593497
- previousRationale: lastCritique.rationale,
593498
- previousFeedback: lastCritique.feedback,
593499
- previousCompletionSummary: lastCritique.completionSummary,
593500
- previousCycle: lastCritique.cycle,
593501
- recordedAtIso: lastCritique.recordedAtIso,
593502
- evidenceSincePreviousReview: evidenceSincePriorCritique
593503
- } : void 0;
593814
+ const reviewReconciliation = void 0;
593815
+ const activeWorkboard = this._currentWorkboardSnapshotForFrame();
593504
593816
  let result;
593505
593817
  try {
593506
593818
  result = await runBackwardPass({
593507
593819
  workingDir: wd,
593508
- goal: this._taskState.originalGoal || this._taskState.goal || "",
593820
+ goal: this._taskState.goal || this._taskState.originalGoal || "",
593509
593821
  planStatus: reconciled.map((t2) => ({
593510
593822
  id: t2.id,
593511
593823
  content: t2.content,
@@ -593518,9 +593830,9 @@ ${_checks}`
593518
593830
  completionScenarioDecomposition: _ledgerScenarioDecomposition,
593519
593831
  reviewReconciliation,
593520
593832
  openLoops,
593521
- workboardSynthesisContext: this._workboard ? (() => {
593833
+ workboardSynthesisContext: activeWorkboard ? (() => {
593522
593834
  try {
593523
- return buildWorkboardSynthesisContext(this._workboard).excludedUnverifiedCardIds.length > 0 ? `Verified: ${this._workboard.cards.filter((c9) => c9.status === "verified").length}, Unverified remaining: ${this._workboard.cards.filter((c9) => c9.status !== "verified").length}, Blockers: ${this._workboard.cards.filter((c9) => c9.status === "blocked" || c9.status === "needs_changes").length}` : void 0;
593835
+ return buildWorkboardSynthesisContext(activeWorkboard).excludedUnverifiedCardIds.length > 0 ? `Verified: ${activeWorkboard.cards.filter((c9) => c9.status === "verified").length}, Unverified remaining: ${activeWorkboard.cards.filter((c9) => c9.status !== "verified").length}, Blockers: ${activeWorkboard.cards.filter((c9) => c9.status === "blocked" || c9.status === "needs_changes").length}` : void 0;
593524
593836
  } catch {
593525
593837
  return void 0;
593526
593838
  }
@@ -593529,35 +593841,23 @@ ${_checks}`
593529
593841
  maxFiles: parseInt(process.env["OMNIUS_BACKWARD_PASS_MAX_FILES"] || "60", 10) || 60,
593530
593842
  maxFilePreviewBytes: parseInt(process.env["OMNIUS_BACKWARD_PASS_MAX_FILE_PREVIEW"] || "8000", 10) || 8e3,
593531
593843
  explicitFiles: modifiedFileDigest.length > 0 ? modifiedFileDigest.map((file) => file.path) : void 0,
593844
+ explicitFilesOnly: true,
593532
593845
  cycle: this._backwardPassCyclesUsed,
593533
593846
  maxCycles
593534
593847
  });
593535
593848
  } catch (e2) {
593536
593849
  const reason = `backward-pass runner failed: ${e2 instanceof Error ? e2.message : String(e2)}`;
593537
- this._completionIncompleteVerification = {
593538
- reason,
593539
- summary: [
593540
- "INCOMPLETE_VERIFICATION: backward-pass review could not verify completion.",
593541
- "",
593542
- `Attempted summary: ${proposedSummary || "(no summary)"}`,
593543
- "",
593544
- "Not verified / blocked:",
593545
- reason,
593546
- "",
593547
- "Evidence:",
593548
- completionScenarioDecomposition
593549
- ].join("\n")
593550
- };
593551
- this._focusSupervisor?.markTerminalIncomplete(reason, turn);
593850
+ this._completionCaveat = [
593851
+ this._completionCaveat || "",
593852
+ `[BACKWARD-PASS ADVISORY] ${reason}`,
593853
+ "Completion authority remains with deterministic verifier and current completion-ledger evidence."
593854
+ ].filter(Boolean).join("\n");
593552
593855
  this.emit({
593553
593856
  type: "status",
593554
- content: `REG-47 backward-pass runner threw: ${e2 instanceof Error ? e2.message : String(e2)}. Ending as incomplete_verification instead of completing.`,
593857
+ content: `Backward-pass review unavailable; preserved as advisory telemetry: ${reason}`,
593555
593858
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
593556
593859
  });
593557
- return {
593558
- proceed: false,
593559
- feedback: "Backward-pass review failed before completion could be verified. Report incomplete_verification rather than claiming success."
593560
- };
593860
+ return { proceed: true, feedback: this._completionCaveat };
593561
593861
  }
593562
593862
  this._backwardPassCyclesUsed++;
593563
593863
  this._lastBackwardPassVerdict = result.verdict.verdict;
@@ -593579,7 +593879,15 @@ ${_checks}`
593579
593879
  return { proceed: true };
593580
593880
  }
593581
593881
  const feedback = result.feedbackMessage;
593582
- if (this._completionLedger) {
593882
+ const currentArtifactPaths = modifiedFileDigest.map((file) => file.path.replace(/\\/g, "/").replace(/^\.\//, "").toLowerCase());
593883
+ const criticReferencesCurrentArtifact = result.verdict.issues.some((issue) => {
593884
+ const issueText = [issue.file, issue.problem, issue.suggested_fix].filter((value2) => typeof value2 === "string").join(" ").replace(/\\/g, "/").toLowerCase();
593885
+ return currentArtifactPaths.some((path16) => {
593886
+ const basename46 = path16.slice(path16.lastIndexOf("/") + 1);
593887
+ return issueText.includes(path16) || basename46.length > 0 && issueText.includes(basename46);
593888
+ });
593889
+ });
593890
+ if (this._completionLedger && criticReferencesCurrentArtifact) {
593583
593891
  this._completionLedger = recordCompletionCritique(this._completionLedger, {
593584
593892
  verdict: result.verdict.verdict === "blocked" ? "blocked" : "request_changes",
593585
593893
  rationale: result.verdict.rationale,
@@ -593587,16 +593895,18 @@ ${_checks}`
593587
593895
  });
593588
593896
  this._saveCompletionLedgerSafe();
593589
593897
  }
593590
- this._lastBackwardPassCritique = {
593591
- verdict: result.verdict.verdict,
593592
- rationale: result.verdict.rationale,
593593
- feedback,
593594
- completionSummary: proposedSummary,
593595
- cycle: this._backwardPassCyclesUsed,
593596
- toolLogLength: toolCallLog.length,
593597
- recordedAtIso: (/* @__PURE__ */ new Date()).toISOString()
593598
- };
593599
- if (result.verdict.verdict === "blocked") {
593898
+ if (criticReferencesCurrentArtifact) {
593899
+ this._lastBackwardPassCritique = {
593900
+ verdict: result.verdict.verdict,
593901
+ rationale: result.verdict.rationale,
593902
+ feedback,
593903
+ completionSummary: proposedSummary,
593904
+ cycle: this._backwardPassCyclesUsed,
593905
+ toolLogLength: toolCallLog.length,
593906
+ recordedAtIso: (/* @__PURE__ */ new Date()).toISOString()
593907
+ };
593908
+ }
593909
+ if (result.verdict.verdict === "blocked" && criticReferencesCurrentArtifact) {
593600
593910
  const reason = `backward-pass critic blocked completion: ${result.verdict.rationale.slice(0, 240)}`;
593601
593911
  this._completionIncompleteVerification = {
593602
593912
  reason,
@@ -593619,6 +593929,19 @@ ${_checks}`
593619
593929
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
593620
593930
  });
593621
593931
  }
593932
+ if (!criticReferencesCurrentArtifact) {
593933
+ this._completionCaveat = [
593934
+ this._completionCaveat || "",
593935
+ `[BACKWARD-PASS ADVISORY] ${result.verdict.verdict}: ${result.verdict.rationale.slice(0, 600)}`,
593936
+ "The critic named no current-epoch artifact; current verifier and completion-ledger evidence remain authoritative."
593937
+ ].filter(Boolean).join("\n");
593938
+ this.emit({
593939
+ type: "status",
593940
+ content: `Backward-pass ${result.verdict.verdict} retained as advisory: no current artifact was referenced.`,
593941
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
593942
+ });
593943
+ return { proceed: true, feedback: this._completionCaveat };
593944
+ }
593622
593945
  return { proceed: false, feedback };
593623
593946
  }
593624
593947
  /**
@@ -596198,6 +596521,20 @@ ${blob}
596198
596521
  if (covered)
596199
596522
  return cov.fingerprint;
596200
596523
  }
596524
+ if (!iv.whole && Number.isFinite(iv.end)) {
596525
+ let best = null;
596526
+ const requestedLength = Math.max(1, iv.end - iv.start + 1);
596527
+ for (const cov of intervals) {
596528
+ if (cov.whole || !Number.isFinite(cov.end))
596529
+ continue;
596530
+ const overlap = Math.max(0, Math.min(iv.end, cov.end) - Math.max(iv.start, cov.start) + 1);
596531
+ if (overlap / requestedLength >= 0.8 && (!best || overlap > best.overlap)) {
596532
+ best = { fingerprint: cov.fingerprint, overlap };
596533
+ }
596534
+ }
596535
+ if (best)
596536
+ return best.fingerprint;
596537
+ }
596201
596538
  return exactFingerprint;
596202
596539
  }
596203
596540
  /** Register a read's region under the fingerprint that cached its result. */
@@ -596940,6 +597277,26 @@ ${notice}`;
596940
597277
  this._trajectoryDirtyCauses.add("user_steering");
596941
597278
  return this._steeringReceipt(record);
596942
597279
  }
597280
+ /**
597281
+ * Request safe-boundary preemption for an already accepted typed input.
597282
+ * Frontends use this after delivery so cancellation reaches an in-flight
597283
+ * request without fabricating a second, disconnected runner.
597284
+ */
597285
+ requestSteeringPreemption(inputId) {
597286
+ const normalizedInputId = inputId.trim();
597287
+ if (!normalizedInputId)
597288
+ return null;
597289
+ const record = this.pendingSteeringInputs.find((candidate) => candidate.inputId === normalizedInputId);
597290
+ if (!record)
597291
+ return null;
597292
+ if (record.intent !== "redirect" && record.intent !== "replace" && record.intent !== "cancel") {
597293
+ return null;
597294
+ }
597295
+ if (this._pendingSteeringPreemption?.inputId !== record.inputId) {
597296
+ this._requestSteeringPreemption(record);
597297
+ }
597298
+ return this._steeringReceipt(record);
597299
+ }
596943
597300
  /** Inject bounded runtime guidance without treating it as user steering. */
596944
597301
  injectRuntimeGuidance(content) {
596945
597302
  this.enqueueRuntimeGuidance(content);
@@ -597194,6 +597551,8 @@ ${notice}`;
597194
597551
  this._archiveSupersededTaskState(previousEpoch, record);
597195
597552
  this._allowImplicitContinuation = false;
597196
597553
  this._taskEpoch += 1;
597554
+ this._taskEpochStartTurn = turn;
597555
+ this._focusSupervisor?.setTaskEpoch(this._taskEpoch, turn);
597197
597556
  record.taskEpoch = this._taskEpoch;
597198
597557
  if (record.intent === "replace") {
597199
597558
  for (const candidate of this.pendingSteeringInputs) {
@@ -598373,8 +598732,10 @@ Respond with the assessment and take the selected evidence-backed action.`;
598373
598732
  convergenceBreaker: this._longHaul?.convergenceBreaker ?? null,
598374
598733
  // WO-9: run cwd so shell family keys canonicalize absolute↔relative
598375
598734
  // path form and command variants collapse into one family.
598376
- cwd: this.authoritativeWorkingDirectory()
598735
+ cwd: this.authoritativeWorkingDirectory(),
598736
+ taskEpoch: this._taskEpoch
598377
598737
  });
598738
+ this._focusSupervisor?.setTaskEpoch(this._taskEpoch);
598378
598739
  if (!this._workingDirectory) {
598379
598740
  this._workingDirectory = _pathResolve(process.cwd());
598380
598741
  }
@@ -599044,6 +599405,7 @@ ${dynamicProjectContext}`
599044
599405
  let lastShellPivotTurn = -1;
599045
599406
  const recentToolResults = /* @__PURE__ */ new Map();
599046
599407
  const exactFileReadObservations = /* @__PURE__ */ new Map();
599408
+ const exactReadEvidenceEpochs = /* @__PURE__ */ new Map();
599047
599409
  let fileMutationEpoch = 0;
599048
599410
  const dedupHitCount = /* @__PURE__ */ new Map();
599049
599411
  const noopedMemoryWriteFingerprints = /* @__PURE__ */ new Set();
@@ -601168,7 +601530,6 @@ ${memoryLines.join("\n")}`
601168
601530
  "After seeing the tool result, continue or call another tool.",
601169
601531
  'When done, output: {"tool": "task_complete", "args": {"summary": "what you did"}}'
601170
601532
  ].join("\n");
601171
- messages2.push({ role: "system", content: toolInjectMsg });
601172
601533
  chatRequest.messages = this._prepareModelFacingMessages([
601173
601534
  ...requestMessages,
601174
601535
  { role: "system", content: toolInjectMsg }
@@ -602111,7 +602472,49 @@ Read the current file if needed, make a different concrete edit, or move to veri
602111
602472
  adversaryRedundantSignal
602112
602473
  });
602113
602474
  let repeatShortCircuit = null;
602114
- if (criticDecision.decision === "guidance") {
602475
+ const exactReadArgs = tc.arguments;
602476
+ const exactReadPath = String(exactReadArgs?.["path"] ?? exactReadArgs?.["file"] ?? "");
602477
+ const exactReadEvidence = exactReadEvidenceEpochs.get(toolFingerprint);
602478
+ const exactReadEvidenceFresh = tc.name === "file_read" && exactReadPath.length > 0 && this._evidenceLedger.validateFreshness(this._normalizeEvidencePath(exactReadPath), this._absoluteToolPath(exactReadPath));
602479
+ const exactReadEvidenceEntry = tc.name === "file_read" && exactReadPath ? this._evidenceLedger.get(this._normalizeEvidencePath(exactReadPath)) : void 0;
602480
+ const exactReadHasCuratedPayload = exactReadEvidenceEntry?.fidelity === "extract";
602481
+ if (tc.name === "file_read" && exactReadEvidenceFresh && exactReadHasCuratedPayload && exactReadEvidence?.taskEpoch === this._taskEpoch && exactReadEvidence.mutationEpoch === fileMutationEpoch) {
602482
+ const path16 = this._normalizeEvidencePath(exactReadPath);
602483
+ const evidence = this._evidenceLedger.get(path16);
602484
+ const curated = this._branchEvidenceByPath.get(path16) ?? [...this._branchEvidenceByPath.entries()].find(([candidate]) => this._normalizeEvidencePath(candidate) === path16)?.[1];
602485
+ const curatedPayload = curated?.output ?? (evidence?.fidelity === "extract" && evidence.content.includes("[BRANCH-EXTRACT") ? evidence.content : null);
602486
+ repeatShortCircuit = {
602487
+ success: true,
602488
+ output: curatedPayload ? this._rehydrateResolvedReadEvidence({
602489
+ fingerprint: toolFingerprint,
602490
+ canonicalPath: path16,
602491
+ contentHash: curated?.contentHash ?? evidence?.contentHash ?? "unknown",
602492
+ payload: curatedPayload,
602493
+ turn
602494
+ }) : [
602495
+ ...evidence?.fidelity === "extract" ? [
602496
+ "[REHYDRATED_FILE_EVIDENCE]",
602497
+ "source=active_context_frame fidelity=extract"
602498
+ ] : [],
602499
+ "[READ EVIDENCE REFERENCE]",
602500
+ `path=${path16 || "unknown"}`,
602501
+ `task_epoch=${this._taskEpoch}`,
602502
+ `freshness=${evidence?.stale ? "stale" : "fresh"}`,
602503
+ evidence?.contentHash ? `sha256=${evidence.contentHash}` : null,
602504
+ "Exact unchanged range was not re-executed. Use the existing evidence handle or request a newly uncovered range after identifying the missing fact."
602505
+ ].filter(Boolean).join("\n"),
602506
+ runtimeAuthored: true,
602507
+ noop: true
602508
+ };
602509
+ this.emit({
602510
+ type: "status",
602511
+ toolName: tc.name,
602512
+ content: `Exact unchanged file_read blocked before dispatch: ${path16}`,
602513
+ turn,
602514
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
602515
+ });
602516
+ }
602517
+ if (criticDecision.decision === "guidance" && !repeatShortCircuit) {
602115
602518
  dedupHitCount.set(toolFingerprint, criticDecision.hitNumber);
602116
602519
  const _existingFp = recentToolResults.get(toolFingerprint);
602117
602520
  if (_existingFp !== void 0) {
@@ -602156,12 +602559,14 @@ Read the current file if needed, make a different concrete edit, or move to veri
602156
602559
  const suppressSuccessfulShellCacheGuidance = tc.name === "shell" && !isFailedShellRepeat;
602157
602560
  if (suppressSuccessfulShellCacheGuidance)
602158
602561
  criticGuidance = null;
602562
+ let exactReadEvidenceFresh2 = true;
602159
602563
  if (isReadLike && this._evidenceLedger) {
602160
602564
  const readArgs = tc.arguments;
602161
602565
  const readPath2 = String(readArgs?.["path"] ?? readArgs?.["file"] ?? "");
602162
602566
  if (readPath2) {
602163
602567
  const evidencePath = this._normalizeEvidencePath(readPath2);
602164
602568
  const wasFresh = evidencePath && this._evidenceLedger.validateFreshness(evidencePath, this._absoluteToolPath(readPath2));
602569
+ exactReadEvidenceFresh2 = Boolean(wasFresh);
602165
602570
  if (!wasFresh) {
602166
602571
  recentToolResults.delete(toolFingerprint);
602167
602572
  dedupHitCount.delete(toolFingerprint);
@@ -602175,7 +602580,41 @@ Read the current file if needed, make a different concrete edit, or move to veri
602175
602580
  }
602176
602581
  }
602177
602582
  }
602178
- if (repeatGateEligible && _existingFp !== void 0 && _repeatGateMax > 0) {
602583
+ const exactReadEvidence2 = exactReadEvidenceEpochs.get(toolFingerprint);
602584
+ const exactFileReadReference = tc.name === "file_read" && exactReadEvidenceFresh2 && exactReadHasCuratedPayload && exactReadEvidence2?.taskEpoch === this._taskEpoch && exactReadEvidence2.mutationEpoch === fileMutationEpoch;
602585
+ if (exactFileReadReference) {
602586
+ const path16 = this._normalizeEvidencePath(String(tc.arguments?.["path"] ?? tc.arguments?.["file"] ?? ""));
602587
+ const evidence = this._evidenceLedger?.get(path16);
602588
+ const curated = this._branchEvidenceByPath.get(path16) ?? [...this._branchEvidenceByPath.entries()].find(([candidate]) => this._normalizeEvidencePath(candidate) === path16)?.[1];
602589
+ const curatedPayload = curated?.output ?? (evidence?.fidelity === "extract" && evidence.content.includes("[BRANCH-EXTRACT") ? evidence.content : null);
602590
+ repeatShortCircuit = {
602591
+ success: true,
602592
+ // Curated branch output is the bounded authoritative payload
602593
+ // for this source version. Rehydrate it instead of replacing
602594
+ // it with a pointer; exact/overlap suppression must not force
602595
+ // the model to reread a large source merely to recover facts.
602596
+ output: curatedPayload ? this._rehydrateResolvedReadEvidence({
602597
+ fingerprint: toolFingerprint,
602598
+ canonicalPath: path16,
602599
+ contentHash: curated?.contentHash ?? evidence?.contentHash ?? "unknown",
602600
+ payload: curatedPayload,
602601
+ turn
602602
+ }) : [
602603
+ ...evidence?.fidelity === "extract" ? [
602604
+ "[REHYDRATED_FILE_EVIDENCE]",
602605
+ "source=active_context_frame fidelity=extract"
602606
+ ] : [],
602607
+ "[READ EVIDENCE REFERENCE]",
602608
+ `path=${path16 || "unknown"}`,
602609
+ `task_epoch=${this._taskEpoch}`,
602610
+ `freshness=${evidence?.stale ? "stale" : "fresh"}`,
602611
+ evidence?.contentHash ? `sha256=${evidence.contentHash}` : null,
602612
+ "Exact unchanged range was not re-executed. Use the existing evidence handle or request a newly uncovered range after identifying the missing fact."
602613
+ ].filter(Boolean).join("\n"),
602614
+ runtimeAuthored: true,
602615
+ noop: true
602616
+ };
602617
+ } else if (repeatGateEligible && _existingFp !== void 0 && _repeatGateMax > 0) {
602179
602618
  const _rehydrateArgs = tc.arguments;
602180
602619
  const _rehydratePath = String(_rehydrateArgs?.["path"] ?? _rehydrateArgs?.["file"] ?? "");
602181
602620
  const _visibleViaEvidenceFrame = _rehydratePath.length > 0 && (this._evidenceLedger?.renderedFullInLastBlock(this._normalizeEvidencePath(_rehydratePath)) ?? false);
@@ -602256,7 +602695,8 @@ ${cachedResult}`,
602256
602695
  cachedResultFailed: tc.name === "shell" && typeof focusCachedEntry?.result === "string" && focusCachedEntry.result.includes("status: failure"),
602257
602696
  duplicateHitCount: focusDuplicateHits,
602258
602697
  context: this._buildFocusContextSnapshot(),
602259
- usesAuthoritativeTargetEvidence
602698
+ usesAuthoritativeTargetEvidence,
602699
+ taskEpoch: this._taskEpoch
602260
602700
  });
602261
602701
  if (focusDecision && focusDecision.kind !== "pass") {
602262
602702
  this._emitFocusSupervisorEvent({
@@ -602817,6 +603257,10 @@ ${cachedResult}`,
602817
603257
  turn,
602818
603258
  fidelity: result.runtimeAuthored === true && result.output.startsWith("[BRANCH-EXTRACT") ? "extract" : void 0
602819
603259
  });
603260
+ exactReadEvidenceEpochs.set(toolFingerprint, {
603261
+ taskEpoch: this._taskEpoch,
603262
+ mutationEpoch: fileMutationEpoch
603263
+ });
602820
603264
  }
602821
603265
  if (this._fileSummaryStore && result.success && result.output && result.output.length > 100) {
602822
603266
  try {
@@ -603822,6 +604266,7 @@ Evidence: ${evidencePreview}`.slice(0, 500);
603822
604266
  this._taskState.toolCallCount++;
603823
604267
  if (realFileMutation) {
603824
604268
  this._lastFileWriteTurn = turn;
604269
+ this._fileWritesThisRun += Math.max(1, realMutationPaths.length);
603825
604270
  const writeEvents = Math.max(1, realMutationPaths.length);
603826
604271
  for (let i2 = 0; i2 < writeEvents; i2++) {
603827
604272
  this._fileWriteTimestamps.push(Date.now());
@@ -603951,7 +604396,8 @@ Evidence: ${evidencePreview}`.slice(0, 500);
603951
604396
  noop: tc.name === "todo_write" ? this._isTodoWriteNoopResult(result) : result.noop,
603952
604397
  alreadyApplied: result.alreadyApplied === true,
603953
604398
  runtimeAuthored: result.runtimeAuthored === true,
603954
- usedAuthoritativeTargetEvidence: usesAuthoritativeTargetEvidence
604399
+ usedAuthoritativeTargetEvidence: usesAuthoritativeTargetEvidence,
604400
+ taskEpoch: this._taskEpoch
603955
604401
  });
603956
604402
  const focusSnapshotAfter = this._focusSupervisor?.snapshot();
603957
604403
  focusAfterToolResult = focusSnapshotAfter ?? void 0;
@@ -606633,9 +607079,8 @@ ${marker}` : marker);
606633
607079
  "oldText",
606634
607080
  "search",
606635
607081
  "expected_old_string",
606636
- "expectedHash",
606637
- "expected_hash",
606638
- "start_line"
607082
+ "start_line",
607083
+ "end_line"
606639
607084
  ];
606640
607085
  for (const key of directKeys) {
606641
607086
  const value2 = args[key];
@@ -607135,13 +607580,13 @@ ${marker}` : marker);
607135
607580
  "Next action: file_read the target file or range, then retry the edit with old_string copied exactly from that read and expected_hash set to the read's sha256."
607136
607581
  ].join("\n");
607137
607582
  }
607138
- staleEditFamilyKey(toolName, pathKey, errorKind, targetHash, latestFileHash) {
607583
+ staleEditFamilyKey(toolName, pathKey, errorKind, targetHash) {
607139
607584
  return [
607585
+ `epoch=${this._taskEpoch}`,
607140
607586
  toolName,
607141
607587
  pathKey || "(unknown)",
607142
607588
  errorKind,
607143
- targetHash,
607144
- latestFileHash || "unknown-file-hash"
607589
+ targetHash
607145
607590
  ].join(":");
607146
607591
  }
607147
607592
  staleEditPreflightBlock(toolName, args) {
@@ -607157,11 +607602,8 @@ ${marker}` : marker);
607157
607602
  if (entry.count >= 2 && !hasFreshRead && !hasFreshMutation) {
607158
607603
  return [
607159
607604
  "[STALE EDIT LOOP BLOCKED] " + toolName + " has already failed " + entry.count + " times for " + entry.path + " (" + entry.errorKind + ").",
607160
- "Do not retry the same stale edit target again. First file_read the current file content once, then either:",
607161
- "1. confirm the desired change is already present and run verification,",
607162
- "2. build a new edit from the exact current text, or",
607163
- "3. choose a different target if this edit is no longer relevant.",
607164
- "Previous stale target preview: " + entry.preview
607605
+ "Blocked until a fresh file read, a real mutation, or a changed semantic edit target is observed.",
607606
+ "Previous target: " + entry.preview
607165
607607
  ].join("\n");
607166
607608
  }
607167
607609
  }
@@ -607354,7 +607796,7 @@ ${marker}` : marker);
607354
607796
  if (!errorKind)
607355
607797
  return;
607356
607798
  const latestFileHash = typeof result.beforeHash === "string" && result.beforeHash.trim() ? result.beforeHash.trim() : typeof result.afterHash === "string" && result.afterHash.trim() ? result.afterHash.trim() : "unknown-file-hash";
607357
- const key = this.staleEditFamilyKey(toolName, targetPathKey, errorKind, target.targetHash, latestFileHash);
607799
+ const key = this.staleEditFamilyKey(toolName, targetPathKey, errorKind, target.targetHash);
607358
607800
  const existing = this._staleEditFamilies.get(key);
607359
607801
  this._staleEditFamilies.set(key, {
607360
607802
  count: (existing?.count ?? 0) + 1,
@@ -608182,6 +608624,11 @@ ${tail}`;
608182
608624
  });
608183
608625
  if (signal)
608184
608626
  this._contextLedger.upsert(signal);
608627
+ messages2.push({
608628
+ role: "user",
608629
+ content: userMsg,
608630
+ taskEpoch: this._taskEpoch
608631
+ });
608185
608632
  }
608186
608633
  this.emit({
608187
608634
  type: "user_interrupt",
@@ -609332,16 +609779,24 @@ ${trimmedNew}`;
609332
609779
  const created = this._extractToolTargetPaths(toolName, args, result).map((path16) => this._normalizeEvidencePath(path16)).filter((path16) => path16 && !path16.startsWith(".omnius/") && /creat/i.test(this._taskState.modifiedFiles.get(path16) ?? ""));
609333
609780
  if (created.length === 0)
609334
609781
  return;
609335
- const board = this._workboard ?? this.getOrCreateWorkboard();
609782
+ const board = this._currentWorkboardSnapshotForFrame() ?? this.getOrCreateWorkboard();
609336
609783
  if (board) {
609337
609784
  const card = this._workboardTodoCardForPaths(board, created);
609338
609785
  if (card && (card.status === "open" || card.status === "in_progress" || card.status === "needs_changes")) {
609339
609786
  try {
609787
+ const runId = this._workboardRunId();
609340
609788
  const completed = completeWorkboardCard(this._workboardDir(), {
609341
- runId: this.currentArtifactRunId(),
609789
+ runId,
609342
609790
  cardId: card.id,
609343
609791
  actor: this.options.subAgent ? "sub-agent" : "agent",
609344
609792
  outcome: "completed",
609793
+ evidence: {
609794
+ kind: "tool_result",
609795
+ summary: `creation ground truth: ${created.join(", ")}`,
609796
+ tool: toolName,
609797
+ ref: created[0],
609798
+ content: String(result.output ?? result.error ?? "").slice(0, 1e3)
609799
+ },
609345
609800
  reason: `Creation ground truth satisfied mapped target(s): ${created.join(", ")} at turn ${turn}.`
609346
609801
  });
609347
609802
  this._workboard = completed.snapshot;
@@ -610786,6 +611241,7 @@ ${catalog}`,
610786
611241
  parameters: {},
610787
611242
  execute: async (args) => {
610788
611243
  const query = String(args["query"] ?? "").toLowerCase().trim();
611244
+ const queryTerms2 = query.split(/[^a-z0-9_]+/).filter((term) => term.length >= 3);
610789
611245
  const subsetMatch = subsetCatalog[query];
610790
611246
  if (subsetMatch && subsetMatch.length > 0) {
610791
611247
  const newlyPromoted = [];
@@ -610828,7 +611284,15 @@ ${catalog}`,
610828
611284
  }
610829
611285
  return { success: true, output: lines.join("\n") };
610830
611286
  }
610831
- const matches = deferred.filter((t2) => t2.name.toLowerCase().includes(query) || (t2.aliases ?? []).some((alias) => alias.toLowerCase().includes(query)) || getDesc(t2).toLowerCase().includes(query) || customToolSearchText(t2).toLowerCase().includes(query)).sort((a2, b) => {
611287
+ const matches = deferred.filter((t2) => t2.name.toLowerCase().includes(query) || (t2.aliases ?? []).some((alias) => alias.toLowerCase().includes(query)) || getDesc(t2).toLowerCase().includes(query) || customToolSearchText(t2).toLowerCase().includes(query) || queryTerms2.some((term) => {
611288
+ const searchable = [
611289
+ t2.name,
611290
+ ...t2.aliases ?? [],
611291
+ getDesc(t2),
611292
+ customToolSearchText(t2)
611293
+ ].join(" ").toLowerCase();
611294
+ return searchable.includes(term);
611295
+ })).sort((a2, b) => {
610832
611296
  const scoreTool = (tool) => {
610833
611297
  const meta = getCustomToolMetadata(tool);
610834
611298
  let score = 0;
@@ -610836,6 +611300,16 @@ ${catalog}`,
610836
611300
  score += 30;
610837
611301
  if (tool.name.toLowerCase().includes(query))
610838
611302
  score += 10;
611303
+ for (const term of queryTerms2) {
611304
+ if (tool.name.toLowerCase() === term)
611305
+ score += 30;
611306
+ else if (tool.name.toLowerCase().includes(term))
611307
+ score += 10;
611308
+ if (getDesc(tool).toLowerCase().includes(term))
611309
+ score += 4;
611310
+ if (customToolSearchText(tool).toLowerCase().includes(term))
611311
+ score += 6;
611312
+ }
610839
611313
  if ((tool.aliases ?? []).some((alias) => alias.toLowerCase() === query))
610840
611314
  score += 24;
610841
611315
  if ((tool.aliases ?? []).some((alias) => alias.toLowerCase().includes(query)))
@@ -633849,7 +634323,7 @@ async function fetchOpenAIModels(baseUrl2, apiKey) {
633849
634323
  sizeBytes: 0,
633850
634324
  modified: m2.created ? formatRelativeTime(new Date(m2.created * 1e3).toISOString()) : "",
633851
634325
  parameterSize: m2.owned_by ?? void 0,
633852
- contextLength: m2.context_length ?? m2.max_model_len ?? void 0
634326
+ contextLength: positiveInteger(m2.context_length) ?? positiveInteger(m2.max_model_len) ?? positiveInteger(m2.meta?.["n_ctx"]) ?? positiveInteger(m2.meta?.["context_length"]) ?? void 0
633853
634327
  })).sort((a2, b) => a2.name.localeCompare(b.name));
633854
634328
  }
633855
634329
  async function fetchPeerModels(peerId, authKey) {
@@ -634149,14 +634623,14 @@ function firstPositive(record, keys) {
634149
634623
  return void 0;
634150
634624
  }
634151
634625
  function contextCapacityFromRecord(record) {
634152
- return firstPositive(record, [
634153
- "n_ctx",
634154
- "n_ctx_train",
634155
- "context_length",
634156
- "context_window",
634157
- "max_model_len",
634158
- "max_context_length"
634159
- ]);
634626
+ const direct = firstPositive(record, CONTEXT_CAPACITY_KEYS);
634627
+ if (direct !== void 0) return direct;
634628
+ const meta = asRecord(record["meta"]);
634629
+ const metaCapacity = meta ? firstPositive(meta, CONTEXT_CAPACITY_KEYS) : void 0;
634630
+ if (metaCapacity !== void 0) return metaCapacity;
634631
+ const defaults3 = asRecord(record["default_generation_settings"]);
634632
+ const params = defaults3 && asRecord(defaults3["params"]);
634633
+ return params ? firstPositive(params, CONTEXT_CAPACITY_KEYS) : void 0;
634160
634634
  }
634161
634635
  function telemetryHeaders(apiKey) {
634162
634636
  return apiKey ? { Authorization: `Bearer ${apiKey}` } : void 0;
@@ -634366,7 +634840,7 @@ function formatRelativeTime(iso2) {
634366
634840
  const months = Math.floor(days / 30);
634367
634841
  return `${months}mo ago`;
634368
634842
  }
634369
- var IMAGE_GEN_PATTERNS, LLAMA_CPP_TELEMETRY_TIMEOUT_MS;
634843
+ var IMAGE_GEN_PATTERNS, LLAMA_CPP_TELEMETRY_TIMEOUT_MS, CONTEXT_CAPACITY_KEYS;
634370
634844
  var init_model_picker = __esm({
634371
634845
  "packages/cli/src/tui/model-picker.ts"() {
634372
634846
  init_dist6();
@@ -634381,6 +634855,14 @@ var init_model_picker = __esm({
634381
634855
  /imagen/i
634382
634856
  ];
634383
634857
  LLAMA_CPP_TELEMETRY_TIMEOUT_MS = 2500;
634858
+ CONTEXT_CAPACITY_KEYS = [
634859
+ "n_ctx",
634860
+ "n_ctx_train",
634861
+ "context_length",
634862
+ "context_window",
634863
+ "max_model_len",
634864
+ "max_context_length"
634865
+ ];
634384
634866
  }
634385
634867
  });
634386
634868
 
@@ -663382,6 +663864,7 @@ var init_runtime_keys = __esm({
663382
663864
  // packages/cli/src/daemon.ts
663383
663865
  var daemon_exports = {};
663384
663866
  __export(daemon_exports, {
663867
+ claimDaemonEndpoint: () => claimDaemonEndpoint,
663385
663868
  ensureDaemon: () => ensureDaemon,
663386
663869
  forceKillDaemon: () => forceKillDaemon,
663387
663870
  getDaemonPid: () => getDaemonPid,
@@ -663389,12 +663872,14 @@ __export(daemon_exports, {
663389
663872
  getDaemonStatus: () => getDaemonStatus,
663390
663873
  getLocalCliVersion: () => getLocalCliVersion,
663391
663874
  isDaemonRunning: () => isDaemonRunning,
663875
+ releaseDaemonEndpointClaim: () => releaseDaemonEndpointClaim,
663876
+ releaseDaemonEndpointForCurrentProcess: () => releaseDaemonEndpointForCurrentProcess,
663392
663877
  restartDaemon: () => restartDaemon,
663393
663878
  startDaemon: () => startDaemon,
663394
663879
  stopDaemon: () => stopDaemon
663395
663880
  });
663396
663881
  import { spawn as spawn35 } from "node:child_process";
663397
- import { existsSync as existsSync140, readFileSync as readFileSync114, writeFileSync as writeFileSync70, mkdirSync as mkdirSync82, unlinkSync as unlinkSync27, openSync as openSync4, closeSync as closeSync4 } from "node:fs";
663882
+ import { existsSync as existsSync140, readFileSync as readFileSync114, writeFileSync as writeFileSync70, mkdirSync as mkdirSync82, unlinkSync as unlinkSync27, openSync as openSync4, closeSync as closeSync4, writeSync as writeSync2, statSync as statSync57 } from "node:fs";
663398
663883
  import { join as join149 } from "node:path";
663399
663884
  import { homedir as homedir51 } from "node:os";
663400
663885
  import { fileURLToPath as fileURLToPath20 } from "node:url";
@@ -663408,6 +663893,106 @@ function getDaemonPort() {
663408
663893
  }
663409
663894
  return parseInt(process.env["OMNIUS_PORT"] ?? String(DEFAULT_PORT2), 10);
663410
663895
  }
663896
+ function daemonEndpoint(port) {
663897
+ return `127.0.0.1:${port}`;
663898
+ }
663899
+ function daemonLockFile(port) {
663900
+ return join149(OMNIUS_DIR2, `daemon-${port}.lock`);
663901
+ }
663902
+ function processIsAlive(pid) {
663903
+ try {
663904
+ process.kill(pid, 0);
663905
+ return true;
663906
+ } catch (error) {
663907
+ return error.code !== "ESRCH";
663908
+ }
663909
+ }
663910
+ function readDaemonLock(lockFile) {
663911
+ try {
663912
+ const value2 = JSON.parse(readFileSync114(lockFile, "utf8"));
663913
+ if (typeof value2.endpoint !== "string" || typeof value2.pid !== "number" || !Number.isInteger(value2.pid) || value2.pid <= 0 || typeof value2.token !== "string" || typeof value2.startedAt !== "number") {
663914
+ return null;
663915
+ }
663916
+ return value2;
663917
+ } catch {
663918
+ return null;
663919
+ }
663920
+ }
663921
+ function daemonLockIsInitializing(lockFile) {
663922
+ try {
663923
+ return Date.now() - statSync57(lockFile).mtimeMs < LOCK_INITIALIZATION_GRACE_MS;
663924
+ } catch {
663925
+ return false;
663926
+ }
663927
+ }
663928
+ function newDaemonLockToken() {
663929
+ return `${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
663930
+ }
663931
+ function claimDaemonEndpoint(port = getDaemonPort(), inheritedToken) {
663932
+ mkdirSync82(OMNIUS_DIR2, { recursive: true });
663933
+ const endpoint = daemonEndpoint(port);
663934
+ const lockFile = daemonLockFile(port);
663935
+ for (let attempt = 0; attempt < 3; attempt++) {
663936
+ const token = inheritedToken ?? newDaemonLockToken();
663937
+ const record = {
663938
+ endpoint,
663939
+ pid: process.pid,
663940
+ token,
663941
+ startedAt: Date.now()
663942
+ };
663943
+ let fd = null;
663944
+ try {
663945
+ fd = openSync4(lockFile, "wx", 384);
663946
+ writeSync2(fd, JSON.stringify(record));
663947
+ closeSync4(fd);
663948
+ return { endpoint, lockFile, pid: process.pid, port, token };
663949
+ } catch (error) {
663950
+ if (fd !== null) {
663951
+ try {
663952
+ closeSync4(fd);
663953
+ } catch {
663954
+ }
663955
+ try {
663956
+ unlinkSync27(lockFile);
663957
+ } catch {
663958
+ }
663959
+ }
663960
+ const code8 = error.code;
663961
+ if (code8 !== "EEXIST") return null;
663962
+ }
663963
+ const existing = readDaemonLock(lockFile);
663964
+ if (existing?.endpoint === endpoint && inheritedToken && existing.token === inheritedToken) {
663965
+ const transferred = { ...existing, pid: process.pid, startedAt: Date.now() };
663966
+ writeFileSync70(lockFile, JSON.stringify(transferred), { encoding: "utf8", mode: 384 });
663967
+ return { endpoint, lockFile, pid: process.pid, port, token: inheritedToken };
663968
+ }
663969
+ if (existing && processIsAlive(existing.pid) || !existing && daemonLockIsInitializing(lockFile)) {
663970
+ return null;
663971
+ }
663972
+ try {
663973
+ unlinkSync27(lockFile);
663974
+ } catch {
663975
+ }
663976
+ }
663977
+ return null;
663978
+ }
663979
+ function releaseDaemonEndpointClaim(claim) {
663980
+ const existing = readDaemonLock(claim.lockFile);
663981
+ if (existing?.pid !== claim.pid || existing.token !== claim.token) return;
663982
+ try {
663983
+ unlinkSync27(claim.lockFile);
663984
+ } catch {
663985
+ }
663986
+ }
663987
+ function releaseDaemonEndpointForCurrentProcess(port = getDaemonPort()) {
663988
+ const lockFile = daemonLockFile(port);
663989
+ const existing = readDaemonLock(lockFile);
663990
+ if (existing?.pid !== process.pid) return;
663991
+ try {
663992
+ unlinkSync27(lockFile);
663993
+ } catch {
663994
+ }
663995
+ }
663411
663996
  async function isDaemonRunning(port) {
663412
663997
  const p2 = port ?? getDaemonPort();
663413
663998
  try {
@@ -663518,9 +664103,15 @@ async function resolveDaemonCommand(nodeExe) {
663518
664103
  }
663519
664104
  async function startDaemon() {
663520
664105
  mkdirSync82(OMNIUS_DIR2, { recursive: true });
664106
+ const daemonPort = getDaemonPort();
664107
+ const endpointClaim = claimDaemonEndpoint(daemonPort);
664108
+ if (!endpointClaim) return null;
663521
664109
  const nodeExe = process.execPath;
663522
664110
  const daemonCommand = await resolveDaemonCommand(nodeExe);
663523
- if (!daemonCommand) return null;
664111
+ if (!daemonCommand) {
664112
+ releaseDaemonEndpointClaim(endpointClaim);
664113
+ return null;
664114
+ }
663524
664115
  let outFd = null;
663525
664116
  let errFd = null;
663526
664117
  try {
@@ -663536,6 +664127,8 @@ async function startDaemon() {
663536
664127
  ...processLeaseEnv(leaseId, ownerId, process.cwd()),
663537
664128
  OMNIUS_DAEMON: "1",
663538
664129
  // signal to serve.ts that it's running as daemon
664130
+ OMNIUS_DAEMON_LOCK_TOKEN: endpointClaim.token,
664131
+ OMNIUS_DAEMON_LOCK_PORT: String(daemonPort),
663539
664132
  OMNIUS_PROCESS_OWNER_KIND: "daemon",
663540
664133
  OMNIUS_PROCESS_LIFECYCLE: "daemon",
663541
664134
  OMNIUS_PROCESS_PERSISTENT: "1"
@@ -663561,6 +664154,7 @@ async function startDaemon() {
663561
664154
  }
663562
664155
  return pid;
663563
664156
  } catch {
664157
+ releaseDaemonEndpointClaim(endpointClaim);
663564
664158
  return null;
663565
664159
  } finally {
663566
664160
  if (outFd !== null) try {
@@ -663683,7 +664277,13 @@ async function ensureDaemon() {
663683
664277
  }
663684
664278
  }
663685
664279
  const pid = await startDaemon();
663686
- if (!pid) return false;
664280
+ if (!pid) {
664281
+ for (let i2 = 0; i2 < 20; i2++) {
664282
+ await new Promise((r2) => setTimeout(r2, 500));
664283
+ if (await isDaemonRunning(port)) return true;
664284
+ }
664285
+ return false;
664286
+ }
663687
664287
  for (let i2 = 0; i2 < 20; i2++) {
663688
664288
  await new Promise((r2) => setTimeout(r2, 500));
663689
664289
  if (await isDaemonRunning(port)) {
@@ -663698,6 +664298,7 @@ async function ensureDaemon() {
663698
664298
  unlinkSync27(PID_FILE2);
663699
664299
  } catch {
663700
664300
  }
664301
+ releaseDaemonEndpointForCurrentProcess(port);
663701
664302
  return false;
663702
664303
  }
663703
664304
  async function getDaemonStatus() {
@@ -663719,13 +664320,14 @@ async function getDaemonStatus() {
663719
664320
  }
663720
664321
  return { running, pid, port, uptime: uptime2, pidFile: PID_FILE2 };
663721
664322
  }
663722
- var OMNIUS_DIR2, PID_FILE2, DEFAULT_PORT2;
664323
+ var OMNIUS_DIR2, PID_FILE2, DEFAULT_PORT2, LOCK_INITIALIZATION_GRACE_MS;
663723
664324
  var init_daemon = __esm({
663724
664325
  "packages/cli/src/daemon.ts"() {
663725
664326
  init_dist5();
663726
664327
  OMNIUS_DIR2 = join149(homedir51(), ".omnius");
663727
664328
  PID_FILE2 = join149(OMNIUS_DIR2, "daemon.pid");
663728
664329
  DEFAULT_PORT2 = 11435;
664330
+ LOCK_INITIALIZATION_GRACE_MS = 5e3;
663729
664331
  }
663730
664332
  });
663731
664333
 
@@ -663883,7 +664485,7 @@ __export(kg_prune_exports, {
663883
664485
  pruneKnowledgeGraph: () => pruneKnowledgeGraph,
663884
664486
  pruneKnowledgeGraphWithInference: () => pruneKnowledgeGraphWithInference
663885
664487
  });
663886
- import { existsSync as existsSync142, statSync as statSync57 } from "node:fs";
664488
+ import { existsSync as existsSync142, statSync as statSync58 } from "node:fs";
663887
664489
  import { join as join151 } from "node:path";
663888
664490
  function stateDirFor(workingDir) {
663889
664491
  return join151(workingDir, ".omnius");
@@ -663903,13 +664505,13 @@ function knowledgeGraphStats(workingDir) {
663903
664505
  };
663904
664506
  if (stats.exists) {
663905
664507
  try {
663906
- stats.sizeBytes = statSync57(dbPath).size;
664508
+ stats.sizeBytes = statSync58(dbPath).size;
663907
664509
  } catch {
663908
664510
  }
663909
664511
  }
663910
664512
  if (existsSync142(archivePath)) {
663911
664513
  try {
663912
- stats.archiveSizeBytes = statSync57(archivePath).size;
664514
+ stats.archiveSizeBytes = statSync58(archivePath).size;
663913
664515
  } catch {
663914
664516
  }
663915
664517
  }
@@ -666530,7 +667132,7 @@ import {
666530
667132
  readFileSync as readFileSync118,
666531
667133
  unlinkSync as unlinkSync30,
666532
667134
  readdirSync as readdirSync47,
666533
- statSync as statSync58,
667135
+ statSync as statSync59,
666534
667136
  copyFileSync as copyFileSync6,
666535
667137
  rmSync as rmSync12
666536
667138
  } from "node:fs";
@@ -666664,7 +667266,7 @@ function mergeDir2(src2, dst) {
666664
667266
  if (entry.isDirectory()) {
666665
667267
  mergeDir2(s2, d2);
666666
667268
  } else if (entry.isFile()) {
666667
- if (!existsSync146(d2) || statSync58(s2).mtimeMs > statSync58(d2).mtimeMs) {
667269
+ if (!existsSync146(d2) || statSync59(s2).mtimeMs > statSync59(d2).mtimeMs) {
666668
667270
  copyFileSync6(s2, d2);
666669
667271
  }
666670
667272
  }
@@ -668149,7 +668751,7 @@ except Exception as exc:
668149
668751
  const p2 = join155(dir, f2);
668150
668752
  let size = 0;
668151
668753
  try {
668152
- size = statSync58(p2).size;
668754
+ size = statSync59(p2).size;
668153
668755
  } catch {
668154
668756
  }
668155
668757
  const entry = meta[f2];
@@ -671187,10 +671789,10 @@ import {
671187
671789
  mkdirSync as mkdirSync87,
671188
671790
  readdirSync as readdirSync48,
671189
671791
  lstatSync as lstatSync2,
671190
- statSync as statSync59,
671792
+ statSync as statSync60,
671191
671793
  rmSync as rmSync13,
671192
671794
  appendFileSync as appendFileSync16,
671193
- writeSync as writeSync2
671795
+ writeSync as writeSync3
671194
671796
  } from "node:fs";
671195
671797
  import { basename as basename32, dirname as dirname49, relative as relative19, join as join156 } from "node:path";
671196
671798
  function omniusPinnedDependencyVersion(name10) {
@@ -671442,7 +672044,7 @@ function parseTelegramMessageIdList(value2) {
671442
672044
  }
671443
672045
  function writeDirectTerminal(data) {
671444
672046
  try {
671445
- writeSync2(1, data);
672047
+ writeSync3(1, data);
671446
672048
  } catch {
671447
672049
  try {
671448
672050
  overlayWrite(data);
@@ -674053,7 +674655,7 @@ async function handleSlashCommand(input, ctx3) {
674053
674655
  ipfsFiles = files.length;
674054
674656
  for (const f2 of files) {
674055
674657
  try {
674056
- ipfsBytes += statSync59(join156(ipfsLocalDir, f2)).size;
674658
+ ipfsBytes += statSync60(join156(ipfsLocalDir, f2)).size;
674057
674659
  } catch {
674058
674660
  }
674059
674661
  }
@@ -674066,7 +674668,7 @@ async function handleSlashCommand(input, ctx3) {
674066
674668
  else {
674067
674669
  heliaBlocks++;
674068
674670
  try {
674069
- heliaBytes += statSync59(join156(dir, entry.name)).size;
674671
+ heliaBytes += statSync60(join156(dir, entry.name)).size;
674070
674672
  } catch {
674071
674673
  }
674072
674674
  }
@@ -674209,7 +674811,7 @@ async function handleSlashCommand(input, ctx3) {
674209
674811
  lines.push(`
674210
674812
  ${c3.bold("Structured Memory (SQLite)")}`);
674211
674813
  lines.push(
674212
- ` Memories: ${c3.bold(String(count))} DB: ${c3.dim(formatFileSize(statSync59(dbPath).size))}`
674814
+ ` Memories: ${c3.bold(String(count))} DB: ${c3.dim(formatFileSize(statSync60(dbPath).size))}`
674213
674815
  );
674214
674816
  cDb(db);
674215
674817
  }
@@ -674241,7 +674843,7 @@ async function handleSlashCommand(input, ctx3) {
674241
674843
  walkStorage(full, subCat);
674242
674844
  } else {
674243
674845
  try {
674244
- const sz = statSync59(full).size;
674846
+ const sz = statSync60(full).size;
674245
674847
  totalBytes += sz;
674246
674848
  if (!categories[category])
674247
674849
  categories[category] = { files: 0, bytes: 0 };
@@ -681393,7 +681995,7 @@ async function showCohereDashboard(ctx3) {
681393
681995
  const snapItems = snaps.slice(0, 20).map((f2) => ({
681394
681996
  key: f2,
681395
681997
  label: f2.replace(".json", ""),
681396
- detail: `${formatFileSize(statSync59(join156(snapDir, f2)).size)}`
681998
+ detail: `${formatFileSize(statSync60(join156(snapDir, f2)).size)}`
681397
681999
  }));
681398
682000
  if (snapItems.length > 0) {
681399
682001
  await tuiSelect({
@@ -696286,48 +696888,86 @@ var init_emotion_engine = __esm({
696286
696888
  }
696287
696889
  return { allowed: true };
696288
696890
  }
696891
+ /** Auxiliary stages share one non-queuing backend slot. */
696892
+ auxiliaryInferenceInFlight = false;
696893
+ /** Failed stages cool down independently; a successful nonempty reply resets them. */
696894
+ internalInferenceCircuit = /* @__PURE__ */ new Map();
696895
+ noteInternalInferenceFailure(stage2, now2 = Date.now()) {
696896
+ const prior = this.internalInferenceCircuit.get(stage2);
696897
+ const failureCount = Math.min(6, (prior?.failureCount ?? 0) + 1);
696898
+ const cooldownMs = Math.min(10 * 6e4, 3e4 * 2 ** (failureCount - 1));
696899
+ this.internalInferenceCircuit.set(stage2, {
696900
+ failureCount,
696901
+ openUntil: now2 + cooldownMs
696902
+ });
696903
+ }
696904
+ resetInternalInferenceCircuit(stage2) {
696905
+ this.internalInferenceCircuit.delete(stage2);
696906
+ }
696289
696907
  async runDirectInternalInference(opts) {
696290
696908
  const cwd4 = resolve71(process.cwd());
696291
696909
  const startedAt2 = Date.now();
696292
- const admission = await this.admitInternalInference();
696293
- if (!admission.allowed) {
696910
+ const circuit = this.internalInferenceCircuit.get(opts.stage);
696911
+ if (circuit && circuit.openUntil > startedAt2) {
696294
696912
  this.recordInternalDecision({
696295
696913
  stage: opts.stage,
696296
696914
  status: "skipped",
696297
696915
  elapsedMs: Date.now() - startedAt2,
696298
- skipReason: admission.reason,
696916
+ skipReason: `internal_inference_circuit_open:${opts.stage}:retry_after_ms=${circuit.openUntil - startedAt2}`,
696299
696917
  promptChars: opts.system.length + opts.user.length
696300
696918
  });
696301
696919
  return null;
696302
696920
  }
696303
- const request = {
696304
- messages: [
696305
- { role: "system", content: opts.system },
696306
- { role: "user", content: opts.user }
696307
- ],
696308
- tools: [],
696309
- temperature: opts.temperature,
696310
- maxTokens: opts.maxTokens,
696311
- timeoutMs: opts.timeoutMs,
696312
- think: false,
696313
- disableEmptyContentRecovery: true,
696314
- poolQueuePolicy: "skip",
696315
- poolQueueTimeoutMs: 1
696316
- };
696317
- recordContextWindowDump({
696318
- source: "emotionEngine",
696319
- stage: opts.stage,
696320
- agentType: "internal",
696321
- sessionId: process.env["OMNIUS_SESSION_ID"] || "emotion-engine",
696322
- runId: process.env["OMNIUS_SESSION_ID"] || "emotion-engine",
696323
- turn: 0,
696324
- attempt: 0,
696325
- model: this.config.model,
696326
- cwd: cwd4,
696327
- note: opts.note,
696328
- request
696329
- });
696921
+ if (this.auxiliaryInferenceInFlight) {
696922
+ this.recordInternalDecision({
696923
+ stage: opts.stage,
696924
+ status: "skipped",
696925
+ elapsedMs: Date.now() - startedAt2,
696926
+ skipReason: `auxiliary_inference_busy:${opts.stage}`,
696927
+ promptChars: opts.system.length + opts.user.length
696928
+ });
696929
+ return null;
696930
+ }
696931
+ this.auxiliaryInferenceInFlight = true;
696330
696932
  try {
696933
+ const admission = await this.admitInternalInference();
696934
+ if (!admission.allowed) {
696935
+ this.recordInternalDecision({
696936
+ stage: opts.stage,
696937
+ status: "skipped",
696938
+ elapsedMs: Date.now() - startedAt2,
696939
+ skipReason: admission.reason,
696940
+ promptChars: opts.system.length + opts.user.length
696941
+ });
696942
+ return null;
696943
+ }
696944
+ const request = {
696945
+ messages: [
696946
+ { role: "system", content: opts.system },
696947
+ { role: "user", content: opts.user }
696948
+ ],
696949
+ tools: [],
696950
+ temperature: opts.temperature,
696951
+ maxTokens: opts.maxTokens,
696952
+ timeoutMs: opts.timeoutMs,
696953
+ think: false,
696954
+ disableEmptyContentRecovery: true,
696955
+ poolQueuePolicy: "skip",
696956
+ poolQueueTimeoutMs: 1
696957
+ };
696958
+ recordContextWindowDump({
696959
+ source: "emotionEngine",
696960
+ stage: opts.stage,
696961
+ agentType: "internal",
696962
+ sessionId: process.env["OMNIUS_SESSION_ID"] || "emotion-engine",
696963
+ runId: process.env["OMNIUS_SESSION_ID"] || "emotion-engine",
696964
+ turn: 0,
696965
+ attempt: 0,
696966
+ model: this.config.model,
696967
+ cwd: cwd4,
696968
+ note: opts.note,
696969
+ request
696970
+ });
696331
696971
  const backend = new OllamaAgenticBackend(
696332
696972
  this.config.backendUrl,
696333
696973
  this.config.model,
@@ -696338,6 +696978,19 @@ var init_emotion_engine = __esm({
696338
696978
  const output = String(
696339
696979
  result.choices?.[0]?.message?.content ?? ""
696340
696980
  ).trim();
696981
+ if (!output) {
696982
+ const error = "empty internal inference response";
696983
+ this.noteInternalInferenceFailure(opts.stage);
696984
+ this.recordInternalDecision({
696985
+ stage: opts.stage,
696986
+ status: "error",
696987
+ elapsedMs: Date.now() - startedAt2,
696988
+ error,
696989
+ promptChars: opts.system.length + opts.user.length
696990
+ });
696991
+ return null;
696992
+ }
696993
+ this.resetInternalInferenceCircuit(opts.stage);
696341
696994
  this.recordInternalDecision({
696342
696995
  stage: opts.stage,
696343
696996
  status: "ok",
@@ -696347,14 +697000,18 @@ var init_emotion_engine = __esm({
696347
697000
  });
696348
697001
  return output;
696349
697002
  } catch (err) {
697003
+ const error = err instanceof Error ? err.message : String(err);
697004
+ this.noteInternalInferenceFailure(opts.stage);
696350
697005
  this.recordInternalDecision({
696351
697006
  stage: opts.stage,
696352
697007
  status: "error",
696353
697008
  elapsedMs: Date.now() - startedAt2,
696354
- error: err instanceof Error ? err.message : String(err),
697009
+ error,
696355
697010
  promptChars: opts.system.length + opts.user.length
696356
697011
  });
696357
697012
  throw err;
697013
+ } finally {
697014
+ this.auxiliaryInferenceInFlight = false;
696358
697015
  }
696359
697016
  }
696360
697017
  recordInternalDecision(entry) {
@@ -697716,7 +698373,7 @@ import {
697716
698373
  existsSync as existsSync157,
697717
698374
  mkdirSync as mkdirSync96,
697718
698375
  readFileSync as readFileSync128,
697719
- statSync as statSync60,
698376
+ statSync as statSync61,
697720
698377
  unlinkSync as unlinkSync33,
697721
698378
  writeFileSync as writeFileSync83
697722
698379
  } from "node:fs";
@@ -698229,7 +698886,7 @@ function materializeTelegramCreativeArtifactForSend(root, rawPath) {
698229
698886
  }
698230
698887
  function safeStatFile(path16) {
698231
698888
  try {
698232
- return statSync60(path16).isFile();
698889
+ return statSync61(path16).isFile();
698233
698890
  } catch {
698234
698891
  return false;
698235
698892
  }
@@ -698500,7 +699157,7 @@ ${(result.error || result.output || "").slice(0, 1200)}`,
698500
699157
  for (const fn of cleanup) fn();
698501
699158
  }
698502
699159
  rememberCreated(this.root, guarded.path.abs);
698503
- const sizeKB = Math.round(statSync60(guarded.path.abs).size / 1024);
699160
+ const sizeKB = Math.round(statSync61(guarded.path.abs).size / 1024);
698504
699161
  this.emitProgress(start2, {
698505
699162
  stage: "save",
698506
699163
  message: `Saved scoped audio file (${sizeKB}KB)`
@@ -701883,7 +702540,7 @@ import {
701883
702540
  existsSync as existsSync160,
701884
702541
  unlinkSync as unlinkSync36,
701885
702542
  readdirSync as readdirSync56,
701886
- statSync as statSync61,
702543
+ statSync as statSync62,
701887
702544
  readFileSync as readFileSync131,
701888
702545
  writeFileSync as writeFileSync85,
701889
702546
  appendFileSync as appendFileSync20
@@ -705103,6 +705760,8 @@ Telegram link integrity contract:
705103
705760
  */
705104
705761
  telegramOwnerLockFile = null;
705105
705762
  telegramOwnerLockFiles = [];
705763
+ /** Per-bridge ownership tokens prevent a second bridge from releasing our lock. */
705764
+ telegramOwnerLockTokens = /* @__PURE__ */ new Map();
705106
705765
  /** Session keys loaded from persistent conversation memory */
705107
705766
  loadedConversationState = /* @__PURE__ */ new Set();
705108
705767
  /** True once persisted Telegram conversation scopes have been bulk-loaded. */
@@ -706194,11 +706853,20 @@ ${message2}`)
706194
706853
  triageTelegramSteeringInput(msg) {
706195
706854
  const text2 = msg.text.trim();
706196
706855
  const lower = text2.toLowerCase();
706197
- if (/^\/(?:stop|cancel|abort|halt)\b/.test(lower)) {
706198
- return { intent: "cancel", reason: "explicit stop/cancel command" };
706856
+ if (/^\/(?:stop|cancel|abort|halt)\b/.test(lower) || /^(?:stop|cancel|abort|halt)(?:[.!]?|\s+(?:the\s+)?(?:current\s+)?(?:task|work|run)\b)/.test(
706857
+ lower
706858
+ )) {
706859
+ return { intent: "cancel", reason: "explicit cancellation request" };
706199
706860
  }
706200
- if (/^\/(?:redirect|reroute|pivot)\b/.test(lower)) {
706201
- return { intent: "redirect", reason: "explicit redirect command" };
706861
+ if (/^\/(?:redirect|reroute|pivot)\b/.test(lower) || /^(?:please\s+)?(?:redirect|reroute|pivot)\s+(?:the\s+)?(?:current\s+)?(?:task|work|run)\b/.test(
706862
+ lower
706863
+ ) || /^(?:please\s+)?(?:switch|change|move)\s+(?:(?:focus|work|task)\s+)?to\b/.test(
706864
+ lower
706865
+ )) {
706866
+ return {
706867
+ intent: "redirect",
706868
+ reason: "explicit natural-language redirect request"
706869
+ };
706202
706870
  }
706203
706871
  if (/^\/(?:replace|new[_-]?task)\b/.test(lower) || /^(?:new task|replace (?:the )?(?:current )?task|forget (?:that|the current task)|instead[,!:]?)/.test(
706204
706872
  lower
@@ -706306,14 +706974,13 @@ ${message2}`)
706306
706974
  content,
706307
706975
  source: "telegram",
706308
706976
  receivedAt: intake.receivedAt,
706309
- intent: intake.intent,
706310
- taskEpoch: intake.taskEpoch
706977
+ intent: intake.intent
706311
706978
  });
706312
706979
  return;
706313
706980
  }
706314
706981
  runner.injectUserMessage(this.formatTelegramSteeringCompatibilityMessage(pending2));
706315
706982
  }
706316
- async preemptTelegramSubAgentForIntake(msg, subAgent, toolContext, intake) {
706983
+ async preemptTelegramSubAgentForIntake(msg, subAgent, intake) {
706317
706984
  const sessionKey = intake.sessionKey;
706318
706985
  await this.transitionTelegramIntake(
706319
706986
  intake,
@@ -706321,59 +706988,33 @@ ${message2}`)
706321
706988
  "trusted Telegram steering receipt sent",
706322
706989
  { runId: subAgent.runId }
706323
706990
  );
706324
- const receipt = intake.intent === "cancel" ? "Cancellation received. I am stopping the current task." : "Redirection received. I am stopping the current step and replanning from your latest instruction.";
706991
+ const receipt = intake.intent === "cancel" ? "Cancellation received. I am stopping the current task." : "Redirection received. I am interrupting the current step and replanning from your latest instruction at the next safe boundary.";
706325
706992
  await this.replyToTelegramMessage(msg, receipt).catch(() => null);
706993
+ if (intake.intent !== "cancel") {
706994
+ intake.taskEpoch = this.advanceTelegramTaskEpoch(sessionKey);
706995
+ }
706326
706996
  await this.transitionTelegramIntake(
706327
706997
  intake,
706328
706998
  "preempt_requested",
706329
- "trusted admin-DM steering preemption requested",
706999
+ "trusted admin-DM steering preemption requested for the active runner",
706330
707000
  { runId: subAgent.runId }
706331
707001
  );
706332
- subAgent.preempted = true;
706333
- if (intake.intent !== "cancel") {
706334
- const epoch = this.advanceTelegramTaskEpoch(sessionKey);
706335
- const displaced = this.telegramQueuedSessionWork.get(sessionKey);
706336
- if (displaced) {
706337
- this.telegramQueuedSessionWork.delete(sessionKey);
706338
- await Promise.all(
706339
- displaced.intakeRecords.map(
706340
- (record) => this.transitionTelegramIntake(
706341
- record,
706342
- "superseded",
706343
- `superseded by trusted ${intake.intent} intake ${intake.inputId}`
706344
- )
706345
- )
706346
- );
706347
- }
706348
- intake.taskEpoch = epoch;
706349
- const queued = this.buildTelegramQueuedSessionWork(
706350
- sessionKey,
706351
- msg,
706352
- toolContext,
706353
- Date.now(),
706354
- intake
706355
- );
706356
- this.telegramQueuedSessionWork.set(sessionKey, queued);
706357
- await this.transitionTelegramIntake(
706358
- intake,
706359
- "deferred",
706360
- "waiting for superseded runner cleanup before dispatch",
706361
- { taskEpoch: epoch }
706362
- );
706363
- }
707002
+ await this.enqueueTelegramMessageForExistingSubAgent(msg, subAgent, intake);
706364
707003
  const runner = subAgent.runner;
706365
- if (typeof runner?.requestSteeringPreemption === "function") {
706366
- runner.requestSteeringPreemption(intake.inputId);
706367
- } else {
707004
+ const preemptionReceipt = runner?.requestSteeringPreemption?.(
707005
+ intake.inputId
707006
+ );
707007
+ if (!preemptionReceipt) {
707008
+ subAgent.preempted = true;
706368
707009
  runner?.abort?.();
706369
707010
  }
707011
+ if (intake.intent === "cancel") subAgent.preempted = true;
706370
707012
  await this.transitionTelegramIntake(
706371
707013
  intake,
706372
707014
  "preempted",
706373
- "active runner interrupted for trusted steering intake",
707015
+ preemptionReceipt ? "active runner turn interrupted; typed steering will apply at its safe boundary" : "runner lacks typed preemption support; active run was cancelled",
706374
707016
  { runId: subAgent.runId }
706375
707017
  );
706376
- this.dispatchQueuedTelegramSessionWorkSoon();
706377
707018
  }
706378
707019
  async requeuePendingTelegramIntakeOnFinalization(subAgent) {
706379
707020
  const pending2 = subAgent.pendingIntakeRecords.splice(0);
@@ -707137,7 +707778,7 @@ Model: <code>${escapeTelegramHTML(model.id)}</code>`
707137
707778
  }
707138
707779
  let sent = 0;
707139
707780
  for (const path16 of paths) {
707140
- if (!existsSync160(path16) || !statSync61(path16).isFile()) continue;
707781
+ if (!existsSync160(path16) || !statSync62(path16).isFile()) continue;
707141
707782
  const kind = classifyMedia(path16) ?? "document";
707142
707783
  const messageId = await this.sendMediaReference(
707143
707784
  msg.chatId,
@@ -712852,8 +713493,7 @@ ${TELEGRAM_PUBLIC_ORCHESTRATOR_CONTRACT}`
712852
713493
  } catch (e2) {
712853
713494
  for (const lockFile of claimed)
712854
713495
  this.releaseTelegramOwnerLock(lockFile);
712855
- if (e2 instanceof Error && e2.message.startsWith("Telegram bot @"))
712856
- throw e2;
713496
+ throw e2;
712857
713497
  }
712858
713498
  }
712859
713499
  this.state = {
@@ -713012,47 +713652,97 @@ ${TELEGRAM_PUBLIC_ORCHESTRATOR_CONTRACT}`
713012
713652
  claimTelegramOwnerLock(lockDir, botUserId, botUsername) {
713013
713653
  mkdirSync98(lockDir, { recursive: true });
713014
713654
  const lockFile = join170(lockDir, `bot-${botUserId}.owner.lock`);
713015
- if (existsSync160(lockFile)) {
713655
+ const ownerToken = randomBytes28(16).toString("hex");
713656
+ const payload = JSON.stringify(
713657
+ {
713658
+ pid: process.pid,
713659
+ cwd: this.repoRoot || process.cwd(),
713660
+ botUsername,
713661
+ botUserId,
713662
+ ownerToken,
713663
+ ts: Date.now()
713664
+ },
713665
+ null,
713666
+ 2
713667
+ );
713668
+ const recoveryFile = `${lockFile}.recovery`;
713669
+ for (let attempt = 0; attempt < 4; attempt++) {
713016
713670
  try {
713017
- const prior = JSON.parse(readFileSync131(lockFile, "utf8"));
713018
- const priorAlive = typeof prior.pid === "number" && prior.pid !== process.pid ? this.processIsAlive(prior.pid) : false;
713019
- if (priorAlive) {
713671
+ writeFileSync85(lockFile, payload, {
713672
+ encoding: "utf-8",
713673
+ mode: 384,
713674
+ flag: "wx"
713675
+ });
713676
+ this.telegramOwnerLockTokens.set(lockFile, ownerToken);
713677
+ return lockFile;
713678
+ } catch (error) {
713679
+ if (error?.code !== "EEXIST") throw error;
713680
+ }
713681
+ let prior = {};
713682
+ try {
713683
+ prior = JSON.parse(readFileSync131(lockFile, "utf8"));
713684
+ } catch {
713685
+ }
713686
+ const priorAlive = typeof prior.pid === "number" && prior.pid !== process.pid ? this.processIsAlive(prior.pid) : typeof prior.pid === "number";
713687
+ if (priorAlive) {
713688
+ throw new Error(
713689
+ `Telegram bot @${prior.botUsername || botUsername || "unknown"} is already being polled by pid ${prior.pid} (cwd ${prior.cwd || "?"}). Stop that instance or use a different bot token in this project.`
713690
+ );
713691
+ }
713692
+ const recoveryToken = randomBytes28(12).toString("hex");
713693
+ try {
713694
+ writeFileSync85(recoveryFile, recoveryToken, {
713695
+ encoding: "utf-8",
713696
+ mode: 384,
713697
+ flag: "wx"
713698
+ });
713699
+ } catch (error) {
713700
+ if (error?.code === "EEXIST") continue;
713701
+ throw error;
713702
+ }
713703
+ try {
713704
+ let currentPid;
713705
+ try {
713706
+ currentPid = JSON.parse(readFileSync131(lockFile, "utf8"))?.pid;
713707
+ } catch {
713708
+ }
713709
+ if (typeof currentPid === "number" && (currentPid === process.pid || this.processIsAlive(currentPid))) {
713020
713710
  throw new Error(
713021
- `Telegram bot @${prior.botUsername || botUsername || "unknown"} is already being polled by pid ${prior.pid} (cwd ${prior.cwd || "?"}). Stop that instance or use a different bot token in this project.`
713711
+ `Telegram bot @${botUsername || "unknown"} acquired an owner while stale-lock recovery was pending.`
713022
713712
  );
713023
713713
  }
713024
- } catch (e2) {
713025
- if (e2 instanceof Error && e2.message.startsWith("Telegram bot @"))
713026
- throw e2;
713714
+ try {
713715
+ unlinkSync36(lockFile);
713716
+ } catch (error) {
713717
+ if (error?.code !== "ENOENT") throw error;
713718
+ }
713719
+ } finally {
713720
+ try {
713721
+ if (readFileSync131(recoveryFile, "utf8") === recoveryToken)
713722
+ unlinkSync36(recoveryFile);
713723
+ } catch {
713724
+ }
713027
713725
  }
713028
713726
  }
713029
- writeFileSync85(
713030
- lockFile,
713031
- JSON.stringify(
713032
- {
713033
- pid: process.pid,
713034
- cwd: this.repoRoot || process.cwd(),
713035
- botUsername,
713036
- botUserId,
713037
- ts: Date.now()
713038
- },
713039
- null,
713040
- 2
713041
- ),
713042
- { encoding: "utf-8", mode: 384 }
713727
+ throw new Error(
713728
+ `Could not atomically acquire Telegram owner lock for @${botUsername || botUserId}; retry after the current startup settles.`
713043
713729
  );
713044
- return lockFile;
713045
713730
  }
713046
713731
  releaseTelegramOwnerLock(lockFile) {
713047
713732
  try {
713733
+ const ownerToken = this.telegramOwnerLockTokens.get(lockFile);
713734
+ if (!ownerToken) return;
713048
713735
  if (!existsSync160(lockFile)) return;
713049
713736
  try {
713050
713737
  const prior = JSON.parse(readFileSync131(lockFile, "utf8"));
713051
- if (prior.pid !== process.pid) return;
713738
+ if (prior.pid !== process.pid || prior.ownerToken !== ownerToken) return;
713052
713739
  } catch {
713740
+ return;
713053
713741
  }
713054
713742
  unlinkSync36(lockFile);
713055
713743
  } catch {
713744
+ } finally {
713745
+ this.telegramOwnerLockTokens.delete(lockFile);
713056
713746
  }
713057
713747
  }
713058
713748
  /**
@@ -714130,7 +714820,6 @@ Join: ${newUrl}`
714130
714820
  await this.preemptTelegramSubAgentForIntake(
714131
714821
  msg,
714132
714822
  existing,
714133
- toolContext,
714134
714823
  intakeRecord
714135
714824
  );
714136
714825
  return;
@@ -719392,7 +720081,7 @@ ${knownList}` : "Private-user telegram_send_file target must be this DM or a kno
719392
720081
  const abs = isAbsolute17(trimmed) ? resolve73(trimmed) : resolve73(base3, trimmed);
719393
720082
  if (!existsSync160(abs))
719394
720083
  return { ok: false, error: `File does not exist: ${trimmed}` };
719395
- if (!statSync61(abs).isFile())
720084
+ if (!statSync62(abs).isFile())
719396
720085
  return { ok: false, error: `Path is not a file: ${trimmed}` };
719397
720086
  return { ok: true, path: abs };
719398
720087
  }
@@ -719906,7 +720595,7 @@ ${text2}`.trim()
719906
720595
  }
719907
720596
  async sendTelegramFileToChat(chatId, path16, options2) {
719908
720597
  const abs = resolve73(path16);
719909
- if (!existsSync160(abs) || !statSync61(abs).isFile()) {
720598
+ if (!existsSync160(abs) || !statSync62(abs).isFile()) {
719910
720599
  throw new Error(`File does not exist or is not a regular file: ${path16}`);
719911
720600
  }
719912
720601
  return this.sendMediaReferenceStrict(
@@ -720176,7 +720865,7 @@ Content-Type: ${contentType}\r
720176
720865
  for (const path16 of paths) {
720177
720866
  const abs = resolve73(path16);
720178
720867
  if (subAgent.deliveredArtifacts.includes(abs)) continue;
720179
- if (!existsSync160(abs) || !statSync61(abs).isFile()) continue;
720868
+ if (!existsSync160(abs) || !statSync62(abs).isFile()) continue;
720180
720869
  subAgent.deliveredArtifacts.push(abs);
720181
720870
  await this.sendMediaReference(
720182
720871
  msg.chatId,
@@ -720218,7 +720907,7 @@ Content-Type: ${contentType}\r
720218
720907
  abs
720219
720908
  );
720220
720909
  if (!materialized.ok) continue;
720221
- if (!existsSync160(materialized.path) || !statSync61(materialized.path).isFile()) {
720910
+ if (!existsSync160(materialized.path) || !statSync62(materialized.path).isFile()) {
720222
720911
  materialized.cleanup?.();
720223
720912
  continue;
720224
720913
  }
@@ -722407,7 +723096,7 @@ __export(projects_exports, {
722407
723096
  setCurrentProject: () => setCurrentProject,
722408
723097
  unregisterProject: () => unregisterProject
722409
723098
  });
722410
- import { readFileSync as readFileSync132, writeFileSync as writeFileSync86, mkdirSync as mkdirSync99, existsSync as existsSync161, statSync as statSync62, renameSync as renameSync15 } from "node:fs";
723099
+ import { readFileSync as readFileSync132, writeFileSync as writeFileSync86, mkdirSync as mkdirSync99, existsSync as existsSync161, statSync as statSync63, renameSync as renameSync15 } from "node:fs";
722411
723100
  import { homedir as homedir58 } from "node:os";
722412
723101
  import { basename as basename43, join as join171, resolve as resolve74 } from "node:path";
722413
723102
  import { randomUUID as randomUUID19 } from "node:crypto";
@@ -722433,7 +723122,7 @@ function listProjects() {
722433
723122
  const alive = [];
722434
723123
  for (const p2 of projects) {
722435
723124
  try {
722436
- if (statSync62(p2.root).isDirectory()) alive.push(p2);
723125
+ if (statSync63(p2.root).isDirectory()) alive.push(p2);
722437
723126
  } catch {
722438
723127
  }
722439
723128
  }
@@ -723573,7 +724262,7 @@ var init_audit_log = __esm({
723573
724262
 
723574
724263
  // packages/cli/src/api/disk-task-output.ts
723575
724264
  import { open } from "node:fs/promises";
723576
- import { existsSync as existsSync164, mkdirSync as mkdirSync102, statSync as statSync63 } from "node:fs";
724265
+ import { existsSync as existsSync164, mkdirSync as mkdirSync102, statSync as statSync64 } from "node:fs";
723577
724266
  import { dirname as dirname54 } from "node:path";
723578
724267
  import * as fsConstants from "node:constants";
723579
724268
  var O_NOFOLLOW2, O_APPEND2, O_CREAT2, O_WRONLY2, OPEN_FLAGS_WRITE, OPEN_MODE, DiskTaskOutput;
@@ -723671,7 +724360,7 @@ var init_disk_task_output = __esm({
723671
724360
  if (!existsSync164(this.path)) {
723672
724361
  return { content: "", nextOffset: offset, eof: true, size: 0 };
723673
724362
  }
723674
- const st = statSync63(this.path);
724363
+ const st = statSync64(this.path);
723675
724364
  if (offset >= st.size) {
723676
724365
  return { content: "", nextOffset: offset, eof: true, size: st.size };
723677
724366
  }
@@ -723858,7 +724547,7 @@ data: ${JSON.stringify(ev)}
723858
724547
  });
723859
724548
 
723860
724549
  // packages/cli/src/api/routes-media.ts
723861
- import { existsSync as existsSync165, mkdirSync as mkdirSync103, statSync as statSync64, copyFileSync as copyFileSync7, createReadStream } from "node:fs";
724550
+ import { existsSync as existsSync165, mkdirSync as mkdirSync103, statSync as statSync65, copyFileSync as copyFileSync7, createReadStream } from "node:fs";
723862
724551
  import { basename as basename44, join as join174, resolve as pathResolve2 } from "node:path";
723863
724552
  function mediaWorkDir() {
723864
724553
  return join174(omniusHomeDir(), "media", "_work");
@@ -724159,7 +724848,7 @@ async function runGeneration(ctx3, kind, buildTool, buildArgs) {
724159
724848
  const published = publishToGallery(srcPath, kind);
724160
724849
  const size = (() => {
724161
724850
  try {
724162
- return statSync64(published.path).size;
724851
+ return statSync65(published.path).size;
724163
724852
  } catch {
724164
724853
  return 0;
724165
724854
  }
@@ -724266,7 +724955,7 @@ function handleFile(ctx3) {
724266
724955
  const ext = full.slice(full.lastIndexOf(".")).toLowerCase();
724267
724956
  ctx3.res.writeHead(200, {
724268
724957
  "Content-Type": MIME_BY_EXT[ext] || "application/octet-stream",
724269
- "Content-Length": statSync64(full).size,
724958
+ "Content-Length": statSync65(full).size,
724270
724959
  "Cache-Control": "private, max-age=3600"
724271
724960
  });
724272
724961
  createReadStream(full).pipe(ctx3.res);
@@ -724850,7 +725539,7 @@ __export(aiwg_exports, {
724850
725539
  resolveAiwgRoot: () => resolveAiwgRoot,
724851
725540
  tryRouteAiwg: () => tryRouteAiwg
724852
725541
  });
724853
- import { existsSync as existsSync167, readFileSync as readFileSync136, readdirSync as readdirSync57, statSync as statSync65 } from "node:fs";
725542
+ import { existsSync as existsSync167, readFileSync as readFileSync136, readdirSync as readdirSync57, statSync as statSync66 } from "node:fs";
724854
725543
  import { join as join176 } from "node:path";
724855
725544
  import { homedir as homedir60 } from "node:os";
724856
725545
  import { execSync as execSync38 } from "node:child_process";
@@ -724952,7 +725641,7 @@ function listAiwgFrameworks() {
724952
725641
  for (const name10 of readdirSync57(frameworksDir)) {
724953
725642
  const p2 = join176(frameworksDir, name10);
724954
725643
  try {
724955
- const st = statSync65(p2);
725644
+ const st = statSync66(p2);
724956
725645
  if (!st.isDirectory()) continue;
724957
725646
  const agg = aggregateDir(p2);
724958
725647
  out.push({
@@ -724989,7 +725678,7 @@ function aggregateDir(dir, depth = 0) {
724989
725678
  out.commands += sub2.commands;
724990
725679
  } else if (e2.isFile()) {
724991
725680
  try {
724992
- const st = statSync65(p2);
725681
+ const st = statSync66(p2);
724993
725682
  out.files++;
724994
725683
  out.bytes += st.size;
724995
725684
  if (e2.name.endsWith(".md")) {
@@ -725123,7 +725812,7 @@ function listAiwgAddons() {
725123
725812
  for (const name10 of readdirSync57(addonsDir)) {
725124
725813
  const p2 = join176(addonsDir, name10);
725125
725814
  try {
725126
- const st = statSync65(p2);
725815
+ const st = statSync66(p2);
725127
725816
  if (!st.isDirectory()) continue;
725128
725817
  const agg = aggregateDir(p2);
725129
725818
  out.push({
@@ -725912,7 +726601,7 @@ import {
725912
726601
  mkdirSync as mkdirSync106,
725913
726602
  readFileSync as readFileSync138,
725914
726603
  readdirSync as readdirSync58,
725915
- statSync as statSync66
726604
+ statSync as statSync67
725916
726605
  } from "node:fs";
725917
726606
  import { join as join179, resolve as pathResolve3 } from "node:path";
725918
726607
  import { homedir as homedir62 } from "node:os";
@@ -727374,7 +728063,7 @@ async function handleFilesRead(ctx3) {
727374
728063
  );
727375
728064
  return true;
727376
728065
  }
727377
- const st = statSync66(resolved);
728066
+ const st = statSync67(resolved);
727378
728067
  if (st.isDirectory()) {
727379
728068
  sendProblem(
727380
728069
  res,
@@ -743166,7 +743855,7 @@ import {
743166
743855
  watch as fsWatch4,
743167
743856
  renameSync as renameSync18,
743168
743857
  unlinkSync as unlinkSync38,
743169
- statSync as statSync67,
743858
+ statSync as statSync68,
743170
743859
  openSync as openSync7,
743171
743860
  readSync as readSync3,
743172
743861
  closeSync as closeSync7
@@ -743526,7 +744215,7 @@ function fileEntryMetadata(dir, entry) {
743526
744215
  kind: fileKindForPath(entry.name)
743527
744216
  };
743528
744217
  try {
743529
- const st = statSync67(target);
744218
+ const st = statSync68(target);
743530
744219
  meta["size"] = st.size;
743531
744220
  meta["mtime"] = new Date(st.mtimeMs).toISOString();
743532
744221
  } catch {
@@ -743538,7 +744227,7 @@ function contentDispositionName(filePath) {
743538
744227
  return name10.replace(/["\r\n]/g, "");
743539
744228
  }
743540
744229
  function streamWorkspaceFile(req3, res, target) {
743541
- const st = statSync67(target);
744230
+ const st = statSync68(target);
743542
744231
  if (!st.isFile()) {
743543
744232
  jsonResponse(res, 400, { error: "Path is not a file", path: target });
743544
744233
  return;
@@ -747444,7 +748133,7 @@ function handleV1RunsById(res, id2) {
747444
748133
  const enriched = { ...job };
747445
748134
  if (outputFile && existsSync173(outputFile)) {
747446
748135
  try {
747447
- const size = statSync67(outputFile).size;
748136
+ const size = statSync68(outputFile).size;
747448
748137
  const tailSize = Math.min(size, 4096);
747449
748138
  const buffer2 = Buffer.alloc(tailSize);
747450
748139
  const fd = openSync7(outputFile, "r");
@@ -748092,7 +748781,7 @@ async function handleRequest(req3, res, ollamaUrl, verbose, runtimeDefaults = {}
748092
748781
  const dir = path16.dirname(cssEntry);
748093
748782
  const fullPath = path16.join(dir, entry.path);
748094
748783
  if (fs14.existsSync(fullPath)) {
748095
- const stat9 = statSync67(fullPath);
748784
+ const stat9 = statSync68(fullPath);
748096
748785
  res.writeHead(200, {
748097
748786
  "Content-Type": entry.ct,
748098
748787
  "Content-Length": String(stat9.size),
@@ -748644,17 +749333,17 @@ async function handleRequest(req3, res, ollamaUrl, verbose, runtimeDefaults = {}
748644
749333
  const child = join183(dir, e2.name);
748645
749334
  const omniusDir = join183(child, ".omnius");
748646
749335
  try {
748647
- if (statSync67(omniusDir).isDirectory()) {
749336
+ if (statSync68(omniusDir).isDirectory()) {
748648
749337
  const name10 = e2.name;
748649
749338
  const prefsFile = join183(omniusDir, "config.json");
748650
749339
  let lastSeen = 0;
748651
749340
  try {
748652
- lastSeen = statSync67(prefsFile).mtimeMs;
749341
+ lastSeen = statSync68(prefsFile).mtimeMs;
748653
749342
  } catch {
748654
749343
  }
748655
749344
  if (!lastSeen) {
748656
749345
  try {
748657
- lastSeen = statSync67(omniusDir).mtimeMs;
749346
+ lastSeen = statSync68(omniusDir).mtimeMs;
748658
749347
  } catch {
748659
749348
  }
748660
749349
  }
@@ -748702,17 +749391,17 @@ async function handleRequest(req3, res, ollamaUrl, verbose, runtimeDefaults = {}
748702
749391
  const child = join183(dir, e2.name);
748703
749392
  const omniusDir = join183(child, ".omnius");
748704
749393
  try {
748705
- if (statSync67(omniusDir).isDirectory()) {
749394
+ if (statSync68(omniusDir).isDirectory()) {
748706
749395
  const name10 = e2.name;
748707
749396
  const prefsFile = join183(omniusDir, "config.json");
748708
749397
  let lastSeen = 0;
748709
749398
  try {
748710
- lastSeen = statSync67(prefsFile).mtimeMs;
749399
+ lastSeen = statSync68(prefsFile).mtimeMs;
748711
749400
  } catch {
748712
749401
  }
748713
749402
  if (!lastSeen) {
748714
749403
  try {
748715
- lastSeen = statSync67(omniusDir).mtimeMs;
749404
+ lastSeen = statSync68(omniusDir).mtimeMs;
748716
749405
  } catch {
748717
749406
  }
748718
749407
  }
@@ -753710,7 +754399,7 @@ import {
753710
754399
  appendFileSync as appendFileSync22,
753711
754400
  rmSync as rmSync17,
753712
754401
  readdirSync as readdirSync60,
753713
- statSync as statSync68,
754402
+ statSync as statSync69,
753714
754403
  mkdirSync as mkdirSync111
753715
754404
  } from "node:fs";
753716
754405
  import { existsSync as existsSync174 } from "node:fs";
@@ -759581,7 +760270,7 @@ This is an independent background session started from /background.`
759581
760270
  if (!entry.startsWith(partialName)) continue;
759582
760271
  const full = join185(searchDir, entry);
759583
760272
  try {
759584
- const st = statSync68(full);
760273
+ const st = statSync69(full);
759585
760274
  const suffix = st.isDirectory() ? "/" : "";
759586
760275
  const display = isAbsolute18 ? full : full.startsWith(repoRoot + sep7) ? full.slice(repoRoot.length + 1) : full;
759587
760276
  completions.push(display + suffix);
@@ -762365,11 +763054,11 @@ Respond concisely and safely. Remember: you are talking to the general public.`;
762365
763054
  }
762366
763055
  if (name10 === "voice_list_files") {
762367
763056
  const baseDir = String(args?.dir ?? ".");
762368
- const { readdirSync: readdirSync62, statSync: statSync70 } = __require("node:fs");
763057
+ const { readdirSync: readdirSync62, statSync: statSync71 } = __require("node:fs");
762369
763058
  const { join: join190, resolve: resolve82 } = __require("node:path");
762370
763059
  const base3 = baseDir.startsWith("/") ? baseDir : resolve82(join190(repoRoot, baseDir));
762371
763060
  const items = readdirSync62(base3).slice(0, 200).map((f2) => {
762372
- const s2 = statSync70(join190(base3, f2));
763061
+ const s2 = statSync71(join190(base3, f2));
762373
763062
  return { name: f2, dir: s2.isDirectory(), size: s2.size };
762374
763063
  });
762375
763064
  return JSON.stringify({ dir: base3, items }, null, 2);
@@ -765202,7 +765891,7 @@ __export(index_repo_exports, {
765202
765891
  indexRepoCommand: () => indexRepoCommand
765203
765892
  });
765204
765893
  import { resolve as resolve80 } from "node:path";
765205
- import { existsSync as existsSync176, statSync as statSync69 } from "node:fs";
765894
+ import { existsSync as existsSync176, statSync as statSync70 } from "node:fs";
765206
765895
  import { cwd as cwd2 } from "node:process";
765207
765896
  async function indexRepoCommand(opts, _config3) {
765208
765897
  const repoRoot = resolve80(opts.repoPath ?? cwd2());
@@ -765212,7 +765901,7 @@ async function indexRepoCommand(opts, _config3) {
765212
765901
  printError(`Path does not exist: ${repoRoot}`);
765213
765902
  process.exit(1);
765214
765903
  }
765215
- const stat9 = statSync69(repoRoot);
765904
+ const stat9 = statSync70(repoRoot);
765216
765905
  if (!stat9.isDirectory()) {
765217
765906
  printError(`Path is not a directory: ${repoRoot}`);
765218
765907
  process.exit(1);
@@ -765696,23 +766385,34 @@ async function serveCommand(opts, config) {
765696
766385
  const ollamaUrl = config.backendUrl || "http://127.0.0.1:11434";
765697
766386
  const isDaemon = opts.daemon || process.env["OMNIUS_DAEMON"] === "1";
765698
766387
  const isQuiet = opts.quiet || isDaemon;
766388
+ let releaseDaemonClaim;
766389
+ if (isDaemon) {
766390
+ const { claimDaemonEndpoint: claimDaemonEndpoint2, releaseDaemonEndpointClaim: releaseDaemonEndpointClaim2 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
766391
+ const inheritedPort = parseInt(process.env["OMNIUS_DAEMON_LOCK_PORT"] ?? "", 10);
766392
+ const claim = claimDaemonEndpoint2(
766393
+ Number.isFinite(inheritedPort) && inheritedPort > 0 ? inheritedPort : port,
766394
+ process.env["OMNIUS_DAEMON_LOCK_TOKEN"]
766395
+ );
766396
+ if (!claim) return;
766397
+ releaseDaemonClaim = () => releaseDaemonEndpointClaim2(claim);
766398
+ }
765699
766399
  if (!isQuiet) {
765700
766400
  printHeader("Omnius REST API");
765701
766401
  printInfo(`Starting API server on port ${port}...`);
765702
766402
  printInfo(`Backend: ${config.backendType} (${ollamaUrl})`);
765703
766403
  }
765704
- if (isDaemon) {
765705
- try {
765706
- const resp = await fetch(`http://127.0.0.1:${port}/health`, {
765707
- signal: AbortSignal.timeout(1500)
765708
- });
765709
- if (resp.ok) {
765710
- return;
766404
+ try {
766405
+ if (isDaemon) {
766406
+ try {
766407
+ const resp = await fetch(`http://127.0.0.1:${port}/health`, {
766408
+ signal: AbortSignal.timeout(1500)
766409
+ });
766410
+ if (resp.ok) {
766411
+ return;
766412
+ }
766413
+ } catch {
765711
766414
  }
765712
- } catch {
765713
766415
  }
765714
- }
765715
- try {
765716
766416
  const server2 = startApiServer({ port, ollamaUrl, quiet: isQuiet });
765717
766417
  if (isDaemon) {
765718
766418
  let lastActivity = Date.now();
@@ -765749,6 +766449,8 @@ async function serveCommand(opts, config) {
765749
766449
  } else {
765750
766450
  if (!isQuiet) printError(`API server failed: ${msg}`);
765751
766451
  }
766452
+ } finally {
766453
+ releaseDaemonClaim?.();
765752
766454
  }
765753
766455
  }
765754
766456
  var init_serve2 = __esm({
@@ -766246,6 +766948,8 @@ function parseCliArgs(argv) {
766246
766948
  live: { type: "boolean" },
766247
766949
  json: { type: "boolean", short: "j" },
766248
766950
  background: { type: "boolean" },
766951
+ daemon: { type: "boolean" },
766952
+ quiet: { type: "boolean" },
766249
766953
  "self-test": { type: "string" },
766250
766954
  help: { type: "boolean", short: "h" },
766251
766955
  version: { type: "boolean", short: "V" }
@@ -766269,6 +766973,8 @@ function parseCliArgs(argv) {
766269
766973
  local: values.local === true,
766270
766974
  json: values.json === true,
766271
766975
  background: values.background === true,
766976
+ daemon: values.daemon === true,
766977
+ quiet: values.quiet === true,
766272
766978
  selfTest: typeof values["self-test"] === "string" ? values["self-test"] : void 0,
766273
766979
  help: values.help === true,
766274
766980
  version: values.version === true
@@ -766494,8 +767200,8 @@ async function main() {
766494
767200
  port: parsed.servePort,
766495
767201
  model: parsed.model,
766496
767202
  verbose: parsed.verbose,
766497
- daemon: process.env["OMNIUS_DAEMON"] === "1",
766498
- quiet: process.argv.includes("--quiet") || process.env["OMNIUS_DAEMON"] === "1"
767203
+ daemon: parsed.daemon === true || process.env["OMNIUS_DAEMON"] === "1",
767204
+ quiet: parsed.quiet === true || process.env["OMNIUS_DAEMON"] === "1"
766499
767205
  },
766500
767206
  config
766501
767207
  );