omnius 1.0.553 → 1.0.555

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,
@@ -566175,12 +566247,18 @@ function stripThinkTags(text2) {
566175
566247
  return "";
566176
566248
  return String(text2).replace(THINK_BLOCK_RE, "").trim();
566177
566249
  }
566250
+ function stripNoThinkPromptDirectives(text2) {
566251
+ if (text2 == null)
566252
+ return "";
566253
+ return String(text2).replace(NO_THINK_PROMPT_DIRECTIVE_RE, "").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
566254
+ }
566178
566255
  function cleanForStorage(text2) {
566179
566256
  if (text2 == null)
566180
566257
  return "";
566181
566258
  let out = String(text2);
566182
566259
  out = cleanScaffolding(out);
566183
566260
  out = stripThinkTags(out);
566261
+ out = stripNoThinkPromptDirectives(out);
566184
566262
  out = out.replace(ANSI_ESCAPE_RE, "");
566185
566263
  out = out.replace(/\s+/g, " ").trim();
566186
566264
  return out;
@@ -566214,7 +566292,7 @@ function extractTaskCompleteSummary(args) {
566214
566292
  }
566215
566293
  return "";
566216
566294
  }
566217
- var SIGNPOST_RE, NEW_TASK_RE, RESTORED_BLOCK_RE, SYSTEM_BLOCK_RE, THINK_BLOCK_RE, ANSI_ESCAPE_RE;
566295
+ var SIGNPOST_RE, NEW_TASK_RE, RESTORED_BLOCK_RE, SYSTEM_BLOCK_RE, THINK_BLOCK_RE, NO_THINK_PROMPT_DIRECTIVE_RE, ANSI_ESCAPE_RE;
566218
566296
  var init_textSanitize = __esm({
566219
566297
  "packages/orchestrator/dist/textSanitize.js"() {
566220
566298
  "use strict";
@@ -566223,6 +566301,7 @@ var init_textSanitize = __esm({
566223
566301
  RESTORED_BLOCK_RE = /^[\s\S]*?\n---\s*\n\s*NEW TASK:\s*/m;
566224
566302
  SYSTEM_BLOCK_RE = /^<system>[\s\S]*?<\/system>\s*\n*/m;
566225
566303
  THINK_BLOCK_RE = /<think>[\s\S]*?<\/think>/g;
566304
+ NO_THINK_PROMPT_DIRECTIVE_RE = /\/(?:no[_-]?think)\b/gi;
566226
566305
  ANSI_ESCAPE_RE = /\x1b\[[0-9;]*[a-zA-Z]|\x1b\][^\x07]*\x07/g;
566227
566306
  }
566228
566307
  });
@@ -566441,6 +566520,28 @@ import { randomUUID as randomUUID16 } from "node:crypto";
566441
566520
  import { appendFileSync as appendFileSync6, existsSync as existsSync88, mkdirSync as mkdirSync50, readFileSync as readFileSync65 } from "node:fs";
566442
566521
  import { join as join98 } from "node:path";
566443
566522
  import { z as z16 } from "zod";
566523
+ function classifySteeringIntent(content, requestedIntent) {
566524
+ if (requestedIntent === "redirect" || requestedIntent === "replace" || requestedIntent === "cancel") {
566525
+ return requestedIntent;
566526
+ }
566527
+ const normalized = content.toLowerCase().replace(/\s+/g, " ").trim();
566528
+ const constraint = /\b(?:do not|don't|never|must not|forbid|forbidden|avoid|read[ -]?only|no (?:file )?(?:writes?|mutations?)|without modifying|scope|safety|safe(?:ty)?|only modify|do not publish)\b/.test(normalized);
566529
+ if (constraint || requestedIntent === "constraint")
566530
+ return "constraint";
566531
+ const priority = /\b(?:prioriti[sz]e|priority|urgent|first|before .*?(?:else|anything)|defer|hold|focus on|instead of)\b/.test(normalized);
566532
+ if (priority || requestedIntent === "priority_change") {
566533
+ return "priority_change";
566534
+ }
566535
+ if (requestedIntent === "context_only")
566536
+ return "context_only";
566537
+ return "context_only";
566538
+ }
566539
+ function steeringRequiresReconciliation(intent) {
566540
+ return intent !== "cancel";
566541
+ }
566542
+ function steeringGatesOldPlan(intent) {
566543
+ return intent === "constraint" || intent === "priority_change";
566544
+ }
566444
566545
  function createSteeringIngress(input) {
566445
566546
  return {
566446
566547
  id: randomUUID16(),
@@ -572353,14 +572454,17 @@ function collectDiff(opts) {
572353
572454
  }
572354
572455
  return { files, strategy: "explicit" };
572355
572456
  }
572457
+ if (opts.explicitFilesOnly)
572458
+ return { files: [], strategy: "explicit" };
572356
572459
  const since = Date.now() - opts.mtimeWindowMs;
572357
572460
  const scan = scanWorkspace({ root: opts.workingDir, maxFiles: cap * 4 });
572358
572461
  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
572462
  return { files: recent, strategy: "mtime" };
572360
572463
  }
572361
572464
  async function collectDiffAsync(opts) {
572362
- if (opts.explicitFiles && opts.explicitFiles.length > 0)
572465
+ if (opts.explicitFilesOnly || opts.explicitFiles && opts.explicitFiles.length > 0) {
572363
572466
  return collectDiff(opts);
572467
+ }
572364
572468
  const cap = Math.max(1, opts.maxFiles);
572365
572469
  if (existsSync96(join106(opts.workingDir, ".git"))) {
572366
572470
  try {
@@ -572423,7 +572527,8 @@ async function runBackwardPass(opts) {
572423
572527
  workingDir: opts.workingDir,
572424
572528
  maxFiles,
572425
572529
  mtimeWindowMs,
572426
- explicitFiles: opts.explicitFiles
572530
+ explicitFiles: opts.explicitFiles,
572531
+ explicitFilesOnly: opts.explicitFilesOnly
572427
572532
  });
572428
572533
  const diff = collected.files.map((f2) => {
572429
572534
  const abs = isAbsolute14(f2.path) ? f2.path : join106(opts.workingDir, f2.path);
@@ -578568,8 +578673,11 @@ function isControllerStateMessage(message2) {
578568
578673
  function isActionGroundTruthMessage(message2) {
578569
578674
  return typeof message2.content === "string" && message2.content.includes(ACTION_GROUND_TRUTH_MARKER);
578570
578675
  }
578676
+ function isActiveSteeringMessage(message2) {
578677
+ return typeof message2.content === "string" && message2.content.includes("[ACTIVE USER STEERING]");
578678
+ }
578571
578679
  function isProtectedControllerMessage(message2) {
578572
- return isControllerStateMessage(message2) || isActionGroundTruthMessage(message2);
578680
+ return isControllerStateMessage(message2) || isActionGroundTruthMessage(message2) || isActiveSteeringMessage(message2);
578573
578681
  }
578574
578682
  function modelFacingMessageCap(message2) {
578575
578683
  if (isControllerStateMessage(message2)) {
@@ -578578,6 +578686,9 @@ function modelFacingMessageCap(message2) {
578578
578686
  if (isActionGroundTruthMessage(message2)) {
578579
578687
  return MODEL_FACING_ACTION_GROUND_TRUTH_CHAR_CAP;
578580
578688
  }
578689
+ if (isActiveSteeringMessage(message2)) {
578690
+ return Math.max(MODEL_FACING_ACTION_GROUND_TRUTH_CHAR_CAP, 7e3);
578691
+ }
578581
578692
  if (message2.role === "tool")
578582
578693
  return MODEL_FACING_TOOL_CHAR_CAP;
578583
578694
  if (message2.role === "system")
@@ -578625,7 +578736,7 @@ function applyModelFacingBudget(messages2, preserveFirstSystem) {
578625
578736
  const message2 = messages2[index];
578626
578737
  const content = messageText(message2.content);
578627
578738
  const isReservedTransactionMessage = reservedTransaction.has(index);
578628
- const isPriorityIntent = message2.role === "user" || isCurrentGoalMessage(message2);
578739
+ const isPriorityIntent = message2.role === "user" || isCurrentGoalMessage(message2) || isActiveSteeringMessage(message2);
578629
578740
  const perMessageCap = modelFacingMessageCap(message2);
578630
578741
  const isProtectedController = isProtectedControllerMessage(message2);
578631
578742
  const allowed = isReservedTransactionMessage ? perMessageCap : isPriorityIntent ? content.length : isProtectedController ? perMessageCap : Math.min(remaining, perMessageCap);
@@ -578648,7 +578759,7 @@ function collapseWhitespace(text2) {
578648
578759
  return text2.replace(/\r\n/g, "\n").split("\n").map((line) => line.trimEnd()).join("\n").replace(/\n{3,}/g, "\n\n").trim();
578649
578760
  }
578650
578761
  function sanitizeModelVisibleContextText(text2) {
578651
- let out = String(text2 ?? "");
578762
+ let out = stripNoThinkPromptDirectives(String(text2 ?? ""));
578652
578763
  out = out.replace(RUNTIME_GUIDANCE_RE, (_match, inner) => {
578653
578764
  return `[runtime_guidance]
578654
578765
  ${String(inner ?? "").trim()}`;
@@ -578663,6 +578774,18 @@ ${out}`.trim();
578663
578774
  }
578664
578775
  return collapseWhitespace(out);
578665
578776
  }
578777
+ function stripNoThinkFromMessageContent(content) {
578778
+ if (typeof content === "string")
578779
+ return stripNoThinkPromptDirectives(content);
578780
+ if (!Array.isArray(content))
578781
+ return content;
578782
+ return content.map((part) => {
578783
+ if (!part || typeof part !== "object")
578784
+ return part;
578785
+ const rec = part;
578786
+ return rec["type"] === "text" && typeof rec["text"] === "string" ? { ...rec, text: stripNoThinkPromptDirectives(rec["text"]) } : part;
578787
+ });
578788
+ }
578666
578789
  function messageText(content) {
578667
578790
  if (typeof content === "string")
578668
578791
  return content;
@@ -578836,7 +578959,10 @@ function retireDuplicateToolFailures(messages2) {
578836
578959
  }
578837
578960
  out[index] = {
578838
578961
  ...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."
578962
+ // Keep the protocol message (some providers require every tool call to
578963
+ // retain a response) but make retired duplicate failures token-empty.
578964
+ // The newest result is the sole model-visible recovery record.
578965
+ content: ""
578840
578966
  };
578841
578967
  }
578842
578968
  return out;
@@ -578853,7 +578979,11 @@ function prepareModelFacingApiMessages(input) {
578853
578979
  });
578854
578980
  const independentlyBounded = splitOversizedSystemMessages(withoutLegacyControl);
578855
578981
  for (let index = 0; index < independentlyBounded.length; index++) {
578856
- const message2 = independentlyBounded[index];
578982
+ const rawMessage = independentlyBounded[index];
578983
+ const message2 = {
578984
+ ...rawMessage,
578985
+ content: stripNoThinkFromMessageContent(rawMessage.content)
578986
+ };
578857
578987
  if (message2.role === "system" && typeof message2.content === "string") {
578858
578988
  if (preserveFirstSystem && sanitized.length === 0) {
578859
578989
  sanitized.push({ ...message2 });
@@ -578877,10 +579007,22 @@ function prepareModelFacingApiMessages(input) {
578877
579007
  }
578878
579008
  sanitized.push({ ...message2 });
578879
579009
  }
578880
- const keep = new Array(sanitized.length).fill(true);
579010
+ const activeUserEpoch = sanitized.reduce((latest, message2) => {
579011
+ if (message2.role !== "user")
579012
+ return latest;
579013
+ const epoch = Number(message2["taskEpoch"]);
579014
+ return Number.isInteger(epoch) && epoch >= 0 && (latest === null || epoch > latest) ? epoch : latest;
579015
+ }, null);
579016
+ const epochScoped = activeUserEpoch === null ? sanitized : sanitized.filter((message2) => {
579017
+ if (message2.role !== "user")
579018
+ return true;
579019
+ const epoch = Number(message2["taskEpoch"]);
579020
+ return Number.isInteger(epoch) && epoch === activeUserEpoch;
579021
+ });
579022
+ const keep = new Array(epochScoped.length).fill(true);
578881
579023
  const seenSystemKeys = /* @__PURE__ */ new Set();
578882
- for (let index = sanitized.length - 1; index >= 0; index--) {
578883
- const message2 = sanitized[index];
579024
+ for (let index = epochScoped.length - 1; index >= 0; index--) {
579025
+ const message2 = epochScoped[index];
578884
579026
  if (message2.role !== "system" || typeof message2.content !== "string")
578885
579027
  continue;
578886
579028
  if (preserveFirstSystem && index === 0)
@@ -578894,7 +579036,7 @@ function prepareModelFacingApiMessages(input) {
578894
579036
  }
578895
579037
  seenSystemKeys.add(key);
578896
579038
  }
578897
- const deduped = retireDuplicateToolFailures(sanitized.filter((_message, index) => keep[index]));
579039
+ const deduped = retireDuplicateToolFailures(epochScoped.filter((_message, index) => keep[index]));
578898
579040
  if (!hasUserMessage(deduped) && !hasConcreteGoalMessage(deduped)) {
578899
579041
  const goal = deriveCurrentGoal({
578900
579042
  explicitGoal: input.currentGoal,
@@ -579019,6 +579161,7 @@ var init_context_compiler = __esm({
579019
579161
  "packages/orchestrator/dist/context-compiler.js"() {
579020
579162
  "use strict";
579021
579163
  init_context_fabric();
579164
+ init_textSanitize();
579022
579165
  MODEL_FACING_CONTEXT_CHAR_BUDGET = 48e3;
579023
579166
  MODEL_FACING_TOOL_CHAR_CAP = 6e3;
579024
579167
  MODEL_FACING_SYSTEM_CHAR_CAP = 8e3;
@@ -579026,7 +579169,7 @@ var init_context_compiler = __esm({
579026
579169
  MODEL_FACING_ACTION_GROUND_TRUTH_CHAR_CAP = 5500;
579027
579170
  CONTROLLER_STATE_MARKER = "[CONTROLLER STATE v1]";
579028
579171
  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;
579172
+ 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
579173
  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
579174
  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
579175
  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 +579602,7 @@ function recordContextWindowDump(input) {
579459
579602
  ...input.note ? { note: input.note } : {},
579460
579603
  ...input.focusSupervisor ? { focusSupervisor: compactFocusSupervisor(input.focusSupervisor) } : {},
579461
579604
  metrics: metrics2,
579605
+ contextAccounting: buildContextAccounting(input.request, metrics2),
579462
579606
  apiView: summarizeApiView(input.request, metrics2),
579463
579607
  request: input.request
579464
579608
  };
@@ -579634,6 +579778,60 @@ function analyzeContextWindowDumpRequest(request) {
579634
579778
  }
579635
579779
  };
579636
579780
  }
579781
+ function contextSourceForMessage(role, text2) {
579782
+ if (/\[ACTIVE USER STEERING\]/.test(text2)) {
579783
+ return "active_user_steering";
579784
+ }
579785
+ if (/\[ACTIVE USER INTENT\]|\[CURRENT USER GOAL\]/.test(text2)) {
579786
+ return "current_user_intent";
579787
+ }
579788
+ if (/\[CONTROLLER STATE v1\]|\[RECENT ACTION GROUND TRUTH\]/.test(text2)) {
579789
+ return "current_controller_state";
579790
+ }
579791
+ if (/\[ACTIVE CONTEXT FRAME\]|Evidence already gathered this run/.test(text2)) {
579792
+ return "active_evidence";
579793
+ }
579794
+ if (role === "tool")
579795
+ return "tool_result";
579796
+ if (role === "system")
579797
+ return "system_instruction";
579798
+ if (role === "user")
579799
+ return "user_history";
579800
+ if (role === "assistant")
579801
+ return "assistant_history";
579802
+ return `role:${role}`;
579803
+ }
579804
+ function buildContextAccounting(request, metrics2) {
579805
+ const buckets = /* @__PURE__ */ new Map();
579806
+ const add3 = (source, chars) => {
579807
+ const bucket = buckets.get(source) ?? { messageCount: 0, chars: 0 };
579808
+ bucket.messageCount++;
579809
+ bucket.chars += chars;
579810
+ buckets.set(source, bucket);
579811
+ };
579812
+ const messages2 = Array.isArray(request["messages"]) ? request["messages"] : [];
579813
+ for (const message2 of messages2) {
579814
+ const record = message2 && typeof message2 === "object" ? message2 : {};
579815
+ const role = typeof record["role"] === "string" ? record["role"] : "unknown";
579816
+ const extracted = textAndImagesFromContent(record["content"]);
579817
+ const toolCallChars = Array.isArray(record["tool_calls"]) ? JSON.stringify(record["tool_calls"]).length : 0;
579818
+ add3(contextSourceForMessage(role, extracted.textWithoutImages), extracted.textWithoutImages.length + toolCallChars);
579819
+ }
579820
+ if (metrics2.toolSchemaChars > 0)
579821
+ add3("tool_schema", metrics2.toolSchemaChars);
579822
+ const sources = [...buckets.entries()].map(([source, bucket]) => ({
579823
+ source,
579824
+ ...bucket,
579825
+ estimatedTokens: Math.ceil(bucket.chars / 4)
579826
+ })).sort((a2, b) => a2.source.localeCompare(b.source));
579827
+ return {
579828
+ schemaVersion: 1,
579829
+ totalMessageChars: metrics2.totalChars,
579830
+ toolSchemaChars: metrics2.toolSchemaChars,
579831
+ estimatedTokens: metrics2.estimatedTokens,
579832
+ sources
579833
+ };
579834
+ }
579637
579835
  function summarizeApiView(request, metrics2) {
579638
579836
  const messages2 = Array.isArray(request["messages"]) ? request["messages"] : [];
579639
579837
  const previews = [];
@@ -579721,7 +579919,7 @@ function isRawDiscoveryToolResult(text2) {
579721
579919
  const isDiscovery = DISCOVERY_SOURCE_TOOLS.some((t2) => text2.includes(t2));
579722
579920
  if (!isDiscovery)
579723
579921
  return false;
579724
- return !text2.includes("[DISCOVERY COMPACTED") && !text2.includes("[DISCOVERY BOUNDED") && !text2.includes("[STOP RE-READING") && !text2.includes("[BRANCH-EXTRACT]");
579922
+ return !text2.includes("[DISCOVERY COMPACTED") && !text2.includes("[DISCOVERY BOUNDED") && !text2.includes("[STOP RE-READING") && !/^\[BRANCH-EXTRACT(?:\s+v\d+)?\]/m.test(text2);
579725
579923
  }
579726
579924
  function toSummary(record, path16) {
579727
579925
  const { request: _request, ...summary } = record;
@@ -581453,6 +581651,9 @@ var init_focusSupervisor = __esm({
581453
581651
  }
581454
581652
  this.taskEpoch = next;
581455
581653
  this.state = "observe";
581654
+ this.failureFamilies.clear();
581655
+ this.convergenceFamilyCounts.clear();
581656
+ this.sawMutationSinceFailure = false;
581456
581657
  this.ignoredDirectiveStreak = 0;
581457
581658
  this.lastIgnoredDirectiveTurn = null;
581458
581659
  this.repeatedViolationCounts.clear();
@@ -581746,6 +581947,8 @@ var init_focusSupervisor = __esm({
581746
581947
  }
581747
581948
  observeToolResult(input) {
581748
581949
  this.lastObservedTurn = Math.max(this.lastObservedTurn, input.turn);
581950
+ if (input.taskEpoch !== void 0)
581951
+ this.setTaskEpoch(input.taskEpoch, input.turn);
581749
581952
  this.expireDirectiveIfNeeded(input.turn);
581750
581953
  if (!this.enabled)
581751
581954
  return;
@@ -581767,7 +581970,7 @@ var init_focusSupervisor = __esm({
581767
581970
  if (input.toolName === "shell" && input.success) {
581768
581971
  if (this.convergenceBreaker) {
581769
581972
  const fam = actionFamily(input.toolName, input.args, this.familyCwd);
581770
- this.convergenceBreaker.resolve(fam);
581973
+ this.convergenceBreaker.resolve(`${this.taskEpoch}:${fam}`);
581771
581974
  this.convergenceFamilyCounts.delete(fam);
581772
581975
  }
581773
581976
  if (this.directive?.requiredNextAction === "run_verification") {
@@ -581855,7 +582058,7 @@ var init_focusSupervisor = __esm({
581855
582058
  const convCount = (this.convergenceFamilyCounts.get(convergenceFamily) ?? 0) + 1;
581856
582059
  this.convergenceFamilyCounts.set(convergenceFamily, convCount);
581857
582060
  const verdict = this.convergenceBreaker.observe({
581858
- family: convergenceFamily,
582061
+ family: `${this.taskEpoch}:${convergenceFamily}`,
581859
582062
  sessionCount: convCount,
581860
582063
  turn: input.turn,
581861
582064
  sample: next.sample,
@@ -581882,7 +582085,15 @@ var init_focusSupervisor = __esm({
581882
582085
  ]
581883
582086
  });
581884
582087
  } else if (verdict.tier === "abandon") {
581885
- this.markTerminalIncomplete(verdict.reason, input.turn);
582088
+ this.setDirective({
582089
+ turn: input.turn,
582090
+ state: "forced_replan",
582091
+ reason: verdict.reason,
582092
+ requiredNextAction: this.resolveRequiredNextAction("creative_pivot_or_research"),
582093
+ forbiddenActionFamilies: [
582094
+ actionFamily(input.toolName, input.args, this.familyCwd)
582095
+ ]
582096
+ });
581886
582097
  } else if (verdict.tier === "stalled") {
581887
582098
  this.setDirective({
581888
582099
  turn: input.turn,
@@ -584467,6 +584678,7 @@ function buildBranchExtractionBrief(input) {
584467
584678
  maxWindowsPerRound: 3,
584468
584679
  maxTotalWindows: MAX_WINDOWS,
584469
584680
  maxPresentedLines: MAX_SNIPPET_LINES,
584681
+ maxPresentedChars: MAX_PRESENTED_CHARS,
584470
584682
  maxInjectedChars: 2400
584471
584683
  }
584472
584684
  };
@@ -584806,7 +585018,8 @@ async function extractEvidence(opts) {
584806
585018
  });
584807
585019
  const requiredIds = requirements.filter((requirement) => requirement.required).map((requirement) => requirement.id);
584808
585020
  const deterministicSatisfied = new Set(deterministic.satisfied);
584809
- if (deterministic.segments.length > 0 && requiredIds.every((id2) => deterministicSatisfied.has(id2))) {
585021
+ const deterministicComplete = deterministic.segments.length > 0 && requiredIds.every((id2) => deterministicSatisfied.has(id2));
585022
+ if (deterministicComplete && !backend) {
584810
585023
  const claim = renderSegments(deterministic.segments, maxInjectedChars);
584811
585024
  const legacySpan = legacyContiguousSpan(deterministic.segments);
584812
585025
  return {
@@ -584843,6 +585056,7 @@ async function extractEvidence(opts) {
584843
585056
  const searchRounds = [...deterministic.rounds];
584844
585057
  let remainingWindows = Math.min(MAX_WINDOWS, brief.discoveryContract?.budget.maxTotalWindows ?? MAX_WINDOWS);
584845
585058
  let remainingPresentedLines = Math.min(MAX_SNIPPET_LINES, brief.discoveryContract?.budget.maxPresentedLines ?? MAX_SNIPPET_LINES);
585059
+ let remainingPresentedChars = Math.min(MAX_PRESENTED_CHARS, brief.discoveryContract?.budget.maxPresentedChars ?? MAX_PRESENTED_CHARS);
584846
585060
  if (backend) {
584847
585061
  const maxSemanticRounds = Math.max(0, (brief.discoveryContract?.budget.maxRounds ?? 3) - searchRounds.length);
584848
585062
  for (let attempt = 0; attempt < Math.min(2, maxSemanticRounds); attempt++) {
@@ -584857,10 +585071,13 @@ async function extractEvidence(opts) {
584857
585071
  if (selectedWindows.length >= perRound)
584858
585072
  break;
584859
585073
  const windowLines = window2.end - window2.start + 1;
584860
- if (windowLines > remainingPresentedLines)
585074
+ const windowChars = window2.text.length;
585075
+ if (windowLines > remainingPresentedLines || windowChars > remainingPresentedChars) {
584861
585076
  continue;
585077
+ }
584862
585078
  selectedWindows.push(window2);
584863
585079
  remainingPresentedLines -= windowLines;
585080
+ remainingPresentedChars -= windowChars;
584864
585081
  }
584865
585082
  remainingWindows -= selectedWindows.length;
584866
585083
  const relativeWindows = selectedWindows.map((window2) => ({
@@ -585059,7 +585276,7 @@ function assessBranchRead(input) {
585059
585276
  ...input.requestedRange ? { requestedRange: input.requestedRange } : {}
585060
585277
  };
585061
585278
  }
585062
- var MAX_WINDOWS, SNIPPET_CONTEXT, HEAD_LINES2, MAX_SNIPPET_LINES, EXTRACT_CONFIDENCE_FLOOR, STOPWORDS2, DEFAULT_BRANCH_READ_CONTEXT_FRACTION;
585279
+ var MAX_WINDOWS, SNIPPET_CONTEXT, HEAD_LINES2, MAX_SNIPPET_LINES, MAX_PRESENTED_CHARS, EXTRACT_CONFIDENCE_FLOOR, STOPWORDS2, DEFAULT_BRANCH_READ_CONTEXT_FRACTION;
585063
585280
  var init_evidenceBranch = __esm({
585064
585281
  "packages/orchestrator/dist/evidenceBranch.js"() {
585065
585282
  "use strict";
@@ -585067,6 +585284,7 @@ var init_evidenceBranch = __esm({
585067
585284
  SNIPPET_CONTEXT = 4;
585068
585285
  HEAD_LINES2 = 10;
585069
585286
  MAX_SNIPPET_LINES = 220;
585287
+ MAX_PRESENTED_CHARS = 24e3;
585070
585288
  EXTRACT_CONFIDENCE_FLOOR = 0.3;
585071
585289
  STOPWORDS2 = /* @__PURE__ */ new Set([
585072
585290
  "the",
@@ -587983,34 +588201,6 @@ function stripThinkBlocks(s2) {
587983
588201
  return s2;
587984
588202
  return s2.replace(/<think>[\s\S]*?<\/think>/g, "").trim();
587985
588203
  }
587986
- function injectNoThinkDirective(messages2) {
587987
- if (!Array.isArray(messages2) || messages2.length === 0)
587988
- return messages2;
587989
- let lastUserIdx = -1;
587990
- for (let i2 = messages2.length - 1; i2 >= 0; i2--) {
587991
- if (messages2[i2]?.role === "user") {
587992
- lastUserIdx = i2;
587993
- break;
587994
- }
587995
- }
587996
- if (lastUserIdx === -1)
587997
- return messages2;
587998
- const target = messages2[lastUserIdx];
587999
- if (!target || typeof target.content !== "string")
588000
- return messages2;
588001
- const hasOllamaNoThink = /\/nothink\b/i.test(target.content);
588002
- const hasQwenNoThink = /\/no[_-]think\b/i.test(target.content);
588003
- if (hasOllamaNoThink && hasQwenNoThink)
588004
- return messages2;
588005
- const suffix = [
588006
- hasOllamaNoThink ? null : "/nothink",
588007
- hasQwenNoThink ? null : "/no_think"
588008
- ].filter(Boolean).join("\n");
588009
- const annotated = `${target.content}
588010
-
588011
- ${suffix}`;
588012
- return messages2.map((m2, i2) => i2 === lastUserIdx ? { ...m2, content: annotated } : m2);
588013
- }
588014
588204
  function backendHttpErrorDetail(text2) {
588015
588205
  const trimmed = text2.trimStart();
588016
588206
  const isHtml = trimmed.startsWith("<!") || trimmed.startsWith("<html");
@@ -588082,7 +588272,7 @@ function sanitizeHistoryThink(messages2) {
588082
588272
  if (m2.role === "assistant") {
588083
588273
  content = stripThinkBlocks(content);
588084
588274
  }
588085
- content = content.replace(/\/nothink\b/gi, "").replace(/\/no[_-]think\b/gi, "");
588275
+ content = stripNoThinkPromptDirectives(content);
588086
588276
  if (m2.role === "assistant") {
588087
588277
  const collapsed = collapseDegenerateAssistantRepetition(content);
588088
588278
  content = collapsed ?? content;
@@ -588446,6 +588636,8 @@ var init_agenticRunner = __esm({
588446
588636
  pendingSteeringInputs = [];
588447
588637
  _steeringSequence = 0;
588448
588638
  _taskEpoch = 0;
588639
+ /** First tool-log turn belonging to the active task epoch. */
588640
+ _taskEpochStartTurn = 0;
588449
588641
  _activeRunId = "";
588450
588642
  /** Session storage is retained for compatibility; superseded task leaves are hidden from active guards. */
588451
588643
  _supersededTodoIds = /* @__PURE__ */ new Set();
@@ -588454,6 +588646,10 @@ var init_agenticRunner = __esm({
588454
588646
  /** Abort scope for only the in-flight model/tool turn. Never use for permanent stop. */
588455
588647
  _turnAbortController = new AbortController();
588456
588648
  _pendingSteeringPreemption = null;
588649
+ /** One authoritative, request-protected steering state; never reconstructed from transcript. */
588650
+ _activeSteering = null;
588651
+ /** Logical turn currently making a model/tool decision across both run loops. */
588652
+ _currentSteeringTurn = 0;
588457
588653
  pendingRuntimeGuidanceMessages = [];
588458
588654
  aborted = false;
588459
588655
  _abortController = new AbortController();
@@ -589044,6 +589240,10 @@ var init_agenticRunner = __esm({
589044
589240
  _workboardDir() {
589045
589241
  return this.options.workboardDir || this._workingDirectory || process.cwd();
589046
589242
  }
589243
+ /** One immutable execution run owns every workboard read and mutation. */
589244
+ _workboardRunId() {
589245
+ return this.currentArtifactRunId();
589246
+ }
589047
589247
  _todoWriteAvailable() {
589048
589248
  return this.tools.has("todo_write");
589049
589249
  }
@@ -589065,7 +589265,7 @@ var init_agenticRunner = __esm({
589065
589265
  return this._workboard;
589066
589266
  }
589067
589267
  const dir = this._workboardDir();
589068
- const runId = this.currentArtifactRunId();
589268
+ const runId = this._workboardRunId();
589069
589269
  const existing = loadWorkboardSnapshot(dir, runId);
589070
589270
  if (existing) {
589071
589271
  this._workboard = this._seedWorkboardCardsIfNeeded(existing, goal);
@@ -589082,6 +589282,8 @@ var init_agenticRunner = __esm({
589082
589282
  runId,
589083
589283
  owner: this.options.subAgent ? "sub-agent" : "agent",
589084
589284
  goal: goal || void 0,
589285
+ rawUserIntent: goal || void 0,
589286
+ taskEpoch: this._taskEpoch,
589085
589287
  title: (this._taskState.goal || "").slice(0, 120) || void 0,
589086
589288
  cards: initialCards
589087
589289
  });
@@ -589186,6 +589388,8 @@ var init_agenticRunner = __esm({
589186
589388
  runId,
589187
589389
  owner: actor,
589188
589390
  goal: this._taskState.originalGoal || this._taskState.goal || void 0,
589391
+ rawUserIntent: this._taskState.originalGoal || this._taskState.goal || void 0,
589392
+ taskEpoch: this._taskEpoch,
589189
589393
  title: (this._taskState.goal || diagnosis.workboardTitle).slice(0, 120) || void 0,
589190
589394
  actor,
589191
589395
  cards: [cardInput]
@@ -589244,6 +589448,52 @@ var init_agenticRunner = __esm({
589244
589448
  const safe = todoId.replace(/[^a-zA-Z0-9_.-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80);
589245
589449
  return `todo-${safe || "item"}`;
589246
589450
  }
589451
+ /**
589452
+ * Todo ids are transport identifiers, not task identity. Prefer declared
589453
+ * artifacts, then an explicit verifier, and only then a normalized title so
589454
+ * repeated todo_write calls cannot fork semantic workboard cards.
589455
+ */
589456
+ _todoWorkboardCanonicalKey(todo) {
589457
+ const artifacts = (todo.declaredArtifacts ?? []).filter((path16) => typeof path16 === "string").map((path16) => this._normalizeEvidencePath(path16)).filter(Boolean).sort();
589458
+ if (artifacts.length > 0)
589459
+ return `artifacts:${[...new Set(artifacts)].join("|")}`;
589460
+ const verifier = normalizeShellCommand(String(todo.verifyCommand ?? ""));
589461
+ if (verifier)
589462
+ return `verifier:${verifier}`;
589463
+ 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));
589464
+ return `text:${[...new Set(words)].sort().join("|")}`;
589465
+ }
589466
+ _todoCardsSemanticallyMatch(existing, input) {
589467
+ if (existing.canonicalKey && input.canonicalKey) {
589468
+ return existing.canonicalKey === input.canonicalKey;
589469
+ }
589470
+ const existingVerifier = normalizeShellCommand(existing.verifierCommand ?? "");
589471
+ const inputVerifier = normalizeShellCommand(input.verifierCommand ?? "");
589472
+ if (existingVerifier && inputVerifier)
589473
+ return existingVerifier === inputVerifier;
589474
+ const existingFiles = new Set((existing.ownedFiles ?? []).map((path16) => this._normalizeEvidencePath(path16)));
589475
+ const inputFiles = (input.ownedFiles ?? []).map((path16) => this._normalizeEvidencePath(path16));
589476
+ if (existingFiles.size > 0 && inputFiles.length > 0) {
589477
+ return inputFiles.some((path16) => existingFiles.has(path16));
589478
+ }
589479
+ const words = (value2) => new Set(value2.toLowerCase().replace(/[^a-z0-9]+/g, " ").split(/\s+/).filter((word2) => word2.length > 3));
589480
+ const left = words(`${existing.title} ${existing.description}`);
589481
+ const right = words(`${input.title} ${input.description ?? ""}`);
589482
+ let shared = 0;
589483
+ for (const word2 of left)
589484
+ if (right.has(word2))
589485
+ shared++;
589486
+ return shared >= 5 && shared / Math.max(left.size, right.size, 1) >= 0.62;
589487
+ }
589488
+ _mergeTodoCardInputs(target, incoming) {
589489
+ target.sourceTodoIds = [.../* @__PURE__ */ new Set([...target.sourceTodoIds ?? [], ...incoming.sourceTodoIds ?? []])];
589490
+ target.ownedFiles = [.../* @__PURE__ */ new Set([...target.ownedFiles ?? [], ...incoming.ownedFiles ?? []])];
589491
+ target.evidenceRequirements = [.../* @__PURE__ */ new Set([...target.evidenceRequirements ?? [], ...incoming.evidenceRequirements ?? []])];
589492
+ if (incoming.status === "in_progress") {
589493
+ target.status = "in_progress";
589494
+ target.lane = "worker";
589495
+ }
589496
+ }
589247
589497
  _todoWorkboardCardInput(todo, path16) {
589248
589498
  const requirements = [];
589249
589499
  if (todo.verifyCommand) {
@@ -589268,6 +589518,8 @@ var init_agenticRunner = __esm({
589268
589518
  const status = todo.status === "blocked" ? "blocked" : todo.status === "pending" ? "open" : "in_progress";
589269
589519
  return {
589270
589520
  id: this._todoWorkboardCardId(todo.id),
589521
+ canonicalKey: this._todoWorkboardCanonicalKey(todo),
589522
+ sourceTodoIds: [todo.id],
589271
589523
  title: todo.content.slice(0, 120),
589272
589524
  description: path16.map((item) => item.content).join(" > ").slice(0, 800),
589273
589525
  lane,
@@ -589275,7 +589527,9 @@ var init_agenticRunner = __esm({
589275
589527
  assignee: todo.owner || "any",
589276
589528
  role: "worker",
589277
589529
  evidenceRequired: true,
589278
- evidenceRequirements: requirements
589530
+ evidenceRequirements: requirements,
589531
+ ownedFiles: (todo.declaredArtifacts ?? []).filter((path17) => typeof path17 === "string").map((path17) => this._normalizeEvidencePath(path17)).filter(Boolean),
589532
+ verifierCommand: todo.verifyCommand
589279
589533
  };
589280
589534
  }
589281
589535
  _mirrorTodosToWorkboard(todos) {
@@ -589286,7 +589540,15 @@ var init_agenticRunner = __esm({
589286
589540
  const activeLeaves = this._todoLeaves(normalized, index).filter((todo) => todo.status !== "completed").slice(0, 20);
589287
589541
  if (activeLeaves.length === 0)
589288
589542
  return;
589289
- const cards = activeLeaves.map((todo) => this._todoWorkboardCardInput(todo, this._todoPath(todo, index)));
589543
+ const cards = [];
589544
+ for (const todo of activeLeaves) {
589545
+ const incoming = this._todoWorkboardCardInput(todo, this._todoPath(todo, index));
589546
+ const equivalent = cards.find((card) => this._todoCardsSemanticallyMatch(card, incoming));
589547
+ if (equivalent)
589548
+ this._mergeTodoCardInputs(equivalent, incoming);
589549
+ else
589550
+ cards.push(incoming);
589551
+ }
589290
589552
  const dir = this._workboardDir();
589291
589553
  const runId = this.currentArtifactRunId();
589292
589554
  const actor = this.options.subAgent ? "sub-agent" : "agent";
@@ -589297,6 +589559,8 @@ var init_agenticRunner = __esm({
589297
589559
  runId,
589298
589560
  owner: actor,
589299
589561
  goal: this._taskState.originalGoal || this._taskState.goal || void 0,
589562
+ rawUserIntent: this._taskState.originalGoal || this._taskState.goal || void 0,
589563
+ taskEpoch: this._taskEpoch,
589300
589564
  title: (this._taskState.goal || "Active todo work").slice(0, 120),
589301
589565
  actor,
589302
589566
  cards
@@ -589305,7 +589569,7 @@ var init_agenticRunner = __esm({
589305
589569
  return;
589306
589570
  }
589307
589571
  for (const cardInput of cards) {
589308
- const existing = board.cards.find((card) => card.id === cardInput.id);
589572
+ let existing = board.cards.find((card) => card.id === cardInput.id) ?? board.cards.find((card) => !card.supersededBy && this._todoCardsSemanticallyMatch(card, cardInput));
589309
589573
  if (!existing) {
589310
589574
  board = addWorkboardCard(dir, {
589311
589575
  ...cardInput,
@@ -589315,6 +589579,28 @@ var init_agenticRunner = __esm({
589315
589579
  });
589316
589580
  continue;
589317
589581
  }
589582
+ const duplicates = board.cards.filter((card) => card.id !== existing.id && !card.supersededBy && this._todoCardsSemanticallyMatch(card, cardInput));
589583
+ for (const duplicate of duplicates) {
589584
+ if (duplicate.evidence.length > 0) {
589585
+ attachWorkboardEvidence(dir, {
589586
+ runId,
589587
+ cardId: existing.id,
589588
+ actor,
589589
+ evidence: duplicate.evidence
589590
+ });
589591
+ }
589592
+ board = updateWorkboardCard(dir, {
589593
+ runId,
589594
+ cardId: duplicate.id,
589595
+ actor,
589596
+ updates: {
589597
+ supersededBy: existing.id,
589598
+ blocker: `Superseded by canonical card '${existing.id}'.`
589599
+ },
589600
+ decisionReason: `Merged duplicate todo card into canonical '${existing.id}'.`
589601
+ });
589602
+ existing = board.cards.find((card) => card.id === existing.id) ?? existing;
589603
+ }
589318
589604
  if (existing.status === "verified")
589319
589605
  continue;
589320
589606
  board = updateWorkboardCard(dir, {
@@ -589326,7 +589612,11 @@ var init_agenticRunner = __esm({
589326
589612
  description: cardInput.description,
589327
589613
  lane: cardInput.lane,
589328
589614
  status: existing.status === "completed" ? "needs_changes" : cardInput.status,
589329
- evidenceRequirements: cardInput.evidenceRequirements
589615
+ evidenceRequirements: cardInput.evidenceRequirements,
589616
+ canonicalKey: cardInput.canonicalKey,
589617
+ sourceTodoIds: [.../* @__PURE__ */ new Set([...existing.sourceTodoIds ?? [], ...cardInput.sourceTodoIds ?? []])],
589618
+ ownedFiles: cardInput.ownedFiles,
589619
+ verifierCommand: cardInput.verifierCommand
589330
589620
  },
589331
589621
  decisionReason: "Synchronized workboard card from current todo state."
589332
589622
  });
@@ -589452,12 +589742,12 @@ var init_agenticRunner = __esm({
589452
589742
  injectWorkboardContext() {
589453
589743
  if (this._workboard || this.options.subAgent) {
589454
589744
  const dir = this._workboardDir();
589455
- let snapshot = readActiveWorkboardSnapshot(dir, this._sessionId);
589745
+ let snapshot = readActiveWorkboardSnapshot(dir, this._workboardRunId());
589456
589746
  if (!snapshot)
589457
589747
  return null;
589458
589748
  snapshot = this._seedWorkboardCardsIfNeeded(snapshot, this._taskState.originalGoal || this._taskState.goal || "");
589459
589749
  this._workboard = snapshot;
589460
- const activeCards = snapshot.cards.filter((c9) => c9.status === "in_progress" || c9.status === "open" || c9.status === "needs_changes");
589750
+ const activeCards = snapshot.cards.filter((c9) => !c9.supersededBy && (c9.status === "in_progress" || c9.status === "open" || c9.status === "needs_changes"));
589461
589751
  if (activeCards.length === 0 && snapshot.cards.every((c9) => c9.status === "verified" || c9.status === "completed"))
589462
589752
  return null;
589463
589753
  const synthesis = buildWorkboardSynthesisContext(snapshot);
@@ -589558,7 +589848,7 @@ ${parts.join("\n")}
589558
589848
  _deriveWorkboardActionContract(snapshot) {
589559
589849
  if (snapshot.cards.length === 0)
589560
589850
  return null;
589561
- const byId = new Map(snapshot.cards.map((card) => [card.id, card]));
589851
+ const byId = new Map(snapshot.cards.filter((card) => !card.supersededBy).map((card) => [card.id, card]));
589562
589852
  const discovery = byId.get("discover-current-state");
589563
589853
  const implementation2 = byId.get("implement-repair");
589564
589854
  const integration = byId.get("integrate-and-run");
@@ -589598,7 +589888,7 @@ ${parts.join("\n")}
589598
589888
  ])
589599
589889
  };
589600
589890
  }
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;
589891
+ 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
589892
  if (!active)
589603
589893
  return null;
589604
589894
  return {
@@ -589738,6 +590028,8 @@ ${parts.join("\n")}
589738
590028
  for (const card of snapshot.cards) {
589739
590029
  if (!card.id.startsWith("todo-"))
589740
590030
  continue;
590031
+ if (card.supersededBy)
590032
+ continue;
589741
590033
  if (card.status === "completed" || card.status === "verified")
589742
590034
  continue;
589743
590035
  const text2 = [
@@ -589760,6 +590052,19 @@ ${parts.join("\n")}
589760
590052
  }
589761
590053
  return best?.card ?? null;
589762
590054
  }
590055
+ _workboardTodoCardForVerifier(snapshot, args) {
590056
+ const command = String(args["command"] ?? args["cmd"] ?? "").trim();
590057
+ if (!command)
590058
+ return null;
590059
+ return snapshot.cards.find((card) => {
590060
+ if (!card.id.startsWith("todo-") || card.supersededBy)
590061
+ return false;
590062
+ if (card.status === "completed" || card.status === "verified")
590063
+ return false;
590064
+ const verifier = card.verifierCommand || card.evidenceRequirements.find((item) => item.startsWith("verifyCommand:"))?.replace(/^verifyCommand:\s*/, "") || "";
590065
+ return verifier.length > 0 && commandReliablySatisfiesVerifyCommand(command, verifier);
590066
+ }) ?? null;
590067
+ }
589763
590068
  _workboardTargetCardId(snapshot, toolName, args, result, meta = {}) {
589764
590069
  const byId = new Map(snapshot.cards.map((card) => [card.id, card]));
589765
590070
  const targetPaths = this._extractToolTargetPaths(toolName, args, result);
@@ -589771,6 +590076,9 @@ ${parts.join("\n")}
589771
590076
  return matchingTodo?.id ?? (byId.has("implement-repair") ? "implement-repair" : null);
589772
590077
  }
589773
590078
  if (toolName === "shell" || toolName === "background_run") {
590079
+ const verifierTodo = this._workboardTodoCardForVerifier(snapshot, args);
590080
+ if (verifierTodo)
590081
+ return verifierTodo.id;
589774
590082
  const implementation2 = byId.get("implement-repair");
589775
590083
  const target = this._workboardHasEditEvidence(implementation2) ? "integrate-and-run" : "discover-current-state";
589776
590084
  return byId.has(target) ? target : null;
@@ -589784,7 +590092,7 @@ ${parts.join("\n")}
589784
590092
  return active?.id ?? null;
589785
590093
  }
589786
590094
  _refreshWorkboardSnapshot(snapshot) {
589787
- const refreshed = readActiveWorkboardSnapshot(this._workboardDir(), this._sessionId) ?? snapshot;
590095
+ const refreshed = readActiveWorkboardSnapshot(this._workboardDir(), this._workboardRunId()) ?? snapshot;
589788
590096
  this._workboard = refreshed;
589789
590097
  return refreshed;
589790
590098
  }
@@ -589855,7 +590163,7 @@ ${parts.join("\n")}
589855
590163
  * Non-fatal: failures to attach evidence are silently caught.
589856
590164
  */
589857
590165
  recordWorkboardToolCall(toolName, args, success, output, result, meta = {}) {
589858
- const board = this._workboard ?? this.getOrCreateWorkboard();
590166
+ const board = this._currentWorkboardSnapshotForFrame() ?? this.getOrCreateWorkboard();
589859
590167
  if (!board)
589860
590168
  return;
589861
590169
  if (toolName === "task_complete" || toolName === "workboard_create")
@@ -589891,13 +590199,26 @@ ${parts.join("\n")}
589891
590199
  if (targetCard.assignee && targetCard.assignee !== actor && targetCard.assignee !== "any") {
589892
590200
  return;
589893
590201
  }
589894
- attachWorkboardEvidence(dir, {
590202
+ const evidenced = attachWorkboardEvidence(dir, {
589895
590203
  runId: this.currentArtifactRunId(),
589896
590204
  cardId: targetCard.id,
589897
590205
  actor,
589898
590206
  evidence
589899
590207
  });
589900
- this._refreshWorkboardSnapshot(advanced);
590208
+ const persistedEvidence = evidenced.cards.find((card) => card.id === targetCard.id)?.evidence.find((item) => item.summary === evidence.summary && item.content === evidence.content);
590209
+ const substantive = success === true && result?.runtimeAuthored !== true;
590210
+ this._workboard = updateWorkboardMetadata(dir, {
590211
+ runId: this.currentArtifactRunId(),
590212
+ actor,
590213
+ taskEpoch: this._taskEpoch,
590214
+ artifactEvidence: persistedEvidence ? [persistedEvidence] : [evidence],
590215
+ lastSubstantiveProgress: substantive ? {
590216
+ turn: this._taskState.toolCallCount,
590217
+ signature: this._buildToolFingerprint(toolName, args),
590218
+ evidenceIds: persistedEvidence ? [persistedEvidence.id] : [],
590219
+ occurredAt: (/* @__PURE__ */ new Date()).toISOString()
590220
+ } : void 0
590221
+ });
589901
590222
  } catch {
589902
590223
  }
589903
590224
  }
@@ -590362,7 +590683,12 @@ ${parts.join("\n")}
590362
590683
  try {
590363
590684
  const dir = _pathJoin(this.omniusStateDir(), "completion-ledgers");
590364
590685
  _fsMkdirSync(dir, { recursive: true });
590365
- saveCompletionLedger(_pathJoin(dir, `${this._sessionId}.json`), this._completionLedger);
590686
+ saveCompletionLedger(
590687
+ // A session can contain several steering epochs. Persist by immutable
590688
+ // artifact run so recovery never hydrates evidence from a retired goal.
590689
+ _pathJoin(dir, `${this.currentArtifactRunId()}.json`),
590690
+ this._completionLedger
590691
+ );
590366
590692
  } catch {
590367
590693
  }
590368
590694
  }
@@ -590807,7 +591133,20 @@ Your hypotheses MUST address this specific error, not generic causes.
590807
591133
  messages: messages2,
590808
591134
  currentGoal: this._taskState.originalGoal || this._taskState.goal || this._taskState.currentStep || this._taskState.nextAction || ""
590809
591135
  });
590810
- return sanitizeHistoryThink(prepared);
591136
+ const withCurrentUserIntent = sanitizeHistoryThink(prepared);
591137
+ if (!withCurrentUserIntent.some((message2) => message2.role === "user")) {
591138
+ const currentIntent = this._taskState.originalGoal || this._taskState.goal || this._taskState.currentStep || this._taskState.nextAction || "";
591139
+ if (currentIntent.trim()) {
591140
+ const insertAt = withCurrentUserIntent[0]?.role === "system" ? 1 : 0;
591141
+ withCurrentUserIntent.splice(insertAt, 0, {
591142
+ role: "user",
591143
+ content: `[ACTIVE USER INTENT]
591144
+ ${currentIntent.trim().slice(0, 6e3)}`,
591145
+ taskEpoch: this._taskEpoch
591146
+ });
591147
+ }
591148
+ }
591149
+ return withCurrentUserIntent;
590811
591150
  }
590812
591151
  // ── Failing-approach detector (the "stop retrying variants" reflex) ───────
590813
591152
  // Encodes the behavior an effective agent uses and the dropbear 27× loop
@@ -590875,7 +591214,7 @@ Your hypotheses MUST address this specific error, not generic causes.
590875
591214
  stage: opts?.dumpStage ?? "aux_inference",
590876
591215
  agentType: "internal",
590877
591216
  sessionId: this._sessionId,
590878
- runId: this.currentArtifactRunId(),
591217
+ runId: this._workboardRunId(),
590879
591218
  model: this._backendModelLabel(this.backend),
590880
591219
  cwd: this._workingDirectory || process.cwd(),
590881
591220
  request: r2
@@ -591769,6 +592108,13 @@ ${extras.join("\n")}`;
591769
592108
  existingCards
591770
592109
  }) : existingCards;
591771
592110
  const delta = diffDiagnosticSets(previousDiagnostics, diagnostics);
592111
+ const verifierActionSignature = normalizeShellCommand(verifierCommand);
592112
+ const verifierResultSignature = [
592113
+ input.success ? "success" : "failure",
592114
+ ...diagnostics.map((diagnostic) => diagnostic.fingerprint).sort()
592115
+ ].join("|");
592116
+ const unchangedVerifierRound = this._compileFixLoop?.verifierActionSignature === verifierActionSignature && this._compileFixLoop?.verifierResultSignature === verifierResultSignature;
592117
+ const verifierStasisCount = unchangedVerifierRound ? (this._compileFixLoop?.verifierStasisCount ?? 0) + 1 : 0;
591772
592118
  const nextCards = this._mergeCompileFixCardsAfterVerifier({
591773
592119
  existingCards,
591774
592120
  observedCards: cards,
@@ -591788,8 +592134,21 @@ ${extras.join("\n")}`;
591788
592134
  cards: nextCards,
591789
592135
  // A live verifier run resolves the gate's demand — the block streak
591790
592136
  // is over regardless of pass/fail.
591791
- preflightBlockStreak: 0
591792
- };
592137
+ preflightBlockStreak: 0,
592138
+ verifierActionSignature,
592139
+ verifierResultSignature,
592140
+ verifierStasisCount,
592141
+ verifierStasisBlocked: verifierStasisCount >= 3 && !(input.success && diagnostics.length === 0),
592142
+ prerequisiteRecoverySignature: void 0
592143
+ };
592144
+ if (this._compileFixLoop.verifierStasisBlocked) {
592145
+ this.emit({
592146
+ type: "status",
592147
+ 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`,
592148
+ turn: input.turn,
592149
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
592150
+ });
592151
+ }
591793
592152
  this._mirrorCompileFixCardsToWorkboard(nextCards, {
591794
592153
  command: verifierCommand,
591795
592154
  success: input.success && diagnostics.length === 0,
@@ -591918,7 +592277,7 @@ ${extras.join("\n")}`;
591918
592277
  const dir = this._workboardDir();
591919
592278
  const actor = this.options.subAgent ? "sub-agent" : "agent";
591920
592279
  for (const card of cards) {
591921
- const existing = (readActiveWorkboardSnapshot(dir, this._sessionId) ?? this._workboard)?.cards.find((item) => item.id === card.id);
592280
+ const existing = (readActiveWorkboardSnapshot(dir, this._workboardRunId()) ?? this._workboard)?.cards.find((item) => item.id === card.id);
591922
592281
  if (!existing) {
591923
592282
  this._workboard = addWorkboardCard(dir, {
591924
592283
  ...compileFixCardToWorkboardInput(card),
@@ -591967,7 +592326,7 @@ ${extras.join("\n")}`;
591967
592326
  }
591968
592327
  });
591969
592328
  if (card.status === "dismissed" || card.status === "verified") {
591970
- const active = readActiveWorkboardSnapshot(dir, this._sessionId);
592329
+ const active = readActiveWorkboardSnapshot(dir, this._workboardRunId());
591971
592330
  const wbCard = active?.cards.find((item) => item.id === card.id);
591972
592331
  if (wbCard && wbCard.status !== "completed" && wbCard.status !== "verified") {
591973
592332
  this._workboard = completeWorkboardCard(dir, {
@@ -591979,7 +592338,7 @@ ${extras.join("\n")}`;
591979
592338
  }).snapshot;
591980
592339
  }
591981
592340
  if (card.status === "verified") {
591982
- const latest = readActiveWorkboardSnapshot(dir, this._sessionId);
592341
+ const latest = readActiveWorkboardSnapshot(dir, this._workboardRunId());
591983
592342
  const latestCard = latest?.cards.find((item) => item.id === card.id);
591984
592343
  if (latestCard?.status === "completed") {
591985
592344
  this._workboard = completeWorkboardCard(dir, {
@@ -591999,7 +592358,7 @@ ${extras.join("\n")}`;
591999
592358
  _mirrorCompileFixCardAssigned(card, turn) {
592000
592359
  try {
592001
592360
  const dir = this._workboardDir();
592002
- const active = readActiveWorkboardSnapshot(dir, this._sessionId);
592361
+ const active = readActiveWorkboardSnapshot(dir, this._workboardRunId());
592003
592362
  const existing = active?.cards.find((item) => item.id === card.id);
592004
592363
  if (!existing || existing.status !== "open")
592005
592364
  return;
@@ -592028,6 +592387,9 @@ ${extras.join("\n")}`;
592028
592387
  state.verifierDirtySinceTurn = turn;
592029
592388
  state.lastVerifierPassedTurn = null;
592030
592389
  state.lastMutationTurn = turn;
592390
+ state.verifierStasisCount = 0;
592391
+ state.verifierStasisBlocked = false;
592392
+ state.prerequisiteRecoverySignature = void 0;
592031
592393
  this._focusSupervisor?.markCompletionBlocked({
592032
592394
  turn,
592033
592395
  reason: "A source mutation invalidated the declared verifier; verifier evidence now owns the active focus.",
@@ -592077,68 +592439,67 @@ ${extras.join("\n")}`;
592077
592439
  if (!state?.active)
592078
592440
  return null;
592079
592441
  const action = compileFixLoopNextRequiredAction(state);
592080
- if (action !== "run_declared_verifier")
592442
+ const verifierLocked = action === "run_declared_verifier" || state.verifierStasisBlocked === true;
592443
+ if (!verifierLocked)
592081
592444
  return null;
592445
+ const blocked = (reason) => {
592446
+ const streak = (state.preflightBlockStreak ?? 0) + 1;
592447
+ state.preflightBlockStreak = streak;
592448
+ return {
592449
+ kind: "block",
592450
+ message: [
592451
+ `[COMPILE ERROR FIX LOOP BLOCKED — verifier action locked]`,
592452
+ reason,
592453
+ `declared_verifier=${state.verifierCommand}`,
592454
+ `dirtySinceTurn=${state.verifierDirtySinceTurn}`,
592455
+ `lastVerifierRunTurn=${state.lastVerifierRunTurn}`,
592456
+ `stasisRounds=${state.verifierStasisCount ?? 0}`,
592457
+ `blockedTool=${toolName} consecutiveBlocks=${streak}`,
592458
+ `Allowed next actions: the declared verifier; one narrow prerequisite read of an owned file; or a scoped source fix that changes verifier inputs.`
592459
+ ].join("\n")
592460
+ };
592461
+ };
592082
592462
  if (toolName === "shell") {
592083
592463
  const command = String(args["command"] ?? args["cmd"] ?? "").trim();
592084
592464
  if (commandReliablySatisfiesVerifyCommand(command, state.verifierCommand)) {
592465
+ if (state.verifierStasisBlocked) {
592466
+ return blocked("The same verifier action/result is in stasis. Change the owned source or obtain fresh prerequisite evidence before rerunning this unchanged verifier.");
592467
+ }
592085
592468
  state.preflightBlockStreak = 0;
592086
592469
  return null;
592087
592470
  }
592088
- if (!shellLikelyMutatesFilesystem) {
592471
+ void shellLikelyMutatesFilesystem;
592472
+ return blocked("Only the declared verifier shell command is admitted while verifier evidence is locked.");
592473
+ }
592474
+ const readLike = /* @__PURE__ */ new Set([
592475
+ "file_read",
592476
+ "grep_search",
592477
+ "find_files",
592478
+ "list_directory",
592479
+ "file_explore"
592480
+ ]);
592481
+ if (readLike.has(toolName)) {
592482
+ const target = String(args["path"] ?? args["file"] ?? args["file_path"] ?? "");
592483
+ const owned = state.cards.flatMap((card) => card.ownedFiles);
592484
+ const scoped = target.length > 0 && owned.some((path16) => this._pathsOverlapForVerifier(target, path16));
592485
+ const signature = `${toolName}:${this._buildExactArgsKey(args)}`;
592486
+ if (scoped && state.prerequisiteRecoverySignature !== signature) {
592487
+ state.prerequisiteRecoverySignature = signature;
592488
+ state.preflightBlockStreak = 0;
592089
592489
  return null;
592090
592490
  }
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)) {
592491
+ 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.");
592492
+ }
592493
+ if (this._isProjectEditTool(toolName)) {
592494
+ const targetPaths = this._extractToolTargetPaths(toolName, args);
592495
+ const scoped = targetPaths.some((path16) => this._compileFixPathsTouchProjectSources([this._normalizeEvidencePath(path16)], state));
592496
+ if (scoped) {
592497
+ state.preflightBlockStreak = 0;
592096
592498
  return null;
592097
592499
  }
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
- };
592500
+ return blocked("A repair mutation must target a file owned by the active compile-fix card.");
592122
592501
  }
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 };
592502
+ return blocked("This tool is unrelated to the locked verifier action.");
592142
592503
  }
592143
592504
  _compileFixLoopCompletionBlocker(turn) {
592144
592505
  const state = this._compileFixLoop;
@@ -593350,8 +593711,8 @@ ${_checks}`
593350
593711
  return { proceed: true };
593351
593712
  const maxCycles = parseInt(process.env["OMNIUS_BACKWARD_PASS_MAX_CYCLES"] || "2", 10) || 2;
593352
593713
  if (this._backwardPassCyclesUsed >= maxCycles) {
593353
- const lastCritique2 = this._lastBackwardPassCritique;
593354
- const evidenceAfterCritique = lastCritique2 ? toolCallLog.slice(lastCritique2.toolLogLength) : [];
593714
+ const lastCritique = this._lastBackwardPassCritique;
593715
+ const evidenceAfterCritique = lastCritique ? toolCallLog.slice(lastCritique.toolLogLength) : [];
593355
593716
  const freshVerification = evidenceAfterCritique.filter((entry) => {
593356
593717
  if (entry.success !== true)
593357
593718
  return false;
@@ -593361,7 +593722,7 @@ ${_checks}`
593361
593722
  const concern = freshVerification.length > 0 ? [
593362
593723
  "Prior reviewer concern may be stale; fresh verification evidence was recorded after that critique.",
593363
593724
  ...freshVerification.map((entry) => `${entry.name}: ${(entry.outputPreview ?? entry.argsKey).slice(0, 220)}`)
593364
- ].join(" ") : lastCritique2?.rationale?.trim() || this._lastBackwardPassVerdict || "unspecified";
593725
+ ].join(" ") : lastCritique?.rationale?.trim() || this._lastBackwardPassVerdict || "unspecified";
593365
593726
  this._completionCaveat = [
593366
593727
  `[COMPLETION CAVEAT] Backward-pass review did not fully approve after ${this._backwardPassCyclesUsed}/${maxCycles} cycle(s).`,
593367
593728
  `${freshVerification.length > 0 ? "Reviewer reconciliation note" : "Unresolved reviewer concern"}: ${concern.slice(0, 600)}`,
@@ -593413,7 +593774,7 @@ ${_checks}`
593413
593774
  });
593414
593775
  }
593415
593776
  };
593416
- const todos = (() => {
593777
+ const allTodos = (() => {
593417
593778
  try {
593418
593779
  const _t = this.readSessionTodos();
593419
593780
  return Array.isArray(_t) ? _t : [];
@@ -593421,17 +593782,15 @@ ${_checks}`
593421
593782
  return [];
593422
593783
  }
593423
593784
  })();
593785
+ const todos = allTodos.filter((todo) => !this._supersededTodoIds.has(todo.id));
593424
593786
  const wd = this._workingDirectory || process.cwd();
593425
593787
  let reconciled = [];
593426
593788
  try {
593427
593789
  reconciled = reconcilePlan(todos, [], { workingDir: wd });
593428
593790
  } catch {
593429
593791
  }
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);
593792
+ const recentFailures = [];
593793
+ const activeEpochToolLog = toolCallLog.filter((entry) => typeof entry.turn === "number" && entry.turn >= this._taskEpochStartTurn);
593435
593794
  const toCriticEvidence = (entries, limit) => entries.filter((entry) => entry.name !== "task_complete").slice(-limit).map((entry) => ({
593436
593795
  name: entry.name,
593437
593796
  argsKey: entry.argsKey.slice(0, 300),
@@ -593440,9 +593799,7 @@ ${_checks}`
593440
593799
  turn: entry.turn,
593441
593800
  mutated: entry.mutated === true
593442
593801
  }));
593443
- const criticToolEvidence = toCriticEvidence(toolCallLog, 40);
593444
- const lastCritique = this._lastBackwardPassCritique;
593445
- const evidenceSincePriorCritique = lastCritique ? toCriticEvidence(toolCallLog.slice(lastCritique.toolLogLength), 20) : [];
593802
+ const criticToolEvidence = toCriticEvidence(activeEpochToolLog, 40);
593446
593803
  const completionContract = this._completionContractForClaims(proposedSummary);
593447
593804
  const openLoops = [
593448
593805
  ...todos.filter((todo) => todo.status !== "completed" && todo.status !== "blocked").slice(0, 12).map((todo) => `todo still ${todo.status}: ${todo.content}`),
@@ -593451,7 +593808,7 @@ ${_checks}`
593451
593808
  const modifiedFileDigest = (() => {
593452
593809
  const seen = /* @__PURE__ */ new Set();
593453
593810
  const files = [];
593454
- for (const entry of toolCallLog) {
593811
+ for (const entry of activeEpochToolLog) {
593455
593812
  if (!Array.isArray(entry.mutatedFiles))
593456
593813
  continue;
593457
593814
  for (const filePath of entry.mutatedFiles) {
@@ -593492,20 +593849,13 @@ ${_checks}`
593492
593849
  ].join("\n\n");
593493
593850
  }
593494
593851
  }
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;
593852
+ const reviewReconciliation = void 0;
593853
+ const activeWorkboard = this._currentWorkboardSnapshotForFrame();
593504
593854
  let result;
593505
593855
  try {
593506
593856
  result = await runBackwardPass({
593507
593857
  workingDir: wd,
593508
- goal: this._taskState.originalGoal || this._taskState.goal || "",
593858
+ goal: this._taskState.goal || this._taskState.originalGoal || "",
593509
593859
  planStatus: reconciled.map((t2) => ({
593510
593860
  id: t2.id,
593511
593861
  content: t2.content,
@@ -593518,9 +593868,9 @@ ${_checks}`
593518
593868
  completionScenarioDecomposition: _ledgerScenarioDecomposition,
593519
593869
  reviewReconciliation,
593520
593870
  openLoops,
593521
- workboardSynthesisContext: this._workboard ? (() => {
593871
+ workboardSynthesisContext: activeWorkboard ? (() => {
593522
593872
  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;
593873
+ 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
593874
  } catch {
593525
593875
  return void 0;
593526
593876
  }
@@ -593529,35 +593879,23 @@ ${_checks}`
593529
593879
  maxFiles: parseInt(process.env["OMNIUS_BACKWARD_PASS_MAX_FILES"] || "60", 10) || 60,
593530
593880
  maxFilePreviewBytes: parseInt(process.env["OMNIUS_BACKWARD_PASS_MAX_FILE_PREVIEW"] || "8000", 10) || 8e3,
593531
593881
  explicitFiles: modifiedFileDigest.length > 0 ? modifiedFileDigest.map((file) => file.path) : void 0,
593882
+ explicitFilesOnly: true,
593532
593883
  cycle: this._backwardPassCyclesUsed,
593533
593884
  maxCycles
593534
593885
  });
593535
593886
  } catch (e2) {
593536
593887
  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);
593888
+ this._completionCaveat = [
593889
+ this._completionCaveat || "",
593890
+ `[BACKWARD-PASS ADVISORY] ${reason}`,
593891
+ "Completion authority remains with deterministic verifier and current completion-ledger evidence."
593892
+ ].filter(Boolean).join("\n");
593552
593893
  this.emit({
593553
593894
  type: "status",
593554
- content: `REG-47 backward-pass runner threw: ${e2 instanceof Error ? e2.message : String(e2)}. Ending as incomplete_verification instead of completing.`,
593895
+ content: `Backward-pass review unavailable; preserved as advisory telemetry: ${reason}`,
593555
593896
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
593556
593897
  });
593557
- return {
593558
- proceed: false,
593559
- feedback: "Backward-pass review failed before completion could be verified. Report incomplete_verification rather than claiming success."
593560
- };
593898
+ return { proceed: true, feedback: this._completionCaveat };
593561
593899
  }
593562
593900
  this._backwardPassCyclesUsed++;
593563
593901
  this._lastBackwardPassVerdict = result.verdict.verdict;
@@ -593579,7 +593917,15 @@ ${_checks}`
593579
593917
  return { proceed: true };
593580
593918
  }
593581
593919
  const feedback = result.feedbackMessage;
593582
- if (this._completionLedger) {
593920
+ const currentArtifactPaths = modifiedFileDigest.map((file) => file.path.replace(/\\/g, "/").replace(/^\.\//, "").toLowerCase());
593921
+ const criticReferencesCurrentArtifact = result.verdict.issues.some((issue) => {
593922
+ const issueText = [issue.file, issue.problem, issue.suggested_fix].filter((value2) => typeof value2 === "string").join(" ").replace(/\\/g, "/").toLowerCase();
593923
+ return currentArtifactPaths.some((path16) => {
593924
+ const basename46 = path16.slice(path16.lastIndexOf("/") + 1);
593925
+ return issueText.includes(path16) || basename46.length > 0 && issueText.includes(basename46);
593926
+ });
593927
+ });
593928
+ if (this._completionLedger && criticReferencesCurrentArtifact) {
593583
593929
  this._completionLedger = recordCompletionCritique(this._completionLedger, {
593584
593930
  verdict: result.verdict.verdict === "blocked" ? "blocked" : "request_changes",
593585
593931
  rationale: result.verdict.rationale,
@@ -593587,16 +593933,18 @@ ${_checks}`
593587
593933
  });
593588
593934
  this._saveCompletionLedgerSafe();
593589
593935
  }
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") {
593936
+ if (criticReferencesCurrentArtifact) {
593937
+ this._lastBackwardPassCritique = {
593938
+ verdict: result.verdict.verdict,
593939
+ rationale: result.verdict.rationale,
593940
+ feedback,
593941
+ completionSummary: proposedSummary,
593942
+ cycle: this._backwardPassCyclesUsed,
593943
+ toolLogLength: toolCallLog.length,
593944
+ recordedAtIso: (/* @__PURE__ */ new Date()).toISOString()
593945
+ };
593946
+ }
593947
+ if (result.verdict.verdict === "blocked" && criticReferencesCurrentArtifact) {
593600
593948
  const reason = `backward-pass critic blocked completion: ${result.verdict.rationale.slice(0, 240)}`;
593601
593949
  this._completionIncompleteVerification = {
593602
593950
  reason,
@@ -593619,6 +593967,19 @@ ${_checks}`
593619
593967
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
593620
593968
  });
593621
593969
  }
593970
+ if (!criticReferencesCurrentArtifact) {
593971
+ this._completionCaveat = [
593972
+ this._completionCaveat || "",
593973
+ `[BACKWARD-PASS ADVISORY] ${result.verdict.verdict}: ${result.verdict.rationale.slice(0, 600)}`,
593974
+ "The critic named no current-epoch artifact; current verifier and completion-ledger evidence remain authoritative."
593975
+ ].filter(Boolean).join("\n");
593976
+ this.emit({
593977
+ type: "status",
593978
+ content: `Backward-pass ${result.verdict.verdict} retained as advisory: no current artifact was referenced.`,
593979
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
593980
+ });
593981
+ return { proceed: true, feedback: this._completionCaveat };
593982
+ }
593622
593983
  return { proceed: false, feedback };
593623
593984
  }
593624
593985
  /**
@@ -596198,6 +596559,20 @@ ${blob}
596198
596559
  if (covered)
596199
596560
  return cov.fingerprint;
596200
596561
  }
596562
+ if (!iv.whole && Number.isFinite(iv.end)) {
596563
+ let best = null;
596564
+ const requestedLength = Math.max(1, iv.end - iv.start + 1);
596565
+ for (const cov of intervals) {
596566
+ if (cov.whole || !Number.isFinite(cov.end))
596567
+ continue;
596568
+ const overlap = Math.max(0, Math.min(iv.end, cov.end) - Math.max(iv.start, cov.start) + 1);
596569
+ if (overlap / requestedLength >= 0.8 && (!best || overlap > best.overlap)) {
596570
+ best = { fingerprint: cov.fingerprint, overlap };
596571
+ }
596572
+ }
596573
+ if (best)
596574
+ return best.fingerprint;
596575
+ }
596201
596576
  return exactFingerprint;
596202
596577
  }
596203
596578
  /** Register a read's region under the fingerprint that cached its result. */
@@ -596839,7 +597214,7 @@ Rewrite it now for ${ctx3.model}.`;
596839
597214
  inlineTokens: 0,
596840
597215
  reservations: /* @__PURE__ */ new Map()
596841
597216
  };
596842
- const preempted = await this._preemptFileReadWithBranch({
597217
+ const extracted = await this._extractFileReadEvidence({
596843
597218
  callId,
596844
597219
  toolName: resolved.name,
596845
597220
  args,
@@ -596847,8 +597222,8 @@ Rewrite it now for ${ctx3.model}.`;
596847
597222
  turn: this._taskState.toolCallCount,
596848
597223
  batchBudget
596849
597224
  });
596850
- if (preempted)
596851
- return preempted;
597225
+ if (extracted)
597226
+ return extracted;
596852
597227
  let result = await tool.execute(args);
596853
597228
  result = await this._guardMaterializedFileReadResult({
596854
597229
  callId,
@@ -596902,7 +597277,7 @@ ${notice}`;
596902
597277
  content,
596903
597278
  source: "legacy-injectUserMessage",
596904
597279
  receivedAt: (/* @__PURE__ */ new Date()).toISOString(),
596905
- intent: "append",
597280
+ intent: classifySteeringIntent(content, "append"),
596906
597281
  state: "received",
596907
597282
  taskEpoch: this._taskEpoch || void 0
596908
597283
  });
@@ -596921,6 +597296,7 @@ ${notice}`;
596921
597296
  content,
596922
597297
  source: input.source || "unknown",
596923
597298
  receivedAt: input.receivedAt || now2,
597299
+ intent: classifySteeringIntent(content, input.intent),
596924
597300
  state: "received",
596925
597301
  taskEpoch: input.taskEpoch ?? (this._taskEpoch || void 0)
596926
597302
  };
@@ -596931,15 +597307,43 @@ ${notice}`;
596931
597307
  this._emitSteeringLifecycle(record, "empty steering input rejected");
596932
597308
  return this._steeringReceipt(record);
596933
597309
  }
596934
- this.pendingUserMessages.push(content);
596935
597310
  record.state = "queued";
596936
597311
  this._emitSteeringLifecycle(record, "queued for next safe turn boundary");
597312
+ if (steeringGatesOldPlan(record.intent)) {
597313
+ this._activeSteering = {
597314
+ input: record,
597315
+ appliedTurn: this._currentSteeringTurn,
597316
+ requiresReconciliation: true,
597317
+ gatesOldPlan: true,
597318
+ visibleRequestTurns: []
597319
+ };
597320
+ }
596937
597321
  if (record.intent === "redirect" || record.intent === "replace" || record.intent === "cancel") {
596938
597322
  this._requestSteeringPreemption(record);
596939
597323
  }
596940
597324
  this._trajectoryDirtyCauses.add("user_steering");
596941
597325
  return this._steeringReceipt(record);
596942
597326
  }
597327
+ /**
597328
+ * Request safe-boundary preemption for an already accepted typed input.
597329
+ * Frontends use this after delivery so cancellation reaches an in-flight
597330
+ * request without fabricating a second, disconnected runner.
597331
+ */
597332
+ requestSteeringPreemption(inputId) {
597333
+ const normalizedInputId = inputId.trim();
597334
+ if (!normalizedInputId)
597335
+ return null;
597336
+ const record = this.pendingSteeringInputs.find((candidate) => candidate.inputId === normalizedInputId);
597337
+ if (!record)
597338
+ return null;
597339
+ if (record.intent !== "redirect" && record.intent !== "replace" && record.intent !== "cancel") {
597340
+ return null;
597341
+ }
597342
+ if (this._pendingSteeringPreemption?.inputId !== record.inputId) {
597343
+ this._requestSteeringPreemption(record);
597344
+ }
597345
+ return this._steeringReceipt(record);
597346
+ }
596943
597347
  /** Inject bounded runtime guidance without treating it as user steering. */
596944
597348
  injectRuntimeGuidance(content) {
596945
597349
  this.enqueueRuntimeGuidance(content);
@@ -596962,18 +597366,15 @@ ${notice}`;
596962
597366
  /** Retract the last pending user message (Esc cancel).
596963
597367
  * Returns the retracted text, or null if queue is empty or already consumed. */
596964
597368
  retractLastPendingMessage() {
596965
- if (this.pendingUserMessages.length === 0)
597369
+ const record = [...this.pendingSteeringInputs].reverse().find((candidate) => candidate.state === "queued" || candidate.state === "acknowledged");
597370
+ if (!record)
596966
597371
  return null;
596967
- const content = this.pendingUserMessages.pop();
596968
- const record = [...this.pendingSteeringInputs].reverse().find((candidate) => candidate.content === content && (candidate.state === "queued" || candidate.state === "acknowledged"));
596969
- if (record) {
596970
- record.state = "cancelled";
596971
- if (this._pendingSteeringPreemption?.inputId === record.inputId) {
596972
- this._pendingSteeringPreemption = null;
596973
- }
596974
- this._emitSteeringLifecycle(record, "retracted before consumption");
597372
+ record.state = "cancelled";
597373
+ if (this._pendingSteeringPreemption?.inputId === record.inputId) {
597374
+ this._pendingSteeringPreemption = null;
596975
597375
  }
596976
- return content;
597376
+ this._emitSteeringLifecycle(record, "retracted before admission at a safe boundary");
597377
+ return record.content;
596977
597378
  }
596978
597379
  /** Abort the current task run — cancels in-flight requests and kills child processes */
596979
597380
  abort() {
@@ -597036,6 +597437,16 @@ ${notice}`;
597036
597437
  steering: receipt,
597037
597438
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
597038
597439
  });
597440
+ this._onTypedEvent?.({
597441
+ type: "steering_lifecycle",
597442
+ runId: this.currentArtifactRunId(),
597443
+ inputId: record.inputId,
597444
+ intent: record.intent,
597445
+ state: record.state,
597446
+ taskEpoch: record.taskEpoch,
597447
+ summary: reason,
597448
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
597449
+ });
597039
597450
  appendSteeringLedgerEntry(this._workingDirectory || process.cwd(), {
597040
597451
  type: "lifecycle",
597041
597452
  packetId: record.inputId,
@@ -597070,9 +597481,6 @@ ${notice}`;
597070
597481
  if (record.taskEpoch && record.taskEpoch !== this._taskEpoch) {
597071
597482
  record.state = "superseded";
597072
597483
  this._emitSteeringLifecycle(record, "superseded by a later task run");
597073
- const index = this.pendingUserMessages.lastIndexOf(record.content);
597074
- if (index >= 0)
597075
- this.pendingUserMessages.splice(index, 1);
597076
597484
  continue;
597077
597485
  }
597078
597486
  record.taskEpoch = this._taskEpoch;
@@ -597106,13 +597514,31 @@ ${notice}`;
597106
597514
  this._supersededTodoIds.add(todo.id);
597107
597515
  this._workboard = null;
597108
597516
  }
597109
- _steeringRecordForContent(content) {
597110
- return this.pendingSteeringInputs.find((record) => record.content === content && (record.state === "queued" || record.state === "acknowledged") && record.taskEpoch === this._taskEpoch);
597517
+ _activateSteering(record, turn) {
597518
+ const requiresReconciliation = steeringRequiresReconciliation(record.intent);
597519
+ const gatesOldPlan = steeringGatesOldPlan(record.intent);
597520
+ const prior = this._activeSteering;
597521
+ if (prior && prior.input.inputId !== record.inputId && !prior.reconciliation && (record.intent === "redirect" || record.intent === "replace")) {
597522
+ prior.input.state = "superseded";
597523
+ this._emitSteeringLifecycle(prior.input, `superseded by ${record.intent} ${record.inputId}`);
597524
+ }
597525
+ this._activeSteering = {
597526
+ input: record,
597527
+ appliedTurn: turn,
597528
+ requiresReconciliation,
597529
+ gatesOldPlan,
597530
+ visibleRequestTurns: []
597531
+ };
597532
+ if (requiresReconciliation) {
597533
+ record.state = "reconciliation_required";
597534
+ this._emitSteeringLifecycle(record, gatesOldPlan ? `admitted at turn ${turn}; old-plan actions are gated pending structured reconciliation` : `admitted at turn ${turn}; awaiting structured reconciliation`);
597535
+ }
597111
597536
  }
597112
597537
  _canonicalReadEvidencePayload(canonicalPath, contentHash2) {
597113
597538
  const branch = this._branchEvidenceByPath.get(canonicalPath);
597114
- if (branch && branch.contentHash === contentHash2)
597539
+ if (branch && branch.contentHash === contentHash2 && branch.taskEpoch === this._taskEpoch) {
597115
597540
  return branch.output;
597541
+ }
597116
597542
  return null;
597117
597543
  }
597118
597544
  _rehydrateResolvedReadEvidence(input) {
@@ -597162,38 +597588,45 @@ ${notice}`;
597162
597588
  }
597163
597589
  async _drainPendingSteeringMessages(messages2, turn) {
597164
597590
  this.drainPendingRuntimeGuidance(turn);
597165
- while (this.pendingUserMessages.length > 0) {
597166
- const userMsg = this.pendingUserMessages.shift();
597167
- const record = this._steeringRecordForContent(userMsg);
597591
+ const pending2 = this.pendingSteeringInputs.filter((record) => (record.state === "queued" || record.state === "acknowledged") && (!record.taskEpoch || record.taskEpoch === this._taskEpoch));
597592
+ for (const record of pending2) {
597168
597593
  const replacement = this._pendingSteeringPreemption;
597169
- if (replacement?.intent === "replace" && record && record.inputId !== replacement.inputId) {
597594
+ if (replacement?.intent === "replace" && record.inputId !== replacement.inputId) {
597170
597595
  record.state = "superseded";
597171
597596
  this._emitSteeringLifecycle(record, `superseded before consumption by replacement ${replacement.inputId}`);
597172
597597
  continue;
597173
597598
  }
597174
- await this.appendInjectedUserMessage(userMsg, messages2, turn);
597175
- if (record) {
597176
- record.state = "consumed";
597177
- this._emitSteeringLifecycle(record, `consumed at turn ${turn}`);
597178
- }
597599
+ await this.appendInjectedUserMessage(record.content, messages2, turn);
597600
+ this._activateSteering(record, turn);
597601
+ }
597602
+ while (this.pendingUserMessages.length > 0) {
597603
+ await this.appendInjectedUserMessage(this.pendingUserMessages.shift(), messages2, turn);
597179
597604
  }
597180
597605
  }
597181
- /** Apply a preemption only at a safe boundary after its user content is visible. */
597182
- _applyPendingSteeringPreemption(messages2, turn) {
597606
+ /**
597607
+ * The only legal steering boundary for every runner loop. It materializes
597608
+ * typed input, applies epoch preemption, and deliberately never equates
597609
+ * transcript insertion with model acknowledgement.
597610
+ */
597611
+ async _applySteeringAtSafeBoundary(messages2, turn) {
597612
+ this._currentSteeringTurn = turn;
597613
+ await this._drainPendingSteeringMessages(messages2, turn);
597183
597614
  const record = this._pendingSteeringPreemption;
597184
597615
  if (!record)
597185
- return false;
597616
+ return "continue";
597186
597617
  this._pendingSteeringPreemption = null;
597187
597618
  if (record.intent === "cancel") {
597188
597619
  record.state = "cancelled";
597189
597620
  this._emitSteeringLifecycle(record, `cancelled active task at turn ${turn}`);
597190
597621
  this.abort();
597191
- return true;
597622
+ return "abort";
597192
597623
  }
597193
597624
  const previousEpoch = this._taskEpoch;
597194
597625
  this._archiveSupersededTaskState(previousEpoch, record);
597195
597626
  this._allowImplicitContinuation = false;
597196
597627
  this._taskEpoch += 1;
597628
+ this._taskEpochStartTurn = turn;
597629
+ this._focusSupervisor?.setTaskEpoch(this._taskEpoch, turn);
597197
597630
  record.taskEpoch = this._taskEpoch;
597198
597631
  if (record.intent === "replace") {
597199
597632
  for (const candidate of this.pendingSteeringInputs) {
@@ -597217,19 +597650,155 @@ ${notice}`;
597217
597650
  this._completionIncompleteVerification = null;
597218
597651
  this._taskState.goal = record.content;
597219
597652
  this._taskState.originalGoal = record.content;
597220
- messages2.push({
597221
- role: "system",
597222
- content: [
597223
- "[ACTIVE USER STEERING - HIGHEST USER PRIORITY]",
597224
- `inputId=${record.inputId} taskEpoch=${this._taskEpoch} intent=${record.intent}`,
597225
- "The prior task epoch is historical evidence only. Do not continue its plan, todos, recovery cards, or completion contract.",
597226
- "Replan from this active user instruction before any further tool call:",
597227
- record.content
597228
- ].join("\n")
597229
- });
597230
- record.state = "consumed";
597231
- this._emitSteeringLifecycle(record, `applied at turn ${turn}; epoch ${previousEpoch} -> ${this._taskEpoch}`);
597232
- return true;
597653
+ this._activateSteering(record, turn);
597654
+ this._emitSteeringLifecycle(record, `epoch transition applied at turn ${turn}; ${previousEpoch} -> ${this._taskEpoch}`);
597655
+ return "restart";
597656
+ }
597657
+ /** A single late, protected steering slot rendered for every request until acknowledgement. */
597658
+ _renderActiveSteeringSlot() {
597659
+ const active = this._activeSteering;
597660
+ if (!active)
597661
+ return null;
597662
+ const { input, reconciliation } = active;
597663
+ if (reconciliation && reconciliation.status !== "needs_clarification") {
597664
+ return null;
597665
+ }
597666
+ const needsClarification = reconciliation?.status === "needs_clarification";
597667
+ return [
597668
+ "[ACTIVE USER STEERING]",
597669
+ `input_id=${input.inputId}`,
597670
+ `task_epoch=${input.taskEpoch ?? this._taskEpoch}`,
597671
+ `kind=${input.intent}`,
597672
+ `admission=${active.gatesOldPlan ? "old_plan_gated" : "context_active"}`,
597673
+ "This is current user authority, not historical transcript context.",
597674
+ input.intent === "redirect" || input.intent === "replace" ? "The prior task epoch is historical evidence only. Do not continue its plan, todos, recovery cards, or completion contract." : null,
597675
+ needsClarification ? "You requested clarification. Do not call tools or resume the old plan; ask the user one concise question." : active.requiresReconciliation ? [
597676
+ "Before any tool call, respond with exactly one structured reconciliation and no tool calls in that response:",
597677
+ "[STEERING_RECONCILIATION]",
597678
+ JSON.stringify({
597679
+ inputId: input.inputId,
597680
+ status: "applied | not_applicable | needs_clarification",
597681
+ changedConstraints: ["concrete constraint or []"],
597682
+ revisedNextAction: "one concrete next action"
597683
+ }),
597684
+ "[/STEERING_RECONCILIATION]"
597685
+ ].join("\n") : null,
597686
+ "User instruction:",
597687
+ input.content.slice(0, 6e3),
597688
+ "[/ACTIVE USER STEERING]"
597689
+ ].filter(Boolean).join("\n");
597690
+ }
597691
+ _markActiveSteeringVisible(turn) {
597692
+ const active = this._activeSteering;
597693
+ if (!active || active.reconciliation || active.visibleRequestTurns.includes(turn))
597694
+ return;
597695
+ active.visibleRequestTurns.push(turn);
597696
+ active.input.state = "visible_in_request";
597697
+ this._emitSteeringLifecycle(active.input, `visible in model request at turn ${turn}`);
597698
+ }
597699
+ _firstJsonObject(text2) {
597700
+ const start2 = text2.indexOf("{");
597701
+ if (start2 < 0)
597702
+ return null;
597703
+ let depth = 0;
597704
+ let quoted = false;
597705
+ let escaped = false;
597706
+ for (let index = start2; index < text2.length; index++) {
597707
+ const char = text2[index];
597708
+ if (quoted) {
597709
+ if (escaped)
597710
+ escaped = false;
597711
+ else if (char === "\\")
597712
+ escaped = true;
597713
+ else if (char === '"')
597714
+ quoted = false;
597715
+ continue;
597716
+ }
597717
+ if (char === '"')
597718
+ quoted = true;
597719
+ else if (char === "{")
597720
+ depth++;
597721
+ else if (char === "}") {
597722
+ depth--;
597723
+ if (depth === 0)
597724
+ return text2.slice(start2, index + 1);
597725
+ }
597726
+ }
597727
+ return null;
597728
+ }
597729
+ /** Parse and validate the model's explicit acknowledgement, never a vague textual mention. */
597730
+ _reconcileActiveSteeringFromModel(content, turn) {
597731
+ const active = this._activeSteering;
597732
+ if (!active || !active.requiresReconciliation || !content)
597733
+ return false;
597734
+ const tagged = content.match(/\[STEERING_RECONCILIATION\]([\s\S]*?)(?:\[\/STEERING_RECONCILIATION\]|$)/i);
597735
+ if (!tagged)
597736
+ return false;
597737
+ const candidate = this._firstJsonObject(tagged[1] ?? "");
597738
+ if (!candidate)
597739
+ return false;
597740
+ try {
597741
+ const parsed = JSON.parse(candidate);
597742
+ const status = parsed["status"];
597743
+ const inputId = parsed["inputId"];
597744
+ if (inputId !== active.input.inputId || status !== "applied" && status !== "not_applicable" && status !== "needs_clarification") {
597745
+ return false;
597746
+ }
597747
+ const changedConstraints = Array.isArray(parsed["changedConstraints"]) ? parsed["changedConstraints"].filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean).slice(0, 12) : [];
597748
+ const revisedNextAction = typeof parsed["revisedNextAction"] === "string" ? parsed["revisedNextAction"].trim().slice(0, 1e3) : "";
597749
+ if (!revisedNextAction)
597750
+ return false;
597751
+ active.reconciliation = {
597752
+ inputId: active.input.inputId,
597753
+ status,
597754
+ changedConstraints,
597755
+ revisedNextAction
597756
+ };
597757
+ active.reconciledTurn = turn;
597758
+ active.requiresReconciliation = status === "needs_clarification";
597759
+ active.gatesOldPlan = status === "needs_clarification";
597760
+ this._taskState.nextAction = revisedNextAction;
597761
+ if (changedConstraints.length > 0) {
597762
+ this._taskState.steeringConstraints = [
597763
+ .../* @__PURE__ */ new Set([...this._taskState.steeringConstraints ?? [], ...changedConstraints])
597764
+ ].slice(-20);
597765
+ }
597766
+ active.input.state = "reconciled";
597767
+ this._emitSteeringLifecycle(active.input, `reconciled by model at turn ${turn}: ${status}`);
597768
+ return true;
597769
+ } catch {
597770
+ return false;
597771
+ }
597772
+ }
597773
+ _steeringToolGate(turn) {
597774
+ const active = this._activeSteering;
597775
+ if (!active || !active.gatesOldPlan)
597776
+ return null;
597777
+ if (!active.reconciliation) {
597778
+ return `[STEERING_RECONCILIATION_REQUIRED]
597779
+ input_id=${active.input.inputId}
597780
+ Do not execute the old-plan tool call. First emit the exact [STEERING_RECONCILIATION] JSON required by ACTIVE USER STEERING.`;
597781
+ }
597782
+ if (active.reconciliation.status === "needs_clarification") {
597783
+ return `[STEERING_CLARIFICATION_REQUIRED]
597784
+ input_id=${active.input.inputId}
597785
+ The model requested user clarification. Do not execute tools or resume the old plan.`;
597786
+ }
597787
+ if (active.reconciledTurn === turn) {
597788
+ return `[STEERING_REPLAN_TURN_REQUIRED]
597789
+ input_id=${active.input.inputId}
597790
+ The steering reconciliation was emitted this turn. Wait for the next model decision before executing a tool.`;
597791
+ }
597792
+ return null;
597793
+ }
597794
+ _markFirstSteeringAffectedAction(toolName, turn) {
597795
+ const active = this._activeSteering;
597796
+ if (!active || !active.reconciliation || active.reconciliation.status === "needs_clarification" || active.firstAffectedAction || active.reconciledTurn === turn) {
597797
+ return;
597798
+ }
597799
+ active.firstAffectedAction = { toolName, turn };
597800
+ active.input.state = "first_affected_action";
597801
+ this._emitSteeringLifecycle(active.input, `first affected action ${toolName} started at turn ${turn}`);
597233
597802
  }
597234
597803
  /**
597235
597804
  * Pause the current task gracefully. The run loop will suspend at the next
@@ -597424,12 +597993,13 @@ ${notice}`;
597424
597993
  }
597425
597994
  }
597426
597995
  /**
597427
- * Mandatory pre-dispatch router for local file reads. It resolves exactly
597428
- * once against the authoritative run directory, computes the actual selected
597429
- * range, and intercepts unsafe reads before registered tool code or any
597430
- * transcript/evidence consumer can observe raw content.
597996
+ * Mandatory on-read extraction path for local file reads. It resolves
597997
+ * exactly once against the authoritative run directory, creates an isolated
597998
+ * inference frame when the selected range cannot safely enter the parent
597999
+ * context, and returns only the verified evidence frame. Registered tool
598000
+ * code and parent transcript consumers never observe the raw oversized body.
597431
598001
  */
597432
- async _preemptFileReadWithBranch(input) {
598002
+ async _extractFileReadEvidence(input) {
597433
598003
  if (this.lookupRegisteredTool(input.toolName)?.name !== "file_read") {
597434
598004
  return null;
597435
598005
  }
@@ -597487,7 +598057,8 @@ ${notice}`;
597487
598057
  });
597488
598058
  const contractFingerprint = _createHash("sha256").update(JSON.stringify(branchBrief.discoveryContract ?? branchBrief)).digest("hex").slice(0, 20);
597489
598059
  const canonicalPath = this._normalizeEvidencePath(rawPath);
597490
- const cacheKey = `${canonicalPath}|${fullHash}|${offset ?? 0}:${limit ?? "EOF"}|${contractFingerprint}`;
598060
+ const branchRequestId = `branch:${this._taskEpoch}:${_createHash("sha256").update(`${canonicalPath}|${fullHash}|${offset ?? 0}:${limit ?? "EOF"}|${contractFingerprint}`).digest("hex").slice(0, 20)}`;
598061
+ const cacheKey = `${this._taskEpoch}|${canonicalPath}|${fullHash}|${offset ?? 0}:${limit ?? "EOF"}|${contractFingerprint}`;
597491
598062
  const cached2 = this._branchEvidenceCache.get(cacheKey);
597492
598063
  if (cached2) {
597493
598064
  const fingerprint = this._buildToolFingerprint(input.toolName, input.args);
@@ -597516,6 +598087,17 @@ ${notice}`;
597516
598087
  branchSourceBytes: cached2.sourceBytes,
597517
598088
  branchCacheHit: true,
597518
598089
  fingerprintState: "resolved_from_cache"
598090
+ },
598091
+ branchEvidence: {
598092
+ schema: "omnius.branch-evidence.v1",
598093
+ requestId: cached2.requestId,
598094
+ taskEpoch: this._taskEpoch,
598095
+ path: canonicalPath,
598096
+ contentHash: fullHash,
598097
+ sourceRange: {
598098
+ startLine: startIndex + 1,
598099
+ endLine: startIndex + Math.max(1, selectedLines.length)
598100
+ }
597519
598101
  }
597520
598102
  };
597521
598103
  }
@@ -597533,6 +598115,7 @@ ${notice}`;
597533
598115
  });
597534
598116
  const verboseOutput = [
597535
598117
  `[BRANCH-EXTRACT v2] path=${rawPath}`,
598118
+ `[VERIFIED_RUNTIME_FILE_READ] request_id=${branchRequestId} task_epoch=${this._taskEpoch}`,
597536
598119
  `routing=mandatory reasons=${decision2.reasons.join(",")} projected_read_tokens=${decision2.projectedReadTokens} fraction_limit_tokens=${decision2.fractionLimitTokens} available_headroom_tokens=${decision2.availableHeadroomTokens}`,
597537
598120
  `source=sha256:${fullHash} selected_lines=${selectedLines.length} selected_bytes=${selectedBytes}${hasRange ? ` range=${offset ?? 1}:${limit ?? "EOF"}` : " range=whole"}`,
597538
598121
  `[DISCOVERY CONTRACT]`,
@@ -597554,6 +598137,7 @@ ${notice}`;
597554
598137
  const required = (branchBrief.discoveryContract?.requirements ?? []).filter((requirement) => requirement.required).map((requirement) => `${requirement.id}:${requirement.question.slice(0, 180)}`).join(" | ");
597555
598138
  const prefix = [
597556
598139
  `[BRANCH-EXTRACT v2] path=${rawPath} sha256=${fullHash}`,
598140
+ `[VERIFIED_RUNTIME_FILE_READ] request_id=${branchRequestId} task_epoch=${this._taskEpoch}`,
597557
598141
  `routing=${decision2.reasons.join(",")} projected=${decision2.projectedReadTokens}/${contextWindow}t limit=${decision2.fractionLimitTokens}t`,
597558
598142
  `[DISCOVERY CONTRACT] required=${required || "next narrow file-local fact"}`,
597559
598143
  `[CURATED SEGMENTS]`
@@ -597573,17 +598157,20 @@ ${suffix}`.slice(0, outputBudgetChars);
597573
598157
  path: canonicalPath,
597574
598158
  contentHash: fullHash,
597575
598159
  sourceBytes: stat9.size,
597576
- createdAt: Date.now()
598160
+ createdAt: Date.now(),
598161
+ taskEpoch: this._taskEpoch,
598162
+ requestId: branchRequestId
597577
598163
  });
597578
598164
  this._branchEvidenceByPath.set(canonicalPath, {
597579
598165
  output,
597580
598166
  contentHash: fullHash,
597581
- mtimeMs: stat9.mtimeMs
598167
+ mtimeMs: stat9.mtimeMs,
598168
+ taskEpoch: this._taskEpoch
597582
598169
  });
597583
598170
  this.emit({
597584
598171
  type: "status",
597585
598172
  toolName: input.toolName,
597586
- content: `Branch-extract preempted ${rawPath}: ${decision2.projectedReadTokens}/${contextWindow} projected tokens (${(decision2.projectedFraction * 100).toFixed(1)}%); resident=${residentTokens}t reserve=${reservedTokens}t pending_reads=${input.batchBudget.inlineTokens}t; ${selectedBytes}B → ${output.length} curated chars; reasons=${decision2.reasons.join(",")}`,
598173
+ content: `Branch extraction executed for file_read ${rawPath}: ${decision2.projectedReadTokens}/${contextWindow} projected tokens (${(decision2.projectedFraction * 100).toFixed(1)}%); resident=${residentTokens}t reserve=${reservedTokens}t pending_reads=${input.batchBudget.inlineTokens}t; ${selectedBytes}B → ${output.length} curated chars; reasons=${decision2.reasons.join(",")}`,
597587
598174
  turn: input.turn,
597588
598175
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
597589
598176
  });
@@ -597599,6 +598186,17 @@ ${suffix}`.slice(0, outputBudgetChars);
597599
598186
  branchSourceBytes: stat9.size,
597600
598187
  branchSelectedBytes: selectedBytes,
597601
598188
  branchProjectedTokens: decision2.projectedReadTokens
598189
+ },
598190
+ branchEvidence: {
598191
+ schema: "omnius.branch-evidence.v1",
598192
+ requestId: branchRequestId,
598193
+ taskEpoch: this._taskEpoch,
598194
+ path: canonicalPath,
598195
+ contentHash: fullHash,
598196
+ sourceRange: {
598197
+ startLine: startIndex + 1,
598198
+ endLine: startIndex + Math.max(1, selectedLines.length)
598199
+ }
597602
598200
  }
597603
598201
  };
597604
598202
  }
@@ -597658,6 +598256,7 @@ ${suffix}`.slice(0, outputBudgetChars);
597658
598256
  });
597659
598257
  const output = [
597660
598258
  `[BRANCH-EXTRACT v2] path=${path16}`,
598259
+ `[VERIFIED_RUNTIME_FILE_READ] request_id=branch:${this._taskEpoch}:${input.callId} task_epoch=${this._taskEpoch}`,
597661
598260
  `routing=post-execution-failsafe reasons=${decision2.reasons.join(",")} projected_read_tokens=${decision2.projectedReadTokens}`,
597662
598261
  `[DISCOVERY CONTRACT] ${brief.request}`,
597663
598262
  `[CURATED SEGMENTS]`,
@@ -597676,6 +598275,17 @@ ${suffix}`.slice(0, outputBudgetChars);
597676
598275
  branchSourceBytes: Buffer.byteLength(input.result.output, "utf8"),
597677
598276
  branchSelectedBytes: Buffer.byteLength(input.result.output, "utf8"),
597678
598277
  branchProjectedTokens: decision2.projectedReadTokens
598278
+ },
598279
+ branchEvidence: {
598280
+ schema: "omnius.branch-evidence.v1",
598281
+ requestId: `branch:${this._taskEpoch}:${input.callId}`,
598282
+ taskEpoch: this._taskEpoch,
598283
+ path: this._normalizeEvidencePath(path16),
598284
+ contentHash: ev.provenance.contentHash,
598285
+ sourceRange: {
598286
+ startLine: 1,
598287
+ endLine: Math.max(1, lines.length)
598288
+ }
597679
598289
  }
597680
598290
  };
597681
598291
  }
@@ -598373,8 +598983,10 @@ Respond with the assessment and take the selected evidence-backed action.`;
598373
598983
  convergenceBreaker: this._longHaul?.convergenceBreaker ?? null,
598374
598984
  // WO-9: run cwd so shell family keys canonicalize absolute↔relative
598375
598985
  // path form and command variants collapse into one family.
598376
- cwd: this.authoritativeWorkingDirectory()
598986
+ cwd: this.authoritativeWorkingDirectory(),
598987
+ taskEpoch: this._taskEpoch
598377
598988
  });
598989
+ this._focusSupervisor?.setTaskEpoch(this._taskEpoch);
598378
598990
  if (!this._workingDirectory) {
598379
598991
  this._workingDirectory = _pathResolve(process.cwd());
598380
598992
  }
@@ -599044,6 +599656,7 @@ ${dynamicProjectContext}`
599044
599656
  let lastShellPivotTurn = -1;
599045
599657
  const recentToolResults = /* @__PURE__ */ new Map();
599046
599658
  const exactFileReadObservations = /* @__PURE__ */ new Map();
599659
+ const exactReadEvidenceEpochs = /* @__PURE__ */ new Map();
599047
599660
  let fileMutationEpoch = 0;
599048
599661
  const dedupHitCount = /* @__PURE__ */ new Map();
599049
599662
  const noopedMemoryWriteFingerprints = /* @__PURE__ */ new Set();
@@ -600564,9 +601177,9 @@ Respond with EXACTLY this structure before your next tool call:
600564
601177
  });
600565
601178
  }
600566
601179
  }
600567
- await this._drainPendingSteeringMessages(messages2, turn);
600568
- if (this._applyPendingSteeringPreemption(messages2, turn)) {
600569
- if (this.aborted)
601180
+ const steeringBoundary = await this._applySteeringAtSafeBoundary(messages2, turn);
601181
+ if (steeringBoundary !== "continue") {
601182
+ if (steeringBoundary === "abort" || this.aborted)
600570
601183
  break;
600571
601184
  continue;
600572
601185
  }
@@ -600976,6 +601589,11 @@ ${memoryLines.join("\n")}`
600976
601589
  role: "system",
600977
601590
  content: this._buildRecentActionGroundTruth(turn)
600978
601591
  });
601592
+ const activeSteeringSlot = this._renderActiveSteeringSlot();
601593
+ if (activeSteeringSlot) {
601594
+ requestMessages.push({ role: "system", content: activeSteeringSlot });
601595
+ this._markActiveSteeringVisible(turn);
601596
+ }
600979
601597
  this._retireLinkedAssistantReadIntents(requestMessages);
600980
601598
  const chatRequest = {
600981
601599
  messages: requestMessages,
@@ -601168,7 +601786,6 @@ ${memoryLines.join("\n")}`
601168
601786
  "After seeing the tool result, continue or call another tool.",
601169
601787
  'When done, output: {"tool": "task_complete", "args": {"summary": "what you did"}}'
601170
601788
  ].join("\n");
601171
- messages2.push({ role: "system", content: toolInjectMsg });
601172
601789
  chatRequest.messages = this._prepareModelFacingMessages([
601173
601790
  ...requestMessages,
601174
601791
  { role: "system", content: toolInjectMsg }
@@ -601365,6 +601982,7 @@ ${memoryLines.join("\n")}`
601365
601982
  if (!choice)
601366
601983
  break;
601367
601984
  const msg = choice.message;
601985
+ this._reconcileActiveSteeringFromModel(msg.content, turn);
601368
601986
  const isThinkOnly = response._thinkOnly === true;
601369
601987
  const isEmptyResponse = !isThinkOnly && (!msg.content || !msg.content.trim()) && (!msg.toolCalls || msg.toolCalls.length === 0);
601370
601988
  if (isEmptyResponse) {
@@ -601466,6 +602084,18 @@ ${memoryLines.join("\n")}`
601466
602084
  executeSingle = async (tc) => {
601467
602085
  if (this.aborted || this._pendingSteeringPreemption)
601468
602086
  return null;
602087
+ const steeringGate = this._steeringToolGate(this._currentSteeringTurn);
602088
+ if (steeringGate) {
602089
+ this.emit({
602090
+ type: "status",
602091
+ toolName: tc.name,
602092
+ content: `Tool call gated by active user steering ${this._activeSteering?.input.inputId ?? "unknown"}`,
602093
+ turn: this._currentSteeringTurn,
602094
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
602095
+ });
602096
+ return { tc, output: steeringGate, success: false };
602097
+ }
602098
+ this._markFirstSteeringAffectedAction(tc.name, this._currentSteeringTurn);
601469
602099
  const resolvedReadBlock = this._rejectRepeatedResolvedRead(tc, messages2);
601470
602100
  if (resolvedReadBlock) {
601471
602101
  this.emit({
@@ -602111,7 +602741,48 @@ Read the current file if needed, make a different concrete edit, or move to veri
602111
602741
  adversaryRedundantSignal
602112
602742
  });
602113
602743
  let repeatShortCircuit = null;
602114
- if (criticDecision.decision === "guidance") {
602744
+ const exactReadArgs = tc.arguments;
602745
+ const exactReadPath = String(exactReadArgs?.["path"] ?? exactReadArgs?.["file"] ?? "");
602746
+ const exactReadEvidence = exactReadEvidenceEpochs.get(toolFingerprint);
602747
+ const exactReadEvidenceFresh = tc.name === "file_read" && exactReadPath.length > 0 && this._evidenceLedger.validateFreshness(this._normalizeEvidencePath(exactReadPath), this._absoluteToolPath(exactReadPath));
602748
+ if (tc.name === "file_read" && exactReadEvidenceFresh && exactReadEvidence?.taskEpoch === this._taskEpoch && exactReadEvidence.mutationEpoch === fileMutationEpoch) {
602749
+ const path16 = this._normalizeEvidencePath(exactReadPath);
602750
+ const evidence = this._evidenceLedger.get(path16);
602751
+ const rawCurated = this._branchEvidenceByPath.get(path16) ?? [...this._branchEvidenceByPath.entries()].find(([candidate]) => this._normalizeEvidencePath(candidate) === path16)?.[1];
602752
+ const curated = rawCurated?.taskEpoch === this._taskEpoch ? rawCurated : void 0;
602753
+ const curatedPayload = curated?.output ?? (evidence?.fidelity === "extract" && evidence.content.includes("[BRANCH-EXTRACT") ? evidence.content : null);
602754
+ repeatShortCircuit = {
602755
+ success: true,
602756
+ output: curatedPayload ? this._rehydrateResolvedReadEvidence({
602757
+ fingerprint: toolFingerprint,
602758
+ canonicalPath: path16,
602759
+ contentHash: curated?.contentHash ?? evidence?.contentHash ?? "unknown",
602760
+ payload: curatedPayload,
602761
+ turn
602762
+ }) : [
602763
+ ...evidence?.fidelity === "extract" ? [
602764
+ "[REHYDRATED_FILE_EVIDENCE]",
602765
+ "source=active_context_frame fidelity=extract"
602766
+ ] : [],
602767
+ "[READ EVIDENCE REFERENCE]",
602768
+ `path=${path16 || "unknown"}`,
602769
+ `task_epoch=${this._taskEpoch}`,
602770
+ `freshness=${evidence?.stale ? "stale" : "fresh"}`,
602771
+ evidence?.contentHash ? `sha256=${evidence.contentHash}` : null,
602772
+ "Exact unchanged range was not re-executed. Use the existing evidence handle or request a newly uncovered range after identifying the missing fact."
602773
+ ].filter(Boolean).join("\n"),
602774
+ runtimeAuthored: true,
602775
+ noop: true
602776
+ };
602777
+ this.emit({
602778
+ type: "status",
602779
+ toolName: tc.name,
602780
+ content: `Exact unchanged file_read blocked before dispatch: ${path16}`,
602781
+ turn,
602782
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
602783
+ });
602784
+ }
602785
+ if (criticDecision.decision === "guidance" && !repeatShortCircuit) {
602115
602786
  dedupHitCount.set(toolFingerprint, criticDecision.hitNumber);
602116
602787
  const _existingFp = recentToolResults.get(toolFingerprint);
602117
602788
  if (_existingFp !== void 0) {
@@ -602156,12 +602827,14 @@ Read the current file if needed, make a different concrete edit, or move to veri
602156
602827
  const suppressSuccessfulShellCacheGuidance = tc.name === "shell" && !isFailedShellRepeat;
602157
602828
  if (suppressSuccessfulShellCacheGuidance)
602158
602829
  criticGuidance = null;
602830
+ let exactReadEvidenceFresh2 = true;
602159
602831
  if (isReadLike && this._evidenceLedger) {
602160
602832
  const readArgs = tc.arguments;
602161
602833
  const readPath2 = String(readArgs?.["path"] ?? readArgs?.["file"] ?? "");
602162
602834
  if (readPath2) {
602163
602835
  const evidencePath = this._normalizeEvidencePath(readPath2);
602164
602836
  const wasFresh = evidencePath && this._evidenceLedger.validateFreshness(evidencePath, this._absoluteToolPath(readPath2));
602837
+ exactReadEvidenceFresh2 = Boolean(wasFresh);
602165
602838
  if (!wasFresh) {
602166
602839
  recentToolResults.delete(toolFingerprint);
602167
602840
  dedupHitCount.delete(toolFingerprint);
@@ -602175,7 +602848,42 @@ Read the current file if needed, make a different concrete edit, or move to veri
602175
602848
  }
602176
602849
  }
602177
602850
  }
602178
- if (repeatGateEligible && _existingFp !== void 0 && _repeatGateMax > 0) {
602851
+ const exactReadEvidence2 = exactReadEvidenceEpochs.get(toolFingerprint);
602852
+ const exactFileReadReference = tc.name === "file_read" && exactReadEvidenceFresh2 && exactReadEvidence2?.taskEpoch === this._taskEpoch && exactReadEvidence2.mutationEpoch === fileMutationEpoch;
602853
+ if (exactFileReadReference) {
602854
+ const path16 = this._normalizeEvidencePath(String(tc.arguments?.["path"] ?? tc.arguments?.["file"] ?? ""));
602855
+ const evidence = this._evidenceLedger?.get(path16);
602856
+ const rawCurated = this._branchEvidenceByPath.get(path16) ?? [...this._branchEvidenceByPath.entries()].find(([candidate]) => this._normalizeEvidencePath(candidate) === path16)?.[1];
602857
+ const curated = rawCurated?.taskEpoch === this._taskEpoch ? rawCurated : void 0;
602858
+ const curatedPayload = curated?.output ?? (evidence?.fidelity === "extract" && evidence.content.includes("[BRANCH-EXTRACT") ? evidence.content : null);
602859
+ repeatShortCircuit = {
602860
+ success: true,
602861
+ // Curated branch output is the bounded authoritative payload
602862
+ // for this source version. Rehydrate it instead of replacing
602863
+ // it with a pointer; exact/overlap suppression must not force
602864
+ // the model to reread a large source merely to recover facts.
602865
+ output: curatedPayload ? this._rehydrateResolvedReadEvidence({
602866
+ fingerprint: toolFingerprint,
602867
+ canonicalPath: path16,
602868
+ contentHash: curated?.contentHash ?? evidence?.contentHash ?? "unknown",
602869
+ payload: curatedPayload,
602870
+ turn
602871
+ }) : [
602872
+ ...evidence?.fidelity === "extract" ? [
602873
+ "[REHYDRATED_FILE_EVIDENCE]",
602874
+ "source=active_context_frame fidelity=extract"
602875
+ ] : [],
602876
+ "[READ EVIDENCE REFERENCE]",
602877
+ `path=${path16 || "unknown"}`,
602878
+ `task_epoch=${this._taskEpoch}`,
602879
+ `freshness=${evidence?.stale ? "stale" : "fresh"}`,
602880
+ evidence?.contentHash ? `sha256=${evidence.contentHash}` : null,
602881
+ "Exact unchanged range was not re-executed. Use the existing evidence handle or request a newly uncovered range after identifying the missing fact."
602882
+ ].filter(Boolean).join("\n"),
602883
+ runtimeAuthored: true,
602884
+ noop: true
602885
+ };
602886
+ } else if (repeatGateEligible && _existingFp !== void 0 && _repeatGateMax > 0) {
602179
602887
  const _rehydrateArgs = tc.arguments;
602180
602888
  const _rehydratePath = String(_rehydrateArgs?.["path"] ?? _rehydrateArgs?.["file"] ?? "");
602181
602889
  const _visibleViaEvidenceFrame = _rehydratePath.length > 0 && (this._evidenceLedger?.renderedFullInLastBlock(this._normalizeEvidencePath(_rehydratePath)) ?? false);
@@ -602256,7 +602964,8 @@ ${cachedResult}`,
602256
602964
  cachedResultFailed: tc.name === "shell" && typeof focusCachedEntry?.result === "string" && focusCachedEntry.result.includes("status: failure"),
602257
602965
  duplicateHitCount: focusDuplicateHits,
602258
602966
  context: this._buildFocusContextSnapshot(),
602259
- usesAuthoritativeTargetEvidence
602967
+ usesAuthoritativeTargetEvidence,
602968
+ taskEpoch: this._taskEpoch
602260
602969
  });
602261
602970
  if (focusDecision && focusDecision.kind !== "pass") {
602262
602971
  this._emitFocusSupervisorEvent({
@@ -602478,7 +603187,7 @@ ${cachedResult}`,
602478
603187
  try {
602479
603188
  tc.arguments = finalArgs;
602480
603189
  const normalizedDispatchName = resolvedTool?.name ?? tc.name;
602481
- let branchPreempted = null;
603190
+ let branchEvidenceResult = null;
602482
603191
  if (normalizedDispatchName === "file_read") {
602483
603192
  const exactReadKey = this._buildToolFingerprint("file_read", tc.arguments);
602484
603193
  const priorRead = exactFileReadObservations.get(exactReadKey);
@@ -602495,7 +603204,7 @@ ${cachedResult}`,
602495
603204
  payload: canonicalPayload,
602496
603205
  turn
602497
603206
  });
602498
- branchPreempted = {
603207
+ branchEvidenceResult = {
602499
603208
  success: true,
602500
603209
  output: rehydrated,
602501
603210
  llmContent: rehydrated,
@@ -602522,7 +603231,7 @@ ${cachedResult}`,
602522
603231
  `path=${currentRead.path}`,
602523
603232
  "No canonical payload was produced by the allowed narrow reread. Change scope with a new range or symbol query; do not repeat identical arguments."
602524
603233
  ].join("\n");
602525
- branchPreempted = {
603234
+ branchEvidenceResult = {
602526
603235
  success: true,
602527
603236
  output: fallbackBlocked,
602528
603237
  llmContent: fallbackBlocked,
@@ -602555,8 +603264,8 @@ ${cachedResult}`,
602555
603264
  }
602556
603265
  }
602557
603266
  }
602558
- if (!branchPreempted) {
602559
- branchPreempted = await this._preemptFileReadWithBranch({
603267
+ if (!branchEvidenceResult) {
603268
+ branchEvidenceResult = await this._extractFileReadEvidence({
602560
603269
  callId: tc.id,
602561
603270
  toolName: normalizedDispatchName,
602562
603271
  args: tc.arguments,
@@ -602565,8 +603274,8 @@ ${cachedResult}`,
602565
603274
  batchBudget: branchReadBatchBudget
602566
603275
  });
602567
603276
  }
602568
- if (branchPreempted) {
602569
- result = branchPreempted;
603277
+ if (branchEvidenceResult) {
603278
+ result = branchEvidenceResult;
602570
603279
  fileReadSafetyChecked = true;
602571
603280
  } else {
602572
603281
  if (typeof tool.executeStream === "function") {
@@ -602817,6 +603526,11 @@ ${cachedResult}`,
602817
603526
  turn,
602818
603527
  fidelity: result.runtimeAuthored === true && result.output.startsWith("[BRANCH-EXTRACT") ? "extract" : void 0
602819
603528
  });
603529
+ exactReadEvidenceEpochs.set(toolFingerprint, {
603530
+ taskEpoch: this._taskEpoch,
603531
+ mutationEpoch: fileMutationEpoch
603532
+ });
603533
+ this._registerReadCoverage("file_read", tc.arguments, toolFingerprint);
602820
603534
  }
602821
603535
  if (this._fileSummaryStore && result.success && result.output && result.output.length > 100) {
602822
603536
  try {
@@ -603822,6 +604536,7 @@ Evidence: ${evidencePreview}`.slice(0, 500);
603822
604536
  this._taskState.toolCallCount++;
603823
604537
  if (realFileMutation) {
603824
604538
  this._lastFileWriteTurn = turn;
604539
+ this._fileWritesThisRun += Math.max(1, realMutationPaths.length);
603825
604540
  const writeEvents = Math.max(1, realMutationPaths.length);
603826
604541
  for (let i2 = 0; i2 < writeEvents; i2++) {
603827
604542
  this._fileWriteTimestamps.push(Date.now());
@@ -603951,7 +604666,8 @@ Evidence: ${evidencePreview}`.slice(0, 500);
603951
604666
  noop: tc.name === "todo_write" ? this._isTodoWriteNoopResult(result) : result.noop,
603952
604667
  alreadyApplied: result.alreadyApplied === true,
603953
604668
  runtimeAuthored: result.runtimeAuthored === true,
603954
- usedAuthoritativeTargetEvidence: usesAuthoritativeTargetEvidence
604669
+ usedAuthoritativeTargetEvidence: usesAuthoritativeTargetEvidence,
604670
+ taskEpoch: this._taskEpoch
603955
604671
  });
603956
604672
  const focusSnapshotAfter = this._focusSupervisor?.snapshot();
603957
604673
  focusAfterToolResult = focusSnapshotAfter ?? void 0;
@@ -604870,9 +605586,7 @@ Only call task_complete when the task is actually complete and the evidence is f
604870
605586
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
604871
605587
  });
604872
605588
  }
604873
- const pendingBeforeAdversary = this.pendingUserMessages.length;
604874
605589
  this.adversaryObserve(messages2, turn);
604875
- const adversaryAddedGuidance = this.pendingUserMessages.length > pendingBeforeAdversary;
604876
605590
  if (/task.?complete|all tests pass/i.test(content)) {
604877
605591
  const completionArgs = { summary: content };
604878
605592
  if (holdTaskCompleteGates(completionArgs, turn)) {
@@ -604932,13 +605646,6 @@ Your most recent tool calls SUCCEEDED. If the task is complete, call task_comple
604932
605646
  role: "system",
604933
605647
  content: this._textEchoGuard.buildIntervention(echoObs)
604934
605648
  });
604935
- if (adversaryAddedGuidance) {
604936
- this.drainPendingRuntimeGuidance(turn);
604937
- while (this.pendingUserMessages.length > 0) {
604938
- const userMsg = this.pendingUserMessages.shift();
604939
- await this.appendInjectedUserMessage(userMsg, messages2, turn);
604940
- }
604941
- }
604942
605649
  continue;
604943
605650
  }
604944
605651
  }
@@ -604971,6 +605678,18 @@ Your most recent tool calls SUCCEEDED. If the task is complete, call task_comple
604971
605678
  }
604972
605679
  const shellTool = this.tools.get("shell");
604973
605680
  if (shellTool) {
605681
+ const steeringGate = this._steeringToolGate(this._currentSteeringTurn);
605682
+ if (steeringGate) {
605683
+ messages2.push({ role: "system", content: steeringGate });
605684
+ this.emit({
605685
+ type: "status",
605686
+ content: "Narrated shell code block blocked by active user steering",
605687
+ turn,
605688
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
605689
+ });
605690
+ continue;
605691
+ }
605692
+ this._markFirstSteeringAffectedAction("shell", this._currentSteeringTurn);
604974
605693
  this.emit({
604975
605694
  type: "status",
604976
605695
  content: `Auto-executing code block: ${shellCommands.slice(0, 80)}...`,
@@ -605032,13 +605751,6 @@ Your most recent tool calls SUCCEEDED. If the task is complete, call task_comple
605032
605751
  content: "Continue working. Use tools to read files, make changes, and run validation. Call task_complete when done."
605033
605752
  });
605034
605753
  }
605035
- if (adversaryAddedGuidance) {
605036
- this.drainPendingRuntimeGuidance(turn);
605037
- while (this.pendingUserMessages.length > 0) {
605038
- const userMsg = this.pendingUserMessages.shift();
605039
- await this.appendInjectedUserMessage(userMsg, messages2, turn);
605040
- }
605041
- }
605042
605754
  }
605043
605755
  try {
605044
605756
  const turnLogTail = toolCallLog.filter((t2) => t2.turn === turn || t2.turn === void 0);
@@ -605195,10 +605907,11 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
605195
605907
  });
605196
605908
  nextSelfEval = bfNow + selfEvalInterval;
605197
605909
  }
605198
- this.drainPendingRuntimeGuidance(turn);
605199
- while (this.pendingUserMessages.length > 0) {
605200
- const userMsg = this.pendingUserMessages.shift();
605201
- await this.appendInjectedUserMessage(userMsg, messages2, turn);
605910
+ const steeringBoundary = await this._applySteeringAtSafeBoundary(messages2, turn);
605911
+ if (steeringBoundary !== "continue") {
605912
+ if (steeringBoundary === "abort" || this.aborted)
605913
+ break;
605914
+ continue;
605202
605915
  }
605203
605916
  let compactedMsgs;
605204
605917
  if (this._pendingCompaction) {
@@ -605234,6 +605947,11 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
605234
605947
  role: "system",
605235
605948
  content: this._buildRecentActionGroundTruth(turn)
605236
605949
  });
605950
+ const activeSteeringSlot = this._renderActiveSteeringSlot();
605951
+ if (activeSteeringSlot) {
605952
+ modelFacingMessages.push({ role: "system", content: activeSteeringSlot });
605953
+ this._markActiveSteeringVisible(turn);
605954
+ }
605237
605955
  const chatRequest = {
605238
605956
  messages: modelFacingMessages,
605239
605957
  tools: toolDefs,
@@ -605358,6 +606076,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
605358
606076
  if (!choice)
605359
606077
  break;
605360
606078
  const msg = choice.message;
606079
+ this._reconcileActiveSteeringFromModel(msg.content, turn);
605361
606080
  const isThinkOnlyBF = response._thinkOnly === true;
605362
606081
  if (msg.toolCalls && msg.toolCalls.length > 0) {
605363
606082
  consecutiveTextOnly = 0;
@@ -606566,7 +607285,7 @@ ${marker}` : marker);
606566
607285
  ].filter(Boolean).join("\n"));
606567
607286
  }
606568
607287
  shouldBypassDiscoveryCompaction(output) {
606569
- return output.includes("[IMAGE_BASE64:") || output.includes("[BRANCH-EXTRACT]") || output.includes("[REPEAT GATE - cached evidence not re-sent]") || output.includes("[REPEATED_READ_REJECTED]") || output.includes("[REPEATED_NARROW_READ_REJECTED]") || output.includes("[CACHED READ — content unchanged") || output.includes("[REHYDRATED FROM CACHE") || output.includes("[Tool output truncated") || output.includes(TRIAGE_ENVELOPE_MARKER);
607288
+ return output.includes("[IMAGE_BASE64:") || /^\[BRANCH-EXTRACT(?:\s+v\d+)?\]/m.test(output) || output.includes("[REPEAT GATE - cached evidence not re-sent]") || output.includes("[REPEATED_READ_REJECTED]") || output.includes("[REPEATED_NARROW_READ_REJECTED]") || output.includes("[CACHED READ — content unchanged") || output.includes("[REHYDRATED FROM CACHE") || output.includes("[Tool output truncated") || output.includes(TRIAGE_ENVELOPE_MARKER);
606570
607289
  }
606571
607290
  countTextLines(text2) {
606572
607291
  if (!text2)
@@ -606633,9 +607352,8 @@ ${marker}` : marker);
606633
607352
  "oldText",
606634
607353
  "search",
606635
607354
  "expected_old_string",
606636
- "expectedHash",
606637
- "expected_hash",
606638
- "start_line"
607355
+ "start_line",
607356
+ "end_line"
606639
607357
  ];
606640
607358
  for (const key of directKeys) {
606641
607359
  const value2 = args[key];
@@ -607135,13 +607853,13 @@ ${marker}` : marker);
607135
607853
  "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
607854
  ].join("\n");
607137
607855
  }
607138
- staleEditFamilyKey(toolName, pathKey, errorKind, targetHash, latestFileHash) {
607856
+ staleEditFamilyKey(toolName, pathKey, errorKind, targetHash) {
607139
607857
  return [
607858
+ `epoch=${this._taskEpoch}`,
607140
607859
  toolName,
607141
607860
  pathKey || "(unknown)",
607142
607861
  errorKind,
607143
- targetHash,
607144
- latestFileHash || "unknown-file-hash"
607862
+ targetHash
607145
607863
  ].join(":");
607146
607864
  }
607147
607865
  staleEditPreflightBlock(toolName, args) {
@@ -607157,11 +607875,8 @@ ${marker}` : marker);
607157
607875
  if (entry.count >= 2 && !hasFreshRead && !hasFreshMutation) {
607158
607876
  return [
607159
607877
  "[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
607878
+ "Blocked until a fresh file read, a real mutation, or a changed semantic edit target is observed.",
607879
+ "Previous target: " + entry.preview
607165
607880
  ].join("\n");
607166
607881
  }
607167
607882
  }
@@ -607354,7 +608069,7 @@ ${marker}` : marker);
607354
608069
  if (!errorKind)
607355
608070
  return;
607356
608071
  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);
608072
+ const key = this.staleEditFamilyKey(toolName, targetPathKey, errorKind, target.targetHash);
607358
608073
  const existing = this._staleEditFamilies.get(key);
607359
608074
  this._staleEditFamilies.set(key, {
607360
608075
  count: (existing?.count ?? 0) + 1,
@@ -608182,6 +608897,11 @@ ${tail}`;
608182
608897
  });
608183
608898
  if (signal)
608184
608899
  this._contextLedger.upsert(signal);
608900
+ messages2.push({
608901
+ role: "user",
608902
+ content: userMsg,
608903
+ taskEpoch: this._taskEpoch
608904
+ });
608185
608905
  }
608186
608906
  this.emit({
608187
608907
  type: "user_interrupt",
@@ -608912,7 +609632,7 @@ ${telegramPersonaHead}` : stripped
608912
609632
  const canonicalPath = this._normalizeEvidencePath(filePath);
608913
609633
  const branchNode = this._branchEvidenceByPath.get(canonicalPath);
608914
609634
  const currentMtime = this._statMtimeMsForToolPath(filePath) ?? 0;
608915
- if (branchNode && branchNode.mtimeMs === currentMtime) {
609635
+ if (branchNode && branchNode.taskEpoch === this._taskEpoch && branchNode.mtimeMs === currentMtime) {
608916
609636
  const nodeTokens = Math.ceil(branchNode.output.length / 4);
608917
609637
  if (recoveredTokens + nodeTokens > fileRecoveryBudget)
608918
609638
  continue;
@@ -609332,16 +610052,24 @@ ${trimmedNew}`;
609332
610052
  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
610053
  if (created.length === 0)
609334
610054
  return;
609335
- const board = this._workboard ?? this.getOrCreateWorkboard();
610055
+ const board = this._currentWorkboardSnapshotForFrame() ?? this.getOrCreateWorkboard();
609336
610056
  if (board) {
609337
610057
  const card = this._workboardTodoCardForPaths(board, created);
609338
610058
  if (card && (card.status === "open" || card.status === "in_progress" || card.status === "needs_changes")) {
609339
610059
  try {
610060
+ const runId = this._workboardRunId();
609340
610061
  const completed = completeWorkboardCard(this._workboardDir(), {
609341
- runId: this.currentArtifactRunId(),
610062
+ runId,
609342
610063
  cardId: card.id,
609343
610064
  actor: this.options.subAgent ? "sub-agent" : "agent",
609344
610065
  outcome: "completed",
610066
+ evidence: {
610067
+ kind: "tool_result",
610068
+ summary: `creation ground truth: ${created.join(", ")}`,
610069
+ tool: toolName,
610070
+ ref: created[0],
610071
+ content: String(result.output ?? result.error ?? "").slice(0, 1e3)
610072
+ },
609345
610073
  reason: `Creation ground truth satisfied mapped target(s): ${created.join(", ")} at turn ${turn}.`
609346
610074
  });
609347
610075
  this._workboard = completed.snapshot;
@@ -610786,6 +611514,7 @@ ${catalog}`,
610786
611514
  parameters: {},
610787
611515
  execute: async (args) => {
610788
611516
  const query = String(args["query"] ?? "").toLowerCase().trim();
611517
+ const queryTerms2 = query.split(/[^a-z0-9_]+/).filter((term) => term.length >= 3);
610789
611518
  const subsetMatch = subsetCatalog[query];
610790
611519
  if (subsetMatch && subsetMatch.length > 0) {
610791
611520
  const newlyPromoted = [];
@@ -610828,7 +611557,15 @@ ${catalog}`,
610828
611557
  }
610829
611558
  return { success: true, output: lines.join("\n") };
610830
611559
  }
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) => {
611560
+ 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) => {
611561
+ const searchable = [
611562
+ t2.name,
611563
+ ...t2.aliases ?? [],
611564
+ getDesc(t2),
611565
+ customToolSearchText(t2)
611566
+ ].join(" ").toLowerCase();
611567
+ return searchable.includes(term);
611568
+ })).sort((a2, b) => {
610832
611569
  const scoreTool = (tool) => {
610833
611570
  const meta = getCustomToolMetadata(tool);
610834
611571
  let score = 0;
@@ -610836,6 +611573,16 @@ ${catalog}`,
610836
611573
  score += 30;
610837
611574
  if (tool.name.toLowerCase().includes(query))
610838
611575
  score += 10;
611576
+ for (const term of queryTerms2) {
611577
+ if (tool.name.toLowerCase() === term)
611578
+ score += 30;
611579
+ else if (tool.name.toLowerCase().includes(term))
611580
+ score += 10;
611581
+ if (getDesc(tool).toLowerCase().includes(term))
611582
+ score += 4;
611583
+ if (customToolSearchText(tool).toLowerCase().includes(term))
611584
+ score += 6;
611585
+ }
610839
611586
  if ((tool.aliases ?? []).some((alias) => alias.toLowerCase() === query))
610840
611587
  score += 24;
610841
611588
  if ((tool.aliases ?? []).some((alias) => alias.toLowerCase().includes(query)))
@@ -611876,7 +612623,7 @@ ${description}`
611876
612623
  if (effectiveThink === true && (effectiveMaxTokens ?? 0) < 4096) {
611877
612624
  effectiveMaxTokens = 4096;
611878
612625
  }
611879
- const requestMessages = effectiveThink ? cleanedMessages : injectNoThinkDirective(cleanedMessages);
612626
+ const requestMessages = cleanedMessages;
611880
612627
  const responseFormat = request.responseFormat ?? request.response_format;
611881
612628
  const isOllama = shouldUseOllamaPoolForBaseUrl(this.baseUrl);
611882
612629
  const body = {
@@ -612012,7 +612759,7 @@ ${description}`
612012
612759
  }
612013
612760
  }
612014
612761
  if (shouldRetryThinkGuard || shouldRecoverFromEmpty) {
612015
- const retryMessages = injectNoThinkDirective(requestMessages);
612762
+ const retryMessages = requestMessages;
612016
612763
  const retryBody = {
612017
612764
  model: this.model,
612018
612765
  messages: retryMessages,
@@ -612093,7 +612840,7 @@ ${description}`
612093
612840
  }
612094
612841
  async nativeOllamaChatCompletion(request) {
612095
612842
  const cleanedMessages = applyMemoryPrefixToMessages(normalizeMessagesForStrictOpenAI(sanitizeHistoryThink(request.messages)), request.memoryPrefix);
612096
- const requestMessages = injectNoThinkDirective(cleanedMessages);
612843
+ const requestMessages = cleanedMessages;
612097
612844
  const responseFormat = request.responseFormat ?? request.response_format;
612098
612845
  const options2 = {
612099
612846
  temperature: request.temperature,
@@ -612277,7 +613024,7 @@ ${description}`
612277
613024
  if (effectiveThink === true && (effectiveMaxTokens ?? 0) < 4096) {
612278
613025
  effectiveMaxTokens = 4096;
612279
613026
  }
612280
- const requestMessages = effectiveThink ? cleanedMessages : injectNoThinkDirective(cleanedMessages);
613027
+ const requestMessages = cleanedMessages;
612281
613028
  const responseFormat = request.responseFormat ?? request.response_format;
612282
613029
  const body = {
612283
613030
  model: this.model,
@@ -612562,6 +613309,7 @@ var NexusAgenticBackend;
612562
613309
  var init_nexusBackend = __esm({
612563
613310
  "packages/orchestrator/dist/nexusBackend.js"() {
612564
613311
  "use strict";
613312
+ init_textSanitize();
612565
613313
  NexusAgenticBackend = class _NexusAgenticBackend {
612566
613314
  sendFn;
612567
613315
  model;
@@ -612592,32 +613340,10 @@ var init_nexusBackend = __esm({
612592
613340
  return this.thinking === true;
612593
613341
  }
612594
613342
  noThinkMessages(messages2) {
612595
- let lastUserIdx = -1;
612596
- for (let i2 = messages2.length - 1; i2 >= 0; i2--) {
612597
- if (messages2[i2]?.role === "user") {
612598
- lastUserIdx = i2;
612599
- break;
612600
- }
612601
- }
612602
- if (lastUserIdx < 0)
612603
- return messages2;
612604
- const target = messages2[lastUserIdx];
612605
- if (!target || typeof target.content !== "string")
612606
- return messages2;
612607
- const hasOllamaNoThink = /\/nothink\b/i.test(target.content);
612608
- const hasQwenNoThink = /\/no[_-]think\b/i.test(target.content);
612609
- if (hasOllamaNoThink && hasQwenNoThink)
612610
- return messages2;
612611
- const suffix = [
612612
- hasOllamaNoThink ? null : "/nothink",
612613
- hasQwenNoThink ? null : "/no_think"
612614
- ].filter(Boolean).join("\n");
612615
- return messages2.map((m2, i2) => i2 === lastUserIdx ? { ...m2, content: `${target.content}
612616
-
612617
- ${suffix}` } : m2);
613343
+ return messages2.map((message2) => typeof message2.content === "string" ? { ...message2, content: stripNoThinkPromptDirectives(message2.content) } : message2);
612618
613344
  }
612619
613345
  requestMessages(request, effectiveThink) {
612620
- return effectiveThink ? request.messages : this.noThinkMessages(request.messages);
613346
+ return this.noThinkMessages(request.messages);
612621
613347
  }
612622
613348
  applyOptionalRequestFields(daemonArgs, request) {
612623
613349
  const responseFormat = request.responseFormat ?? request.response_format;
@@ -619166,6 +619892,7 @@ __export(dist_exports3, {
619166
619892
  classifyHandoff: () => classifyHandoff,
619167
619893
  classifyKind: () => classifyKind,
619168
619894
  classifyOllamaProcesses: () => classifyOllamaProcesses,
619895
+ classifySteeringIntent: () => classifySteeringIntent,
619169
619896
  cleanForStorage: () => cleanForStorage,
619170
619897
  cleanScaffolding: () => cleanScaffolding,
619171
619898
  cleanupStaleOllamaProcesses: () => cleanupStaleOllamaProcesses,
@@ -619384,6 +620111,9 @@ __export(dist_exports3, {
619384
620111
  skillShouldShow: () => skillShouldShow,
619385
620112
  specificityScore: () => specificityScore,
619386
620113
  stabilityFilePath: () => stabilityFilePath,
620114
+ steeringGatesOldPlan: () => steeringGatesOldPlan,
620115
+ steeringRequiresReconciliation: () => steeringRequiresReconciliation,
620116
+ stripNoThinkPromptDirectives: () => stripNoThinkPromptDirectives,
619387
620117
  stripThinkTags: () => stripThinkTags,
619388
620118
  stripXmlControlBlocks: () => stripXmlControlBlocks,
619389
620119
  stripYamlFrontmatter: () => stripYamlFrontmatter,
@@ -633849,7 +634579,7 @@ async function fetchOpenAIModels(baseUrl2, apiKey) {
633849
634579
  sizeBytes: 0,
633850
634580
  modified: m2.created ? formatRelativeTime(new Date(m2.created * 1e3).toISOString()) : "",
633851
634581
  parameterSize: m2.owned_by ?? void 0,
633852
- contextLength: m2.context_length ?? m2.max_model_len ?? void 0
634582
+ contextLength: positiveInteger(m2.context_length) ?? positiveInteger(m2.max_model_len) ?? positiveInteger(m2.meta?.["n_ctx"]) ?? positiveInteger(m2.meta?.["context_length"]) ?? void 0
633853
634583
  })).sort((a2, b) => a2.name.localeCompare(b.name));
633854
634584
  }
633855
634585
  async function fetchPeerModels(peerId, authKey) {
@@ -634149,14 +634879,14 @@ function firstPositive(record, keys) {
634149
634879
  return void 0;
634150
634880
  }
634151
634881
  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
- ]);
634882
+ const direct = firstPositive(record, CONTEXT_CAPACITY_KEYS);
634883
+ if (direct !== void 0) return direct;
634884
+ const meta = asRecord(record["meta"]);
634885
+ const metaCapacity = meta ? firstPositive(meta, CONTEXT_CAPACITY_KEYS) : void 0;
634886
+ if (metaCapacity !== void 0) return metaCapacity;
634887
+ const defaults3 = asRecord(record["default_generation_settings"]);
634888
+ const params = defaults3 && asRecord(defaults3["params"]);
634889
+ return params ? firstPositive(params, CONTEXT_CAPACITY_KEYS) : void 0;
634160
634890
  }
634161
634891
  function telemetryHeaders(apiKey) {
634162
634892
  return apiKey ? { Authorization: `Bearer ${apiKey}` } : void 0;
@@ -634366,7 +635096,7 @@ function formatRelativeTime(iso2) {
634366
635096
  const months = Math.floor(days / 30);
634367
635097
  return `${months}mo ago`;
634368
635098
  }
634369
- var IMAGE_GEN_PATTERNS, LLAMA_CPP_TELEMETRY_TIMEOUT_MS;
635099
+ var IMAGE_GEN_PATTERNS, LLAMA_CPP_TELEMETRY_TIMEOUT_MS, CONTEXT_CAPACITY_KEYS;
634370
635100
  var init_model_picker = __esm({
634371
635101
  "packages/cli/src/tui/model-picker.ts"() {
634372
635102
  init_dist6();
@@ -634381,6 +635111,14 @@ var init_model_picker = __esm({
634381
635111
  /imagen/i
634382
635112
  ];
634383
635113
  LLAMA_CPP_TELEMETRY_TIMEOUT_MS = 2500;
635114
+ CONTEXT_CAPACITY_KEYS = [
635115
+ "n_ctx",
635116
+ "n_ctx_train",
635117
+ "context_length",
635118
+ "context_window",
635119
+ "max_model_len",
635120
+ "max_context_length"
635121
+ ];
634384
635122
  }
634385
635123
  });
634386
635124
 
@@ -634747,8 +635485,8 @@ function formatBranchExtractSummary(output) {
634747
635485
  }
634748
635486
  }
634749
635487
  const isDuplicate = /^\[branch-duplicate-blocked\]/i.test(lines[0]);
634750
- const header = isDuplicate ? "Branch-extract duplicate reuse" : "Branch-extract preempted";
634751
- const whatHappened = isDuplicate ? "a cache-safe duplicate was detected" : "read was auto-summarized before injecting into context";
635488
+ const header = isDuplicate ? "Branch-extract duplicate reuse" : "Branch extraction completed";
635489
+ const whatHappened = isDuplicate ? "a cache-safe duplicate was detected" : "an isolated inference worker returned bounded, verified evidence";
634752
635490
  const out = [
634753
635491
  `↳ ${header}`,
634754
635492
  ` ├ what happened: ${whatHappened}`,
@@ -634814,7 +635552,7 @@ function summarizeInternalControlOutput(output) {
634814
635552
  if (!output) return null;
634815
635553
  const firstLine = output.split(/\r?\n/)[0]?.trim().toLowerCase() ?? "";
634816
635554
  const lower = output.toLowerCase();
634817
- if (firstLine.includes("[branch-extract") || firstLine.includes("[branch-duplicate-blocked]") || lower.includes("branch-extract preempted")) {
635555
+ if (firstLine.includes("[branch-extract") || firstLine.includes("[branch-duplicate-blocked]") || lower.includes("branch extraction executed") || lower.includes("branch extraction completed")) {
634818
635556
  return formatBranchExtractSummary(output);
634819
635557
  }
634820
635558
  if (firstLine.includes("[echo break") || firstLine.includes("[echo-break") || lower.includes("echo-1:")) {
@@ -663382,19 +664120,23 @@ var init_runtime_keys = __esm({
663382
664120
  // packages/cli/src/daemon.ts
663383
664121
  var daemon_exports = {};
663384
664122
  __export(daemon_exports, {
664123
+ claimDaemonEndpoint: () => claimDaemonEndpoint,
663385
664124
  ensureDaemon: () => ensureDaemon,
664125
+ ensureDaemonVersion: () => ensureDaemonVersion,
663386
664126
  forceKillDaemon: () => forceKillDaemon,
663387
664127
  getDaemonPid: () => getDaemonPid,
663388
664128
  getDaemonReportedVersion: () => getDaemonReportedVersion,
663389
664129
  getDaemonStatus: () => getDaemonStatus,
663390
664130
  getLocalCliVersion: () => getLocalCliVersion,
663391
664131
  isDaemonRunning: () => isDaemonRunning,
664132
+ releaseDaemonEndpointClaim: () => releaseDaemonEndpointClaim,
664133
+ releaseDaemonEndpointForCurrentProcess: () => releaseDaemonEndpointForCurrentProcess,
663392
664134
  restartDaemon: () => restartDaemon,
663393
664135
  startDaemon: () => startDaemon,
663394
664136
  stopDaemon: () => stopDaemon
663395
664137
  });
663396
664138
  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";
664139
+ 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
664140
  import { join as join149 } from "node:path";
663399
664141
  import { homedir as homedir51 } from "node:os";
663400
664142
  import { fileURLToPath as fileURLToPath20 } from "node:url";
@@ -663408,6 +664150,106 @@ function getDaemonPort() {
663408
664150
  }
663409
664151
  return parseInt(process.env["OMNIUS_PORT"] ?? String(DEFAULT_PORT2), 10);
663410
664152
  }
664153
+ function daemonEndpoint(port) {
664154
+ return `127.0.0.1:${port}`;
664155
+ }
664156
+ function daemonLockFile(port) {
664157
+ return join149(OMNIUS_DIR2, `daemon-${port}.lock`);
664158
+ }
664159
+ function processIsAlive(pid) {
664160
+ try {
664161
+ process.kill(pid, 0);
664162
+ return true;
664163
+ } catch (error) {
664164
+ return error.code !== "ESRCH";
664165
+ }
664166
+ }
664167
+ function readDaemonLock(lockFile) {
664168
+ try {
664169
+ const value2 = JSON.parse(readFileSync114(lockFile, "utf8"));
664170
+ if (typeof value2.endpoint !== "string" || typeof value2.pid !== "number" || !Number.isInteger(value2.pid) || value2.pid <= 0 || typeof value2.token !== "string" || typeof value2.startedAt !== "number") {
664171
+ return null;
664172
+ }
664173
+ return value2;
664174
+ } catch {
664175
+ return null;
664176
+ }
664177
+ }
664178
+ function daemonLockIsInitializing(lockFile) {
664179
+ try {
664180
+ return Date.now() - statSync57(lockFile).mtimeMs < LOCK_INITIALIZATION_GRACE_MS;
664181
+ } catch {
664182
+ return false;
664183
+ }
664184
+ }
664185
+ function newDaemonLockToken() {
664186
+ return `${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
664187
+ }
664188
+ function claimDaemonEndpoint(port = getDaemonPort(), inheritedToken) {
664189
+ mkdirSync82(OMNIUS_DIR2, { recursive: true });
664190
+ const endpoint = daemonEndpoint(port);
664191
+ const lockFile = daemonLockFile(port);
664192
+ for (let attempt = 0; attempt < 3; attempt++) {
664193
+ const token = inheritedToken ?? newDaemonLockToken();
664194
+ const record = {
664195
+ endpoint,
664196
+ pid: process.pid,
664197
+ token,
664198
+ startedAt: Date.now()
664199
+ };
664200
+ let fd = null;
664201
+ try {
664202
+ fd = openSync4(lockFile, "wx", 384);
664203
+ writeSync2(fd, JSON.stringify(record));
664204
+ closeSync4(fd);
664205
+ return { endpoint, lockFile, pid: process.pid, port, token };
664206
+ } catch (error) {
664207
+ if (fd !== null) {
664208
+ try {
664209
+ closeSync4(fd);
664210
+ } catch {
664211
+ }
664212
+ try {
664213
+ unlinkSync27(lockFile);
664214
+ } catch {
664215
+ }
664216
+ }
664217
+ const code8 = error.code;
664218
+ if (code8 !== "EEXIST") return null;
664219
+ }
664220
+ const existing = readDaemonLock(lockFile);
664221
+ if (existing?.endpoint === endpoint && inheritedToken && existing.token === inheritedToken) {
664222
+ const transferred = { ...existing, pid: process.pid, startedAt: Date.now() };
664223
+ writeFileSync70(lockFile, JSON.stringify(transferred), { encoding: "utf8", mode: 384 });
664224
+ return { endpoint, lockFile, pid: process.pid, port, token: inheritedToken };
664225
+ }
664226
+ if (existing && processIsAlive(existing.pid) || !existing && daemonLockIsInitializing(lockFile)) {
664227
+ return null;
664228
+ }
664229
+ try {
664230
+ unlinkSync27(lockFile);
664231
+ } catch {
664232
+ }
664233
+ }
664234
+ return null;
664235
+ }
664236
+ function releaseDaemonEndpointClaim(claim) {
664237
+ const existing = readDaemonLock(claim.lockFile);
664238
+ if (existing?.pid !== claim.pid || existing.token !== claim.token) return;
664239
+ try {
664240
+ unlinkSync27(claim.lockFile);
664241
+ } catch {
664242
+ }
664243
+ }
664244
+ function releaseDaemonEndpointForCurrentProcess(port = getDaemonPort()) {
664245
+ const lockFile = daemonLockFile(port);
664246
+ const existing = readDaemonLock(lockFile);
664247
+ if (existing?.pid !== process.pid) return;
664248
+ try {
664249
+ unlinkSync27(lockFile);
664250
+ } catch {
664251
+ }
664252
+ }
663411
664253
  async function isDaemonRunning(port) {
663412
664254
  const p2 = port ?? getDaemonPort();
663413
664255
  try {
@@ -663444,7 +664286,19 @@ async function getDaemonReportedVersion(port) {
663444
664286
  return null;
663445
664287
  }
663446
664288
  }
663447
- async function restartDaemon(port) {
664289
+ async function waitForDaemonReady(port, expectedVersion, attempts = 24) {
664290
+ let observedVersion = null;
664291
+ for (let attempt = 0; attempt < attempts; attempt++) {
664292
+ await new Promise((resolve82) => setTimeout(resolve82, 500));
664293
+ if (!await isDaemonRunning(port)) continue;
664294
+ observedVersion = await getDaemonReportedVersion(port);
664295
+ if (!expectedVersion || expectedVersion === "0.0.0" || observedVersion === expectedVersion) {
664296
+ return { ok: true, observedVersion };
664297
+ }
664298
+ }
664299
+ return { ok: false, observedVersion };
664300
+ }
664301
+ async function restartDaemon(port, expectedVersion) {
663448
664302
  const p2 = port ?? getDaemonPort();
663449
664303
  try {
663450
664304
  const { spawnSync: spawnSync9 } = await import("node:child_process");
@@ -663454,12 +664308,14 @@ async function restartDaemon(port) {
663454
664308
  });
663455
664309
  if (enabled2.status === 0) {
663456
664310
  spawnSync9("systemctl", ["--user", "restart", "omnius-daemon.service"], { stdio: "ignore", timeout: 2e4 });
663457
- return;
664311
+ return (await waitForDaemonReady(p2, expectedVersion)).ok;
663458
664312
  }
663459
664313
  } catch {
663460
664314
  }
663461
664315
  await forceKillDaemon(p2);
663462
- await startDaemon();
664316
+ const pid = await startDaemon();
664317
+ if (!pid) return false;
664318
+ return (await waitForDaemonReady(p2, expectedVersion)).ok;
663463
664319
  }
663464
664320
  function getDaemonPid() {
663465
664321
  if (!existsSync140(PID_FILE2)) return null;
@@ -663518,9 +664374,15 @@ async function resolveDaemonCommand(nodeExe) {
663518
664374
  }
663519
664375
  async function startDaemon() {
663520
664376
  mkdirSync82(OMNIUS_DIR2, { recursive: true });
664377
+ const daemonPort = getDaemonPort();
664378
+ const endpointClaim = claimDaemonEndpoint(daemonPort);
664379
+ if (!endpointClaim) return null;
663521
664380
  const nodeExe = process.execPath;
663522
664381
  const daemonCommand = await resolveDaemonCommand(nodeExe);
663523
- if (!daemonCommand) return null;
664382
+ if (!daemonCommand) {
664383
+ releaseDaemonEndpointClaim(endpointClaim);
664384
+ return null;
664385
+ }
663524
664386
  let outFd = null;
663525
664387
  let errFd = null;
663526
664388
  try {
@@ -663536,6 +664398,8 @@ async function startDaemon() {
663536
664398
  ...processLeaseEnv(leaseId, ownerId, process.cwd()),
663537
664399
  OMNIUS_DAEMON: "1",
663538
664400
  // signal to serve.ts that it's running as daemon
664401
+ OMNIUS_DAEMON_LOCK_TOKEN: endpointClaim.token,
664402
+ OMNIUS_DAEMON_LOCK_PORT: String(daemonPort),
663539
664403
  OMNIUS_PROCESS_OWNER_KIND: "daemon",
663540
664404
  OMNIUS_PROCESS_LIFECYCLE: "daemon",
663541
664405
  OMNIUS_PROCESS_PERSISTENT: "1"
@@ -663561,6 +664425,7 @@ async function startDaemon() {
663561
664425
  }
663562
664426
  return pid;
663563
664427
  } catch {
664428
+ releaseDaemonEndpointClaim(endpointClaim);
663564
664429
  return null;
663565
664430
  } finally {
663566
664431
  if (outFd !== null) try {
@@ -663652,24 +664517,18 @@ async function forceKillDaemon(port) {
663652
664517
  }
663653
664518
  return killed;
663654
664519
  }
663655
- async function ensureDaemon() {
663656
- const port = getDaemonPort();
664520
+ async function ensureDaemonVersion(expectedVersion = getLocalCliVersion(), port = getDaemonPort()) {
664521
+ const finish = (ok3, action, observedVersion) => ({ ok: ok3, action, expectedVersion, observedVersion, port });
663657
664522
  if (await isDaemonRunning(port)) {
663658
664523
  if (process.env["OMNIUS_NO_VERSION_GUARD"] !== "1") {
663659
664524
  const running = await getDaemonReportedVersion(port);
663660
- const local = getLocalCliVersion();
663661
- if (running && local !== "0.0.0" && running !== local) {
663662
- await restartDaemon(port);
663663
- for (let i2 = 0; i2 < 24; i2++) {
663664
- await new Promise((r2) => setTimeout(r2, 500));
663665
- if (await isDaemonRunning(port) && await getDaemonReportedVersion(port) === local) {
663666
- return true;
663667
- }
663668
- }
663669
- return await isDaemonRunning(port);
664525
+ if (expectedVersion !== "0.0.0" && running !== expectedVersion) {
664526
+ const ok3 = await restartDaemon(port, expectedVersion);
664527
+ const observedVersion = await getDaemonReportedVersion(port);
664528
+ return finish(ok3 && observedVersion === expectedVersion, ok3 ? "restarted" : "failed", observedVersion);
663670
664529
  }
663671
664530
  }
663672
- return true;
664531
+ return finish(true, "unchanged", await getDaemonReportedVersion(port));
663673
664532
  }
663674
664533
  const stalePid = getDaemonPid();
663675
664534
  if (stalePid) {
@@ -663683,13 +664542,19 @@ async function ensureDaemon() {
663683
664542
  }
663684
664543
  }
663685
664544
  const pid = await startDaemon();
663686
- if (!pid) return false;
663687
- for (let i2 = 0; i2 < 20; i2++) {
663688
- await new Promise((r2) => setTimeout(r2, 500));
663689
- if (await isDaemonRunning(port)) {
663690
- return true;
664545
+ if (!pid) {
664546
+ for (let i2 = 0; i2 < 20; i2++) {
664547
+ await new Promise((r2) => setTimeout(r2, 500));
664548
+ if (await isDaemonRunning(port)) {
664549
+ const observedVersion = await getDaemonReportedVersion(port);
664550
+ const versionMatches = expectedVersion === "0.0.0" || observedVersion === expectedVersion;
664551
+ return finish(versionMatches, versionMatches ? "started" : "failed", observedVersion);
664552
+ }
663691
664553
  }
664554
+ return finish(false, "failed", null);
663692
664555
  }
664556
+ const ready = await waitForDaemonReady(port, expectedVersion, 20);
664557
+ if (ready.ok) return finish(true, "started", ready.observedVersion);
663693
664558
  try {
663694
664559
  process.kill(pid, "SIGTERM");
663695
664560
  } catch {
@@ -663698,7 +664563,11 @@ async function ensureDaemon() {
663698
664563
  unlinkSync27(PID_FILE2);
663699
664564
  } catch {
663700
664565
  }
663701
- return false;
664566
+ releaseDaemonEndpointForCurrentProcess(port);
664567
+ return finish(false, "failed", ready.observedVersion);
664568
+ }
664569
+ async function ensureDaemon() {
664570
+ return (await ensureDaemonVersion()).ok;
663702
664571
  }
663703
664572
  async function getDaemonStatus() {
663704
664573
  const port = getDaemonPort();
@@ -663719,13 +664588,14 @@ async function getDaemonStatus() {
663719
664588
  }
663720
664589
  return { running, pid, port, uptime: uptime2, pidFile: PID_FILE2 };
663721
664590
  }
663722
- var OMNIUS_DIR2, PID_FILE2, DEFAULT_PORT2;
664591
+ var OMNIUS_DIR2, PID_FILE2, DEFAULT_PORT2, LOCK_INITIALIZATION_GRACE_MS;
663723
664592
  var init_daemon = __esm({
663724
664593
  "packages/cli/src/daemon.ts"() {
663725
664594
  init_dist5();
663726
664595
  OMNIUS_DIR2 = join149(homedir51(), ".omnius");
663727
664596
  PID_FILE2 = join149(OMNIUS_DIR2, "daemon.pid");
663728
664597
  DEFAULT_PORT2 = 11435;
664598
+ LOCK_INITIALIZATION_GRACE_MS = 5e3;
663729
664599
  }
663730
664600
  });
663731
664601
 
@@ -663883,7 +664753,7 @@ __export(kg_prune_exports, {
663883
664753
  pruneKnowledgeGraph: () => pruneKnowledgeGraph,
663884
664754
  pruneKnowledgeGraphWithInference: () => pruneKnowledgeGraphWithInference
663885
664755
  });
663886
- import { existsSync as existsSync142, statSync as statSync57 } from "node:fs";
664756
+ import { existsSync as existsSync142, statSync as statSync58 } from "node:fs";
663887
664757
  import { join as join151 } from "node:path";
663888
664758
  function stateDirFor(workingDir) {
663889
664759
  return join151(workingDir, ".omnius");
@@ -663903,13 +664773,13 @@ function knowledgeGraphStats(workingDir) {
663903
664773
  };
663904
664774
  if (stats.exists) {
663905
664775
  try {
663906
- stats.sizeBytes = statSync57(dbPath).size;
664776
+ stats.sizeBytes = statSync58(dbPath).size;
663907
664777
  } catch {
663908
664778
  }
663909
664779
  }
663910
664780
  if (existsSync142(archivePath)) {
663911
664781
  try {
663912
- stats.archiveSizeBytes = statSync57(archivePath).size;
664782
+ stats.archiveSizeBytes = statSync58(archivePath).size;
663913
664783
  } catch {
663914
664784
  }
663915
664785
  }
@@ -666530,7 +667400,7 @@ import {
666530
667400
  readFileSync as readFileSync118,
666531
667401
  unlinkSync as unlinkSync30,
666532
667402
  readdirSync as readdirSync47,
666533
- statSync as statSync58,
667403
+ statSync as statSync59,
666534
667404
  copyFileSync as copyFileSync6,
666535
667405
  rmSync as rmSync12
666536
667406
  } from "node:fs";
@@ -666664,7 +667534,7 @@ function mergeDir2(src2, dst) {
666664
667534
  if (entry.isDirectory()) {
666665
667535
  mergeDir2(s2, d2);
666666
667536
  } else if (entry.isFile()) {
666667
- if (!existsSync146(d2) || statSync58(s2).mtimeMs > statSync58(d2).mtimeMs) {
667537
+ if (!existsSync146(d2) || statSync59(s2).mtimeMs > statSync59(d2).mtimeMs) {
666668
667538
  copyFileSync6(s2, d2);
666669
667539
  }
666670
667540
  }
@@ -668149,7 +669019,7 @@ except Exception as exc:
668149
669019
  const p2 = join155(dir, f2);
668150
669020
  let size = 0;
668151
669021
  try {
668152
- size = statSync58(p2).size;
669022
+ size = statSync59(p2).size;
668153
669023
  } catch {
668154
669024
  }
668155
669025
  const entry = meta[f2];
@@ -671187,10 +672057,10 @@ import {
671187
672057
  mkdirSync as mkdirSync87,
671188
672058
  readdirSync as readdirSync48,
671189
672059
  lstatSync as lstatSync2,
671190
- statSync as statSync59,
672060
+ statSync as statSync60,
671191
672061
  rmSync as rmSync13,
671192
672062
  appendFileSync as appendFileSync16,
671193
- writeSync as writeSync2
672063
+ writeSync as writeSync3
671194
672064
  } from "node:fs";
671195
672065
  import { basename as basename32, dirname as dirname49, relative as relative19, join as join156 } from "node:path";
671196
672066
  function omniusPinnedDependencyVersion(name10) {
@@ -671442,7 +672312,7 @@ function parseTelegramMessageIdList(value2) {
671442
672312
  }
671443
672313
  function writeDirectTerminal(data) {
671444
672314
  try {
671445
- writeSync2(1, data);
672315
+ writeSync3(1, data);
671446
672316
  } catch {
671447
672317
  try {
671448
672318
  overlayWrite(data);
@@ -674053,7 +674923,7 @@ async function handleSlashCommand(input, ctx3) {
674053
674923
  ipfsFiles = files.length;
674054
674924
  for (const f2 of files) {
674055
674925
  try {
674056
- ipfsBytes += statSync59(join156(ipfsLocalDir, f2)).size;
674926
+ ipfsBytes += statSync60(join156(ipfsLocalDir, f2)).size;
674057
674927
  } catch {
674058
674928
  }
674059
674929
  }
@@ -674066,7 +674936,7 @@ async function handleSlashCommand(input, ctx3) {
674066
674936
  else {
674067
674937
  heliaBlocks++;
674068
674938
  try {
674069
- heliaBytes += statSync59(join156(dir, entry.name)).size;
674939
+ heliaBytes += statSync60(join156(dir, entry.name)).size;
674070
674940
  } catch {
674071
674941
  }
674072
674942
  }
@@ -674209,7 +675079,7 @@ async function handleSlashCommand(input, ctx3) {
674209
675079
  lines.push(`
674210
675080
  ${c3.bold("Structured Memory (SQLite)")}`);
674211
675081
  lines.push(
674212
- ` Memories: ${c3.bold(String(count))} DB: ${c3.dim(formatFileSize(statSync59(dbPath).size))}`
675082
+ ` Memories: ${c3.bold(String(count))} DB: ${c3.dim(formatFileSize(statSync60(dbPath).size))}`
674213
675083
  );
674214
675084
  cDb(db);
674215
675085
  }
@@ -674241,7 +675111,7 @@ async function handleSlashCommand(input, ctx3) {
674241
675111
  walkStorage(full, subCat);
674242
675112
  } else {
674243
675113
  try {
674244
- const sz = statSync59(full).size;
675114
+ const sz = statSync60(full).size;
674245
675115
  totalBytes += sz;
674246
675116
  if (!categories[category])
674247
675117
  categories[category] = { files: 0, bytes: 0 };
@@ -681393,7 +682263,7 @@ async function showCohereDashboard(ctx3) {
681393
682263
  const snapItems = snaps.slice(0, 20).map((f2) => ({
681394
682264
  key: f2,
681395
682265
  label: f2.replace(".json", ""),
681396
- detail: `${formatFileSize(statSync59(join156(snapDir, f2)).size)}`
682266
+ detail: `${formatFileSize(statSync60(join156(snapDir, f2)).size)}`
681397
682267
  }));
681398
682268
  if (snapItems.length > 0) {
681399
682269
  await tuiSelect({
@@ -687306,6 +688176,23 @@ async function handleUpdate(subcommand, ctx3) {
687306
688176
  installOverlay.dismiss();
687307
688177
  return;
687308
688178
  }
688179
+ installOverlay.setPhase("Daemon");
688180
+ installOverlay.setStatus("Gracefully upgrading shared daemon...");
688181
+ const { ensureDaemonVersion: ensureDaemonVersion2, getLocalCliVersion: getLocalCliVersion2 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
688182
+ const expectedDaemonVersion = getLocalCliVersion2();
688183
+ const daemonUpgrade = await ensureDaemonVersion2(expectedDaemonVersion);
688184
+ if (!daemonUpgrade.ok) {
688185
+ installOverlay.stop("Update installed, but daemon upgrade was not verified");
688186
+ await new Promise((r2) => setTimeout(r2, 1200));
688187
+ installOverlay.dismiss();
688188
+ renderError(
688189
+ `Updated CLI to ${expectedDaemonVersion}, but the shared daemon still reports ${daemonUpgrade.observedVersion ?? "unavailable"}. The TUI will remain open; retry /update after resolving the daemon service.`
688190
+ );
688191
+ return;
688192
+ }
688193
+ installOverlay.setStatus(
688194
+ daemonUpgrade.action === "restarted" ? `Daemon upgraded to ${expectedDaemonVersion}` : `Daemon verified at ${expectedDaemonVersion}`
688195
+ );
687309
688196
  registry2.killAll();
687310
688197
  ctx3.contextSave?.();
687311
688198
  const hadActiveTask = ctx3.savePendingTaskState?.() ?? false;
@@ -696286,48 +697173,86 @@ var init_emotion_engine = __esm({
696286
697173
  }
696287
697174
  return { allowed: true };
696288
697175
  }
697176
+ /** Auxiliary stages share one non-queuing backend slot. */
697177
+ auxiliaryInferenceInFlight = false;
697178
+ /** Failed stages cool down independently; a successful nonempty reply resets them. */
697179
+ internalInferenceCircuit = /* @__PURE__ */ new Map();
697180
+ noteInternalInferenceFailure(stage2, now2 = Date.now()) {
697181
+ const prior = this.internalInferenceCircuit.get(stage2);
697182
+ const failureCount = Math.min(6, (prior?.failureCount ?? 0) + 1);
697183
+ const cooldownMs = Math.min(10 * 6e4, 3e4 * 2 ** (failureCount - 1));
697184
+ this.internalInferenceCircuit.set(stage2, {
697185
+ failureCount,
697186
+ openUntil: now2 + cooldownMs
697187
+ });
697188
+ }
697189
+ resetInternalInferenceCircuit(stage2) {
697190
+ this.internalInferenceCircuit.delete(stage2);
697191
+ }
696289
697192
  async runDirectInternalInference(opts) {
696290
697193
  const cwd4 = resolve71(process.cwd());
696291
697194
  const startedAt2 = Date.now();
696292
- const admission = await this.admitInternalInference();
696293
- if (!admission.allowed) {
697195
+ const circuit = this.internalInferenceCircuit.get(opts.stage);
697196
+ if (circuit && circuit.openUntil > startedAt2) {
696294
697197
  this.recordInternalDecision({
696295
697198
  stage: opts.stage,
696296
697199
  status: "skipped",
696297
697200
  elapsedMs: Date.now() - startedAt2,
696298
- skipReason: admission.reason,
697201
+ skipReason: `internal_inference_circuit_open:${opts.stage}:retry_after_ms=${circuit.openUntil - startedAt2}`,
696299
697202
  promptChars: opts.system.length + opts.user.length
696300
697203
  });
696301
697204
  return null;
696302
697205
  }
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
- });
697206
+ if (this.auxiliaryInferenceInFlight) {
697207
+ this.recordInternalDecision({
697208
+ stage: opts.stage,
697209
+ status: "skipped",
697210
+ elapsedMs: Date.now() - startedAt2,
697211
+ skipReason: `auxiliary_inference_busy:${opts.stage}`,
697212
+ promptChars: opts.system.length + opts.user.length
697213
+ });
697214
+ return null;
697215
+ }
697216
+ this.auxiliaryInferenceInFlight = true;
696330
697217
  try {
697218
+ const admission = await this.admitInternalInference();
697219
+ if (!admission.allowed) {
697220
+ this.recordInternalDecision({
697221
+ stage: opts.stage,
697222
+ status: "skipped",
697223
+ elapsedMs: Date.now() - startedAt2,
697224
+ skipReason: admission.reason,
697225
+ promptChars: opts.system.length + opts.user.length
697226
+ });
697227
+ return null;
697228
+ }
697229
+ const request = {
697230
+ messages: [
697231
+ { role: "system", content: opts.system },
697232
+ { role: "user", content: opts.user }
697233
+ ],
697234
+ tools: [],
697235
+ temperature: opts.temperature,
697236
+ maxTokens: opts.maxTokens,
697237
+ timeoutMs: opts.timeoutMs,
697238
+ think: false,
697239
+ disableEmptyContentRecovery: true,
697240
+ poolQueuePolicy: "skip",
697241
+ poolQueueTimeoutMs: 1
697242
+ };
697243
+ recordContextWindowDump({
697244
+ source: "emotionEngine",
697245
+ stage: opts.stage,
697246
+ agentType: "internal",
697247
+ sessionId: process.env["OMNIUS_SESSION_ID"] || "emotion-engine",
697248
+ runId: process.env["OMNIUS_SESSION_ID"] || "emotion-engine",
697249
+ turn: 0,
697250
+ attempt: 0,
697251
+ model: this.config.model,
697252
+ cwd: cwd4,
697253
+ note: opts.note,
697254
+ request
697255
+ });
696331
697256
  const backend = new OllamaAgenticBackend(
696332
697257
  this.config.backendUrl,
696333
697258
  this.config.model,
@@ -696338,6 +697263,19 @@ var init_emotion_engine = __esm({
696338
697263
  const output = String(
696339
697264
  result.choices?.[0]?.message?.content ?? ""
696340
697265
  ).trim();
697266
+ if (!output) {
697267
+ const error = "empty internal inference response";
697268
+ this.noteInternalInferenceFailure(opts.stage);
697269
+ this.recordInternalDecision({
697270
+ stage: opts.stage,
697271
+ status: "error",
697272
+ elapsedMs: Date.now() - startedAt2,
697273
+ error,
697274
+ promptChars: opts.system.length + opts.user.length
697275
+ });
697276
+ return null;
697277
+ }
697278
+ this.resetInternalInferenceCircuit(opts.stage);
696341
697279
  this.recordInternalDecision({
696342
697280
  stage: opts.stage,
696343
697281
  status: "ok",
@@ -696347,14 +697285,18 @@ var init_emotion_engine = __esm({
696347
697285
  });
696348
697286
  return output;
696349
697287
  } catch (err) {
697288
+ const error = err instanceof Error ? err.message : String(err);
697289
+ this.noteInternalInferenceFailure(opts.stage);
696350
697290
  this.recordInternalDecision({
696351
697291
  stage: opts.stage,
696352
697292
  status: "error",
696353
697293
  elapsedMs: Date.now() - startedAt2,
696354
- error: err instanceof Error ? err.message : String(err),
697294
+ error,
696355
697295
  promptChars: opts.system.length + opts.user.length
696356
697296
  });
696357
697297
  throw err;
697298
+ } finally {
697299
+ this.auxiliaryInferenceInFlight = false;
696358
697300
  }
696359
697301
  }
696360
697302
  recordInternalDecision(entry) {
@@ -697716,7 +698658,7 @@ import {
697716
698658
  existsSync as existsSync157,
697717
698659
  mkdirSync as mkdirSync96,
697718
698660
  readFileSync as readFileSync128,
697719
- statSync as statSync60,
698661
+ statSync as statSync61,
697720
698662
  unlinkSync as unlinkSync33,
697721
698663
  writeFileSync as writeFileSync83
697722
698664
  } from "node:fs";
@@ -698229,7 +699171,7 @@ function materializeTelegramCreativeArtifactForSend(root, rawPath) {
698229
699171
  }
698230
699172
  function safeStatFile(path16) {
698231
699173
  try {
698232
- return statSync60(path16).isFile();
699174
+ return statSync61(path16).isFile();
698233
699175
  } catch {
698234
699176
  return false;
698235
699177
  }
@@ -698500,7 +699442,7 @@ ${(result.error || result.output || "").slice(0, 1200)}`,
698500
699442
  for (const fn of cleanup) fn();
698501
699443
  }
698502
699444
  rememberCreated(this.root, guarded.path.abs);
698503
- const sizeKB = Math.round(statSync60(guarded.path.abs).size / 1024);
699445
+ const sizeKB = Math.round(statSync61(guarded.path.abs).size / 1024);
698504
699446
  this.emitProgress(start2, {
698505
699447
  stage: "save",
698506
699448
  message: `Saved scoped audio file (${sizeKB}KB)`
@@ -701883,7 +702825,7 @@ import {
701883
702825
  existsSync as existsSync160,
701884
702826
  unlinkSync as unlinkSync36,
701885
702827
  readdirSync as readdirSync56,
701886
- statSync as statSync61,
702828
+ statSync as statSync62,
701887
702829
  readFileSync as readFileSync131,
701888
702830
  writeFileSync as writeFileSync85,
701889
702831
  appendFileSync as appendFileSync20
@@ -702374,34 +703316,9 @@ function telegramRouterDiagnosticIsDualEmptyVisible(diag) {
702374
703316
  return diag.jsonModeStatus === "empty-after-strip" && diag.plainStatus === "empty-after-strip";
702375
703317
  }
702376
703318
  function telegramThinkSuppressedRequest(request) {
702377
- const messages2 = Array.isArray(request.messages) ? request.messages.slice() : [];
702378
- let appended = false;
702379
- for (let i2 = messages2.length - 1; i2 >= 0; i2--) {
702380
- const m2 = messages2[i2];
702381
- if (!m2 || m2.role !== "user") continue;
702382
- const content = typeof m2.content === "string" ? m2.content : "";
702383
- const hasOllamaNoThink = /\/nothink\b/i.test(content);
702384
- const hasQwenNoThink = /\/no[_-]think\b/i.test(content);
702385
- if (hasOllamaNoThink && hasQwenNoThink) {
702386
- appended = true;
702387
- break;
702388
- }
702389
- const suffix = [
702390
- hasOllamaNoThink ? null : "/nothink",
702391
- hasQwenNoThink ? null : "/no_think"
702392
- ].filter(Boolean).join("\n");
702393
- messages2[i2] = {
702394
- ...m2,
702395
- content: content.endsWith("\n") ? `${content}${suffix}` : `${content}
702396
-
702397
- ${suffix}`
702398
- };
702399
- appended = true;
702400
- break;
702401
- }
702402
- if (!appended) {
702403
- messages2.push({ role: "user", content: "/nothink\n/no_think" });
702404
- }
703319
+ const messages2 = Array.isArray(request.messages) ? request.messages.map(
703320
+ (message2) => message2 && typeof message2.content === "string" ? { ...message2, content: stripNoThinkPromptDirectives(message2.content) } : message2
703321
+ ) : [];
702405
703322
  return { ...request, messages: messages2, think: false };
702406
703323
  }
702407
703324
  function parseTelegramInteractionDecision(text2, forcedRoute, options2 = {}) {
@@ -702854,7 +703771,7 @@ function isTelegramInternalControlText(text2) {
702854
703771
  /\[discovery contract\]/i,
702855
703772
  /\[curated segments\]/i,
702856
703773
  /\[branch-duplicate-blocked\]/i,
702857
- /branch-extract preempted/i,
703774
+ /branch extraction (?:executed|completed)/i,
702858
703775
  /contract: use these anchors as evidence/i,
702859
703776
  /\becho break\b/i
702860
703777
  ];
@@ -705103,6 +706020,8 @@ Telegram link integrity contract:
705103
706020
  */
705104
706021
  telegramOwnerLockFile = null;
705105
706022
  telegramOwnerLockFiles = [];
706023
+ /** Per-bridge ownership tokens prevent a second bridge from releasing our lock. */
706024
+ telegramOwnerLockTokens = /* @__PURE__ */ new Map();
705106
706025
  /** Session keys loaded from persistent conversation memory */
705107
706026
  loadedConversationState = /* @__PURE__ */ new Set();
705108
706027
  /** True once persisted Telegram conversation scopes have been bulk-loaded. */
@@ -706194,11 +707113,20 @@ ${message2}`)
706194
707113
  triageTelegramSteeringInput(msg) {
706195
707114
  const text2 = msg.text.trim();
706196
707115
  const lower = text2.toLowerCase();
706197
- if (/^\/(?:stop|cancel|abort|halt)\b/.test(lower)) {
706198
- return { intent: "cancel", reason: "explicit stop/cancel command" };
707116
+ if (/^\/(?:stop|cancel|abort|halt)\b/.test(lower) || /^(?:stop|cancel|abort|halt)(?:[.!]?|\s+(?:the\s+)?(?:current\s+)?(?:task|work|run)\b)/.test(
707117
+ lower
707118
+ )) {
707119
+ return { intent: "cancel", reason: "explicit cancellation request" };
706199
707120
  }
706200
- if (/^\/(?:redirect|reroute|pivot)\b/.test(lower)) {
706201
- return { intent: "redirect", reason: "explicit redirect command" };
707121
+ if (/^\/(?:redirect|reroute|pivot)\b/.test(lower) || /^(?:please\s+)?(?:redirect|reroute|pivot)\s+(?:the\s+)?(?:current\s+)?(?:task|work|run)\b/.test(
707122
+ lower
707123
+ ) || /^(?:please\s+)?(?:switch|change|move)\s+(?:(?:focus|work|task)\s+)?to\b/.test(
707124
+ lower
707125
+ )) {
707126
+ return {
707127
+ intent: "redirect",
707128
+ reason: "explicit natural-language redirect request"
707129
+ };
706202
707130
  }
706203
707131
  if (/^\/(?:replace|new[_-]?task)\b/.test(lower) || /^(?:new task|replace (?:the )?(?:current )?task|forget (?:that|the current task)|instead[,!:]?)/.test(
706204
707132
  lower
@@ -706211,7 +707139,11 @@ ${message2}`)
706211
707139
  if (/\?$/.test(text2) || /^(?:clarify|correction|to be clear)\b/.test(lower)) {
706212
707140
  return { intent: "clarify", reason: "plain-text clarification; scope preserved" };
706213
707141
  }
706214
- return { intent: "append", reason: "conservative plain-text intake; momentum preserved" };
707142
+ const classified = classifySteeringIntent(text2, "append");
707143
+ return {
707144
+ intent: classified,
707145
+ reason: classified === "constraint" || classified === "priority_change" ? "shared safety/scope/priority steering classifier" : "conservative context-only intake; momentum preserved"
707146
+ };
706215
707147
  }
706216
707148
  telegramIntakePath(sessionKey) {
706217
707149
  const digest3 = createHash49("sha256").update(sessionKey).digest("hex").slice(0, 20);
@@ -706306,14 +707238,13 @@ ${message2}`)
706306
707238
  content,
706307
707239
  source: "telegram",
706308
707240
  receivedAt: intake.receivedAt,
706309
- intent: intake.intent,
706310
- taskEpoch: intake.taskEpoch
707241
+ intent: intake.intent
706311
707242
  });
706312
707243
  return;
706313
707244
  }
706314
707245
  runner.injectUserMessage(this.formatTelegramSteeringCompatibilityMessage(pending2));
706315
707246
  }
706316
- async preemptTelegramSubAgentForIntake(msg, subAgent, toolContext, intake) {
707247
+ async preemptTelegramSubAgentForIntake(msg, subAgent, intake) {
706317
707248
  const sessionKey = intake.sessionKey;
706318
707249
  await this.transitionTelegramIntake(
706319
707250
  intake,
@@ -706321,59 +707252,33 @@ ${message2}`)
706321
707252
  "trusted Telegram steering receipt sent",
706322
707253
  { runId: subAgent.runId }
706323
707254
  );
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.";
707255
+ 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
707256
  await this.replyToTelegramMessage(msg, receipt).catch(() => null);
707257
+ if (intake.intent !== "cancel") {
707258
+ intake.taskEpoch = this.advanceTelegramTaskEpoch(sessionKey);
707259
+ }
706326
707260
  await this.transitionTelegramIntake(
706327
707261
  intake,
706328
707262
  "preempt_requested",
706329
- "trusted admin-DM steering preemption requested",
707263
+ "trusted admin-DM steering preemption requested for the active runner",
706330
707264
  { runId: subAgent.runId }
706331
707265
  );
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
- }
707266
+ await this.enqueueTelegramMessageForExistingSubAgent(msg, subAgent, intake);
706364
707267
  const runner = subAgent.runner;
706365
- if (typeof runner?.requestSteeringPreemption === "function") {
706366
- runner.requestSteeringPreemption(intake.inputId);
706367
- } else {
707268
+ const preemptionReceipt = runner?.requestSteeringPreemption?.(
707269
+ intake.inputId
707270
+ );
707271
+ if (!preemptionReceipt) {
707272
+ subAgent.preempted = true;
706368
707273
  runner?.abort?.();
706369
707274
  }
707275
+ if (intake.intent === "cancel") subAgent.preempted = true;
706370
707276
  await this.transitionTelegramIntake(
706371
707277
  intake,
706372
707278
  "preempted",
706373
- "active runner interrupted for trusted steering intake",
707279
+ preemptionReceipt ? "active runner turn interrupted; typed steering will apply at its safe boundary" : "runner lacks typed preemption support; active run was cancelled",
706374
707280
  { runId: subAgent.runId }
706375
707281
  );
706376
- this.dispatchQueuedTelegramSessionWorkSoon();
706377
707282
  }
706378
707283
  async requeuePendingTelegramIntakeOnFinalization(subAgent) {
706379
707284
  const pending2 = subAgent.pendingIntakeRecords.splice(0);
@@ -706410,13 +707315,16 @@ ${message2}`)
706410
707315
  if (!inputId) return;
706411
707316
  const record = this.telegramIntakeRecords.get(inputId);
706412
707317
  if (!record) return;
706413
- const lifecycle = typed.type === "steering_preempt_requested" ? "preempt_requested" : typed.type === "steering_preempted" ? "preempted" : typed.type === "steering_input_consumed" || typed.type === "steering_consumed" ? "consumed" : typed.type === "steering_input_accepted" || typed.type === "steering_received" ? "accepted" : null;
707318
+ const lifecycle = typed.type === "steering_lifecycle" ? typed.state === "received" ? "acknowledged" : typed.state === "visible_in_request" ? "visible_in_request" : typed.state === "reconciliation_required" ? "reconciliation_required" : typed.state === "reconciled" ? "reconciled" : typed.state === "first_affected_action" ? "first_affected_action" : typed.state === "cancelled" ? "cancelled" : typed.state === "superseded" ? "superseded" : null : typed.type === "steering_preempt_requested" ? "preempt_requested" : typed.type === "steering_preempted" ? "preempted" : typed.type === "steering_input_accepted" || typed.type === "steering_received" ? "accepted" : null;
706414
707319
  if (!lifecycle) return;
706415
707320
  void this.transitionTelegramIntake(
706416
707321
  record,
706417
707322
  lifecycle,
706418
- `runner lifecycle event: ${typed.type}`,
706419
- typeof typed.turn === "number" ? { runnerTurn: typed.turn } : {}
707323
+ typed.summary || `runner lifecycle event: ${typed.type}`,
707324
+ {
707325
+ ...typeof typed.turn === "number" ? { runnerTurn: typed.turn } : {},
707326
+ ...typeof typed.taskEpoch === "number" ? { taskEpoch: typed.taskEpoch } : {}
707327
+ }
706420
707328
  );
706421
707329
  }
706422
707330
  async replyWithTelegramHelp(msg, isAdmin) {
@@ -707137,7 +708045,7 @@ Model: <code>${escapeTelegramHTML(model.id)}</code>`
707137
708045
  }
707138
708046
  let sent = 0;
707139
708047
  for (const path16 of paths) {
707140
- if (!existsSync160(path16) || !statSync61(path16).isFile()) continue;
708048
+ if (!existsSync160(path16) || !statSync62(path16).isFile()) continue;
707141
708049
  const kind = classifyMedia(path16) ?? "document";
707142
708050
  const messageId = await this.sendMediaReference(
707143
708051
  msg.chatId,
@@ -710971,9 +711879,7 @@ ${lines.join("\n")}`
710971
711879
  observationContext,
710972
711880
  "",
710973
711881
  `Current Telegram message text (untrusted user data):
710974
- ${this.quoteTelegramContextBlock(msg.text, 1200)}`,
710975
- "",
710976
- "/nothink\n/no_think"
711882
+ ${this.quoteTelegramContextBlock(msg.text, 1200)}`
710977
711883
  ].filter(Boolean).join("\n");
710978
711884
  try {
710979
711885
  const result = await this.telegramRouterJsonCompletion(
@@ -711471,10 +712377,7 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`,
711471
712377
  TELEGRAM_INTERACTION_DECISION_REPAIR_SCHEMA,
711472
712378
  ``,
711473
712379
  `Original router output:`,
711474
- rawPreview,
711475
- ``,
711476
- `/nothink
711477
- /no_think`
712380
+ rawPreview
711478
712381
  ].join("\n");
711479
712382
  try {
711480
712383
  const result = await this.telegramRouterJsonCompletion(
@@ -711549,10 +712452,7 @@ ${userPrompt.slice(-4e3)}` : userPrompt;
711549
712452
  invalidPreview,
711550
712453
  ``,
711551
712454
  `Router context (trailing-window):`,
711552
- trimmedUserPrompt,
711553
- ``,
711554
- `/nothink
711555
- /no_think`
712455
+ trimmedUserPrompt
711556
712456
  ].join("\n");
711557
712457
  try {
711558
712458
  const result = await this.telegramRouterJsonCompletion(
@@ -712852,8 +713752,7 @@ ${TELEGRAM_PUBLIC_ORCHESTRATOR_CONTRACT}`
712852
713752
  } catch (e2) {
712853
713753
  for (const lockFile of claimed)
712854
713754
  this.releaseTelegramOwnerLock(lockFile);
712855
- if (e2 instanceof Error && e2.message.startsWith("Telegram bot @"))
712856
- throw e2;
713755
+ throw e2;
712857
713756
  }
712858
713757
  }
712859
713758
  this.state = {
@@ -713012,47 +713911,97 @@ ${TELEGRAM_PUBLIC_ORCHESTRATOR_CONTRACT}`
713012
713911
  claimTelegramOwnerLock(lockDir, botUserId, botUsername) {
713013
713912
  mkdirSync98(lockDir, { recursive: true });
713014
713913
  const lockFile = join170(lockDir, `bot-${botUserId}.owner.lock`);
713015
- if (existsSync160(lockFile)) {
713914
+ const ownerToken = randomBytes28(16).toString("hex");
713915
+ const payload = JSON.stringify(
713916
+ {
713917
+ pid: process.pid,
713918
+ cwd: this.repoRoot || process.cwd(),
713919
+ botUsername,
713920
+ botUserId,
713921
+ ownerToken,
713922
+ ts: Date.now()
713923
+ },
713924
+ null,
713925
+ 2
713926
+ );
713927
+ const recoveryFile = `${lockFile}.recovery`;
713928
+ for (let attempt = 0; attempt < 4; attempt++) {
713016
713929
  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) {
713930
+ writeFileSync85(lockFile, payload, {
713931
+ encoding: "utf-8",
713932
+ mode: 384,
713933
+ flag: "wx"
713934
+ });
713935
+ this.telegramOwnerLockTokens.set(lockFile, ownerToken);
713936
+ return lockFile;
713937
+ } catch (error) {
713938
+ if (error?.code !== "EEXIST") throw error;
713939
+ }
713940
+ let prior = {};
713941
+ try {
713942
+ prior = JSON.parse(readFileSync131(lockFile, "utf8"));
713943
+ } catch {
713944
+ }
713945
+ const priorAlive = typeof prior.pid === "number" && prior.pid !== process.pid ? this.processIsAlive(prior.pid) : typeof prior.pid === "number";
713946
+ if (priorAlive) {
713947
+ throw new Error(
713948
+ `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.`
713949
+ );
713950
+ }
713951
+ const recoveryToken = randomBytes28(12).toString("hex");
713952
+ try {
713953
+ writeFileSync85(recoveryFile, recoveryToken, {
713954
+ encoding: "utf-8",
713955
+ mode: 384,
713956
+ flag: "wx"
713957
+ });
713958
+ } catch (error) {
713959
+ if (error?.code === "EEXIST") continue;
713960
+ throw error;
713961
+ }
713962
+ try {
713963
+ let currentPid;
713964
+ try {
713965
+ currentPid = JSON.parse(readFileSync131(lockFile, "utf8"))?.pid;
713966
+ } catch {
713967
+ }
713968
+ if (typeof currentPid === "number" && (currentPid === process.pid || this.processIsAlive(currentPid))) {
713020
713969
  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.`
713970
+ `Telegram bot @${botUsername || "unknown"} acquired an owner while stale-lock recovery was pending.`
713022
713971
  );
713023
713972
  }
713024
- } catch (e2) {
713025
- if (e2 instanceof Error && e2.message.startsWith("Telegram bot @"))
713026
- throw e2;
713973
+ try {
713974
+ unlinkSync36(lockFile);
713975
+ } catch (error) {
713976
+ if (error?.code !== "ENOENT") throw error;
713977
+ }
713978
+ } finally {
713979
+ try {
713980
+ if (readFileSync131(recoveryFile, "utf8") === recoveryToken)
713981
+ unlinkSync36(recoveryFile);
713982
+ } catch {
713983
+ }
713027
713984
  }
713028
713985
  }
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 }
713986
+ throw new Error(
713987
+ `Could not atomically acquire Telegram owner lock for @${botUsername || botUserId}; retry after the current startup settles.`
713043
713988
  );
713044
- return lockFile;
713045
713989
  }
713046
713990
  releaseTelegramOwnerLock(lockFile) {
713047
713991
  try {
713992
+ const ownerToken = this.telegramOwnerLockTokens.get(lockFile);
713993
+ if (!ownerToken) return;
713048
713994
  if (!existsSync160(lockFile)) return;
713049
713995
  try {
713050
713996
  const prior = JSON.parse(readFileSync131(lockFile, "utf8"));
713051
- if (prior.pid !== process.pid) return;
713997
+ if (prior.pid !== process.pid || prior.ownerToken !== ownerToken) return;
713052
713998
  } catch {
713999
+ return;
713053
714000
  }
713054
714001
  unlinkSync36(lockFile);
713055
714002
  } catch {
714003
+ } finally {
714004
+ this.telegramOwnerLockTokens.delete(lockFile);
713056
714005
  }
713057
714006
  }
713058
714007
  /**
@@ -714130,7 +715079,6 @@ Join: ${newUrl}`
714130
715079
  await this.preemptTelegramSubAgentForIntake(
714131
715080
  msg,
714132
715081
  existing,
714133
- toolContext,
714134
715082
  intakeRecord
714135
715083
  );
714136
715084
  return;
@@ -719392,7 +720340,7 @@ ${knownList}` : "Private-user telegram_send_file target must be this DM or a kno
719392
720340
  const abs = isAbsolute17(trimmed) ? resolve73(trimmed) : resolve73(base3, trimmed);
719393
720341
  if (!existsSync160(abs))
719394
720342
  return { ok: false, error: `File does not exist: ${trimmed}` };
719395
- if (!statSync61(abs).isFile())
720343
+ if (!statSync62(abs).isFile())
719396
720344
  return { ok: false, error: `Path is not a file: ${trimmed}` };
719397
720345
  return { ok: true, path: abs };
719398
720346
  }
@@ -719906,7 +720854,7 @@ ${text2}`.trim()
719906
720854
  }
719907
720855
  async sendTelegramFileToChat(chatId, path16, options2) {
719908
720856
  const abs = resolve73(path16);
719909
- if (!existsSync160(abs) || !statSync61(abs).isFile()) {
720857
+ if (!existsSync160(abs) || !statSync62(abs).isFile()) {
719910
720858
  throw new Error(`File does not exist or is not a regular file: ${path16}`);
719911
720859
  }
719912
720860
  return this.sendMediaReferenceStrict(
@@ -720176,7 +721124,7 @@ Content-Type: ${contentType}\r
720176
721124
  for (const path16 of paths) {
720177
721125
  const abs = resolve73(path16);
720178
721126
  if (subAgent.deliveredArtifacts.includes(abs)) continue;
720179
- if (!existsSync160(abs) || !statSync61(abs).isFile()) continue;
721127
+ if (!existsSync160(abs) || !statSync62(abs).isFile()) continue;
720180
721128
  subAgent.deliveredArtifacts.push(abs);
720181
721129
  await this.sendMediaReference(
720182
721130
  msg.chatId,
@@ -720218,7 +721166,7 @@ Content-Type: ${contentType}\r
720218
721166
  abs
720219
721167
  );
720220
721168
  if (!materialized.ok) continue;
720221
- if (!existsSync160(materialized.path) || !statSync61(materialized.path).isFile()) {
721169
+ if (!existsSync160(materialized.path) || !statSync62(materialized.path).isFile()) {
720222
721170
  materialized.cleanup?.();
720223
721171
  continue;
720224
721172
  }
@@ -722407,7 +723355,7 @@ __export(projects_exports, {
722407
723355
  setCurrentProject: () => setCurrentProject,
722408
723356
  unregisterProject: () => unregisterProject
722409
723357
  });
722410
- import { readFileSync as readFileSync132, writeFileSync as writeFileSync86, mkdirSync as mkdirSync99, existsSync as existsSync161, statSync as statSync62, renameSync as renameSync15 } from "node:fs";
723358
+ import { readFileSync as readFileSync132, writeFileSync as writeFileSync86, mkdirSync as mkdirSync99, existsSync as existsSync161, statSync as statSync63, renameSync as renameSync15 } from "node:fs";
722411
723359
  import { homedir as homedir58 } from "node:os";
722412
723360
  import { basename as basename43, join as join171, resolve as resolve74 } from "node:path";
722413
723361
  import { randomUUID as randomUUID19 } from "node:crypto";
@@ -722433,7 +723381,7 @@ function listProjects() {
722433
723381
  const alive = [];
722434
723382
  for (const p2 of projects) {
722435
723383
  try {
722436
- if (statSync62(p2.root).isDirectory()) alive.push(p2);
723384
+ if (statSync63(p2.root).isDirectory()) alive.push(p2);
722437
723385
  } catch {
722438
723386
  }
722439
723387
  }
@@ -723573,7 +724521,7 @@ var init_audit_log = __esm({
723573
724521
 
723574
724522
  // packages/cli/src/api/disk-task-output.ts
723575
724523
  import { open } from "node:fs/promises";
723576
- import { existsSync as existsSync164, mkdirSync as mkdirSync102, statSync as statSync63 } from "node:fs";
724524
+ import { existsSync as existsSync164, mkdirSync as mkdirSync102, statSync as statSync64 } from "node:fs";
723577
724525
  import { dirname as dirname54 } from "node:path";
723578
724526
  import * as fsConstants from "node:constants";
723579
724527
  var O_NOFOLLOW2, O_APPEND2, O_CREAT2, O_WRONLY2, OPEN_FLAGS_WRITE, OPEN_MODE, DiskTaskOutput;
@@ -723671,7 +724619,7 @@ var init_disk_task_output = __esm({
723671
724619
  if (!existsSync164(this.path)) {
723672
724620
  return { content: "", nextOffset: offset, eof: true, size: 0 };
723673
724621
  }
723674
- const st = statSync63(this.path);
724622
+ const st = statSync64(this.path);
723675
724623
  if (offset >= st.size) {
723676
724624
  return { content: "", nextOffset: offset, eof: true, size: st.size };
723677
724625
  }
@@ -723858,7 +724806,7 @@ data: ${JSON.stringify(ev)}
723858
724806
  });
723859
724807
 
723860
724808
  // 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";
724809
+ import { existsSync as existsSync165, mkdirSync as mkdirSync103, statSync as statSync65, copyFileSync as copyFileSync7, createReadStream } from "node:fs";
723862
724810
  import { basename as basename44, join as join174, resolve as pathResolve2 } from "node:path";
723863
724811
  function mediaWorkDir() {
723864
724812
  return join174(omniusHomeDir(), "media", "_work");
@@ -724159,7 +725107,7 @@ async function runGeneration(ctx3, kind, buildTool, buildArgs) {
724159
725107
  const published = publishToGallery(srcPath, kind);
724160
725108
  const size = (() => {
724161
725109
  try {
724162
- return statSync64(published.path).size;
725110
+ return statSync65(published.path).size;
724163
725111
  } catch {
724164
725112
  return 0;
724165
725113
  }
@@ -724266,7 +725214,7 @@ function handleFile(ctx3) {
724266
725214
  const ext = full.slice(full.lastIndexOf(".")).toLowerCase();
724267
725215
  ctx3.res.writeHead(200, {
724268
725216
  "Content-Type": MIME_BY_EXT[ext] || "application/octet-stream",
724269
- "Content-Length": statSync64(full).size,
725217
+ "Content-Length": statSync65(full).size,
724270
725218
  "Cache-Control": "private, max-age=3600"
724271
725219
  });
724272
725220
  createReadStream(full).pipe(ctx3.res);
@@ -724850,7 +725798,7 @@ __export(aiwg_exports, {
724850
725798
  resolveAiwgRoot: () => resolveAiwgRoot,
724851
725799
  tryRouteAiwg: () => tryRouteAiwg
724852
725800
  });
724853
- import { existsSync as existsSync167, readFileSync as readFileSync136, readdirSync as readdirSync57, statSync as statSync65 } from "node:fs";
725801
+ import { existsSync as existsSync167, readFileSync as readFileSync136, readdirSync as readdirSync57, statSync as statSync66 } from "node:fs";
724854
725802
  import { join as join176 } from "node:path";
724855
725803
  import { homedir as homedir60 } from "node:os";
724856
725804
  import { execSync as execSync38 } from "node:child_process";
@@ -724952,7 +725900,7 @@ function listAiwgFrameworks() {
724952
725900
  for (const name10 of readdirSync57(frameworksDir)) {
724953
725901
  const p2 = join176(frameworksDir, name10);
724954
725902
  try {
724955
- const st = statSync65(p2);
725903
+ const st = statSync66(p2);
724956
725904
  if (!st.isDirectory()) continue;
724957
725905
  const agg = aggregateDir(p2);
724958
725906
  out.push({
@@ -724989,7 +725937,7 @@ function aggregateDir(dir, depth = 0) {
724989
725937
  out.commands += sub2.commands;
724990
725938
  } else if (e2.isFile()) {
724991
725939
  try {
724992
- const st = statSync65(p2);
725940
+ const st = statSync66(p2);
724993
725941
  out.files++;
724994
725942
  out.bytes += st.size;
724995
725943
  if (e2.name.endsWith(".md")) {
@@ -725123,7 +726071,7 @@ function listAiwgAddons() {
725123
726071
  for (const name10 of readdirSync57(addonsDir)) {
725124
726072
  const p2 = join176(addonsDir, name10);
725125
726073
  try {
725126
- const st = statSync65(p2);
726074
+ const st = statSync66(p2);
725127
726075
  if (!st.isDirectory()) continue;
725128
726076
  const agg = aggregateDir(p2);
725129
726077
  out.push({
@@ -725912,7 +726860,7 @@ import {
725912
726860
  mkdirSync as mkdirSync106,
725913
726861
  readFileSync as readFileSync138,
725914
726862
  readdirSync as readdirSync58,
725915
- statSync as statSync66
726863
+ statSync as statSync67
725916
726864
  } from "node:fs";
725917
726865
  import { join as join179, resolve as pathResolve3 } from "node:path";
725918
726866
  import { homedir as homedir62 } from "node:os";
@@ -727374,7 +728322,7 @@ async function handleFilesRead(ctx3) {
727374
728322
  );
727375
728323
  return true;
727376
728324
  }
727377
- const st = statSync66(resolved);
728325
+ const st = statSync67(resolved);
727378
728326
  if (st.isDirectory()) {
727379
728327
  sendProblem(
727380
728328
  res,
@@ -743166,7 +744114,7 @@ import {
743166
744114
  watch as fsWatch4,
743167
744115
  renameSync as renameSync18,
743168
744116
  unlinkSync as unlinkSync38,
743169
- statSync as statSync67,
744117
+ statSync as statSync68,
743170
744118
  openSync as openSync7,
743171
744119
  readSync as readSync3,
743172
744120
  closeSync as closeSync7
@@ -743526,7 +744474,7 @@ function fileEntryMetadata(dir, entry) {
743526
744474
  kind: fileKindForPath(entry.name)
743527
744475
  };
743528
744476
  try {
743529
- const st = statSync67(target);
744477
+ const st = statSync68(target);
743530
744478
  meta["size"] = st.size;
743531
744479
  meta["mtime"] = new Date(st.mtimeMs).toISOString();
743532
744480
  } catch {
@@ -743538,7 +744486,7 @@ function contentDispositionName(filePath) {
743538
744486
  return name10.replace(/["\r\n]/g, "");
743539
744487
  }
743540
744488
  function streamWorkspaceFile(req3, res, target) {
743541
- const st = statSync67(target);
744489
+ const st = statSync68(target);
743542
744490
  if (!st.isFile()) {
743543
744491
  jsonResponse(res, 400, { error: "Path is not a file", path: target });
743544
744492
  return;
@@ -743763,29 +744711,11 @@ async function writeMemoryEpisodes(sessionId, userMessage, assistantContent, too
743763
744711
  function sanitizeChatContent(raw) {
743764
744712
  return sanitizeAgentOutputForUser(raw);
743765
744713
  }
743766
- function appendNoThinkDirectivesToMessages(messages2) {
743767
- let lastUserIdx = -1;
743768
- for (let i2 = messages2.length - 1; i2 >= 0; i2--) {
743769
- if (messages2[i2]?.role === "user") {
743770
- lastUserIdx = i2;
743771
- break;
743772
- }
743773
- }
743774
- if (lastUserIdx < 0) return messages2;
743775
- const target = messages2[lastUserIdx];
743776
- if (!target || typeof target.content !== "string") return messages2;
743777
- const hasOllamaNoThink = /\/nothink\b/i.test(target.content);
743778
- const hasQwenNoThink = /\/no[_-]think\b/i.test(target.content);
743779
- if (hasOllamaNoThink && hasQwenNoThink) return messages2;
743780
- const suffix = [
743781
- hasOllamaNoThink ? null : "/nothink",
743782
- hasQwenNoThink ? null : "/no_think"
743783
- ].filter(Boolean).join("\n");
743784
- return messages2.map(
743785
- (m2, i2) => i2 === lastUserIdx ? { ...m2, content: `${target.content}
743786
-
743787
- ${suffix}` } : m2
743788
- );
744714
+ function sanitizeNoThinkTransportMessages(messages2) {
744715
+ return messages2.map((message2) => ({
744716
+ ...message2,
744717
+ content: stripNoThinkPromptDirectives(message2.content)
744718
+ }));
743789
744719
  }
743790
744720
  async function directChatBackend(opts) {
743791
744721
  const { model, messages: messages2, stream, res, sessionId, ollamaUrl, extraFields } = opts;
@@ -743916,7 +744846,7 @@ async function directChatBackend(opts) {
743916
744846
  const ollamaFormat = ollamaFormatFromOpenAIResponseFormat(
743917
744847
  ef["response_format"]
743918
744848
  );
743919
- const ollamaMessages = appendNoThinkDirectivesToMessages(messages2);
744849
+ const ollamaMessages = sanitizeNoThinkTransportMessages(messages2);
743920
744850
  const reqBody = JSON.stringify({
743921
744851
  model: cleanModel,
743922
744852
  messages: ollamaMessages,
@@ -744229,7 +745159,7 @@ async function completeRealtimeTextOnly(opts) {
744229
745159
  ) ?? originalModel;
744230
745160
  }
744231
745161
  const makeOllamaChatBody = (modelName) => {
744232
- const rtMessages = Array.isArray(requestBody["messages"]) ? appendNoThinkDirectivesToMessages(
745162
+ const rtMessages = Array.isArray(requestBody["messages"]) ? sanitizeNoThinkTransportMessages(
744233
745163
  requestBody["messages"]
744234
745164
  ) : requestBody["messages"];
744235
745165
  return JSON.stringify({
@@ -745904,7 +746834,7 @@ async function handleV1ChatCompletions(req3, res, ollamaUrl) {
745904
746834
  const finalThink = thinkingAllowed && callerProvidedThink ? routedBody["think"] : false;
745905
746835
  const ollamaBody = { ...routedBody };
745906
746836
  if (finalThink === false && Array.isArray(ollamaBody["messages"])) {
745907
- ollamaBody["messages"] = appendNoThinkDirectivesToMessages(
746837
+ ollamaBody["messages"] = sanitizeNoThinkTransportMessages(
745908
746838
  ollamaBody["messages"]
745909
746839
  );
745910
746840
  }
@@ -747444,7 +748374,7 @@ function handleV1RunsById(res, id2) {
747444
748374
  const enriched = { ...job };
747445
748375
  if (outputFile && existsSync173(outputFile)) {
747446
748376
  try {
747447
- const size = statSync67(outputFile).size;
748377
+ const size = statSync68(outputFile).size;
747448
748378
  const tailSize = Math.min(size, 4096);
747449
748379
  const buffer2 = Buffer.alloc(tailSize);
747450
748380
  const fd = openSync7(outputFile, "r");
@@ -748092,7 +749022,7 @@ async function handleRequest(req3, res, ollamaUrl, verbose, runtimeDefaults = {}
748092
749022
  const dir = path16.dirname(cssEntry);
748093
749023
  const fullPath = path16.join(dir, entry.path);
748094
749024
  if (fs14.existsSync(fullPath)) {
748095
- const stat9 = statSync67(fullPath);
749025
+ const stat9 = statSync68(fullPath);
748096
749026
  res.writeHead(200, {
748097
749027
  "Content-Type": entry.ct,
748098
749028
  "Content-Length": String(stat9.size),
@@ -748644,17 +749574,17 @@ async function handleRequest(req3, res, ollamaUrl, verbose, runtimeDefaults = {}
748644
749574
  const child = join183(dir, e2.name);
748645
749575
  const omniusDir = join183(child, ".omnius");
748646
749576
  try {
748647
- if (statSync67(omniusDir).isDirectory()) {
749577
+ if (statSync68(omniusDir).isDirectory()) {
748648
749578
  const name10 = e2.name;
748649
749579
  const prefsFile = join183(omniusDir, "config.json");
748650
749580
  let lastSeen = 0;
748651
749581
  try {
748652
- lastSeen = statSync67(prefsFile).mtimeMs;
749582
+ lastSeen = statSync68(prefsFile).mtimeMs;
748653
749583
  } catch {
748654
749584
  }
748655
749585
  if (!lastSeen) {
748656
749586
  try {
748657
- lastSeen = statSync67(omniusDir).mtimeMs;
749587
+ lastSeen = statSync68(omniusDir).mtimeMs;
748658
749588
  } catch {
748659
749589
  }
748660
749590
  }
@@ -748702,17 +749632,17 @@ async function handleRequest(req3, res, ollamaUrl, verbose, runtimeDefaults = {}
748702
749632
  const child = join183(dir, e2.name);
748703
749633
  const omniusDir = join183(child, ".omnius");
748704
749634
  try {
748705
- if (statSync67(omniusDir).isDirectory()) {
749635
+ if (statSync68(omniusDir).isDirectory()) {
748706
749636
  const name10 = e2.name;
748707
749637
  const prefsFile = join183(omniusDir, "config.json");
748708
749638
  let lastSeen = 0;
748709
749639
  try {
748710
- lastSeen = statSync67(prefsFile).mtimeMs;
749640
+ lastSeen = statSync68(prefsFile).mtimeMs;
748711
749641
  } catch {
748712
749642
  }
748713
749643
  if (!lastSeen) {
748714
749644
  try {
748715
- lastSeen = statSync67(omniusDir).mtimeMs;
749645
+ lastSeen = statSync68(omniusDir).mtimeMs;
748716
749646
  } catch {
748717
749647
  }
748718
749648
  }
@@ -749858,25 +750788,6 @@ data: ${JSON.stringify(data)}
749858
750788
  jsonResponse(res, 200, { ok: true, enabled: config.torEnabled });
749859
750789
  return;
749860
750790
  }
749861
- if (pathname === "/v1/update" && method === "POST") {
749862
- const config = loadConfig();
749863
- config.updating = true;
749864
- try {
749865
- require4("./config").saveConfig?.(config);
749866
- } catch {
749867
- }
749868
- setImmediate(() => {
749869
- try {
749870
- const { execSync: execSync41 } = require4("node:child_process");
749871
- execSync41("npm update -g omnius 2>/dev/null || true", {
749872
- stdio: "pipe"
749873
- });
749874
- } catch {
749875
- }
749876
- });
749877
- jsonResponse(res, 200, { ok: true, message: "Update initiated" });
749878
- return;
749879
- }
749880
750791
  if (pathname === "/v1/share/generate" && method === "POST") {
749881
750792
  const body = await parseJsonBody(req3);
749882
750793
  const config = loadConfig();
@@ -753710,7 +754621,7 @@ import {
753710
754621
  appendFileSync as appendFileSync22,
753711
754622
  rmSync as rmSync17,
753712
754623
  readdirSync as readdirSync60,
753713
- statSync as statSync68,
754624
+ statSync as statSync69,
753714
754625
  mkdirSync as mkdirSync111
753715
754626
  } from "node:fs";
753716
754627
  import { existsSync as existsSync174 } from "node:fs";
@@ -757396,6 +758307,17 @@ ${entry.fullContent}`
757396
758307
  case "status":
757397
758308
  if (_apiCallbacks?.onStatus)
757398
758309
  _apiCallbacks.onStatus(event.content ?? "");
758310
+ if (event.steering) {
758311
+ const stage2 = event.steering.state.replace(/_/g, " ");
758312
+ const line = `Steering ${stage2}: ${event.content ?? event.steering.inputId}`;
758313
+ if (isNeovimActive()) {
758314
+ writeToNeovimOutput(`\x1B[38;5;81m${line}\x1B[0m\r
758315
+ `);
758316
+ } else {
758317
+ contentWrite(() => renderInfo(line));
758318
+ }
758319
+ break;
758320
+ }
757399
758321
  if (event.toolName === "shell" && liveShellBlock && !isNeovimActive()) {
757400
758322
  appendShellLiveChunk(liveShellBlock.state, event.content ?? "");
757401
758323
  scheduleLiveShellRepaint();
@@ -759581,7 +760503,7 @@ This is an independent background session started from /background.`
759581
760503
  if (!entry.startsWith(partialName)) continue;
759582
760504
  const full = join185(searchDir, entry);
759583
760505
  try {
759584
- const st = statSync68(full);
760506
+ const st = statSync69(full);
759585
760507
  const suffix = st.isDirectory() ? "/" : "";
759586
760508
  const display = isAbsolute18 ? full : full.startsWith(repoRoot + sep7) ? full.slice(repoRoot.length + 1) : full;
759587
760509
  completions.push(display + suffix);
@@ -760433,26 +761355,15 @@ Log: ${nexusLogPath}`
760433
761355
  currentConfig.backendUrl
760434
761356
  );
760435
761357
  });
760436
- Promise.resolve().then(() => (init_daemon(), daemon_exports)).then(async ({ ensureDaemon: ensureDaemon2, isDaemonRunning: isDaemonRunning2 }) => {
761358
+ Promise.resolve().then(() => (init_daemon(), daemon_exports)).then(async ({ ensureDaemonVersion: ensureDaemonVersion2 }) => {
760437
761359
  const apiPort = parseInt(process.env["OMNIUS_PORT"] || "11435", 10);
760438
- if (await isDaemonRunning2(apiPort)) {
760439
- setTimeout(() => {
760440
- if (statusBar.isActive)
760441
- writeContent(
760442
- () => renderInfo(
760443
- `REST API: http://localhost:${apiPort} (shared daemon)`
760444
- )
760445
- );
760446
- }, 1500);
760447
- return;
760448
- }
760449
- const daemonOk = await ensureDaemon2();
760450
- if (daemonOk) {
761360
+ const daemon = await ensureDaemonVersion2();
761361
+ if (daemon.ok) {
760451
761362
  setTimeout(() => {
760452
761363
  if (statusBar.isActive)
760453
761364
  writeContent(
760454
761365
  () => renderInfo(
760455
- `REST API: http://localhost:${apiPort} (daemon started)`
761366
+ `REST API: http://localhost:${apiPort} (${daemon.action === "restarted" ? "daemon upgraded" : daemon.action === "started" ? "daemon started" : "shared daemon"})`
760456
761367
  )
760457
761368
  );
760458
761369
  }, 1500);
@@ -762365,11 +763276,11 @@ Respond concisely and safely. Remember: you are talking to the general public.`;
762365
763276
  }
762366
763277
  if (name10 === "voice_list_files") {
762367
763278
  const baseDir = String(args?.dir ?? ".");
762368
- const { readdirSync: readdirSync62, statSync: statSync70 } = __require("node:fs");
763279
+ const { readdirSync: readdirSync62, statSync: statSync71 } = __require("node:fs");
762369
763280
  const { join: join190, resolve: resolve82 } = __require("node:path");
762370
763281
  const base3 = baseDir.startsWith("/") ? baseDir : resolve82(join190(repoRoot, baseDir));
762371
763282
  const items = readdirSync62(base3).slice(0, 200).map((f2) => {
762372
- const s2 = statSync70(join190(base3, f2));
763283
+ const s2 = statSync71(join190(base3, f2));
762373
763284
  return { name: f2, dir: s2.isDirectory(), size: s2.size };
762374
763285
  });
762375
763286
  return JSON.stringify({ dir: base3, items }, null, 2);
@@ -763639,7 +764550,14 @@ ${result.text}`;
763639
764550
  interpretation = null;
763640
764551
  }
763641
764552
  const packet = buildSteeringPacket(ingress, interpretation);
763642
- activeTask.runner.injectUserMessage(packet);
764553
+ activeTask.runner.injectSteeringInput({
764554
+ inputId: ingress.id,
764555
+ content: packet,
764556
+ source: "tui",
764557
+ receivedAt: ingress.timestamp,
764558
+ intent: isReplacement ? "replace" : classifySteeringIntent(input, "context_only"),
764559
+ state: "received"
764560
+ });
763643
764561
  activeTask.steeringPacketIds.add(ingress.id);
763644
764562
  appendSteeringLedgerEntry(repoRoot, {
763645
764563
  type: "ingress",
@@ -765202,7 +766120,7 @@ __export(index_repo_exports, {
765202
766120
  indexRepoCommand: () => indexRepoCommand
765203
766121
  });
765204
766122
  import { resolve as resolve80 } from "node:path";
765205
- import { existsSync as existsSync176, statSync as statSync69 } from "node:fs";
766123
+ import { existsSync as existsSync176, statSync as statSync70 } from "node:fs";
765206
766124
  import { cwd as cwd2 } from "node:process";
765207
766125
  async function indexRepoCommand(opts, _config3) {
765208
766126
  const repoRoot = resolve80(opts.repoPath ?? cwd2());
@@ -765212,7 +766130,7 @@ async function indexRepoCommand(opts, _config3) {
765212
766130
  printError(`Path does not exist: ${repoRoot}`);
765213
766131
  process.exit(1);
765214
766132
  }
765215
- const stat9 = statSync69(repoRoot);
766133
+ const stat9 = statSync70(repoRoot);
765216
766134
  if (!stat9.isDirectory()) {
765217
766135
  printError(`Path is not a directory: ${repoRoot}`);
765218
766136
  process.exit(1);
@@ -765696,23 +766614,34 @@ async function serveCommand(opts, config) {
765696
766614
  const ollamaUrl = config.backendUrl || "http://127.0.0.1:11434";
765697
766615
  const isDaemon = opts.daemon || process.env["OMNIUS_DAEMON"] === "1";
765698
766616
  const isQuiet = opts.quiet || isDaemon;
766617
+ let releaseDaemonClaim;
766618
+ if (isDaemon) {
766619
+ const { claimDaemonEndpoint: claimDaemonEndpoint2, releaseDaemonEndpointClaim: releaseDaemonEndpointClaim2 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
766620
+ const inheritedPort = parseInt(process.env["OMNIUS_DAEMON_LOCK_PORT"] ?? "", 10);
766621
+ const claim = claimDaemonEndpoint2(
766622
+ Number.isFinite(inheritedPort) && inheritedPort > 0 ? inheritedPort : port,
766623
+ process.env["OMNIUS_DAEMON_LOCK_TOKEN"]
766624
+ );
766625
+ if (!claim) return;
766626
+ releaseDaemonClaim = () => releaseDaemonEndpointClaim2(claim);
766627
+ }
765699
766628
  if (!isQuiet) {
765700
766629
  printHeader("Omnius REST API");
765701
766630
  printInfo(`Starting API server on port ${port}...`);
765702
766631
  printInfo(`Backend: ${config.backendType} (${ollamaUrl})`);
765703
766632
  }
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;
766633
+ try {
766634
+ if (isDaemon) {
766635
+ try {
766636
+ const resp = await fetch(`http://127.0.0.1:${port}/health`, {
766637
+ signal: AbortSignal.timeout(1500)
766638
+ });
766639
+ if (resp.ok) {
766640
+ return;
766641
+ }
766642
+ } catch {
765711
766643
  }
765712
- } catch {
765713
766644
  }
765714
- }
765715
- try {
765716
766645
  const server2 = startApiServer({ port, ollamaUrl, quiet: isQuiet });
765717
766646
  if (isDaemon) {
765718
766647
  let lastActivity = Date.now();
@@ -765749,6 +766678,8 @@ async function serveCommand(opts, config) {
765749
766678
  } else {
765750
766679
  if (!isQuiet) printError(`API server failed: ${msg}`);
765751
766680
  }
766681
+ } finally {
766682
+ releaseDaemonClaim?.();
765752
766683
  }
765753
766684
  }
765754
766685
  var init_serve2 = __esm({
@@ -766246,6 +767177,8 @@ function parseCliArgs(argv) {
766246
767177
  live: { type: "boolean" },
766247
767178
  json: { type: "boolean", short: "j" },
766248
767179
  background: { type: "boolean" },
767180
+ daemon: { type: "boolean" },
767181
+ quiet: { type: "boolean" },
766249
767182
  "self-test": { type: "string" },
766250
767183
  help: { type: "boolean", short: "h" },
766251
767184
  version: { type: "boolean", short: "V" }
@@ -766269,6 +767202,8 @@ function parseCliArgs(argv) {
766269
767202
  local: values.local === true,
766270
767203
  json: values.json === true,
766271
767204
  background: values.background === true,
767205
+ daemon: values.daemon === true,
767206
+ quiet: values.quiet === true,
766272
767207
  selfTest: typeof values["self-test"] === "string" ? values["self-test"] : void 0,
766273
767208
  help: values.help === true,
766274
767209
  version: values.version === true
@@ -766494,8 +767429,8 @@ async function main() {
766494
767429
  port: parsed.servePort,
766495
767430
  model: parsed.model,
766496
767431
  verbose: parsed.verbose,
766497
- daemon: process.env["OMNIUS_DAEMON"] === "1",
766498
- quiet: process.argv.includes("--quiet") || process.env["OMNIUS_DAEMON"] === "1"
767432
+ daemon: parsed.daemon === true || process.env["OMNIUS_DAEMON"] === "1",
767433
+ quiet: parsed.quiet === true || process.env["OMNIUS_DAEMON"] === "1"
766499
767434
  },
766500
767435
  config
766501
767436
  );