omnius 1.0.852 → 1.0.853

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/library.js CHANGED
@@ -5470,49 +5470,49 @@ function migrateOperationalWorldPatch(input, currentGraph) {
5470
5470
  const entityType = operation["op"] === "upsert_node" ? "node" : operation["op"] === "upsert_edge" ? "edge" : null;
5471
5471
  if (!entityType)
5472
5472
  continue;
5473
- const record8 = operation[entityType];
5474
- if (!isRecord(record8) || record8["metadataProvenance"] !== void 0)
5473
+ const record9 = operation[entityType];
5474
+ if (!isRecord(record9) || record9["metadataProvenance"] !== void 0)
5475
5475
  continue;
5476
5476
  const idKey = entityType === "node" ? "nodeId" : "edgeId";
5477
- const entityId = typeof record8[idKey] === "string" ? record8[idKey] : "unknown";
5477
+ const entityId = typeof record9[idKey] === "string" ? record9[idKey] : "unknown";
5478
5478
  const derived = ["metadata_provenance"];
5479
- const evidenceIds = Array.isArray(record8["evidenceRefIds"]) ? record8["evidenceRefIds"].filter((id5) => typeof id5 === "string") : [];
5479
+ const evidenceIds = Array.isArray(record9["evidenceRefIds"]) ? record9["evidenceRefIds"].filter((id5) => typeof id5 === "string") : [];
5480
5480
  if (evidenceIds.length === 0) {
5481
5481
  evidenceIds.push(evidenceId);
5482
5482
  needsPatchEvidence = true;
5483
5483
  derived.push("source_evidence");
5484
5484
  }
5485
- record8["evidenceRefIds"] = evidenceIds;
5485
+ record9["evidenceRefIds"] = evidenceIds;
5486
5486
  if (entityType === "node") {
5487
- const bindingIds = Array.isArray(record8["bindingIds"]) ? record8["bindingIds"].filter((id5) => typeof id5 === "string") : [];
5487
+ const bindingIds = Array.isArray(record9["bindingIds"]) ? record9["bindingIds"].filter((id5) => typeof id5 === "string") : [];
5488
5488
  for (const id5 of evidenceIds) {
5489
5489
  const evidenceBinding = id5 === evidenceId ? bindingId : evidenceBindingById.get(id5);
5490
5490
  if (evidenceBinding && !bindingIds.includes(evidenceBinding)) {
5491
5491
  bindingIds.push(evidenceBinding);
5492
5492
  }
5493
5493
  }
5494
- record8["bindingIds"] = bindingIds;
5494
+ record9["bindingIds"] = bindingIds;
5495
5495
  }
5496
- if (record8["confidence"] === void 0) {
5497
- record8["confidence"] = 0;
5496
+ if (record9["confidence"] === void 0) {
5497
+ record9["confidence"] = 0;
5498
5498
  derived.push("confidence");
5499
5499
  }
5500
- if (record8["revision"] === void 0) {
5501
- record8["revision"] = revision;
5500
+ if (record9["revision"] === void 0) {
5501
+ record9["revision"] = revision;
5502
5502
  derived.push("revision");
5503
5503
  }
5504
- if (record8["validFrom"] === void 0) {
5505
- record8["validFrom"] = observedAt;
5504
+ if (record9["validFrom"] === void 0) {
5505
+ record9["validFrom"] = observedAt;
5506
5506
  derived.push("temporal_validity");
5507
5507
  }
5508
- if (record8["scope"] === void 0) {
5509
- record8["scope"] = {
5508
+ if (record9["scope"] === void 0) {
5509
+ record9["scope"] = {
5510
5510
  kind: "legacy_unscoped",
5511
5511
  scopeId: `legacy:${stableHash(graphId2)}`
5512
5512
  };
5513
5513
  derived.push("scope");
5514
5514
  }
5515
- record8["metadataProvenance"] = legacyProvenance(legacySourceRecordId(entityType, entityId), derived);
5515
+ record9["metadataProvenance"] = legacyProvenance(legacySourceRecordId(entityType, entityId), derived);
5516
5516
  }
5517
5517
  if (needsPatchEvidence && !currentGraph.sourceBindings.some((entry) => entry.bindingId === bindingId) && !operations2.some((operation) => isRecord(operation) && operation["op"] === "upsert_source_binding" && isRecord(operation["sourceBinding"]) && operation["sourceBinding"]["bindingId"] === bindingId)) {
5518
5518
  operations2.unshift({
@@ -61116,8 +61116,8 @@ async function closeBrowserSession() {
61116
61116
  const contextClose = contextIndex >= 0 ? handleCloses[contextIndex] : void 0;
61117
61117
  const closing = Promise.allSettled([
61118
61118
  ...handleCloses,
61119
- ...downloads.map((record8) => {
61120
- const cleanup = cleanupBrowserDownload(record8, 1e3);
61119
+ ...downloads.map((record9) => {
61120
+ const cleanup = cleanupBrowserDownload(record9, 1e3);
61121
61121
  return contextClose ? Promise.race([cleanup, contextClose]) : cleanup;
61122
61122
  })
61123
61123
  ]).then((results) => {
@@ -61239,16 +61239,16 @@ function attachDiagnosticListeners(p) {
61239
61239
  });
61240
61240
  };
61241
61241
  onOwned(p, "download", (source) => {
61242
- if (session.downloads.some((record9) => record9.source === source))
61242
+ if (session.downloads.some((record10) => record10.source === source))
61243
61243
  return;
61244
- const record8 = {
61244
+ const record9 = {
61245
61245
  id: `${session.playwrightSessionId}-download-${++session.downloadSequence}`,
61246
61246
  source,
61247
61247
  suggestedFilename: String(source.suggestedFilename()).slice(0, 300),
61248
61248
  url: String(source.url()).slice(0, 2e3),
61249
61249
  status: "pending"
61250
61250
  };
61251
- session.downloads.push(record8);
61251
+ session.downloads.push(record9);
61252
61252
  if (session.downloads.length > 32) {
61253
61253
  const expired = session.downloads.shift();
61254
61254
  void cleanupBrowserDownload(expired, 1e3).catch(() => {
@@ -61569,47 +61569,47 @@ async function observeBrowserDom(pageHandle, selector = BROWSER_INTERACTIVE_SELE
61569
61569
  browserState().lastDomSummarySelectors = extractDomSummarySelectors(summary);
61570
61570
  return { snapshot, summary };
61571
61571
  }
61572
- function browserDownloadMetadata(record8) {
61572
+ function browserDownloadMetadata(record9) {
61573
61573
  return {
61574
- downloadId: record8.id,
61575
- suggestedFilename: record8.suggestedFilename,
61576
- url: record8.url,
61577
- status: record8.status,
61578
- ...record8.receipt ? { path: record8.receipt.path, bytes: record8.receipt.bytes, sha256: record8.receipt.sha256 } : {},
61579
- ...record8.error ? { error: record8.error } : {},
61580
- ...record8.receipt?.cleanupWarnings ? { cleanupWarnings: record8.receipt.cleanupWarnings } : {},
61581
- ...record8.cleanupError ? { cleanupError: record8.cleanupError } : {}
61574
+ downloadId: record9.id,
61575
+ suggestedFilename: record9.suggestedFilename,
61576
+ url: record9.url,
61577
+ status: record9.status,
61578
+ ...record9.receipt ? { path: record9.receipt.path, bytes: record9.receipt.bytes, sha256: record9.receipt.sha256 } : {},
61579
+ ...record9.error ? { error: record9.error } : {},
61580
+ ...record9.receipt?.cleanupWarnings ? { cleanupWarnings: record9.receipt.cleanupWarnings } : {},
61581
+ ...record9.cleanupError ? { cleanupError: record9.cleanupError } : {}
61582
61582
  };
61583
61583
  }
61584
- async function cleanupBrowserDownload(record8, timeout, signal) {
61585
- if (record8.cleanupComplete)
61584
+ async function cleanupBrowserDownload(record9, timeout, signal) {
61585
+ if (record9.cleanupComplete)
61586
61586
  return;
61587
- if (!record8.cleanup) {
61588
- const operations2 = [Promise.resolve().then(() => record8.source.delete())];
61589
- if (record8.status !== "saved")
61590
- operations2.push(Promise.resolve().then(() => record8.source.cancel()));
61587
+ if (!record9.cleanup) {
61588
+ const operations2 = [Promise.resolve().then(() => record9.source.delete())];
61589
+ if (record9.status !== "saved")
61590
+ operations2.push(Promise.resolve().then(() => record9.source.cancel()));
61591
61591
  const cleanup = Promise.allSettled(operations2).then((results) => {
61592
61592
  const failures = results.filter((result) => result.status === "rejected");
61593
61593
  if (failures.length)
61594
61594
  throw new Error(failures.map((result) => String(result.reason)).join("; "));
61595
61595
  });
61596
- record8.cleanup = cleanup;
61596
+ record9.cleanup = cleanup;
61597
61597
  void cleanup.then(() => {
61598
- record8.cleanupComplete = true;
61599
- if (record8.cleanup === cleanup) {
61600
- record8.cleanup = void 0;
61601
- record8.cleanupError = void 0;
61598
+ record9.cleanupComplete = true;
61599
+ if (record9.cleanup === cleanup) {
61600
+ record9.cleanup = void 0;
61601
+ record9.cleanupError = void 0;
61602
61602
  }
61603
61603
  }, (error) => {
61604
- if (record8.cleanup === cleanup)
61605
- record8.cleanup = void 0;
61606
- record8.cleanupError = error instanceof Error ? error.message : String(error);
61604
+ if (record9.cleanup === cleanup)
61605
+ record9.cleanup = void 0;
61606
+ record9.cleanupError = error instanceof Error ? error.message : String(error);
61607
61607
  });
61608
61608
  }
61609
61609
  let timer;
61610
61610
  let aborted2;
61611
61611
  try {
61612
- await Promise.race([record8.cleanup, new Promise((_resolve, reject) => {
61612
+ await Promise.race([record9.cleanup, new Promise((_resolve, reject) => {
61613
61613
  timer = setTimeout(() => reject(new Error(`Native download cleanup still pending after ${timeout}ms`)), timeout);
61614
61614
  aborted2 = () => reject(signal?.reason ?? new Error("Native download cleanup canceled"));
61615
61615
  if (signal?.aborted)
@@ -61643,9 +61643,9 @@ async function clickElementForBrowserDownload(locator, timeout, signal = browser
61643
61643
  let timer;
61644
61644
  const received = new Promise((resolve38, reject) => {
61645
61645
  listener = (source) => {
61646
- const record8 = session.downloads.find((candidate) => candidate.source === source);
61647
- if (record8)
61648
- resolve38(record8);
61646
+ const record9 = session.downloads.find((candidate) => candidate.source === source);
61647
+ if (record9)
61648
+ resolve38(record9);
61649
61649
  else
61650
61650
  reject(new Error("Browser download has no owning session record"));
61651
61651
  };
@@ -61655,8 +61655,8 @@ async function clickElementForBrowserDownload(locator, timeout, signal = browser
61655
61655
  timer = setTimeout(() => reject(new Error(session.verifiedBrowserProtocol === "webdriver-bidi" ? "No native download receipt arrived from Firefox BiDi before the timeout. This bridge cannot retain downloads without navigation IDs, including scripted Blob downloads. The click may already have had an effect; do not repeat it or claim a saved file. Observe actual state before choosing another action." : "No Playwright download event arrived before the timeout. The page may use a native file chooser/save dialog outside the DOM. This does not confirm a dialog is open; when desktop access is authorized, use tool_search('desktop') and observe the actual OS window before acting.")), timeout);
61656
61656
  });
61657
61657
  try {
61658
- const [record8] = await Promise.all([received, locator.click({ timeout })]);
61659
- return record8;
61658
+ const [record9] = await Promise.all([received, locator.click({ timeout })]);
61659
+ return record9;
61660
61660
  } finally {
61661
61661
  if (timer)
61662
61662
  clearTimeout(timer);
@@ -61664,17 +61664,17 @@ async function clickElementForBrowserDownload(locator, timeout, signal = browser
61664
61664
  signal?.removeEventListener("abort", abort);
61665
61665
  }
61666
61666
  }
61667
- async function saveBrowserDownload(record8, options) {
61667
+ async function saveBrowserDownload(record9, options) {
61668
61668
  const session = browserState();
61669
61669
  const signal = options.signal ?? session.controller?.signal;
61670
- if (record8.status !== "pending")
61671
- return fail(`Download ${record8.id} is ${record8.status}; use downloads to inspect its recorded result.`, options.start);
61672
- record8.status = "saving";
61670
+ if (record9.status !== "pending")
61671
+ return fail(`Download ${record9.id} is ${record9.status}; use downloads to inspect its recorded result.`, options.start);
61672
+ record9.status = "saving";
61673
61673
  try {
61674
- const receipt = await persistBrowserDownload(record8.source, {
61675
- downloadId: record8.id,
61676
- suggestedFilename: record8.suggestedFilename,
61677
- url: record8.url,
61674
+ const receipt = await persistBrowserDownload(record9.source, {
61675
+ downloadId: record9.id,
61676
+ suggestedFilename: record9.suggestedFilename,
61677
+ url: record9.url,
61678
61678
  sessionId: session.playwrightSessionId,
61679
61679
  workingDir: session.workingDir,
61680
61680
  outputPath: options.outputPath,
@@ -61682,13 +61682,13 @@ async function saveBrowserDownload(record8, options) {
61682
61682
  maxBytes: options.maxBytes,
61683
61683
  signal
61684
61684
  });
61685
- record8.status = "saved";
61686
- record8.receipt = receipt;
61685
+ record9.status = "saved";
61686
+ record9.receipt = receipt;
61687
61687
  try {
61688
- await cleanupBrowserDownload(record8, Math.min(1e3, options.timeout), signal);
61688
+ await cleanupBrowserDownload(record9, Math.min(1e3, options.timeout), signal);
61689
61689
  } catch (error) {
61690
- record8.cleanupError = error instanceof Error ? error.message : String(error);
61691
- (receipt.cleanupWarnings ??= []).push(`Native temporary-copy cleanup is retained by the browser session: ${record8.cleanupError}`);
61690
+ record9.cleanupError = error instanceof Error ? error.message : String(error);
61691
+ (receipt.cleanupWarnings ??= []).push(`Native temporary-copy cleanup is retained by the browser session: ${record9.cleanupError}`);
61692
61692
  }
61693
61693
  const event = createEvidenceEvent({
61694
61694
  sessionId: session.playwrightSessionId ?? void 0,
@@ -61726,14 +61726,14 @@ ${receipt.cleanupWarnings.join("\n")}` : ""}`,
61726
61726
  evidenceEvents: [event]
61727
61727
  };
61728
61728
  } catch (error) {
61729
- record8.status = "failed";
61730
- record8.error = error instanceof Error ? error.message : String(error);
61729
+ record9.status = "failed";
61730
+ record9.error = error instanceof Error ? error.message : String(error);
61731
61731
  try {
61732
- await cleanupBrowserDownload(record8, Math.min(1e3, options.timeout), signal);
61732
+ await cleanupBrowserDownload(record9, Math.min(1e3, options.timeout), signal);
61733
61733
  } catch (cleanupError) {
61734
- record8.cleanupError = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
61734
+ record9.cleanupError = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
61735
61735
  }
61736
- return { ...fail(record8.error, options.start), data: { schema: "omnius.browser-download.v1", ...browserDownloadMetadata(record8) } };
61736
+ return { ...fail(record9.error, options.start), data: { schema: "omnius.browser-download.v1", ...browserDownloadMetadata(record9) } };
61737
61737
  }
61738
61738
  }
61739
61739
  async function runBrowserLocatorAction(pageHandle, selector, index, timeout, action) {
@@ -62831,12 +62831,12 @@ var init_playwright_browser = __esm({
62831
62831
  await requireBrowserBiDiDownloadLink(element);
62832
62832
  },
62833
62833
  saveDownload: (element, signal) => browserSessionScope.run(this.session, async () => {
62834
- const record8 = await clickElementForBrowserDownload(element, 3e4, signal);
62835
- const outputPath = join11(".omnius", "browser-downloads", this.session.playwrightSessionId, randomUUID11(), safeBrowserDownloadFilename(record8.suggestedFilename));
62836
- const result = await saveBrowserDownload(record8, { outputPath, timeout: 3e4, maxBytes: 268435456, start: Date.now(), signal });
62837
- if (!result.success || !record8.receipt)
62834
+ const record9 = await clickElementForBrowserDownload(element, 3e4, signal);
62835
+ const outputPath = join11(".omnius", "browser-downloads", this.session.playwrightSessionId, randomUUID11(), safeBrowserDownloadFilename(record9.suggestedFilename));
62836
+ const result = await saveBrowserDownload(record9, { outputPath, timeout: 3e4, maxBytes: 268435456, start: Date.now(), signal });
62837
+ if (!result.success || !record9.receipt)
62838
62838
  throw new Error(result.error ?? "The browser download was not verified");
62839
- return { path: record8.receipt.path, sizeBytes: record8.receipt.bytes, sha256: record8.receipt.sha256, verified: true };
62839
+ return { path: record9.receipt.path, sizeBytes: record9.receipt.bytes, sha256: record9.receipt.sha256, verified: true };
62840
62840
  })
62841
62841
  });
62842
62842
  const visual = options.rapidVisual ?? (options.rapidVisualGrounder && createBrowserVisualOptions({
@@ -62962,9 +62962,9 @@ ${message}`,
62962
62962
  }
62963
62963
  async executeWithSessionReceipt(args) {
62964
62964
  const sessionBefore = browserState().playwrightSessionId;
62965
- const downloadsBefore = new Set(browserState().downloads.map((record8) => record8.id));
62965
+ const downloadsBefore = new Set(browserState().downloads.map((record9) => record9.id));
62966
62966
  let result = await this._execute(args);
62967
- const freshDownloads = args.action === "download" ? [] : browserState().downloads.filter((record8) => !downloadsBefore.has(record8.id)).map(browserDownloadMetadata);
62967
+ const freshDownloads = args.action === "download" ? [] : browserState().downloads.filter((record9) => !downloadsBefore.has(record9.id)).map(browserDownloadMetadata);
62968
62968
  if (freshDownloads.length) {
62969
62969
  let payload2 = { observation: result.llmContent || result.output };
62970
62970
  try {
@@ -63237,10 +63237,10 @@ Use action=download with the exact download_id to save local bytes without click
63237
63237
  const downloadId = typeof args.download_id === "string" ? args.download_id.trim() : "";
63238
63238
  if (Boolean(selector) === Boolean(downloadId))
63239
63239
  return fail("download requires exactly one of selector or download_id", start);
63240
- const record8 = downloadId ? browserState().downloads.find((candidate) => candidate.id === downloadId) : await clickForBrowserDownload(selector, elementIndex, timeout);
63241
- if (!record8)
63240
+ const record9 = downloadId ? browserState().downloads.find((candidate) => candidate.id === downloadId) : await clickForBrowserDownload(selector, elementIndex, timeout);
63241
+ if (!record9)
63242
63242
  return fail("Unknown download_id for this browser session; inspect downloads for its current native events", start);
63243
- return saveBrowserDownload(record8, { outputPath, timeout, maxBytes: Number(args.max_bytes ?? 268435456), start });
63243
+ return saveBrowserDownload(record9, { outputPath, timeout, maxBytes: Number(args.max_bytes ?? 268435456), start });
63244
63244
  }
63245
63245
  case "click": {
63246
63246
  if (!selector)
@@ -65040,8 +65040,8 @@ function stableStringify(value) {
65040
65040
  return JSON.stringify(value);
65041
65041
  if (Array.isArray(value))
65042
65042
  return `[${value.map(stableStringify).join(",")}]`;
65043
- const record8 = value;
65044
- return `{${Object.keys(record8).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(record8[key])}`).join(",")}}`;
65043
+ const record9 = value;
65044
+ return `{${Object.keys(record9).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(record9[key])}`).join(",")}}`;
65045
65045
  }
65046
65046
  function boundedInteger(value, fallback, minimum, maximum) {
65047
65047
  if (typeof value !== "number" || !Number.isFinite(value))
@@ -65192,10 +65192,10 @@ var init_contextMemoryLedger = __esm({
65192
65192
  (id, epoch, kind, authority, trust_class, body, content_hash, provenance_json, metadata_json, observed_at, valid_from)
65193
65193
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
65194
65194
  `).run(id5, input.epoch, input.kind, input.authority, trustClass, input.body, hash2(`${input.epoch}\0${input.kind}\0${input.body}`), stringify(input.provenance), stringify(input.metadata), observedAt, validFrom);
65195
- const record8 = this.getRecord(id5);
65196
- if (!record8)
65195
+ const record9 = this.getRecord(id5);
65196
+ if (!record9)
65197
65197
  throw new Error(`Failed to append context-memory record ${id5}`);
65198
- return record8;
65198
+ return record9;
65199
65199
  }
65200
65200
  getRecord(id5) {
65201
65201
  const row2 = this.db.prepare("SELECT * FROM context_memory_record WHERE id = ?").get(id5);
@@ -65225,10 +65225,10 @@ var init_contextMemoryLedger = __esm({
65225
65225
  }
65226
65226
  attachTransactionRecord(transactionId2, recordId) {
65227
65227
  const transaction = this.getTransaction(transactionId2);
65228
- const record8 = this.getRecord(recordId);
65229
- if (!transaction || !record8)
65228
+ const record9 = this.getRecord(recordId);
65229
+ if (!transaction || !record9)
65230
65230
  throw new Error("Transactions can only attach existing records");
65231
- if (transaction.epoch !== record8.epoch)
65231
+ if (transaction.epoch !== record9.epoch)
65232
65232
  throw new Error("Transaction and record epochs must match");
65233
65233
  const attached = this.db.prepare("SELECT 1 AS attached FROM context_memory_transaction_record WHERE transaction_id = ? AND record_id = ?").get(transactionId2, recordId);
65234
65234
  if (attached)
@@ -65250,7 +65250,7 @@ var init_contextMemoryLedger = __esm({
65250
65250
  epoch: String(row2["epoch"]),
65251
65251
  ...typeof row2["task_id"] === "string" ? { taskId: row2["task_id"] } : {},
65252
65252
  status: row2["status"],
65253
- recordIds: records.map((record8) => record8.record_id),
65253
+ recordIds: records.map((record9) => record9.record_id),
65254
65254
  createdAt: String(row2["created_at"]),
65255
65255
  updatedAt: String(row2["updated_at"])
65256
65256
  };
@@ -65283,8 +65283,8 @@ var init_contextMemoryLedger = __esm({
65283
65283
  commitWorkingSet(input) {
65284
65284
  const activeRecordIds = [...new Set(input.activeRecordIds)].sort();
65285
65285
  for (const recordId of activeRecordIds) {
65286
- const record8 = this.getRecord(recordId);
65287
- if (!record8 || record8.epoch !== input.epoch) {
65286
+ const record9 = this.getRecord(recordId);
65287
+ if (!record9 || record9.epoch !== input.epoch) {
65288
65288
  throw new Error("Working-set roots must exist in the declared task epoch");
65289
65289
  }
65290
65290
  }
@@ -65346,7 +65346,7 @@ var init_contextMemoryLedger = __esm({
65346
65346
  }
65347
65347
  }
65348
65348
  }
65349
- const allRecords = [...selected].map((id5) => this.getRecord(id5)).filter((record8) => Boolean(record8 && record8.epoch === input.epoch)).sort((a, b) => RECORD_KIND_RANK[b.kind] - RECORD_KIND_RANK[a.kind] || a.validFrom.localeCompare(b.validFrom) || a.id.localeCompare(b.id));
65349
+ const allRecords = [...selected].map((id5) => this.getRecord(id5)).filter((record9) => Boolean(record9 && record9.epoch === input.epoch)).sort((a, b) => RECORD_KIND_RANK[b.kind] - RECORD_KIND_RANK[a.kind] || a.validFrom.localeCompare(b.validFrom) || a.id.localeCompare(b.id));
65350
65350
  const requiredTransactionRecordIds = /* @__PURE__ */ new Set();
65351
65351
  for (const transactionId2 of transactionIds) {
65352
65352
  for (const recordId of this.getTransaction(transactionId2)?.recordIds ?? []) {
@@ -65354,15 +65354,15 @@ var init_contextMemoryLedger = __esm({
65354
65354
  }
65355
65355
  }
65356
65356
  const maxRecords = input.maxRecords ?? Number.MAX_SAFE_INTEGER;
65357
- const required = allRecords.filter((record8) => requiredTransactionRecordIds.has(record8.id));
65358
- const optional = allRecords.filter((record8) => !requiredTransactionRecordIds.has(record8.id));
65357
+ const required = allRecords.filter((record9) => requiredTransactionRecordIds.has(record9.id));
65358
+ const optional = allRecords.filter((record9) => !requiredTransactionRecordIds.has(record9.id));
65359
65359
  const records = [
65360
65360
  ...required,
65361
65361
  ...optional.slice(0, Math.max(0, maxRecords - required.length))
65362
65362
  ].sort((a, b) => RECORD_KIND_RANK[b.kind] - RECORD_KIND_RANK[a.kind] || a.validFrom.localeCompare(b.validFrom) || a.id.localeCompare(b.id));
65363
- const ids = records.map((record8) => record8.id);
65363
+ const ids = records.map((record9) => record9.id);
65364
65364
  const visibleTransactionIds = ids.length === 0 ? [] : this.db.prepare(`SELECT DISTINCT transaction_id FROM context_memory_transaction_record WHERE record_id IN (${ids.map(() => "?").join(",")})`).all(...ids);
65365
- return { records, transactionIds: visibleTransactionIds.map((row2) => row2.transaction_id).sort(), fingerprint: hash2(records.map((record8) => `${record8.id}:${record8.contentHash}:${record8.validUntil ?? "active"}`).join("\n")) };
65365
+ return { records, transactionIds: visibleTransactionIds.map((row2) => row2.transaction_id).sort(), fingerprint: hash2(records.map((record9) => `${record9.id}:${record9.contentHash}:${record9.validUntil ?? "active"}`).join("\n")) };
65366
65366
  }
65367
65367
  /**
65368
65368
  * Select only records that were temporally valid at `asOf`. Normal retrieval
@@ -65435,11 +65435,11 @@ var init_contextMemoryLedger = __esm({
65435
65435
  ...(query.activeRecordIds ?? []).map((id5) => ({ id: id5, expectedKind: void 0, label: "active record" }))
65436
65436
  ];
65437
65437
  for (const root of roots) {
65438
- const record8 = this.getRecord(root.id);
65439
- if (!record8 || record8.epoch !== query.epoch) {
65438
+ const record9 = this.getRecord(root.id);
65439
+ if (!record9 || record9.epoch !== query.epoch) {
65440
65440
  return { rootIds: [], reason: `${root.label} is not available in the requested task epoch` };
65441
65441
  }
65442
- if (root.expectedKind && record8.kind !== root.expectedKind) {
65442
+ if (root.expectedKind && record9.kind !== root.expectedKind) {
65443
65443
  return { rootIds: [], reason: `${root.label} does not have the required ${root.expectedKind} record type` };
65444
65444
  }
65445
65445
  }
@@ -65474,24 +65474,24 @@ var init_contextMemoryLedger = __esm({
65474
65474
  const tokenBudget = boundedInteger(query.maxBodyTokens, 12e3, 1, 12e3) * 4;
65475
65475
  const maxBodyChars = Math.min(charBudget, tokenBudget);
65476
65476
  const graph = this.expandRetrievalGraph({ epoch: query.epoch, rootIds: roots.rootIds, maxHops: maxGraphHops, maxNodes: 128 });
65477
- const ranked = this.listRecordsAt(query.epoch, asOf).filter((record8) => allowedAuthorities.has(record8.authority)).filter((record8) => sourceUris.size === 0 || Boolean(record8.provenance.sourceUri && sourceUris.has(record8.provenance.sourceUri.toLowerCase()))).filter((record8) => sourceRevisions.size === 0 || Boolean(record8.provenance.sourceRevision && sourceRevisions.has(record8.provenance.sourceRevision))).filter((record8) => sourceRanges.length === 0 || Boolean(record8.provenance.sourceUri && record8.provenance.sourceRange && sourceRanges.some((constraint) => constraint.sourceUri.toLowerCase() === record8.provenance.sourceUri.toLowerCase() && constraint.start <= record8.provenance.sourceRange.end && constraint.end >= record8.provenance.sourceRange.start))).map((record8) => {
65478
- const haystack = `${record8.body}
65479
- ${record8.provenance.sourceUri ?? ""}`.toLowerCase();
65477
+ const ranked = this.listRecordsAt(query.epoch, asOf).filter((record9) => allowedAuthorities.has(record9.authority)).filter((record9) => sourceUris.size === 0 || Boolean(record9.provenance.sourceUri && sourceUris.has(record9.provenance.sourceUri.toLowerCase()))).filter((record9) => sourceRevisions.size === 0 || Boolean(record9.provenance.sourceRevision && sourceRevisions.has(record9.provenance.sourceRevision))).filter((record9) => sourceRanges.length === 0 || Boolean(record9.provenance.sourceUri && record9.provenance.sourceRange && sourceRanges.some((constraint) => constraint.sourceUri.toLowerCase() === record9.provenance.sourceUri.toLowerCase() && constraint.start <= record9.provenance.sourceRange.end && constraint.end >= record9.provenance.sourceRange.start))).map((record9) => {
65478
+ const haystack = `${record9.body}
65479
+ ${record9.provenance.sourceUri ?? ""}`.toLowerCase();
65480
65480
  const matchedTerms = terms3.filter((term) => haystack.includes(term)).length;
65481
65481
  const lexical = terms3.length > 0 ? matchedTerms / terms3.length : 0;
65482
- const exact = record8.provenance.sourceUri && sourceUris.has(record8.provenance.sourceUri.toLowerCase()) ? 1 : 0;
65482
+ const exact = record9.provenance.sourceUri && sourceUris.has(record9.provenance.sourceUri.toLowerCase()) ? 1 : 0;
65483
65483
  const revision = sourceRevisions.size > 0 ? 1 : 0;
65484
- const range2 = record8.provenance.sourceUri && record8.provenance.sourceRange ? sourceRanges.some((constraint) => constraint.sourceUri.toLowerCase() === record8.provenance.sourceUri.toLowerCase() && constraint.start <= record8.provenance.sourceRange.end && constraint.end >= record8.provenance.sourceRange.start) ? 1 : 0 : 0;
65485
- const graphInfo = graph.nodes.get(record8.id);
65484
+ const range2 = record9.provenance.sourceUri && record9.provenance.sourceRange ? sourceRanges.some((constraint) => constraint.sourceUri.toLowerCase() === record9.provenance.sourceUri.toLowerCase() && constraint.start <= record9.provenance.sourceRange.end && constraint.end >= record9.provenance.sourceRange.start) ? 1 : 0 : 0;
65485
+ const graphInfo = graph.nodes.get(record9.id);
65486
65486
  const graphScore = graphInfo ? 1 / (1 + graphInfo.hops) : 0;
65487
65487
  let semantic = 0;
65488
65488
  try {
65489
- semantic = Math.max(0, Math.min(1, query.semanticScore?.(record8) ?? 0));
65489
+ semantic = Math.max(0, Math.min(1, query.semanticScore?.(record9) ?? 0));
65490
65490
  } catch {
65491
65491
  semantic = 0;
65492
65492
  }
65493
65493
  return {
65494
- record: record8,
65494
+ record: record9,
65495
65495
  exact: Math.max(exact, range2),
65496
65496
  lexical,
65497
65497
  graph: graphScore,
@@ -65529,7 +65529,7 @@ ${record8.provenance.sourceUri ?? ""}`.toLowerCase();
65529
65529
  validateGraphCut(input) {
65530
65530
  const retired = new Set(input.retireRecordIds);
65531
65531
  const active = this.materializeWorkingSet({ epoch: input.epoch, activeRecordIds: input.activeRecordIds });
65532
- const blockedRecordIds = active.records.filter((record8) => retired.has(record8.id)).map((record8) => record8.id);
65532
+ const blockedRecordIds = active.records.filter((record9) => retired.has(record9.id)).map((record9) => record9.id);
65533
65533
  const reasons3 = blockedRecordIds.map((id5) => `record ${id5} is in the active dependency closure`);
65534
65534
  for (const transactionId2 of active.transactionIds) {
65535
65535
  const transaction = this.getTransaction(transactionId2);
@@ -65579,8 +65579,8 @@ function stableStringify2(value) {
65579
65579
  return JSON.stringify(value);
65580
65580
  if (Array.isArray(value))
65581
65581
  return `[${value.map(stableStringify2).join(",")}]`;
65582
- const record8 = value;
65583
- return `{${Object.keys(record8).sort().map((key) => `${JSON.stringify(key)}:${stableStringify2(record8[key])}`).join(",")}}`;
65582
+ const record9 = value;
65583
+ return `{${Object.keys(record9).sort().map((key) => `${JSON.stringify(key)}:${stableStringify2(record9[key])}`).join(",")}}`;
65584
65584
  }
65585
65585
  function parseObject2(value) {
65586
65586
  if (typeof value !== "string")
@@ -67910,34 +67910,34 @@ var init_evidenceIngestion = __esm({
67910
67910
  }
67911
67911
  ingest(records, options = {}) {
67912
67912
  const state = this.emptyResult();
67913
- for (const record8 of records)
67914
- this.appendRecord(record8, options, state);
67913
+ for (const record9 of records)
67914
+ this.appendRecord(record9, options, state);
67915
67915
  return state;
67916
67916
  }
67917
67917
  async ingestAsync(records, options = {}) {
67918
67918
  const state = this.emptyResult();
67919
- for await (const record8 of records)
67920
- this.appendRecord(record8, options, state);
67919
+ for await (const record9 of records)
67920
+ this.appendRecord(record9, options, state);
67921
67921
  return state;
67922
67922
  }
67923
- appendRecord(record8, options, state) {
67923
+ appendRecord(record9, options, state) {
67924
67924
  const metadata = {
67925
- ...record8.metadata ?? {},
67925
+ ...record9.metadata ?? {},
67926
67926
  ...options.scopeId ? { scopeId: options.scopeId } : {}
67927
67927
  };
67928
67928
  const documentInput = {
67929
- ...record8.id ? { id: record8.id } : {},
67930
- source: record8.source,
67931
- ...record8.sourceUri ? { sourceUri: record8.sourceUri } : {},
67932
- ...record8.messageId ? { messageId: record8.messageId } : {},
67933
- ...record8.timestamp ? { timestamp: record8.timestamp } : {},
67934
- version: record8.version,
67935
- originalText: record8.text,
67929
+ ...record9.id ? { id: record9.id } : {},
67930
+ source: record9.source,
67931
+ ...record9.sourceUri ? { sourceUri: record9.sourceUri } : {},
67932
+ ...record9.messageId ? { messageId: record9.messageId } : {},
67933
+ ...record9.timestamp ? { timestamp: record9.timestamp } : {},
67934
+ version: record9.version,
67935
+ originalText: record9.text,
67936
67936
  metadata
67937
67937
  };
67938
- const stored = this.store.appendDocument(documentInput, chunkStructuredEvidence(record8.text, {
67939
- kind: record8.kind ?? "auto",
67940
- sourceUri: record8.sourceUri,
67938
+ const stored = this.store.appendDocument(documentInput, chunkStructuredEvidence(record9.text, {
67939
+ kind: record9.kind ?? "auto",
67940
+ sourceUri: record9.sourceUri,
67941
67941
  targetTokens: options.targetTokens,
67942
67942
  maxTokens: options.maxTokens,
67943
67943
  overlapTokens: options.overlapTokens
@@ -67983,8 +67983,8 @@ function stableStringify3(value) {
67983
67983
  return JSON.stringify(value);
67984
67984
  if (Array.isArray(value))
67985
67985
  return `[${value.map(stableStringify3).join(",")}]`;
67986
- const record8 = value;
67987
- return `{${Object.keys(record8).sort().map((key) => `${JSON.stringify(key)}:${stableStringify3(record8[key])}`).join(",")}}`;
67986
+ const record9 = value;
67987
+ return `{${Object.keys(record9).sort().map((key) => `${JSON.stringify(key)}:${stableStringify3(record9[key])}`).join(",")}}`;
67988
67988
  }
67989
67989
  function parseObject3(value) {
67990
67990
  if (typeof value !== "string")
@@ -68166,7 +68166,7 @@ var init_structuredMemoryStore = __esm({
68166
68166
  let supersedesId = input.supersedesId;
68167
68167
  if (input.canonicalKey) {
68168
68168
  const active = this.activeForKey(input.canonicalKey, void 0, input.scopeId);
68169
- const conflicting = active.filter((record8) => record8.bodyHash !== bodyHash);
68169
+ const conflicting = active.filter((record9) => record9.bodyHash !== bodyHash);
68170
68170
  if (!supersedesId && conflicting.length > 0) {
68171
68171
  if (input.conflictDisposition === "supersede") {
68172
68172
  if (conflicting.length !== 1) {
@@ -68242,7 +68242,7 @@ var init_structuredMemoryStore = __esm({
68242
68242
  this.extractionTransaction = true;
68243
68243
  try {
68244
68244
  input.assertCurrent();
68245
- const records = input.records.map((record8) => this.append(record8));
68245
+ const records = input.records.map((record9) => this.append(record9));
68246
68246
  input.assertCurrent();
68247
68247
  if (!input.settle(records))
68248
68248
  throw new Error("Structured extraction lost its queue claim");
@@ -68263,7 +68263,7 @@ var init_structuredMemoryStore = __esm({
68263
68263
  const active = this.activeForKey(canonicalKey, activeAt, scopeId);
68264
68264
  if (active.length === 0)
68265
68265
  return null;
68266
- if (new Set(active.map((record8) => record8.bodyHash)).size > 1)
68266
+ if (new Set(active.map((record9) => record9.bodyHash)).size > 1)
68267
68267
  return null;
68268
68268
  return active[0];
68269
68269
  }
@@ -68376,12 +68376,12 @@ var init_structuredMemoryStore = __esm({
68376
68376
  LIMIT ?
68377
68377
  `).all(...params, limit2);
68378
68378
  return rows.map((row2) => {
68379
- const record8 = mapRecord2(row2);
68379
+ const record9 = mapRecord2(row2);
68380
68380
  const lexical = 1 / (1 + Math.abs(Number(row2["lexical_rank"] ?? 0)));
68381
- const generationPenalty = 1 + record8.compressionGeneration * 0.05;
68381
+ const generationPenalty = 1 + record9.compressionGeneration * 0.05;
68382
68382
  return {
68383
- record: record8,
68384
- score: lexical * (0.75 + record8.importance * 0.25) / generationPenalty,
68383
+ record: record9,
68384
+ score: lexical * (0.75 + record9.importance * 0.25) / generationPenalty,
68385
68385
  matchedQuery: text12
68386
68386
  };
68387
68387
  });
@@ -68917,8 +68917,8 @@ var init_virtualMemoryReceiptStore = __esm({
68917
68917
  return JSON.stringify(value) ?? "null";
68918
68918
  if (Array.isArray(value))
68919
68919
  return `[${value.map(stableStringify4).join(",")}]`;
68920
- const record8 = value;
68921
- return `{${Object.keys(record8).sort().map((key) => `${JSON.stringify(key)}:${stableStringify4(record8[key])}`).join(",")}}`;
68920
+ const record9 = value;
68921
+ return `{${Object.keys(record9).sort().map((key) => `${JSON.stringify(key)}:${stableStringify4(record9[key])}`).join(",")}}`;
68922
68922
  };
68923
68923
  VirtualMemoryReceiptStore = class {
68924
68924
  db;
@@ -70885,17 +70885,17 @@ function maintainMemoryGraph(store, item) {
70885
70885
  ${item.body}`);
70886
70886
  const nodesByText = /* @__PURE__ */ new Map();
70887
70887
  for (const node of graph.nodes) {
70888
- const record8 = store.upsertGraphNode({
70888
+ const record9 = store.upsertGraphNode({
70889
70889
  scopeId: item.scopeId,
70890
70890
  text: node.text,
70891
70891
  nodeType: node.nodeType,
70892
70892
  weight: node.weight,
70893
70893
  metadata: { evidence: node.evidence }
70894
70894
  });
70895
- nodesByText.set(node.text.toLowerCase(), record8);
70895
+ nodesByText.set(node.text.toLowerCase(), record9);
70896
70896
  store.linkItemToGraphNode({
70897
70897
  itemId: item.id,
70898
- nodeId: record8.id,
70898
+ nodeId: record9.id,
70899
70899
  weight: node.weight,
70900
70900
  evidence: node.evidence
70901
70901
  });
@@ -88050,9 +88050,9 @@ function optionalIsoTimestamp(value, name) {
88050
88050
  return void 0;
88051
88051
  return normalizeIsoTimestamp(value, name);
88052
88052
  }
88053
- function definedOnly(record8) {
88053
+ function definedOnly(record9) {
88054
88054
  const out = {};
88055
- for (const [key, value] of Object.entries(record8)) {
88055
+ for (const [key, value] of Object.entries(record9)) {
88056
88056
  if (value !== void 0)
88057
88057
  out[key] = value;
88058
88058
  }
@@ -339815,11 +339815,11 @@ function compareRecordsForAdmission(left, right) {
339815
339815
  return right.blockPriority - left.blockPriority || right.recordPriority - left.recordPriority || left.blockOrder - right.blockOrder || left.recordOrder - right.recordOrder || compareText(left.semanticId, right.semanticId) || compareText(left.recordId, right.recordId);
339816
339816
  }
339817
339817
  function canonicalBlock(block) {
339818
- const records = [...block.records].map((record8) => ({
339819
- recordId: record8.recordId,
339820
- content: record8.content,
339821
- order: record8.order ?? 0,
339822
- priority: record8.priority ?? 0
339818
+ const records = [...block.records].map((record9) => ({
339819
+ recordId: record9.recordId,
339820
+ content: record9.content,
339821
+ order: record9.order ?? 0,
339822
+ priority: record9.priority ?? 0
339823
339823
  })).sort(
339824
339824
  (left, right) => left.order - right.order || right.priority - left.priority || compareText(left.recordId, right.recordId)
339825
339825
  );
@@ -339848,17 +339848,17 @@ function normalizeBlock(block) {
339848
339848
  const order = normalizedInteger(block.order, 0, "block order");
339849
339849
  const priority = normalizedInteger(block.priority, 0, "block priority");
339850
339850
  const recordIds = /* @__PURE__ */ new Set();
339851
- const records = block.records.map((record8) => {
339852
- assertId(record8.recordId, "recordId");
339853
- if (recordIds.has(record8.recordId)) {
339851
+ const records = block.records.map((record9) => {
339852
+ assertId(record9.recordId, "recordId");
339853
+ if (recordIds.has(record9.recordId)) {
339854
339854
  throw new TelegramContextPacketValidationError(
339855
- `Duplicate recordId=${JSON.stringify(record8.recordId)} in semanticId=${JSON.stringify(block.semanticId)}`
339855
+ `Duplicate recordId=${JSON.stringify(record9.recordId)} in semanticId=${JSON.stringify(block.semanticId)}`
339856
339856
  );
339857
339857
  }
339858
- recordIds.add(record8.recordId);
339859
- if (typeof record8.content !== "string") {
339858
+ recordIds.add(record9.recordId);
339859
+ if (typeof record9.content !== "string") {
339860
339860
  throw new TelegramContextPacketValidationError(
339861
- `content for recordId=${JSON.stringify(record8.recordId)} must be a string`
339861
+ `content for recordId=${JSON.stringify(record9.recordId)} must be a string`
339862
339862
  );
339863
339863
  }
339864
339864
  return {
@@ -339867,10 +339867,10 @@ function normalizeBlock(block) {
339867
339867
  stability: block.stability,
339868
339868
  blockOrder: order,
339869
339869
  blockPriority: priority,
339870
- recordId: record8.recordId,
339871
- content: record8.content,
339872
- recordOrder: normalizedInteger(record8.order, 0, "record order"),
339873
- recordPriority: normalizedInteger(record8.priority, 0, "record priority")
339870
+ recordId: record9.recordId,
339871
+ content: record9.content,
339872
+ recordOrder: normalizedInteger(record9.order, 0, "record order"),
339873
+ recordPriority: normalizedInteger(record9.priority, 0, "record priority")
339874
339874
  };
339875
339875
  });
339876
339876
  records.sort(compareRecordsForRender);
@@ -339893,11 +339893,11 @@ function selectBlockRevisions(blocks) {
339893
339893
  stability: normalized4.stability,
339894
339894
  order: normalized4.order,
339895
339895
  priority: normalized4.priority,
339896
- records: normalized4.records.map((record8) => ({
339897
- recordId: record8.recordId,
339898
- content: record8.content,
339899
- order: record8.recordOrder,
339900
- priority: record8.recordPriority
339896
+ records: normalized4.records.map((record9) => ({
339897
+ recordId: record9.recordId,
339898
+ content: record9.content,
339899
+ order: record9.recordOrder,
339900
+ priority: record9.recordPriority
339901
339901
  }))
339902
339902
  };
339903
339903
  const canonical9 = canonicalBlock(source);
@@ -339930,28 +339930,28 @@ function segmentFooter(segment) {
339930
339930
  segment
339931
339931
  });
339932
339932
  }
339933
- function serializeRecord(record8) {
339933
+ function serializeRecord(record9) {
339934
339934
  return JSON.stringify({
339935
339935
  type: "telegram_context_record_v2",
339936
339936
  schemaVersion: TELEGRAM_CONTEXT_PACKET_SCHEMA_VERSION,
339937
- semanticId: record8.semanticId,
339938
- revision: record8.revision,
339939
- recordId: record8.recordId,
339940
- content: record8.content
339937
+ semanticId: record9.semanticId,
339938
+ revision: record9.revision,
339939
+ recordId: record9.recordId,
339940
+ content: record9.content
339941
339941
  });
339942
339942
  }
339943
- function omittedRecordRef(record8) {
339943
+ function omittedRecordRef(record9) {
339944
339944
  return {
339945
- semanticId: record8.semanticId,
339946
- revision: record8.revision,
339947
- recordId: record8.recordId
339945
+ semanticId: record9.semanticId,
339946
+ revision: record9.revision,
339947
+ recordId: record9.recordId
339948
339948
  };
339949
339949
  }
339950
339950
  function buildOmissionReceipt(segment, omitted) {
339951
339951
  if (omitted.length === 0) return void 0;
339952
339952
  const omittedRecords = [...omitted].sort(compareRecordsForRender).map(omittedRecordRef);
339953
339953
  const omittedSemanticIds = [
339954
- ...new Set(omittedRecords.map((record8) => record8.semanticId))
339954
+ ...new Set(omittedRecords.map((record9) => record9.semanticId))
339955
339955
  ].sort(compareText);
339956
339956
  return {
339957
339957
  type: "telegram_context_omission_receipt_v2",
@@ -340004,7 +340004,7 @@ function compileSegment(segment, blocks, budgetChars) {
340004
340004
  for (const candidate of admissionOrder) {
340005
340005
  const tentativeIncluded = [...included, candidate];
340006
340006
  const tentativeOmitted = admissionOrder.filter(
340007
- (record8) => !included.has(record8) && record8 !== candidate
340007
+ (record9) => !included.has(record9) && record9 !== candidate
340008
340008
  );
340009
340009
  const tentative = renderSegmentText(
340010
340010
  segment,
@@ -340013,11 +340013,11 @@ function compileSegment(segment, blocks, budgetChars) {
340013
340013
  );
340014
340014
  if (tentative.text.length <= budgetChars) included.add(candidate);
340015
340015
  }
340016
- const includedRecords = records.filter((record8) => included.has(record8));
340017
- const omittedRecords = records.filter((record8) => !included.has(record8));
340016
+ const includedRecords = records.filter((record9) => included.has(record9));
340017
+ const omittedRecords = records.filter((record9) => !included.has(record9));
340018
340018
  const rendered = renderSegmentText(segment, includedRecords, omittedRecords);
340019
340019
  const compiledBlocks = blocks.flatMap((block) => {
340020
- const admitted = block.records.filter((record8) => included.has(record8));
340020
+ const admitted = block.records.filter((record9) => included.has(record9));
340021
340021
  if (admitted.length === 0) return [];
340022
340022
  return [
340023
340023
  {
@@ -340026,14 +340026,14 @@ function compileSegment(segment, blocks, budgetChars) {
340026
340026
  stability: block.stability,
340027
340027
  order: block.order,
340028
340028
  priority: block.priority,
340029
- records: admitted.sort(compareRecordsForRender).map((record8) => ({
340030
- semanticId: record8.semanticId,
340031
- revision: record8.revision,
340032
- recordId: record8.recordId,
340033
- content: record8.content,
340034
- order: record8.recordOrder,
340035
- priority: record8.recordPriority,
340036
- serializedChars: serializeRecord(record8).length
340029
+ records: admitted.sort(compareRecordsForRender).map((record9) => ({
340030
+ semanticId: record9.semanticId,
340031
+ revision: record9.revision,
340032
+ recordId: record9.recordId,
340033
+ content: record9.content,
340034
+ order: record9.recordOrder,
340035
+ priority: record9.recordPriority,
340036
+ serializedChars: serializeRecord(record9).length
340037
340037
  }))
340038
340038
  }
340039
340039
  ];
@@ -342462,8 +342462,8 @@ function reviewBinding(input) {
342462
342462
  })) };
342463
342463
  }
342464
342464
  function projectTaskRequirementReviewEvidence(evidence) {
342465
- const record8 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
342466
- const snapshot = (value) => record8(value) && value.schema === "omnius.task-execution-snapshot.v1" && record8(value.contract) && value.contract.schema === "omnius.task-objective-contract.v1" && Array.isArray(value.contract.criteria) && Array.isArray(value.evidence);
342465
+ const record9 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
342466
+ const snapshot = (value) => record9(value) && value.schema === "omnius.task-execution-snapshot.v1" && record9(value.contract) && value.contract.schema === "omnius.task-objective-contract.v1" && Array.isArray(value.contract.criteria) && Array.isArray(value.evidence);
342467
342467
  const project = (value) => {
342468
342468
  const { frontier: _frontier, workPlan: _plan, workPlanSha256: _planSha, selectedWork: _selected, pendingLegacyOperationRefs: _pending, snapshotSha256: _snapshotSha, ...material } = value;
342469
342469
  const contract = value.contract;
@@ -342471,7 +342471,7 @@ function projectTaskRequirementReviewEvidence(evidence) {
342471
342471
  ...material,
342472
342472
  schema: "omnius.task-requirement-review-evidence.v1",
342473
342473
  contract: { ...contract, criteria: contract.criteria.map((criterion) => {
342474
- if (!record8(criterion))
342474
+ if (!record9(criterion))
342475
342475
  return criterion;
342476
342476
  const { status: _initialStatus, ...obligation2 } = criterion;
342477
342477
  return obligation2;
@@ -342480,7 +342480,7 @@ function projectTaskRequirementReviewEvidence(evidence) {
342480
342480
  };
342481
342481
  if (snapshot(evidence))
342482
342482
  return project(evidence);
342483
- if (record8(evidence) && snapshot(evidence.executionSnapshot))
342483
+ if (record9(evidence) && snapshot(evidence.executionSnapshot))
342484
342484
  return { ...evidence, executionSnapshot: project(evidence.executionSnapshot) };
342485
342485
  return evidence;
342486
342486
  }
@@ -343033,7 +343033,7 @@ function parseKeylessInferenceRegistry(html) {
343033
343033
  // packages/orchestrator/dist/inference-provider-error.js
343034
343034
  var object4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
343035
343035
  var reasons = /* @__PURE__ */ new Set(["unsupported_schema", "request", "rate", "auth", "upstream"]);
343036
- var knownUnsupportedKeywords = /* @__PURE__ */ new Set(["uniqueItems", "rootAnyOf", "requiredAllProperties"]);
343036
+ var knownUnsupportedKeywords = /* @__PURE__ */ new Set(["uniqueItems", "rootAnyOf", "requiredAllProperties", "oneOf"]);
343037
343037
  var optionalPropertyName = /^[A-Za-z_][A-Za-z0-9_-]{0,127}$/;
343038
343038
  var InferenceProviderError = class extends Error {
343039
343039
  status;
@@ -343100,7 +343100,8 @@ function normalizeInferenceProviderError(value, headers) {
343100
343100
  const missingProperty = detail.type === "invalid_request_error" && detail.param === "schema" && typeof detail.message === "string" ? /^'required' is required to be supplied and to be an array including every key in properties\. Missing '([A-Za-z_][A-Za-z0-9_-]{0,127})'\.$/.exec(detail.message)?.[1] : void 0;
343101
343101
  const unsupportedKeywords = [.../* @__PURE__ */ new Set([
343102
343102
  ...fields2.flatMap((field) => unsupportedGrammarKeywords(field.message)),
343103
- ...missingProperty ? ["requiredAllProperties"] : []
343103
+ ...missingProperty ? ["requiredAllProperties"] : [],
343104
+ ...detail.type === "invalid_request_error" && detail.param === "schema" && detail.message === "'oneOf' is not permitted." ? ["oneOf"] : []
343104
343105
  ])];
343105
343106
  let reason = "upstream", inferredStatus = 500;
343106
343107
  if (knownStatus === 429 || codes.some((item) => rateCodes.has(item))) {
@@ -344156,7 +344157,7 @@ function collectOpenCodeResponsesResponse(response, request, options) {
344156
344157
  }
344157
344158
 
344158
344159
  // packages/orchestrator/dist/provider-schema-adapter.js
344159
- var SUPPORTED_PROVIDER_SCHEMA_ADAPTATIONS = Object.freeze(["uniqueItems", "rootAnyOf", "requiredAllProperties"]);
344160
+ var SUPPORTED_PROVIDER_SCHEMA_ADAPTATIONS = Object.freeze(["uniqueItems", "rootAnyOf", "requiredAllProperties", "oneOf"]);
344160
344161
  var object9 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
344161
344162
  function hasProviderRequiredAllPropertiesConflict(format, missingProperty) {
344162
344163
  if (format.type !== "json_schema")
@@ -344172,7 +344173,7 @@ function hasProviderRequiredAllPropertiesConflict(format, missingProperty) {
344172
344173
  }
344173
344174
  function lowerProviderSchema(schema, unsupportedKeywords) {
344174
344175
  const lowered = structuredClone(schema);
344175
- const adaptations = new Set(unsupportedKeywords.filter((keyword) => keyword === "uniqueItems"));
344176
+ const adaptations = new Set(unsupportedKeywords.filter((keyword) => keyword === "uniqueItems" || keyword === "oneOf"));
344176
344177
  if (adaptations.size === 0)
344177
344178
  return lowered;
344178
344179
  const seen = /* @__PURE__ */ new WeakSet();
@@ -344180,8 +344181,12 @@ function lowerProviderSchema(schema, unsupportedKeywords) {
344180
344181
  if (!object9(value) || seen.has(value))
344181
344182
  return;
344182
344183
  seen.add(value);
344183
- for (const keyword of adaptations)
344184
- delete value[keyword];
344184
+ if (adaptations.has("uniqueItems"))
344185
+ delete value.uniqueItems;
344186
+ if (adaptations.has("oneOf") && !("anyOf" in value) && Array.isArray(value.oneOf) && value.oneOf.length && value.oneOf.every(object9)) {
344187
+ value.anyOf = value.oneOf;
344188
+ delete value.oneOf;
344189
+ }
344185
344190
  for (const keyword of ["properties", "patternProperties", "$defs", "definitions", "dependentSchemas", "dependencies"]) {
344186
344191
  if (object9(value[keyword]))
344187
344192
  for (const child of Object.values(value[keyword]))
@@ -345672,7 +345677,8 @@ var RemoteInferenceFallback = class _RemoteInferenceFallback {
345672
345677
  const instructions = formatExpectedInferenceInstructions(request) + [
345673
345678
  promptOnly ? "Native structured output is disabled for this request by model metadata or observed compatibility policy. Generate the exact original JSON contract above as text; the unchanged host schema and callback still validate the entire response before it is admitted." : "",
345674
345679
  keywords.includes("uniqueItems") ? "The provider's native grammar cannot express uniqueItems. The unchanged host contract still requires those arrays to contain no duplicates." : "",
345675
- keywords.includes("rootAnyOf") ? "The provider's native grammar cannot express the root anyOf alternatives. The complete original schema above remains authoritative: obey its coupled fulfillment, continuation, identity and null-field constraints." : ""
345680
+ keywords.includes("rootAnyOf") ? "The provider's native grammar cannot express the root anyOf alternatives. The complete original schema above remains authoritative: obey its coupled fulfillment, continuation, identity and null-field constraints." : "",
345681
+ keywords.includes("oneOf") ? "The provider's native grammar offers an inclusive anyOf in place of oneOf. The complete original host contract remains authoritative: a oneOf value must match exactly one of its original alternatives." : ""
345676
345682
  ].filter(Boolean).map((line) => `
345677
345683
  ${line}`).join("");
345678
345684
  const { responseFormat: _camelFormat, response_format: _snakeFormat, ...withoutNativeFormat } = request;
@@ -345702,7 +345708,7 @@ ${line}`).join("");
345702
345708
  responseFormat: prepared.responseFormat,
345703
345709
  response_format: prepared.response_format
345704
345710
  });
345705
- const nativeIdle = streamDeadline !== void 0 && request.nativePlanningStreamIdleTimeoutMs === 9e4 && this.policy.requestTimeoutMsSource === "default";
345711
+ const nativeIdle = streamDeadline !== void 0 && (request.nativePlanningStreamIdleTimeoutMs === 9e4 || request.structuredReviewStreamIdleTimeoutMs === 9e4) && this.policy.requestTimeoutMsSource === "default";
345706
345712
  const timeoutMs = nativeIdle ? Math.min(9e4, request.timeoutMs > 0 ? request.timeoutMs : Infinity, Math.max(1, streamDeadline - this.now())) : Math.min(request.timeoutMs, this.policy.requestTimeoutMs);
345707
345713
  return {
345708
345714
  ...host,
@@ -346531,40 +346537,40 @@ function cleanId(value, max = 240) {
346531
346537
  function normalizeExpectedOutcomeContractV1(value) {
346532
346538
  if (!value || typeof value !== "object" || Array.isArray(value))
346533
346539
  return null;
346534
- const record8 = value;
346535
- if (record8["schema"] !== "omnius.expected-outcome-contract.v1")
346540
+ const record9 = value;
346541
+ if (record9["schema"] !== "omnius.expected-outcome-contract.v1")
346536
346542
  return null;
346537
- const route = record8["route"];
346538
- const continuity = record8["continuity"];
346539
- const planningMode = record8["planningMode"];
346543
+ const route = record9["route"];
346544
+ const continuity = record9["continuity"];
346545
+ const planningMode = record9["planningMode"];
346540
346546
  if (!ROUTES.has(route) || !CONTINUITIES.has(continuity))
346541
346547
  return null;
346542
346548
  if (!PLANNING_MODES.has(planningMode))
346543
346549
  return null;
346544
- const confidence2 = record8["confidence"];
346545
- const reason = cleanId(record8["reason"], 1e3);
346546
- if (typeof confidence2 !== "number" || !Number.isFinite(confidence2) || confidence2 < 0 || confidence2 > 1 || !reason || !Array.isArray(record8["citedEvidenceIds"])) {
346550
+ const confidence2 = record9["confidence"];
346551
+ const reason = cleanId(record9["reason"], 1e3);
346552
+ if (typeof confidence2 !== "number" || !Number.isFinite(confidence2) || confidence2 < 0 || confidence2 > 1 || !reason || !Array.isArray(record9["citedEvidenceIds"])) {
346547
346553
  return null;
346548
346554
  }
346549
346555
  const citedEvidenceIds = [
346550
- ...new Set(record8["citedEvidenceIds"].map((value2) => cleanId(value2, 500)).filter((value2) => Boolean(value2)))
346556
+ ...new Set(record9["citedEvidenceIds"].map((value2) => cleanId(value2, 500)).filter((value2) => Boolean(value2)))
346551
346557
  ].slice(0, 64);
346552
- if (citedEvidenceIds.length !== record8["citedEvidenceIds"].length)
346558
+ if (citedEvidenceIds.length !== record9["citedEvidenceIds"].length)
346553
346559
  return null;
346554
- const outcome = record8["outcome"];
346560
+ const outcome = record9["outcome"];
346555
346561
  if (!OUTCOMES.has(outcome))
346556
346562
  return null;
346557
- if (!Array.isArray(record8["requiredEffects"]))
346563
+ if (!Array.isArray(record9["requiredEffects"]))
346558
346564
  return null;
346559
346565
  const requiredEffects = [
346560
- ...new Set(record8["requiredEffects"].filter((effect) => typeof effect === "string" && EFFECTS.has(effect)))
346566
+ ...new Set(record9["requiredEffects"].filter((effect) => typeof effect === "string" && EFFECTS.has(effect)))
346561
346567
  ];
346562
- if (requiredEffects.length !== record8["requiredEffects"].length || !requiredEffects.includes(CORE_EFFECT[outcome])) {
346568
+ if (requiredEffects.length !== record9["requiredEffects"].length || !requiredEffects.includes(CORE_EFFECT[outcome])) {
346563
346569
  return null;
346564
346570
  }
346565
- const activeScopeId = cleanId(record8["activeScopeId"], 500);
346566
- const inputId = cleanId(record8["inputId"]);
346567
- const decisionId = cleanId(record8["decisionId"]);
346571
+ const activeScopeId = cleanId(record9["activeScopeId"], 500);
346572
+ const inputId = cleanId(record9["inputId"]);
346573
+ const decisionId = cleanId(record9["decisionId"]);
346568
346574
  return {
346569
346575
  schema: "omnius.expected-outcome-contract.v1",
346570
346576
  route,
@@ -346604,17 +346610,17 @@ function expectedOutcomeAllowsTextOnlyCompletion(contract) {
346604
346610
  function normalizeCompletionDeliveryReceipt(value) {
346605
346611
  if (!value || typeof value !== "object" || Array.isArray(value))
346606
346612
  return null;
346607
- const record8 = value;
346608
- if (record8["schema"] !== "omnius.completion-delivery-receipt.v1")
346613
+ const record9 = value;
346614
+ if (record9["schema"] !== "omnius.completion-delivery-receipt.v1")
346609
346615
  return null;
346610
- const provider = cleanId(record8["provider"], 120);
346611
- const target2 = cleanId(record8["target"], 500);
346612
- const receiptId = cleanId(record8["receiptId"], 500);
346613
- const deliveredAtIso = cleanId(record8["deliveredAtIso"], 80);
346616
+ const provider = cleanId(record9["provider"], 120);
346617
+ const target2 = cleanId(record9["target"], 500);
346618
+ const receiptId = cleanId(record9["receiptId"], 500);
346619
+ const deliveredAtIso = cleanId(record9["deliveredAtIso"], 80);
346614
346620
  if (!provider || !target2 || !receiptId || !deliveredAtIso)
346615
346621
  return null;
346616
- const artifactPaths = Array.isArray(record8["artifactPaths"]) ? [
346617
- ...new Set(record8["artifactPaths"].filter((path7) => typeof path7 === "string").map((path7) => path7.trim().slice(0, 1e3)).filter(Boolean))
346622
+ const artifactPaths = Array.isArray(record9["artifactPaths"]) ? [
346623
+ ...new Set(record9["artifactPaths"].filter((path7) => typeof path7 === "string").map((path7) => path7.trim().slice(0, 1e3)).filter(Boolean))
346618
346624
  ].slice(0, 32) : void 0;
346619
346625
  return {
346620
346626
  schema: "omnius.completion-delivery-receipt.v1",
@@ -346947,10 +346953,10 @@ function normalizeTaskObjectiveContractV1(value) {
346947
346953
  const raw = input["deliveryTarget"];
346948
346954
  if (!raw || typeof raw !== "object" || Array.isArray(raw))
346949
346955
  return null;
346950
- const record8 = raw;
346951
- const surface = clean(record8["surface"], 120);
346952
- const targetId = clean(record8["targetId"], 500);
346953
- const threadId = clean(record8["threadId"], 500);
346956
+ const record9 = raw;
346957
+ const surface = clean(record9["surface"], 120);
346958
+ const targetId = clean(record9["targetId"], 500);
346959
+ const threadId = clean(record9["threadId"], 500);
346954
346960
  if (!surface || !targetId)
346955
346961
  return null;
346956
346962
  deliveryTarget = { surface, targetId, ...threadId ? { threadId } : {} };
@@ -347811,21 +347817,21 @@ function prepareReviewedObjectiveInterpretationRevisionV1(input) {
347811
347817
  };
347812
347818
  return { ...body, id: `interpretation:${taskExecutionDigest(body)}` };
347813
347819
  }
347814
- function revisedLedger(ledger, record8) {
347820
+ function revisedLedger(ledger, record9) {
347815
347821
  const next = {
347816
347822
  ...structuredClone(ledger),
347817
- objectiveContract: structuredClone(record8.nextContract),
347818
- reviewedInterpretation: structuredClone(record8),
347823
+ objectiveContract: structuredClone(record9.nextContract),
347824
+ reviewedInterpretation: structuredClone(record9),
347819
347825
  status: "open",
347820
347826
  updatedAtIso: (/* @__PURE__ */ new Date()).toISOString()
347821
347827
  };
347822
347828
  delete next.terminal;
347823
347829
  delete next.objectiveFrontier;
347824
347830
  delete next.objectiveConvergence;
347825
- if (record8.nextWorkPlan)
347826
- next.workPlan = structuredClone(record8.nextWorkPlan);
347831
+ if (record9.nextWorkPlan)
347832
+ next.workPlan = structuredClone(record9.nextWorkPlan);
347827
347833
  else if (next.workPlan) {
347828
- const rebound = rebindTaskWorkPlanV1({ plan: next.workPlan, contract: record8.nextContract, evidenceIds: next.evidence.map((e) => e.id), evidence: next.evidence });
347834
+ const rebound = rebindTaskWorkPlanV1({ plan: next.workPlan, contract: record9.nextContract, evidenceIds: next.evidence.map((e) => e.id), evidence: next.evidence });
347829
347835
  if (rebound)
347830
347836
  next.workPlan = rebound;
347831
347837
  else
@@ -347869,21 +347875,21 @@ function commitReviewedObjectiveInterpretationRevisionV1(input) {
347869
347875
  const raw = readFileSync24(input.ledgerPath, "utf8");
347870
347876
  if (sha6(raw) !== input.expectedLedgerSha256)
347871
347877
  throw new Error("Reviewed interpretation ledger compare-and-swap failed");
347872
- const ledger = restoreCompletionLedgerSnapshot(JSON.parse(raw)), record8 = input.prepare(ledger);
347873
- prepared = record8;
347874
- if (record8.priorLedgerSha256 !== input.expectedLedgerSha256)
347878
+ const ledger = restoreCompletionLedgerSnapshot(JSON.parse(raw)), record9 = input.prepare(ledger);
347879
+ prepared = record9;
347880
+ if (record9.priorLedgerSha256 !== input.expectedLedgerSha256)
347875
347881
  throw new Error("Reviewed interpretation prior bytes changed");
347876
- const next = revisedLedger(ledger, record8), nextRaw = encoded(next);
347882
+ const next = revisedLedger(ledger, record9), nextRaw = encoded(next);
347877
347883
  const transaction = {
347878
347884
  schema: "omnius.reviewed-objective-interpretation-transaction.v1",
347879
- record: record8,
347885
+ record: record9,
347880
347886
  nextLedger: next,
347881
347887
  nextLedgerSha256: sha6(nextRaw)
347882
347888
  };
347883
347889
  writeAtomic(recordPath, encoded(transaction));
347884
347890
  input.persistenceFaultForTest?.("committed_before_projection");
347885
347891
  writeAtomic(input.ledgerPath, nextRaw);
347886
- return { record: record8, ledger: next, recordPath };
347892
+ return { record: record9, ledger: next, recordPath };
347887
347893
  } catch (error) {
347888
347894
  let committed = false;
347889
347895
  try {
@@ -347949,36 +347955,36 @@ function reconcileReviewedObjectiveInterpretationRevisionV1(ledgerPath, expected
347949
347955
 
347950
347956
  // packages/orchestrator/dist/nativeRequirementAmendment.js
347951
347957
  var hash11 = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
347952
- function validateNativeTaskRequirementAmendmentRecordV1(record8, evidence) {
347958
+ function validateNativeTaskRequirementAmendmentRecordV1(record9, evidence) {
347953
347959
  try {
347954
- const { id: id5, ...body } = record8, a = record8.authority, r = a.review;
347955
- const old = normalizeTaskObjectiveContractV1(record8.priorContract), next = normalizeTaskObjectiveContractV1(a.nextContract);
347956
- const oldOutcome = normalizeExpectedOutcomeContractV1(record8.priorExpectedOutcome), outcome = normalizeExpectedOutcomeContractV1(a.nextExpectedOutcome);
347957
- const binding = record8.schema === "omnius.native-requirement-amendment-record.v1" && id5 === `native-amendment:${taskExecutionDigest(body)}` && !!old && !!next?.requirements && !!oldOutcome && !!outcome && a.schema === "omnius.native-requirement-amendment.v1" && validateTaskNativeExecutionScopeV1(a.scope) && next.revision === old.revision + 1 && next.originalRequestRef === old.originalRequestRef && next.originalRequestHash === old.originalRequestHash && next.goal === old.goal && r.priorContractSha256 === taskExecutionDigest(old) && r.nextContractSha256 === taskExecutionDigest(next) && r.priorExpectedOutcomeSha256 === taskExecutionDigest(oldOutcome) && r.nextExpectedOutcomeSha256 === taskExecutionDigest(outcome) && validateTaskRequirementEvidenceV1({
347960
+ const { id: id5, ...body } = record9, a = record9.authority, r = a.review;
347961
+ const old = normalizeTaskObjectiveContractV1(record9.priorContract), next = normalizeTaskObjectiveContractV1(a.nextContract);
347962
+ const oldOutcome = normalizeExpectedOutcomeContractV1(record9.priorExpectedOutcome), outcome = normalizeExpectedOutcomeContractV1(a.nextExpectedOutcome);
347963
+ const binding = record9.schema === "omnius.native-requirement-amendment-record.v1" && id5 === `native-amendment:${taskExecutionDigest(body)}` && !!old && !!next?.requirements && !!oldOutcome && !!outcome && a.schema === "omnius.native-requirement-amendment.v1" && validateTaskNativeExecutionScopeV1(a.scope) && next.revision === old.revision + 1 && next.originalRequestRef === old.originalRequestRef && next.originalRequestHash === old.originalRequestHash && next.goal === old.goal && r.priorContractSha256 === taskExecutionDigest(old) && r.nextContractSha256 === taskExecutionDigest(next) && r.priorExpectedOutcomeSha256 === taskExecutionDigest(oldOutcome) && r.nextExpectedOutcomeSha256 === taskExecutionDigest(outcome) && validateTaskRequirementEvidenceV1({
347958
347964
  requirements: next.requirements,
347959
347965
  evidence: a.nativeEvidence,
347960
347966
  nativeScopeSha256: a.scope.nativeScopeSha256,
347961
347967
  nativeEvidenceSnapshotSha256: r.nativeEvidenceSnapshotSha256
347962
- }) && a.nextIssuedDecision.decisionId === outcome.decisionId && taskExecutionDigest(a.nextIssuedDecision.payload) === a.nextIssuedDecision.payloadSha256 && a.scope.issuedDecisionPayloadSha256 === a.nextIssuedDecision.payloadSha256 && evidence.some((entry) => entry.id === record8.provenanceEvidenceId && entry.kind === "human_input" && entry.success === true && entry.rawRef === a.inputId && entry.metrics?.nativeInputSha256 === a.scope.nativeInputSha256);
347963
- if (!binding || !old || !oldOutcome || !Array.isArray(record8.priorEvidence) || record8.priorEvidence.some((prior) => !evidence.some((current) => current.id === prior.id && (taskExecutionDigest(current) === taskExecutionDigest(prior) || // Native adoption can retain a stale read/review diagnosis without transferring authority.
347968
+ }) && a.nextIssuedDecision.decisionId === outcome.decisionId && taskExecutionDigest(a.nextIssuedDecision.payload) === a.nextIssuedDecision.payloadSha256 && a.scope.issuedDecisionPayloadSha256 === a.nextIssuedDecision.payloadSha256 && evidence.some((entry) => entry.id === record9.provenanceEvidenceId && entry.kind === "human_input" && entry.success === true && entry.rawRef === a.inputId && entry.metrics?.nativeInputSha256 === a.scope.nativeInputSha256);
347969
+ if (!binding || !old || !oldOutcome || !Array.isArray(record9.priorEvidence) || record9.priorEvidence.some((prior) => !evidence.some((current) => current.id === prior.id && (taskExecutionDigest(current) === taskExecutionDigest(prior) || // Native adoption can retain a stale read/review diagnosis without transferring authority.
347964
347970
  !prior.externalEffectReceipt && !prior.deliveryReceipt && !prior.receipt && prior.role !== "mutation" && current.progressClass === "control_bookkeeping" && current.success === void 0 && !current.objectiveEvidenceKinds?.length))))
347965
347971
  return false;
347966
347972
  const priorLedger = createCompletionLedger({
347967
- runId: record8.priorScope.nativeRunnerRunId,
347968
- taskEpoch: record8.priorScope.taskEpoch,
347973
+ runId: record9.priorScope.nativeRunnerRunId,
347974
+ taskEpoch: record9.priorScope.taskEpoch,
347969
347975
  goal: old.goal,
347970
347976
  objectiveContract: old
347971
347977
  });
347972
- priorLedger.evidence = structuredClone(record8.priorEvidence);
347973
- priorLedger.workPlan = structuredClone(record8.priorWorkPlan);
347978
+ priorLedger.evidence = structuredClone(record9.priorEvidence);
347979
+ priorLedger.workPlan = structuredClone(record9.priorWorkPlan);
347974
347980
  const replay = applyNativeTaskRequirementAmendmentInternal({
347975
347981
  ledger: priorLedger,
347976
347982
  priorExpectedOutcome: oldOutcome,
347977
- priorScope: record8.priorScope,
347983
+ priorScope: record9.priorScope,
347978
347984
  amendment: a,
347979
347985
  steering: { inputId: a.inputId, source: "telegram", taskEpoch: a.scope.taskEpoch, intent: "append" }
347980
347986
  }, false);
347981
- return replay.nativeRequirementAmendments?.at(-1)?.id === record8.id;
347987
+ return replay.nativeRequirementAmendments?.at(-1)?.id === record9.id;
347982
347988
  } catch {
347983
347989
  return false;
347984
347990
  }
@@ -349240,7 +349246,7 @@ function restoreCompletionLedgerSnapshot(value) {
349240
349246
  throw new Error("Unsupported completion ledger schema");
349241
349247
  }
349242
349248
  parsed.schema = COMPLETION_LEDGER_SCHEMA;
349243
- if (parsed.nativeRequirementAmendments !== void 0 && (!Array.isArray(parsed.nativeRequirementAmendments) || parsed.nativeRequirementAmendments.some((record8) => !validateNativeTaskRequirementAmendmentRecordV1(record8, parsed.evidence))))
349249
+ if (parsed.nativeRequirementAmendments !== void 0 && (!Array.isArray(parsed.nativeRequirementAmendments) || parsed.nativeRequirementAmendments.some((record9) => !validateNativeTaskRequirementAmendmentRecordV1(record9, parsed.evidence))))
349244
349250
  throw new Error("Invalid persisted native requirement amendment authority");
349245
349251
  if (parsed.objectiveContract) {
349246
349252
  const contract = normalizeTaskObjectiveContractV1(parsed.objectiveContract);
@@ -349500,11 +349506,11 @@ function validateContinuationStrengthening(input) {
349500
349506
  ].some((receipt) => receipt.criterionId === proof.criterionId || receipt.supportedAnswer !== void 0)))
349501
349507
  throw new Error("Task objective strengthening cannot inherit a seeded answer review");
349502
349508
  }
349503
- function claimPath(record8) {
349504
- return `${record8.input.predecessor.ledgerPath}.continuation-${record8.input.predecessor.ledgerSha256}.json`;
349509
+ function claimPath(record9) {
349510
+ return `${record9.input.predecessor.ledgerPath}.continuation-${record9.input.predecessor.ledgerSha256}.json`;
349505
349511
  }
349506
- function withContinuationClaimLock(record8, operation) {
349507
- const path7 = `${claimPath(record8)}.lock`;
349512
+ function withContinuationClaimLock(record9, operation) {
349513
+ const path7 = `${claimPath(record9)}.lock`;
349508
349514
  const token5 = JSON.stringify({ pid: process.pid, nonce: Math.random().toString(16).slice(2) });
349509
349515
  let fd;
349510
349516
  try {
@@ -349538,14 +349544,14 @@ function withContinuationClaimLock(record8, operation) {
349538
349544
  unlinkSync9(path7);
349539
349545
  }
349540
349546
  }
349541
- function readClaim(record8) {
349542
- const claim = JSON.parse(readFileSync26(claimPath(record8), "utf8"));
349543
- if (claim.schema !== "omnius.task-objective-continuation-claim.v1" || claim.predecessorLedgerSha256 !== record8.input.predecessor.ledgerSha256 || claim.authoritySha256 !== record8.authoritySha256 || claim.recipientBridgeRunId !== record8.input.scope.recipientBridgeRunId || claim.currentGeneration !== record8.input.scope.currentGeneration || !["pending", "committed", "inference_started"].includes(claim.phase))
349547
+ function readClaim(record9) {
349548
+ const claim = JSON.parse(readFileSync26(claimPath(record9), "utf8"));
349549
+ if (claim.schema !== "omnius.task-objective-continuation-claim.v1" || claim.predecessorLedgerSha256 !== record9.input.predecessor.ledgerSha256 || claim.authoritySha256 !== record9.authoritySha256 || claim.recipientBridgeRunId !== record9.input.scope.recipientBridgeRunId || claim.currentGeneration !== record9.input.scope.currentGeneration || !["pending", "committed", "inference_started"].includes(claim.phase))
349544
349550
  throw new Error("Task objective predecessor belongs to a different admitted recipient");
349545
349551
  return claim;
349546
349552
  }
349547
- function writeClaim(record8, claim, exclusive = false) {
349548
- const path7 = claimPath(record8), temporary = `${path7}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
349553
+ function writeClaim(record9, claim, exclusive = false) {
349554
+ const path7 = claimPath(record9), temporary = `${path7}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
349549
349555
  const fd = openSync7(temporary, "wx", 384);
349550
349556
  try {
349551
349557
  try {
@@ -349573,57 +349579,57 @@ function writeClaim(record8, claim, exclusive = false) {
349573
349579
  throw error;
349574
349580
  }
349575
349581
  }
349576
- function claimTaskObjectiveContinuation(record8) {
349577
- return withContinuationClaimLock(record8, () => claimTaskObjectiveContinuationLocked(record8));
349582
+ function claimTaskObjectiveContinuation(record9) {
349583
+ return withContinuationClaimLock(record9, () => claimTaskObjectiveContinuationLocked(record9));
349578
349584
  }
349579
- function claimTaskObjectiveContinuationLocked(record8) {
349580
- const path7 = claimPath(record8);
349585
+ function claimTaskObjectiveContinuationLocked(record9) {
349586
+ const path7 = claimPath(record9);
349581
349587
  const claim = {
349582
349588
  schema: "omnius.task-objective-continuation-claim.v1",
349583
- predecessorLedgerSha256: record8.input.predecessor.ledgerSha256,
349584
- authoritySha256: record8.authoritySha256,
349585
- recipientBridgeRunId: record8.input.scope.recipientBridgeRunId,
349586
- currentGeneration: record8.input.scope.currentGeneration,
349587
- recipientRunId: record8.recipientRunId,
349589
+ predecessorLedgerSha256: record9.input.predecessor.ledgerSha256,
349590
+ authoritySha256: record9.authoritySha256,
349591
+ recipientBridgeRunId: record9.input.scope.recipientBridgeRunId,
349592
+ currentGeneration: record9.input.scope.currentGeneration,
349593
+ recipientRunId: record9.recipientRunId,
349588
349594
  phase: "pending"
349589
349595
  };
349590
349596
  if (existsSync27(path7)) {
349591
- const old = readClaim(record8);
349592
- if (old.recipientRunId === record8.recipientRunId)
349597
+ const old = readClaim(record9);
349598
+ if (old.recipientRunId === record9.recipientRunId)
349593
349599
  return;
349594
349600
  if (old.phase === "inference_started")
349595
349601
  throw new Error("Task objective continuation requires recipient interruption reconciliation");
349596
- writeClaim(record8, claim);
349602
+ writeClaim(record9, claim);
349597
349603
  } else {
349598
- writeClaim(record8, claim, true);
349604
+ writeClaim(record9, claim, true);
349599
349605
  }
349600
349606
  }
349601
- function commitTaskObjectiveContinuation(record8) {
349602
- return withContinuationClaimLock(record8, () => commitTaskObjectiveContinuationLocked(record8));
349607
+ function commitTaskObjectiveContinuation(record9) {
349608
+ return withContinuationClaimLock(record9, () => commitTaskObjectiveContinuationLocked(record9));
349603
349609
  }
349604
- function commitTaskObjectiveContinuationLocked(record8) {
349605
- const claim = readClaim(record8);
349606
- if (claim.recipientRunId !== record8.recipientRunId)
349610
+ function commitTaskObjectiveContinuationLocked(record9) {
349611
+ const claim = readClaim(record9);
349612
+ if (claim.recipientRunId !== record9.recipientRunId)
349607
349613
  throw new Error("Task objective continuation recipient was superseded");
349608
- const recordSha256 = taskObjectiveContinuationDigest(record8);
349614
+ const recordSha256 = taskObjectiveContinuationDigest(record9);
349609
349615
  if (claim.phase !== "pending" && claim.recordSha256 !== recordSha256)
349610
349616
  throw new Error("Task objective continuation committed proof changed");
349611
- writeClaim(record8, { ...claim, phase: claim.phase === "inference_started" ? claim.phase : "committed", recordSha256 });
349617
+ writeClaim(record9, { ...claim, phase: claim.phase === "inference_started" ? claim.phase : "committed", recordSha256 });
349612
349618
  }
349613
- function startTaskObjectiveContinuationInference(record8) {
349614
- return withContinuationClaimLock(record8, () => startTaskObjectiveContinuationInferenceLocked(record8));
349619
+ function startTaskObjectiveContinuationInference(record9) {
349620
+ return withContinuationClaimLock(record9, () => startTaskObjectiveContinuationInferenceLocked(record9));
349615
349621
  }
349616
- function startTaskObjectiveContinuationInferenceLocked(record8) {
349617
- const claim = readClaim(record8);
349618
- if (claim.recipientRunId !== record8.recipientRunId || claim.phase === "pending" || claim.recordSha256 !== taskObjectiveContinuationDigest(record8))
349622
+ function startTaskObjectiveContinuationInferenceLocked(record9) {
349623
+ const claim = readClaim(record9);
349624
+ if (claim.recipientRunId !== record9.recipientRunId || claim.phase === "pending" || claim.recordSha256 !== taskObjectiveContinuationDigest(record9))
349619
349625
  throw new Error("Task objective continuation source restoration is not committed for this recipient");
349620
349626
  if (claim.phase === "committed")
349621
- writeClaim(record8, { ...claim, phase: "inference_started" });
349627
+ writeClaim(record9, { ...claim, phase: "inference_started" });
349622
349628
  }
349623
- function committedClaim(record8) {
349629
+ function committedClaim(record9) {
349624
349630
  try {
349625
- const claim = readClaim(record8);
349626
- return claim.recipientRunId === record8.recipientRunId && claim.phase !== "pending" && claim.recordSha256 === taskObjectiveContinuationDigest(record8);
349631
+ const claim = readClaim(record9);
349632
+ return claim.recipientRunId === record9.recipientRunId && claim.phase !== "pending" && claim.recordSha256 === taskObjectiveContinuationDigest(record9);
349627
349633
  } catch {
349628
349634
  return false;
349629
349635
  }
@@ -349694,7 +349700,7 @@ function admitTaskObjectiveContinuation(input) {
349694
349700
  }) !== seed.manifestSha256)
349695
349701
  throw new Error("Task objective continuation manifest changed");
349696
349702
  validateContinuationStrengthening({ seed, prior, recipient: input.contract, ledger });
349697
- const record8 = {
349703
+ const record9 = {
349698
349704
  schema: "omnius.task-objective-continuation-record.v1",
349699
349705
  recipientRunId: input.recipientRunId,
349700
349706
  taskEpoch: p.taskEpoch,
@@ -349704,28 +349710,28 @@ function admitTaskObjectiveContinuation(input) {
349704
349710
  importedEvidence: [],
349705
349711
  maximumInheritedEvidenceOrdinal: Math.max(0, ledger.taskObjectiveContinuation?.maximumInheritedEvidenceOrdinal ?? 0, ...ledger.evidence.map((entry) => /^ev_(\d+)$/.test(entry.id) ? Number(entry.id.slice(3)) : 0))
349706
349712
  };
349707
- admittedRecords.add(record8);
349708
- return { ledger, record: record8 };
349713
+ admittedRecords.add(record9);
349714
+ return { ledger, record: record9 };
349709
349715
  }
349710
349716
  function taskObjectiveContinuationAuthorizesEvidence(ledger, entry) {
349711
349717
  let current = ledger, row2 = entry;
349712
349718
  const seen = /* @__PURE__ */ new Set();
349713
349719
  for (; ; ) {
349714
349720
  try {
349715
- const record8 = current?.taskObjectiveContinuation, contract = current?.objectiveContract;
349716
- if (!record8 || !contract || record8.recipientRunId !== current.runId || record8.taskEpoch !== current.taskEpoch || record8.taskEpoch !== contract.taskEpoch || record8.authoritySha256 !== taskObjectiveContinuationDigest(record8.input) || contract.originalRequestRef !== record8.input.objective.originalRequestRef || contract.originalRequestHash !== record8.input.objective.originalRequestHash)
349721
+ const record9 = current?.taskObjectiveContinuation, contract = current?.objectiveContract;
349722
+ if (!record9 || !contract || record9.recipientRunId !== current.runId || record9.taskEpoch !== current.taskEpoch || record9.taskEpoch !== contract.taskEpoch || record9.authoritySha256 !== taskObjectiveContinuationDigest(record9.input) || contract.originalRequestRef !== record9.input.objective.originalRequestRef || contract.originalRequestHash !== record9.input.objective.originalRequestHash)
349717
349723
  return false;
349718
349724
  const policy = { ...contract, criteria: contract.criteria.map((criterion) => ({ ...criterion, status: "open" })) };
349719
- if (taskObjectiveContinuationDigest(policy) !== (record8.input.contractStrengthening?.recipientContractSha256 ?? record8.input.objective.contractSha256))
349725
+ if (taskObjectiveContinuationDigest(policy) !== (record9.input.contractStrengthening?.recipientContractSha256 ?? record9.input.objective.contractSha256))
349720
349726
  return false;
349721
- const claim = readClaim(record8);
349722
- if (claim.recipientRunId !== record8.recipientRunId || (claim.phase === "pending" ? !admittedRecords.has(record8) : claim.recordSha256 !== taskObjectiveContinuationDigest(record8)))
349727
+ const claim = readClaim(record9);
349728
+ if (claim.recipientRunId !== record9.recipientRunId || (claim.phase === "pending" ? !admittedRecords.has(record9) : claim.recordSha256 !== taskObjectiveContinuationDigest(record9)))
349723
349729
  return false;
349724
- const predecessor = record8.input.predecessor;
349730
+ const predecessor = record9.input.predecessor;
349725
349731
  if (seen.has(predecessor.ledgerPath))
349726
349732
  return false;
349727
349733
  seen.add(predecessor.ledgerPath);
349728
- const imported = record8.importedEvidence.find((item) => item.evidenceId === row2.id);
349734
+ const imported = record9.importedEvidence.find((item) => item.evidenceId === row2.id);
349729
349735
  if (!imported || imported.predecessorRunId !== predecessor.runId || imported.predecessorLedgerSha256 !== predecessor.ledgerSha256 || imported.issuerRunId !== row2.workOperation?.runId || taskObjectiveContinuationDigest(imported.criterionIds) !== taskObjectiveContinuationDigest(row2.criterionIds ?? []))
349730
349736
  return false;
349731
349737
  const bytes3 = readFileSync26(predecessor.ledgerPath);
@@ -349748,11 +349754,11 @@ function taskObjectiveContinuationAuthorizesSource(ledger, entry) {
349748
349754
  try {
349749
349755
  if (entry.adoption?.schema !== "omnius.artifact-review-source-adoption.v1")
349750
349756
  return false;
349751
- const record8 = ledger?.taskObjectiveContinuation;
349752
- if (!record8 || record8.schema !== "omnius.task-objective-continuation-record.v1" || record8.recipientRunId !== ledger.runId || record8.recipientRunId !== entry.owner.runId || record8.taskEpoch !== ledger.taskEpoch || record8.taskEpoch !== entry.owner.taskEpoch || record8.input.scope.sessionId !== entry.owner.scopeId || record8.authoritySha256 !== taskObjectiveContinuationDigest(record8.input) || record8.authoritySha256 !== entry.adoption.authoritySha256 || !committedClaim(record8))
349757
+ const record9 = ledger?.taskObjectiveContinuation;
349758
+ if (!record9 || record9.schema !== "omnius.task-objective-continuation-record.v1" || record9.recipientRunId !== ledger.runId || record9.recipientRunId !== entry.owner.runId || record9.taskEpoch !== ledger.taskEpoch || record9.taskEpoch !== entry.owner.taskEpoch || record9.input.scope.sessionId !== entry.owner.scopeId || record9.authoritySha256 !== taskObjectiveContinuationDigest(record9.input) || record9.authoritySha256 !== entry.adoption.authoritySha256 || !committedClaim(record9))
349753
349759
  return false;
349754
- const adopted = record8.adoptions.find((value) => value.sourceId === entry.sourceId && taskObjectiveContinuationDigest(value.issuer) === taskObjectiveContinuationDigest(entry.adoption.issuer));
349755
- return !!adopted && adopted.criterionIds.length > 0 && adopted.criterionIds.every((id5) => record8.input.resources.some((resource) => resource.criterionId === id5 && resource.sourceSha256 === adopted.sourceSha256 && resource.pathAliases.includes(entry.verifiedSourcePath))) && entry.observation.documentExtraction?.documentHash === adopted.sourceSha256;
349760
+ const adopted = record9.adoptions.find((value) => value.sourceId === entry.sourceId && taskObjectiveContinuationDigest(value.issuer) === taskObjectiveContinuationDigest(entry.adoption.issuer));
349761
+ return !!adopted && adopted.criterionIds.length > 0 && adopted.criterionIds.every((id5) => record9.input.resources.some((resource) => resource.criterionId === id5 && resource.sourceSha256 === adopted.sourceSha256 && resource.pathAliases.includes(entry.verifiedSourcePath))) && entry.observation.documentExtraction?.documentHash === adopted.sourceSha256;
349756
349762
  } catch {
349757
349763
  return false;
349758
349764
  }
@@ -349871,37 +349877,37 @@ function checkOutcome(entry) {
349871
349877
  return "unverified";
349872
349878
  return entry.role === "verification" ? "passed" : "exit_zero";
349873
349879
  }
349874
- function acceptedHostVerification(entry, ledger, record8) {
349880
+ function acceptedHostVerification(entry, ledger, record9) {
349875
349881
  const receipt = normalizeVerificationReceiptV1(entry.verificationReceipt);
349876
- const contract = record8.taskObjectiveContract, frontier = record8.objectiveFrontier;
349877
- if (entry.toolName !== "host_terminal_verifier" || entry.role !== "verification" || entry.success !== true || entry.receipt || !receipt || receipt.outcome !== "passed" || !receipt.artifactRevision || !receipt.evidenceKinds?.includes("verification") || entry.family !== receipt.verifierMethod || !entry.criterionIds?.includes(receipt.criterionId) || !contract || !ledger.objectiveContract || !ledger.objectiveFrontier || contract.taskEpoch !== record8.taskEpoch || hash13(contract) !== hash13(ledger.objectiveContract) || !frontier || frontier.runId !== record8.runId || frontier.taskEpoch !== record8.taskEpoch || frontier.contractRevision !== contract.revision || hash13(frontier) !== hash13(ledger.objectiveFrontier) || !frontier.satisfiedCriterionIds.includes(receipt.criterionId) || !record8.evidenceIds.includes(entry.id) || !Array.isArray(record8.verificationReceipts) || !record8.verificationReceipts.some((value) => hash13(normalizeVerificationReceiptV1(value)) === hash13(receipt)))
349882
+ const contract = record9.taskObjectiveContract, frontier = record9.objectiveFrontier;
349883
+ if (entry.toolName !== "host_terminal_verifier" || entry.role !== "verification" || entry.success !== true || entry.receipt || !receipt || receipt.outcome !== "passed" || !receipt.artifactRevision || !receipt.evidenceKinds?.includes("verification") || entry.family !== receipt.verifierMethod || !entry.criterionIds?.includes(receipt.criterionId) || !contract || !ledger.objectiveContract || !ledger.objectiveFrontier || contract.taskEpoch !== record9.taskEpoch || hash13(contract) !== hash13(ledger.objectiveContract) || !frontier || frontier.runId !== record9.runId || frontier.taskEpoch !== record9.taskEpoch || frontier.contractRevision !== contract.revision || hash13(frontier) !== hash13(ledger.objectiveFrontier) || !frontier.satisfiedCriterionIds.includes(receipt.criterionId) || !record9.evidenceIds.includes(entry.id) || !Array.isArray(record9.verificationReceipts) || !record9.verificationReceipts.some((value) => hash13(normalizeVerificationReceiptV1(value)) === hash13(receipt)))
349878
349884
  return null;
349879
349885
  const criterion = contract.criteria.find((item) => item.id === receipt.criterionId);
349880
349886
  const accepted = frontier.criteria.find((item) => item.id === receipt.criterionId);
349881
349887
  const snapshot = ledger.evidence.find((item) => item.id === receipt.artifactEvidenceId);
349882
349888
  if (criterion?.mode !== "verification" || !criterion.acceptableVerifierMethods?.includes(receipt.verifierMethod) || accepted?.status !== "satisfied" || !accepted.evidenceIds.includes(receipt.evidenceId) || !accepted.evidenceIds.includes(receipt.artifactEvidenceId) || !snapshot || snapshot.kind !== "runtime_observation" || snapshot.role !== "observation" || snapshot.success !== true || !snapshot.criterionIds?.includes(receipt.criterionId) || !receipt.evidenceIds.includes(snapshot.id) || !["hostUiSnapshotSha256", "hostUiOutcomeSha256", "hostEffectStateSha256"].every((key) => typeof snapshot.metrics?.[key] === "string" && /^[a-f0-9]{64}$/.test(snapshot.metrics[key])) || ledger.evidence.indexOf(snapshot) >= ledger.evidence.indexOf(entry))
349883
349889
  return null;
349884
- const snapshotAt = timestamp(snapshot.observedAtIso), checkedAt = timestamp(entry.observedAtIso), committedAt = timestamp(record8.committedAtIso);
349890
+ const snapshotAt = timestamp(snapshot.observedAtIso), checkedAt = timestamp(entry.observedAtIso), committedAt = timestamp(record9.committedAtIso);
349885
349891
  if (![snapshotAt, checkedAt, committedAt].every(Number.isFinite) || snapshotAt > checkedAt || checkedAt > committedAt)
349886
349892
  return null;
349887
349893
  return { receipt, snapshot };
349888
349894
  }
349889
349895
  function buildTerminalTaskReport(input) {
349890
- const { record: record8, ledger } = input;
349891
- if (record8.phase !== "committed")
349896
+ const { record: record9, ledger } = input;
349897
+ if (record9.phase !== "committed")
349892
349898
  throw new Error("terminal_task_report_requires_committed_receipt");
349893
- const matches = Boolean(ledger && ledger.runId === record8.runId && ledger.taskEpoch === record8.taskEpoch);
349899
+ const matches = Boolean(ledger && ledger.runId === record9.runId && ledger.taskEpoch === record9.taskEpoch);
349894
349900
  const evidence = matches ? ledger.evidence.filter((entry) => classifyCompletionProgress(entry) !== "control_bookkeeping") : [];
349895
349901
  const objective = matches ? ledger.objectiveContract : void 0, frontier = matches ? ledger.objectiveFrontier : void 0;
349896
- const verifiedGoal = record8.status === "completed" && objective && frontier && frontier.runId === record8.runId && frontier.taskEpoch === record8.taskEpoch && frontier.contractRevision === objective.revision && objective.criteria.some((criterion) => criterion.mode === "verification") && objective.criteria.filter((criterion) => criterion.mode !== "delivery").every((criterion) => frontier.criteria.find((state) => state.id === criterion.id)?.status === "satisfied" && frontier.satisfiedCriterionIds.includes(criterion.id));
349902
+ const verifiedGoal = record9.status === "completed" && objective && frontier && frontier.runId === record9.runId && frontier.taskEpoch === record9.taskEpoch && frontier.contractRevision === objective.revision && objective.criteria.some((criterion) => criterion.mode === "verification") && objective.criteria.filter((criterion) => criterion.mode !== "delivery").every((criterion) => frontier.criteria.find((state) => state.id === criterion.id)?.status === "satisfied" && frontier.satisfiedCriterionIds.includes(criterion.id));
349897
349903
  const changes = /* @__PURE__ */ new Map();
349898
349904
  const observations = [];
349899
349905
  const checks = [];
349900
349906
  const limits = /* @__PURE__ */ new Map();
349901
349907
  const nextSteps = /* @__PURE__ */ new Set();
349902
349908
  const limit2 = (id5, source, detail) => limits.set(id5, { id: id5, source, detail: text8(detail, 500) });
349903
- const failure = record8.runtimeFailure;
349904
- const currentFailureScope = Boolean(failure && failure.runId === record8.runId && failure.taskEpoch === record8.taskEpoch && failure.schema === "omnius.terminal-runtime-failure.v1");
349909
+ const failure = record9.runtimeFailure;
349910
+ const currentFailureScope = Boolean(failure && failure.runId === record9.runId && failure.taskEpoch === record9.taskEpoch && failure.schema === "omnius.terminal-runtime-failure.v1");
349905
349911
  const currentAdmissionFailure = currentFailureScope && failure && failure.code === "context_admission_failed" && failure.phase === "before_transport" && failure.contextAdmission.decision === "reject";
349906
349912
  const currentEmptyResponseFailure = currentFailureScope && failure && failure.code === "model_empty_response_stall" && failure.phase === "after_transport" && Number.isSafeInteger(failure.consecutiveEmptyResponses) && failure.consecutiveEmptyResponses >= 6;
349907
349913
  const currentInferenceFailure = currentFailureScope && failure && (failure.code === "remote_inference_unavailable" || failure.code === "inference_stream_interrupted" || failure.code === "fallback_approval_required" || failure.code === "fallback_declined") && failure.phase === "after_transport" && failure.retryable === false;
@@ -349925,7 +349931,7 @@ function buildTerminalTaskReport(input) {
349925
349931
  }
349926
349932
  if (input.workflow) {
349927
349933
  const workflow = input.workflow;
349928
- if (workflow.runId !== record8.runId || workflow.taskEpoch !== record8.taskEpoch || !/^omnius-artifact:\/\/sha256\/[a-f0-9]{64}$/.test(workflow.planReference)) {
349934
+ if (workflow.runId !== record9.runId || workflow.taskEpoch !== record9.taskEpoch || !/^omnius-artifact:\/\/sha256\/[a-f0-9]{64}$/.test(workflow.planReference)) {
349929
349935
  limit2("workflow_scope", "evidence_scope", "The feature workflow summary did not match this run and task epoch; its contents were excluded.");
349930
349936
  nextSteps.add("Reconstruct the current feature workflow from its saved checkpoint before repeating work.");
349931
349937
  } else if (!workflow.complete) {
@@ -349956,7 +349962,7 @@ function buildTerminalTaskReport(input) {
349956
349962
  }
349957
349963
  if (entry.receipt || entry.role === "verification") {
349958
349964
  const hostCheck = entry.toolName === "host_terminal_verifier" && !entry.receipt;
349959
- const hostVerification = hostCheck && ledger ? acceptedHostVerification(entry, ledger, record8) : null;
349965
+ const hostVerification = hostCheck && ledger ? acceptedHostVerification(entry, ledger, record9) : null;
349960
349966
  const identity4 = commandIdentity(entry);
349961
349967
  let freshness = "current";
349962
349968
  if (identity4 && latestCommands.get(identity4) > index)
@@ -350010,7 +350016,7 @@ function buildTerminalTaskReport(input) {
350010
350016
  nextSteps.add(`Inspect the ${toolName} result and finish any unrun work before relying on the recorded checks.`);
350011
350017
  }
350012
350018
  });
350013
- for (const gap of record8.verificationAudit.gaps) {
350019
+ for (const gap of record9.verificationAudit.gaps) {
350014
350020
  const entry = evidence.find((item) => item.id === gap.source);
350015
350021
  const check = entry && checks.find((item) => item.evidenceId === entry.id);
350016
350022
  if (check && limits.has(`check:${entry.id}`))
@@ -350028,7 +350034,7 @@ function buildTerminalTaskReport(input) {
350028
350034
  detail = "A recorded evidence gap remains unresolved; inspect the current run evidence.";
350029
350035
  limit2(`audit:${gap.id}`, gap.source, detail);
350030
350036
  }
350031
- for (const obligation2 of record8.completionReadiness?.obligations ?? []) {
350037
+ for (const obligation2 of record9.completionReadiness?.obligations ?? []) {
350032
350038
  if (obligation2.status !== "satisfied") {
350033
350039
  limit2(`obligation:${obligation2.id}`, obligation2.kind, `${obligation2.kind.replace(/_/g, " ")} ${obligation2.sourceId}: ${obligation2.status} (${obligation2.reasonCode.replace(/_/g, " ")}).`);
350034
350040
  nextSteps.add(`Resolve the ${obligation2.status} ${obligation2.kind.replace(/_/g, " ")}: ${text8(obligation2.sourceId, 250)}.`);
@@ -350044,13 +350050,13 @@ function buildTerminalTaskReport(input) {
350044
350050
  const body = {
350045
350051
  schema: "omnius.terminal-task-report.v1",
350046
350052
  source: "host_terminal_receipt",
350047
- runId: record8.runId,
350048
- ...record8.taskEpoch !== void 0 ? { taskEpoch: record8.taskEpoch } : {},
350049
- terminalReceiptId: record8.id,
350050
- status: record8.status,
350051
- ...record8.readinessHash ? { readinessHash: record8.readinessHash } : {},
350052
- ledgerSnapshotHash: hash13(matches ? { runId: ledger.runId, taskEpoch: ledger.taskEpoch, updatedAtIso: ledger.updatedAtIso, evidence: ledger.evidence, audit: record8.verificationAudit, readinessHash: record8.readinessHash } : null),
350053
- generatedAtIso: record8.committedAtIso,
350053
+ runId: record9.runId,
350054
+ ...record9.taskEpoch !== void 0 ? { taskEpoch: record9.taskEpoch } : {},
350055
+ terminalReceiptId: record9.id,
350056
+ status: record9.status,
350057
+ ...record9.readinessHash ? { readinessHash: record9.readinessHash } : {},
350058
+ ledgerSnapshotHash: hash13(matches ? { runId: ledger.runId, taskEpoch: ledger.taskEpoch, updatedAtIso: ledger.updatedAtIso, evidence: ledger.evidence, audit: record9.verificationAudit, readinessHash: record9.readinessHash } : null),
350059
+ generatedAtIso: record9.committedAtIso,
350054
350060
  changes: [...changes.values()].slice(-CAP),
350055
350061
  checks: checks.slice(-CAP),
350056
350062
  observations: observations.slice(-CAP),
@@ -350611,7 +350617,7 @@ async function buildLiveVirtualContextProjection(input) {
350611
350617
  includeSuperseded: false,
350612
350618
  maximumCompressionGeneration: 4,
350613
350619
  limit: 1e4
350614
- }).map((record8) => [record8.id, record8.bodyHash, record8.validUntil]))).digest("hex") : "none";
350620
+ }).map((record9) => [record9.id, record9.bodyHash, record9.validUntil]))).digest("hex") : "none";
350615
350621
  const signature = projectionSignature({
350616
350622
  query,
350617
350623
  scopeId: input.scopeId,
@@ -350983,7 +350989,7 @@ async function extractStructuredMemoriesWithInference(input) {
350983
350989
  includeExpired: false,
350984
350990
  limit: 24
350985
350991
  });
350986
- const existingIds = new Set(existing.map((record8) => record8.id));
350992
+ const existingIds = new Set(existing.map((record9) => record9.id));
350987
350993
  const raw = await input.infer({
350988
350994
  system: EXTRACTION_SYSTEM,
350989
350995
  input: {
@@ -350995,13 +351001,13 @@ async function extractStructuredMemoriesWithInference(input) {
350995
351001
  char_end: span.charEnd,
350996
351002
  text: span.text
350997
351003
  })),
350998
- existing_active_memories: existing.map((record8) => ({
350999
- id: record8.id,
351000
- memory_class: record8.memoryClass,
351001
- canonical_key: record8.canonicalKey,
351002
- body: record8.body.slice(0, 500),
351003
- valid_from: record8.validFrom,
351004
- source_chunk_ids: record8.provenance.map((source) => source.chunkId)
351004
+ existing_active_memories: existing.map((record9) => ({
351005
+ id: record9.id,
351006
+ memory_class: record9.memoryClass,
351007
+ canonical_key: record9.canonicalKey,
351008
+ body: record9.body.slice(0, 500),
351009
+ valid_from: record9.validFrom,
351010
+ source_chunk_ids: record9.provenance.map((source) => source.chunkId)
351005
351011
  })),
351006
351012
  output_schema: {
351007
351013
  memories: [{
@@ -351090,7 +351096,7 @@ async function extractStructuredMemoriesWithInference(input) {
351090
351096
  }
351091
351097
  const effectiveTtl = ttl !== void 0 ? Math.floor(ttl) : memoryClass === "current_plan" ? 7 * 24 * 60 * 60 : void 0;
351092
351098
  try {
351093
- const record8 = {
351099
+ const record9 = {
351094
351100
  ...input.recordIdPrefix ? { id: `${input.recordIdPrefix}:${batch.index}:${index}` } : {},
351095
351101
  ...input.validFrom ? { validFrom: input.validFrom } : {},
351096
351102
  scopeId: input.scopeId,
@@ -351107,10 +351113,10 @@ async function extractStructuredMemoriesWithInference(input) {
351107
351113
  metadata: { producer: "inference-structured-memory-v1", batch: batchIndex + 1 }
351108
351114
  };
351109
351115
  if (input.commitBatch)
351110
- records.push(record8);
351116
+ records.push(record9);
351111
351117
  else {
351112
351118
  assertCurrent();
351113
- written.push(input.memoryStore.append(record8));
351119
+ written.push(input.memoryStore.append(record9));
351114
351120
  }
351115
351121
  } catch (error) {
351116
351122
  rejected.push(`${label}: ${error instanceof Error ? error.message : String(error)}`);
@@ -351322,10 +351328,10 @@ function validateRelease(release) {
351322
351328
  const operations2 = /* @__PURE__ */ new Set();
351323
351329
  const routing = json3(delivery.records[0].expectedRouting);
351324
351330
  for (const reference2 of delivery.records) {
351325
- const record8 = reopen(reference2), expected = reference2.expectedRouting;
351326
- if (record8.schema !== "omnius.telegram-turn-delivery-ledger.v1" || record8.status !== "delivered" || !Number.isSafeInteger(record8.telegramMessageId) || record8.telegramMessageId <= 0 || typeof record8.exactText !== "string" || record8.exactTextSha256 !== reference2.expectedTextSha256 || sha10(record8.exactText) !== reference2.expectedTextSha256 || record8.exactTextBytes !== Buffer.byteLength(record8.exactText) || typeof record8.outboundOperationId !== "string" || !record8.outboundOperationId || operations2.has(record8.outboundOperationId) || json3(expected) !== routing || !expected.sessionKey || !expected.senderActorKey || !expected.runId || !expected.inputId || !expected.chatId || !Number.isSafeInteger(expected.messageId) || expected.messageId <= 0 || terminal.expectedOutcomeContract?.inputId !== expected.inputId || !Number.isSafeInteger(expected.messageThreadId) || expected.messageThreadId < 0 || !Number.isSafeInteger(expected.generation) || expected.generation < 0 || Object.entries(expected).some(([key, value]) => record8.routing?.[key] !== value) || release.owner.ownerKey !== `telegram:${expected.sessionKey}:${expected.senderActorKey}`)
351331
+ const record9 = reopen(reference2), expected = reference2.expectedRouting;
351332
+ if (record9.schema !== "omnius.telegram-turn-delivery-ledger.v1" || record9.status !== "delivered" || !Number.isSafeInteger(record9.telegramMessageId) || record9.telegramMessageId <= 0 || typeof record9.exactText !== "string" || record9.exactTextSha256 !== reference2.expectedTextSha256 || sha10(record9.exactText) !== reference2.expectedTextSha256 || record9.exactTextBytes !== Buffer.byteLength(record9.exactText) || typeof record9.outboundOperationId !== "string" || !record9.outboundOperationId || operations2.has(record9.outboundOperationId) || json3(expected) !== routing || !expected.sessionKey || !expected.senderActorKey || !expected.runId || !expected.inputId || !expected.chatId || !Number.isSafeInteger(expected.messageId) || expected.messageId <= 0 || terminal.expectedOutcomeContract?.inputId !== expected.inputId || !Number.isSafeInteger(expected.messageThreadId) || expected.messageThreadId < 0 || !Number.isSafeInteger(expected.generation) || expected.generation < 0 || Object.entries(expected).some(([key, value]) => record9.routing?.[key] !== value) || release.owner.ownerKey !== `telegram:${expected.sessionKey}:${expected.senderActorKey}`)
351327
351333
  throw new InvalidExtraction("Structured extraction provider acknowledgement is missing or foreign");
351328
- operations2.add(record8.outboundOperationId);
351334
+ operations2.add(record9.outboundOperationId);
351329
351335
  }
351330
351336
  }
351331
351337
  var StructuredMemoryExtractionQueue = class {
@@ -351619,7 +351625,7 @@ var StructuredMemoryExtractionQueue = class {
351619
351625
  requestId,
351620
351626
  raw,
351621
351627
  rawSha256: sha10(raw),
351622
- writtenIds: written.map((record8) => record8.id),
351628
+ writtenIds: written.map((record9) => record9.id),
351623
351629
  rejected
351624
351630
  }),
351625
351631
  queueEmbedding: false,
@@ -353525,6 +353531,29 @@ function reopenSourceReviewWebReads(input) {
353525
353531
  return reads;
353526
353532
  }
353527
353533
 
353534
+ // packages/orchestrator/dist/completion-review-pending.js
353535
+ function record6(value) {
353536
+ return typeof value === "object" && value !== null && !Array.isArray(value);
353537
+ }
353538
+ function isCompletionReviewPendingV1(value) {
353539
+ return record6(value) && Object.keys(value).length === 5 && Object.keys(value).every((key) => ["schema", "phase", "retryable", "resumeTool", "resumeArgs"].includes(key)) && value.schema === "omnius.completion-review-pending.v1" && (value.phase === "artifact_semantic" || value.phase === "artifact_claim") && value.retryable === true && value.resumeTool === "task_complete" && record6(value.resumeArgs) && Object.keys(value.resumeArgs).length === 1 && Object.keys(value.resumeArgs)[0] === "resume_review" && value.resumeArgs.resume_review === true;
353540
+ }
353541
+ function isCompletionReviewPendingResult(toolName, result) {
353542
+ return toolName === "task_complete" && record6(result) && result.success === false && result.completionAdmission === "rejected" && isCompletionReviewPendingV1(result.completionReviewPending);
353543
+ }
353544
+ function isCompletionRestoredPayloadV1(value) {
353545
+ return record6(value) && Object.keys(value).every((key) => ["schema", "userReply", "summary", "status", "question", "missingCriterionIds"].includes(key)) && value.schema === "omnius.completion-restored-payload.v1" && typeof value.userReply === "string" && value.userReply.trim().length > 0 && typeof value.summary === "string" && (value.status === void 0 || ["completed", "incomplete", "needs_input"].includes(value.status)) && (value.question === void 0 || typeof value.question === "string") && (value.missingCriterionIds === void 0 || Array.isArray(value.missingCriterionIds) && value.missingCriterionIds.every((id5) => typeof id5 === "string" && id5.trim().length > 0));
353546
+ }
353547
+ function completionReviewPendingGuard(value) {
353548
+ return [
353549
+ "[TASK_COMPLETE REVIEW PENDING]",
353550
+ `The host ${value.phase} reviewer is temporarily unavailable. Completion has not been accepted.`,
353551
+ "The host retained the exact pending reply, artifact selection and current task ownership. The required goal and evidence remain unchanged.",
353552
+ 'Retry only task_complete({"summary":"Retry pending completion review","resume_review":true}).',
353553
+ "Do not inspect, rewrite, resend or rerun completed work to repair reviewer availability. Omit user_reply, status and artifact selection overrides; the host reopens the frozen candidate and rechecks its current owner."
353554
+ ].join("\n");
353555
+ }
353556
+
353528
353557
  // packages/orchestrator/dist/contextBudget.js
353529
353558
  import { freemem as freemem2, totalmem as totalmem3 } from "node:os";
353530
353559
  var TIER_BASE = {
@@ -353773,11 +353802,11 @@ function recoveryMaterialDigest(value) {
353773
353802
 
353774
353803
  // packages/orchestrator/dist/desktop-verification.js
353775
353804
  var id4 = (value, limit2 = 200) => typeof value === "string" && value.length > 0 && value.length <= limit2;
353776
- var record6 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
353805
+ var record7 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
353777
353806
  function desktopVerificationScope(tool) {
353778
353807
  try {
353779
353808
  const scope = tool.getDesktopVerificationScope?.();
353780
- if (!record6(scope) || !/^[a-f0-9]{64}$/.test(String(scope.desktopSessionId)) || scope.nativeSessionId !== void 0 && !id4(scope.nativeSessionId) || Object.keys(scope).some((key) => !["desktopSessionId", "nativeSessionId"].includes(key)))
353809
+ if (!record7(scope) || !/^[a-f0-9]{64}$/.test(String(scope.desktopSessionId)) || scope.nativeSessionId !== void 0 && !id4(scope.nativeSessionId) || Object.keys(scope).some((key) => !["desktopSessionId", "nativeSessionId"].includes(key)))
353781
353810
  return void 0;
353782
353811
  return {
353783
353812
  desktopSessionId: scope.desktopSessionId,
@@ -353788,7 +353817,7 @@ function desktopVerificationScope(tool) {
353788
353817
  }
353789
353818
  }
353790
353819
  function desktopVerificationReceipt(value) {
353791
- if (!record6(value) || value.schema !== "omnius.desktop-verification.v1" || !/^[a-f0-9]{64}$/.test(String(value.desktopSessionId)))
353820
+ if (!record7(value) || value.schema !== "omnius.desktop-verification.v1" || !/^[a-f0-9]{64}$/.test(String(value.desktopSessionId)))
353792
353821
  return void 0;
353793
353822
  const fields2 = value.kind === "native_observation" ? ["schema", "kind", "desktopSessionId", "nativeSessionId", "revision"] : value.kind === "input_dispatch" ? ["schema", "kind", "desktopSessionId", "dispatchId", "inputKind", "windowId"] : [];
353794
353823
  if (Object.keys(value).some((key) => !fields2.includes(key)))
@@ -354660,20 +354689,20 @@ function validateRanges(ranges) {
354660
354689
  });
354661
354690
  }
354662
354691
  function normalizeRecords(records) {
354663
- return records.map((record8) => {
354664
- if (!record8 || typeof record8 !== "object")
354692
+ return records.map((record9) => {
354693
+ if (!record9 || typeof record9 !== "object")
354665
354694
  throw new Error("artifact manifest record is malformed");
354666
- if (record8.fidelity !== "full")
354695
+ if (record9.fidelity !== "full")
354667
354696
  throw new Error("artifact manifest record fidelity must be full");
354668
- if (typeof record8.recordedAt !== "string" || Number.isNaN(Date.parse(record8.recordedAt))) {
354697
+ if (typeof record9.recordedAt !== "string" || Number.isNaN(Date.parse(record9.recordedAt))) {
354669
354698
  throw new Error("artifact manifest record timestamp is invalid");
354670
354699
  }
354671
354700
  return {
354672
- path: validateMetadataText(record8.path, MAX_PROVENANCE_PATH_CHARS, "artifact provenance path"),
354673
- revision: validateMetadataText(record8.revision, MAX_REVISION_CHARS, "artifact provenance revision"),
354674
- ranges: validateRanges(record8.ranges),
354701
+ path: validateMetadataText(record9.path, MAX_PROVENANCE_PATH_CHARS, "artifact provenance path"),
354702
+ revision: validateMetadataText(record9.revision, MAX_REVISION_CHARS, "artifact provenance revision"),
354703
+ ranges: validateRanges(record9.ranges),
354675
354704
  fidelity: "full",
354676
- recordedAt: record8.recordedAt
354705
+ recordedAt: record9.recordedAt
354677
354706
  };
354678
354707
  }).sort((left, right) => left.path.localeCompare(right.path) || left.revision.localeCompare(right.revision) || JSON.stringify(left.ranges).localeCompare(JSON.stringify(right.ranges)) || left.fidelity.localeCompare(right.fidelity) || left.recordedAt.localeCompare(right.recordedAt));
354679
354708
  }
@@ -354800,7 +354829,7 @@ var ContentAddressedArtifactStore = class {
354800
354829
  atomicWrite(objectPath, input.content);
354801
354830
  }
354802
354831
  const existingManifest = existsSync30(manifestPath) ? this.readManifestByHash(hash17) : void 0;
354803
- const record8 = {
354832
+ const record9 = {
354804
354833
  path: path7,
354805
354834
  revision,
354806
354835
  ranges,
@@ -354808,7 +354837,7 @@ var ContentAddressedArtifactStore = class {
354808
354837
  recordedAt: (/* @__PURE__ */ new Date()).toISOString()
354809
354838
  };
354810
354839
  const records = existingManifest?.records ?? [];
354811
- const alreadyRecorded = records.some((candidate) => candidate.path === record8.path && candidate.revision === record8.revision && candidate.fidelity === record8.fidelity && JSON.stringify(candidate.ranges) === JSON.stringify(record8.ranges));
354840
+ const alreadyRecorded = records.some((candidate) => candidate.path === record9.path && candidate.revision === record9.revision && candidate.fidelity === record9.fidelity && JSON.stringify(candidate.ranges) === JSON.stringify(record9.ranges));
354812
354841
  if (!alreadyRecorded && records.length >= this.maxManifestRecords) {
354813
354842
  throw new Error(`artifact manifest exceeds configured ${this.maxManifestRecords}-record limit`);
354814
354843
  }
@@ -354825,7 +354854,7 @@ var ContentAddressedArtifactStore = class {
354825
354854
  throw new Error("artifact manifest conflicts with the canonical object");
354826
354855
  }
354827
354856
  if (!alreadyRecorded) {
354828
- manifest.records = normalizeRecords([...records, record8]);
354857
+ manifest.records = normalizeRecords([...records, record9]);
354829
354858
  atomicWrite(manifestPath, `${JSON.stringify(manifest, null, 2)}
354830
354859
  `);
354831
354860
  } else if (!existsSync30(manifestPath)) {
@@ -355227,24 +355256,24 @@ function deriveFeatureWorkflowStatus(plan, state, board, workspaceRevision) {
355227
355256
  const gaps = [];
355228
355257
  for (const compiled of compileFeatureWorkflow(plan).cards) {
355229
355258
  const card = plan.cards.find((c) => featureWorkflowCardId(plan, c.id) === compiled.id);
355230
- const record8 = state.results[card.id];
355259
+ const record9 = state.results[card.id];
355231
355260
  const boardCard = board.cards.find((c) => c.id === compiled.id);
355232
355261
  let reason = !boardCard || boardCard.status !== "verified" ? "workboard_not_verified" : "";
355233
355262
  if (Object.values(state.operations).some((op) => op.binding.cardId === card.id))
355234
355263
  reason = "host_operation_pending";
355235
- if (record8?.binding.kind === "verification" && !record8.success)
355264
+ if (record9?.binding.kind === "verification" && !record9.success)
355236
355265
  reason = "verification_failed";
355237
355266
  if (Object.values(state.operations).some((op) => op.binding.cardId === card.id && op.state === "interrupted"))
355238
355267
  reason = "interrupted_operation_requires_host_reconciliation";
355239
- if (!reason && (!record8?.success || record8.binding.cardContract !== featureWorkflowCardContract(plan, card)))
355268
+ if (!reason && (!record9?.success || record9.binding.cardContract !== featureWorkflowCardContract(plan, card)))
355240
355269
  reason = "host_receipt_missing_or_stale";
355241
- if (!reason && record8 && !equal(record8.binding.inputSlots, currentInputReferences(plan, card, state.slots)))
355270
+ if (!reason && record9 && !equal(record9.binding.inputSlots, currentInputReferences(plan, card, state.slots)))
355242
355271
  reason = "input_artifact_changed";
355243
355272
  if (!reason && plan.slots.some((s) => s.cardId === card.id && (!state.slots[s.id] || state.slots[s.id].cardContract !== featureWorkflowCardContract(plan, card))))
355244
355273
  reason = "output_artifact_missing_or_stale";
355245
- if (!reason && record8 && (card.phase === "integration" || card.phase === "acceptance" || card.phase === "handoff") && (record8.mutationSequence !== state.mutationSequence || record8.workspaceRevision !== workspaceRevision))
355274
+ if (!reason && record9 && (card.phase === "integration" || card.phase === "acceptance" || card.phase === "handoff") && (record9.mutationSequence !== state.mutationSequence || record9.workspaceRevision !== workspaceRevision))
355246
355275
  reason = "integrated_revision_changed";
355247
- if (!reason && card.role === "reviewer" && record8?.reviewDisposition !== "approved")
355276
+ if (!reason && card.role === "reviewer" && record9?.reviewDisposition !== "approved")
355248
355277
  reason = "independent_review_missing";
355249
355278
  if (!reason && featureWorkflowDependencies(plan, card).some((id5) => !valid.has(id5)))
355250
355279
  reason = "prerequisite_unverified";
@@ -355252,7 +355281,7 @@ function deriveFeatureWorkflowStatus(plan, state, board, workspaceRevision) {
355252
355281
  gaps.push({
355253
355282
  cardId: card.id,
355254
355283
  reason,
355255
- ...record8 && !record8.success && record8.blockers.length ? { detail: record8.blockers.join("; ").slice(0, 1200) } : {}
355284
+ ...record9 && !record9.success && record9.blockers.length ? { detail: record9.blockers.join("; ").slice(0, 1200) } : {}
355256
355285
  });
355257
355286
  else
355258
355287
  valid.add(card.id);
@@ -355695,8 +355724,8 @@ var FeatureWorkflowController = class {
355695
355724
  fail3("checkpoint_result_mismatch");
355696
355725
  this.validateInputBindings(result.binding);
355697
355726
  const receipt = JSON.parse(this.store.read(result.receiptReference).content);
355698
- const { receiptReference: _ref, ...record8 } = result;
355699
- if (!equal(receipt.record, record8))
355727
+ const { receiptReference: _ref, ...record9 } = result;
355728
+ if (!equal(receipt.record, record9))
355700
355729
  fail3("checkpoint_receipt_mismatch");
355701
355730
  if (result.childReportReference) {
355702
355731
  const body = this.store.read(result.childReportReference).content;
@@ -355737,20 +355766,20 @@ var FeatureWorkflowController = class {
355737
355766
  const workspaceRevision = featureWorkflowWorkspaceRevision(this.options.workingDir, plan);
355738
355767
  for (const compiled of compileFeatureWorkflow(plan).cards) {
355739
355768
  const card = plan.cards.find((c) => featureWorkflowCardId(plan, c.id) === compiled.id);
355740
- const record8 = state.results[card.id];
355741
- if (!record8?.success || record8.binding.cardContract !== featureWorkflowCardContract(plan, card))
355769
+ const record9 = state.results[card.id];
355770
+ if (!record9?.success || record9.binding.cardContract !== featureWorkflowCardContract(plan, card))
355742
355771
  continue;
355743
- if (!equal(record8.binding.inputSlots, currentInputReferences(plan, card, state.slots)))
355772
+ if (!equal(record9.binding.inputSlots, currentInputReferences(plan, card, state.slots)))
355744
355773
  continue;
355745
- if (plan.slots.some((s) => s.cardId === card.id && state.slots[s.id]?.cardContract !== record8.binding.cardContract))
355774
+ if (plan.slots.some((s) => s.cardId === card.id && state.slots[s.id]?.cardContract !== record9.binding.cardContract))
355746
355775
  continue;
355747
- if ((card.phase === "integration" || card.phase === "acceptance" || card.phase === "handoff") && (record8.workspaceRevision !== workspaceRevision || record8.mutationSequence !== state.mutationSequence))
355776
+ if ((card.phase === "integration" || card.phase === "acceptance" || card.phase === "handoff") && (record9.workspaceRevision !== workspaceRevision || record9.mutationSequence !== state.mutationSequence))
355748
355777
  continue;
355749
355778
  const board = this.board();
355750
355779
  if (featureWorkflowDependencies(plan, card).some((id5) => board.cards.find((c) => c.id === featureWorkflowCardId(plan, id5))?.status !== "verified"))
355751
355780
  continue;
355752
355781
  if (board.cards.find((c) => c.id === compiled.id)?.status !== "verified")
355753
- this.applyResultToBoard(card, record8);
355782
+ this.applyResultToBoard(card, record9);
355754
355783
  }
355755
355784
  }
355756
355785
  interruptedOperations() {
@@ -356101,7 +356130,7 @@ var FeatureWorkflowController = class {
356101
356130
  }
356102
356131
  if (!successful && blockers.length === 0)
356103
356132
  blockers.push("The host operation failed; inspect its receipt and retry the remaining bounded work.");
356104
- const record8 = {
356133
+ const record9 = {
356105
356134
  binding: clone(binding),
356106
356135
  actorId,
356107
356136
  success: successful,
@@ -356114,8 +356143,8 @@ var FeatureWorkflowController = class {
356114
356143
  mutationSequence: state.mutationSequence,
356115
356144
  workspaceRevision
356116
356145
  };
356117
- const receiptReference = this.writeBody(JSON.stringify({ record: record8, observedArtifacts: stagedSlots }), `feature-workflow/${plan.id}/receipt/${binding.parentOperationId}`);
356118
- state.results[card.id] = { ...record8, receiptReference };
356146
+ const receiptReference = this.writeBody(JSON.stringify({ record: record9, observedArtifacts: stagedSlots }), `feature-workflow/${plan.id}/receipt/${binding.parentOperationId}`);
356147
+ state.results[card.id] = { ...record9, receiptReference };
356119
356148
  delete state.operations[binding.parentOperationId];
356120
356149
  state.recentSettlements.push({
356121
356150
  operationId: binding.parentOperationId,
@@ -356128,17 +356157,17 @@ var FeatureWorkflowController = class {
356128
356157
  this.persist();
356129
356158
  return this.status();
356130
356159
  }
356131
- applyResultToBoard(card, record8) {
356160
+ applyResultToBoard(card, record9) {
356132
356161
  const state = this.requireState();
356133
356162
  const cardId = featureWorkflowCardId(this.acceptedPlan, card.id);
356134
356163
  const evidence = {
356135
- id: `workflow:${hash15(record8.binding.parentOperationId)}`,
356164
+ id: `workflow:${hash15(record9.binding.parentOperationId)}`,
356136
356165
  kind: "tool_result",
356137
- summary: `${card.phase} host operation ${record8.success ? "completed" : "requires more work"}`,
356138
- ref: record8.receiptReference,
356139
- result: record8.success ? "success" : "failure"
356166
+ summary: `${card.phase} host operation ${record9.success ? "completed" : "requires more work"}`,
356167
+ ref: record9.receiptReference,
356168
+ result: record9.success ? "success" : "failure"
356140
356169
  };
356141
- if (record8.commandReceipt)
356170
+ if (record9.commandReceipt)
356142
356171
  attachTrustedWorkboardCommandEvidence(this.boardDir, {
356143
356172
  runId: state.boardRunId,
356144
356173
  cardId,
@@ -356148,7 +356177,7 @@ var FeatureWorkflowController = class {
356148
356177
  command: card.verifier?.command,
356149
356178
  tool: "terminal"
356150
356179
  },
356151
- receipt: record8.commandReceipt
356180
+ receipt: record9.commandReceipt
356152
356181
  });
356153
356182
  else
356154
356183
  attachWorkboardEvidence(this.boardDir, {
@@ -356157,7 +356186,7 @@ var FeatureWorkflowController = class {
356157
356186
  actor: "feature-workflow",
356158
356187
  evidence
356159
356188
  });
356160
- if (!record8.success) {
356189
+ if (!record9.success) {
356161
356190
  completeWorkboardCard(this.boardDir, {
356162
356191
  runId: state.boardRunId,
356163
356192
  cardId,
@@ -356174,7 +356203,7 @@ var FeatureWorkflowController = class {
356174
356203
  cardId,
356175
356204
  outcome: "completed",
356176
356205
  actor: "feature-workflow",
356177
- notes: record8.receiptReference
356206
+ notes: record9.receiptReference
356178
356207
  });
356179
356208
  if (!completed.accepted)
356180
356209
  fail3(`board_completion_${completed.code}`);
@@ -356183,8 +356212,8 @@ var FeatureWorkflowController = class {
356183
356212
  runId: state.boardRunId,
356184
356213
  cardId,
356185
356214
  outcome: "verified",
356186
- actor: `feature-workflow:receipt:${record8.receiptReference}`,
356187
- notes: record8.receiptReference
356215
+ actor: `feature-workflow:receipt:${record9.receiptReference}`,
356216
+ notes: record9.receiptReference
356188
356217
  });
356189
356218
  if (!verified.accepted)
356190
356219
  fail3(`board_verification_${verified.code}`);
@@ -356633,28 +356662,28 @@ function cloneSnapshot(value) {
356633
356662
  function isSnapshot(value) {
356634
356663
  if (!isRecord3(value))
356635
356664
  return false;
356636
- const record8 = value;
356637
- const pending = record8["pendingAcknowledgements"];
356638
- const ambiguous = record8["ambiguousEffects"];
356639
- const childLineage = record8["childLineage"];
356640
- const baseValid = record8["schema"] === INTERRUPTION_LIFECYCLE_SCHEMA && isNonEmptyString(record8["sessionId"]) && typeof record8["runId"] === "string" && isNonNegativeInteger(record8["taskEpoch"]) && isOwner(record8["owner"]) && Array.isArray(childLineage) && childLineage.every(isNonEmptyString) && INTERRUPTION_PHASES.has(record8["phase"]) && isNonNegativeInteger(record8["sequence"]) && typeof record8["resumable"] === "boolean" && typeof record8["recovered"] === "boolean" && (record8["requestedBy"] === void 0 || isOwner(record8["requestedBy"])) && (record8["reason"] === void 0 || typeof record8["reason"] === "string") && isIsoTimestamp(record8["transitionedAt"]) && Array.isArray(pending) && pending.every(isAcknowledgement) && new Set(pending.map((entry) => entry.id)).size === pending.length && Array.isArray(ambiguous) && ambiguous.every(isAmbiguousEffect) && new Set(ambiguous.map((entry) => entry.operationId)).size === ambiguous.length;
356665
+ const record9 = value;
356666
+ const pending = record9["pendingAcknowledgements"];
356667
+ const ambiguous = record9["ambiguousEffects"];
356668
+ const childLineage = record9["childLineage"];
356669
+ const baseValid = record9["schema"] === INTERRUPTION_LIFECYCLE_SCHEMA && isNonEmptyString(record9["sessionId"]) && typeof record9["runId"] === "string" && isNonNegativeInteger(record9["taskEpoch"]) && isOwner(record9["owner"]) && Array.isArray(childLineage) && childLineage.every(isNonEmptyString) && INTERRUPTION_PHASES.has(record9["phase"]) && isNonNegativeInteger(record9["sequence"]) && typeof record9["resumable"] === "boolean" && typeof record9["recovered"] === "boolean" && (record9["requestedBy"] === void 0 || isOwner(record9["requestedBy"])) && (record9["reason"] === void 0 || typeof record9["reason"] === "string") && isIsoTimestamp(record9["transitionedAt"]) && Array.isArray(pending) && pending.every(isAcknowledgement) && new Set(pending.map((entry) => entry.id)).size === pending.length && Array.isArray(ambiguous) && ambiguous.every(isAmbiguousEffect) && new Set(ambiguous.map((entry) => entry.operationId)).size === ambiguous.length;
356641
356670
  if (!baseValid)
356642
356671
  return false;
356643
- const owner = record8["owner"];
356672
+ const owner = record9["owner"];
356644
356673
  const acknowledgements = pending;
356645
356674
  const acknowledgementById = new Map(acknowledgements.map((entry) => [entry.id, entry]));
356646
356675
  if (acknowledgements.some((entry) => entry.generation !== owner.generation)) {
356647
356676
  return false;
356648
356677
  }
356649
- const phase = record8["phase"];
356678
+ const phase = record9["phase"];
356650
356679
  const resumablePhases = /* @__PURE__ */ new Set([
356651
356680
  "pausing",
356652
356681
  "paused",
356653
356682
  "resuming"
356654
356683
  ]);
356655
- if (record8["resumable"] !== resumablePhases.has(phase))
356684
+ if (record9["resumable"] !== resumablePhases.has(phase))
356656
356685
  return false;
356657
- if (phase !== "stopped" && !isNonEmptyString(record8["runId"]))
356686
+ if (phase !== "stopped" && !isNonEmptyString(record9["runId"]))
356658
356687
  return false;
356659
356688
  if ((TERMINAL_PHASES.has(phase) || phase === "paused" || phase === "resuming") && acknowledgements.some((entry) => entry.status === "pending")) {
356660
356689
  return false;
@@ -357915,21 +357944,21 @@ var TypedModelOutputStream = class {
357915
357944
  if (prefix.trim())
357916
357945
  appendVisible(prefix);
357917
357946
  if (reservedMarker === LEGACY_STEERING_GATE_MARKER) {
357918
- const record8 = consumeLegacySteeringGate(this.buffer.slice(reservedAt), final);
357919
- if (record8 === "pending") {
357947
+ const record9 = consumeLegacySteeringGate(this.buffer.slice(reservedAt), final);
357948
+ if (record9 === "pending") {
357920
357949
  this.buffer = this.buffer.slice(reservedAt);
357921
357950
  break;
357922
357951
  }
357923
- if (record8) {
357952
+ if (record9) {
357924
357953
  const region2 = {
357925
357954
  kind: "internal_contract_echo",
357926
357955
  visibility: "internal_control",
357927
- raw: record8.raw,
357956
+ raw: record9.raw,
357928
357957
  value: { marker: reservedMarker }
357929
357958
  };
357930
357959
  regions.push(region2);
357931
357960
  this.options.onRegion?.(region2);
357932
- this.buffer = record8.remainder;
357961
+ this.buffer = record9.remainder;
357933
357962
  this.separatorAfterRegion = this.hasVisibleContent;
357934
357963
  continue;
357935
357964
  }
@@ -359979,8 +360008,8 @@ function deepEqual(left, right) {
359979
360008
  return value.map(canonical9);
359980
360009
  if (!value || typeof value !== "object")
359981
360010
  return value;
359982
- const record8 = value;
359983
- return Object.fromEntries(Object.keys(record8).sort().map((key) => [key, canonical9(record8[key])]));
360011
+ const record9 = value;
360012
+ return Object.fromEntries(Object.keys(record9).sort().map((key) => [key, canonical9(record9[key])]));
359984
360013
  };
359985
360014
  return JSON.stringify(canonical9(left)) === JSON.stringify(canonical9(right));
359986
360015
  }
@@ -362364,33 +362393,33 @@ function atomicWriteJson(path7, value) {
362364
362393
  `, "utf8");
362365
362394
  renameSync16(tmp, path7);
362366
362395
  }
362367
- function prepareCompletionFinalization(stateDir, record8) {
362368
- const path7 = completionFinalizationPreparePath(stateDir, record8.runId);
362396
+ function prepareCompletionFinalization(stateDir, record9) {
362397
+ const path7 = completionFinalizationPreparePath(stateDir, record9.runId);
362369
362398
  mkdirSync28(join44(stateDir, "completion-finalizations"), { recursive: true });
362370
- atomicWriteJson(path7, { ...record8, phase: "prepared" });
362399
+ atomicWriteJson(path7, { ...record9, phase: "prepared" });
362371
362400
  return path7;
362372
362401
  }
362373
- function commitCompletionFinalization(stateDir, record8) {
362374
- const path7 = completionFinalizationPath(stateDir, record8.runId);
362402
+ function commitCompletionFinalization(stateDir, record9) {
362403
+ const path7 = completionFinalizationPath(stateDir, record9.runId);
362375
362404
  mkdirSync28(join44(stateDir, "completion-finalizations"), { recursive: true });
362376
- atomicWriteJson(path7, { ...record8, phase: "committed" });
362405
+ atomicWriteJson(path7, { ...record9, phase: "committed" });
362377
362406
  try {
362378
- unlinkSync14(completionFinalizationPreparePath(stateDir, record8.runId));
362407
+ unlinkSync14(completionFinalizationPreparePath(stateDir, record9.runId));
362379
362408
  } catch {
362380
362409
  }
362381
362410
  return path7;
362382
362411
  }
362383
- function commitTerminalTrajectoryProjection(stateDir, record8, payload2) {
362412
+ function commitTerminalTrajectoryProjection(stateDir, record9, payload2) {
362384
362413
  const dir = join44(stateDir, "terminal-trajectories");
362385
- const safeRunId = record8.runId.replace(/[^a-zA-Z0-9._-]+/g, "-").slice(0, 180);
362414
+ const safeRunId = record9.runId.replace(/[^a-zA-Z0-9._-]+/g, "-").slice(0, 180);
362386
362415
  const path7 = join44(dir, `${safeRunId}.json`);
362387
362416
  mkdirSync28(dir, { recursive: true });
362388
362417
  const projection = {
362389
362418
  schema: "omnius.terminal-trajectory.v1",
362390
- terminalReceiptId: record8.id,
362391
- runId: record8.runId,
362392
- status: record8.status,
362393
- committedAtIso: record8.committedAtIso,
362419
+ terminalReceiptId: record9.id,
362420
+ runId: record9.runId,
362421
+ status: record9.status,
362422
+ committedAtIso: record9.committedAtIso,
362394
362423
  payload: payload2
362395
362424
  };
362396
362425
  atomicWriteJson(path7, projection);
@@ -362969,14 +362998,14 @@ function receiptDigest(input) {
362969
362998
  function validateOverrideReceipt(value) {
362970
362999
  if (!value || typeof value !== "object" || Array.isArray(value))
362971
363000
  return null;
362972
- const record8 = value;
362973
- if (record8["schema"] !== COMPLETION_OVERRIDE_SCHEMA)
363001
+ const record9 = value;
363002
+ if (record9["schema"] !== COMPLETION_OVERRIDE_SCHEMA)
362974
363003
  return null;
362975
- const runId = bounded2(record8["runId"], 500);
362976
- const readinessHash = bounded2(record8["readinessHash"], 64).toLowerCase();
362977
- const reason = bounded2(record8["reason"], 2e3);
362978
- const persistedAtIso = bounded2(record8["persistedAtIso"], 80);
362979
- const receiptId = bounded2(record8["receiptId"], 100);
363004
+ const runId = bounded2(record9["runId"], 500);
363005
+ const readinessHash = bounded2(record9["readinessHash"], 64).toLowerCase();
363006
+ const reason = bounded2(record9["reason"], 2e3);
363007
+ const persistedAtIso = bounded2(record9["persistedAtIso"], 80);
363008
+ const receiptId = bounded2(record9["receiptId"], 100);
362980
363009
  if (!runId || !SHA2562.test(readinessHash) || !reason || !validIso2(persistedAtIso)) {
362981
363010
  return null;
362982
363011
  }
@@ -368501,9 +368530,9 @@ function loadBoundaryRecords(omniusDir) {
368501
368530
  try {
368502
368531
  const parsed = JSON.parse(lines[i]);
368503
368532
  if (parsed && parsed.v === 1 && parsed.handoff && typeof parsed.recordedAt === "number") {
368504
- const record8 = parsed;
368505
- if (shouldPersistTaskHandoff(record8.handoff))
368506
- records.push(record8);
368533
+ const record9 = parsed;
368534
+ if (shouldPersistTaskHandoff(record9.handoff))
368535
+ records.push(record9);
368507
368536
  }
368508
368537
  } catch {
368509
368538
  }
@@ -371127,8 +371156,8 @@ function stableValueKey(value) {
371127
371156
  hash17 = (hash17 << 5) + hash17 + raw.charCodeAt(i) | 0;
371128
371157
  return `{size:${raw.length},hash:${Math.abs(hash17).toString(36)}}`;
371129
371158
  }
371130
- const record8 = value;
371131
- return `{${Object.keys(record8).sort().map((key) => `${JSON.stringify(key)}:${stableValueKey(record8[key])}`).join(",")}}`;
371159
+ const record9 = value;
371160
+ return `{${Object.keys(record9).sort().map((key) => `${JSON.stringify(key)}:${stableValueKey(record9[key])}`).join(",")}}`;
371132
371161
  }
371133
371162
  var StreamingToolExecutor = class {
371134
371163
  tools = /* @__PURE__ */ new Map();
@@ -371345,7 +371374,10 @@ var StreamingToolExecutor = class {
371345
371374
  return {
371346
371375
  success: prior.result.success,
371347
371376
  output: prior.result.output ? `${prefix}${prior.result.output}` : prior.result.output,
371348
- error: prior.result.error
371377
+ error: prior.result.error,
371378
+ completionAdmission: prior.result.completionAdmission,
371379
+ completionReviewPending: prior.result.completionReviewPending,
371380
+ completionRestoredPayload: prior.result.completionRestoredPayload
371349
371381
  };
371350
371382
  }
371351
371383
  mirrorPriorEquivalent(entry) {
@@ -373081,7 +373113,7 @@ function encodeRepeatedCompletedObservations(history, makeMessage) {
373081
373113
  continue;
373082
373114
  }
373083
373115
  const latest = run.at(-1);
373084
- const record8 = {
373116
+ const record9 = {
373085
373117
  schema: "omnius.repeated-completed-observations.v1",
373086
373118
  count: run.length,
373087
373119
  latestTransactionId: latest.call.transactionId,
@@ -373098,7 +373130,7 @@ function encodeRepeatedCompletedObservations(history, makeMessage) {
373098
373130
  const summary = {
373099
373131
  id: `repeated-observations:${latest.call.transactionId}`,
373100
373132
  message: makeMessage(`[REPEATED COMPLETED OBSERVATIONS v1]
373101
- ${JSON.stringify(record8)}`),
373133
+ ${JSON.stringify(record9)}`),
373102
373134
  kind: "stable",
373103
373135
  ordinal: latest.result.ordinal + 0.125,
373104
373136
  turn: latest.result.turn,
@@ -373752,8 +373784,8 @@ function stable5(value) {
373752
373784
  }
373753
373785
  if (Array.isArray(value))
373754
373786
  return `[${value.map(stable5).join(",")}]`;
373755
- const record8 = value;
373756
- return `{${Object.keys(record8).sort().map((key) => `${JSON.stringify(key)}:${stable5(record8[key])}`).join(",")}}`;
373787
+ const record9 = value;
373788
+ return `{${Object.keys(record9).sort().map((key) => `${JSON.stringify(key)}:${stable5(record9[key])}`).join(",")}}`;
373757
373789
  }
373758
373790
  function keyedDigest(value, key) {
373759
373791
  return createHmac("sha256", key).update(stable5(value)).digest("hex");
@@ -373961,15 +373993,15 @@ var FailureResolutionTransactionCoordinator = class {
373961
373993
  this.now = options.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
373962
373994
  }
373963
373995
  resolve(input) {
373964
- const record8 = this.prepare(input);
373965
- return this.advance(input.workingDir, record8);
373996
+ const record9 = this.prepare(input);
373997
+ return this.advance(input.workingDir, record9);
373966
373998
  }
373967
373999
  recover(workingDir, runId) {
373968
374000
  const directory = failureResolutionTransactionDirectory(workingDir, runId);
373969
374001
  if (!existsSync51(directory))
373970
374002
  return [];
373971
374003
  const records = readdirSync17(directory).filter((name) => name.endsWith(".json")).sort().map((name) => readResolutionRecord(join60(directory, name)));
373972
- return records.map((record8) => this.advance(workingDir, record8));
374004
+ return records.map((record9) => this.advance(workingDir, record9));
373973
374005
  }
373974
374006
  prepare(input) {
373975
374007
  const runId = normalizeWorkboardRunId(input.runId);
@@ -374034,7 +374066,7 @@ var FailureResolutionTransactionCoordinator = class {
374034
374066
  }
374035
374067
  return existing;
374036
374068
  }
374037
- const record8 = {
374069
+ const record9 = {
374038
374070
  schema: FAILURE_RESOLUTION_TRANSACTION_SCHEMA,
374039
374071
  id: id5,
374040
374072
  state: "prepared",
@@ -374042,45 +374074,45 @@ var FailureResolutionTransactionCoordinator = class {
374042
374074
  preparedAt,
374043
374075
  updatedAt: preparedAt
374044
374076
  };
374045
- writeResolutionRecord(input.workingDir, record8);
374046
- return record8;
374077
+ writeResolutionRecord(input.workingDir, record9);
374078
+ return record9;
374047
374079
  }
374048
374080
  advance(workingDir, input) {
374049
- let record8 = cloneRecord(input);
374050
- if (record8.state === "committed")
374051
- return record8;
374081
+ let record9 = cloneRecord(input);
374082
+ if (record9.state === "committed")
374083
+ return record9;
374052
374084
  this.crashHook?.("before_failure_store");
374053
- for (const failureId of record8.receipt.failureIds) {
374085
+ for (const failureId of record9.receipt.failureIds) {
374054
374086
  const failure = this.failureStore.getById(failureId);
374055
374087
  if (!failure) {
374056
374088
  throw new Error(`failure resolution store record '${failureId}' disappeared`);
374057
374089
  }
374058
374090
  if (!failure.resolved) {
374059
- this.failureStore.markResolved(failureId, record8.receipt.committedAt);
374091
+ this.failureStore.markResolved(failureId, record9.receipt.committedAt);
374060
374092
  }
374061
374093
  }
374062
374094
  this.crashHook?.("after_failure_store");
374063
- record8 = {
374064
- ...record8,
374065
- failureStoreCommittedAt: record8.failureStoreCommittedAt ?? this.now(),
374095
+ record9 = {
374096
+ ...record9,
374097
+ failureStoreCommittedAt: record9.failureStoreCommittedAt ?? this.now(),
374066
374098
  updatedAt: this.now()
374067
374099
  };
374068
- writeResolutionRecord(workingDir, record8);
374100
+ writeResolutionRecord(workingDir, record9);
374069
374101
  this.crashHook?.("before_workboard");
374070
374102
  commitWorkboardFailureResolution(workingDir, {
374071
- runId: record8.receipt.runId,
374103
+ runId: record9.receipt.runId,
374072
374104
  actor: "runner",
374073
- receipt: record8.receipt
374105
+ receipt: record9.receipt
374074
374106
  });
374075
374107
  this.crashHook?.("after_workboard");
374076
- record8 = {
374077
- ...record8,
374108
+ record9 = {
374109
+ ...record9,
374078
374110
  state: "committed",
374079
- workboardCommittedAt: record8.workboardCommittedAt ?? this.now(),
374111
+ workboardCommittedAt: record9.workboardCommittedAt ?? this.now(),
374080
374112
  updatedAt: this.now()
374081
374113
  };
374082
- writeResolutionRecord(workingDir, record8);
374083
- return record8;
374114
+ writeResolutionRecord(workingDir, record9);
374115
+ return record9;
374084
374116
  }
374085
374117
  };
374086
374118
  function failureResolutionTransactionDirectory(workingDir, runId) {
@@ -374090,14 +374122,14 @@ function failureResolutionTransactionPath(workingDir, runId, transaction) {
374090
374122
  const safeTransaction = requiredString(transaction, "transaction id").replace(/[^a-zA-Z0-9_.-]/g, "_").slice(0, 160);
374091
374123
  return join60(failureResolutionTransactionDirectory(workingDir, runId), `${safeTransaction}.json`);
374092
374124
  }
374093
- function writeResolutionRecord(workingDir, record8) {
374094
- const path7 = failureResolutionTransactionPath(workingDir, record8.receipt.runId, record8.id);
374095
- mkdirSync38(failureResolutionTransactionDirectory(workingDir, record8.receipt.runId), {
374125
+ function writeResolutionRecord(workingDir, record9) {
374126
+ const path7 = failureResolutionTransactionPath(workingDir, record9.receipt.runId, record9.id);
374127
+ mkdirSync38(failureResolutionTransactionDirectory(workingDir, record9.receipt.runId), {
374096
374128
  recursive: true
374097
374129
  });
374098
374130
  const temporary = `${path7}.tmp.${process.pid}.${Date.now()}`;
374099
374131
  try {
374100
- writeFileSync33(temporary, `${JSON.stringify(record8, null, 2)}
374132
+ writeFileSync33(temporary, `${JSON.stringify(record9, null, 2)}
374101
374133
  `, "utf8");
374102
374134
  renameSync20(temporary, path7);
374103
374135
  } catch (error) {
@@ -374115,8 +374147,8 @@ function readResolutionRecord(path7) {
374115
374147
  }
374116
374148
  return cloneRecord(parsed);
374117
374149
  }
374118
- function cloneRecord(record8) {
374119
- return JSON.parse(JSON.stringify(record8));
374150
+ function cloneRecord(record9) {
374151
+ return JSON.parse(JSON.stringify(record9));
374120
374152
  }
374121
374153
  function transactionId(value) {
374122
374154
  return createHash88("sha256").update(stableJson4(value)).digest("hex").slice(0, 32);
@@ -374576,10 +374608,10 @@ function hasAssistantPayload(message) {
374576
374608
  const text12 = messageText(message.content).trim();
374577
374609
  if (text12 && !/^(null|undefined)$/i.test(text12))
374578
374610
  return true;
374579
- const record8 = message;
374580
- if (Array.isArray(record8["tool_calls"]) && record8["tool_calls"].length > 0)
374611
+ const record9 = message;
374612
+ if (Array.isArray(record9["tool_calls"]) && record9["tool_calls"].length > 0)
374581
374613
  return true;
374582
- return Boolean(record8["function_call"]);
374614
+ return Boolean(record9["function_call"]);
374583
374615
  }
374584
374616
  function staleToolFailureKey(content) {
374585
374617
  const text12 = content.replace(/\s+/g, " ").trim();
@@ -375403,9 +375435,9 @@ function canonical7(value) {
375403
375435
  return `[${value.map((item) => item === void 0 || typeof item === "function" || typeof item === "symbol" ? "null" : canonical7(item)).join(",")}]`;
375404
375436
  }
375405
375437
  if (typeof value === "object") {
375406
- const record8 = value;
375407
- return `{${Object.keys(record8).sort().flatMap((key) => {
375408
- const child = record8[key];
375438
+ const record9 = value;
375439
+ return `{${Object.keys(record9).sort().flatMap((key) => {
375440
+ const child = record9[key];
375409
375441
  if (child === void 0 || typeof child === "function" || typeof child === "symbol")
375410
375442
  return [];
375411
375443
  return [`${JSON.stringify(key)}:${canonical7(child)}`];
@@ -375552,7 +375584,7 @@ function recordContextWindowDump(input) {
375552
375584
  request: input.request
375553
375585
  });
375554
375586
  const storedRequest = redactContextDumpRequest(input.request);
375555
- const record8 = {
375587
+ const record9 = {
375556
375588
  schemaVersion: 1,
375557
375589
  id: id5,
375558
375590
  timestamp: timestamp5,
@@ -375578,20 +375610,20 @@ function recordContextWindowDump(input) {
375578
375610
  try {
375579
375611
  mkdirSync39(dir, { recursive: true, mode: 448 });
375580
375612
  chmodSync2(dir, 448);
375581
- const filePath = join61(dir, `${record8.id}.json`);
375582
- const payload2 = JSON.stringify(record8, null, 2);
375613
+ const filePath = join61(dir, `${record9.id}.json`);
375614
+ const payload2 = JSON.stringify(record9, null, 2);
375583
375615
  writePrivateFileAtomic(filePath, payload2);
375584
- writePrivateFileAtomic(join61(dir, `latest-${record8.agentType}.json`), payload2);
375616
+ writePrivateFileAtomic(join61(dir, `latest-${record9.agentType}.json`), payload2);
375585
375617
  writePrivateFileAtomic(join61(dir, "latest.json"), payload2);
375586
375618
  const indexPath = join61(dir, "index.jsonl");
375587
- appendFileSync7(indexPath, JSON.stringify(toSummary(record8, filePath)) + "\n", { encoding: "utf-8", mode: 384 });
375619
+ appendFileSync7(indexPath, JSON.stringify(toSummary(record9, filePath)) + "\n", { encoding: "utf-8", mode: 384 });
375588
375620
  chmodSync2(indexPath, 384);
375589
375621
  rotatePrivateIndex(indexPath);
375590
375622
  maybePruneOldDumpFiles(dir);
375591
375623
  } catch {
375592
375624
  return null;
375593
375625
  }
375594
- return record8;
375626
+ return record9;
375595
375627
  }
375596
375628
  function analyzeContextWindowDumpRequest(request) {
375597
375629
  const messages = Array.isArray(request["messages"]) ? request["messages"] : [];
@@ -375749,10 +375781,10 @@ function buildContextAccounting(request, metrics) {
375749
375781
  };
375750
375782
  const messages = Array.isArray(request["messages"]) ? request["messages"] : [];
375751
375783
  for (const message of messages) {
375752
- const record8 = message && typeof message === "object" ? message : {};
375753
- const role = typeof record8["role"] === "string" ? record8["role"] : "unknown";
375754
- const extracted = textAndImagesFromContent(record8["content"]);
375755
- const toolCallChars = Array.isArray(record8["tool_calls"]) ? JSON.stringify(record8["tool_calls"]).length : 0;
375784
+ const record9 = message && typeof message === "object" ? message : {};
375785
+ const role = typeof record9["role"] === "string" ? record9["role"] : "unknown";
375786
+ const extracted = textAndImagesFromContent(record9["content"]);
375787
+ const toolCallChars = Array.isArray(record9["tool_calls"]) ? JSON.stringify(record9["tool_calls"]).length : 0;
375756
375788
  add(contextSourceForMessage(role, extracted.textWithoutImages), extracted.textWithoutImages.length + toolCallChars);
375757
375789
  }
375758
375790
  if (metrics.toolSchemaChars > 0)
@@ -375860,8 +375892,8 @@ function isRawDiscoveryToolResult(text12) {
375860
375892
  return false;
375861
375893
  return !text12.includes("[DISCOVERY COMPACTED") && !text12.includes("[DISCOVERY BOUNDED") && !text12.includes("[STOP RE-READING") && !/^\[BRANCH-EXTRACT(?:\s+v\d+)?\]/m.test(text12);
375862
375894
  }
375863
- function toSummary(record8, path7) {
375864
- const { request: _request, requestCompilation, requestBudget, ...summary } = record8;
375895
+ function toSummary(record9, path7) {
375896
+ const { request: _request, requestCompilation, requestBudget, ...summary } = record9;
375865
375897
  return {
375866
375898
  ...summary,
375867
375899
  ...requestCompilation ? {
@@ -376578,20 +376610,20 @@ function safeErrorObjects(error) {
376578
376610
  let current = error;
376579
376611
  while (current && typeof current === "object" && !seen.has(current) && result.length < 4) {
376580
376612
  seen.add(current);
376581
- const record8 = current;
376582
- result.push(record8);
376583
- const responseJson = record8["responseJson"];
376584
- if (record8["name"] === "InferenceHttpError" && responseJson && typeof responseJson === "object" && !Array.isArray(responseJson) && !seen.has(responseJson) && result.length < 4) {
376613
+ const record9 = current;
376614
+ result.push(record9);
376615
+ const responseJson = record9["responseJson"];
376616
+ if (record9["name"] === "InferenceHttpError" && responseJson && typeof responseJson === "object" && !Array.isArray(responseJson) && !seen.has(responseJson) && result.length < 4) {
376585
376617
  seen.add(responseJson);
376586
376618
  result.push(responseJson);
376587
376619
  }
376588
- current = record8["cause"];
376620
+ current = record9["cause"];
376589
376621
  }
376590
376622
  return result;
376591
376623
  }
376592
376624
  function safeErrorNumber(error, key) {
376593
- for (const record8 of safeErrorObjects(error)) {
376594
- const value = record8[key];
376625
+ for (const record9 of safeErrorObjects(error)) {
376626
+ const value = record9[key];
376595
376627
  if (typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 599) {
376596
376628
  return value;
376597
376629
  }
@@ -376599,25 +376631,25 @@ function safeErrorNumber(error, key) {
376599
376631
  return void 0;
376600
376632
  }
376601
376633
  function safeErrorCode(error) {
376602
- for (const record8 of safeErrorObjects(error)) {
376603
- const value = record8["code"];
376634
+ for (const record9 of safeErrorObjects(error)) {
376635
+ const value = record9["code"];
376604
376636
  if (typeof value === "string" && /^[A-Z0-9_]{2,40}$/.test(value))
376605
376637
  return value;
376606
376638
  }
376607
376639
  return "";
376608
376640
  }
376609
376641
  function safeErrorName(error) {
376610
- for (const record8 of safeErrorObjects(error)) {
376611
- const value = record8["name"];
376642
+ for (const record9 of safeErrorObjects(error)) {
376643
+ const value = record9["name"];
376612
376644
  if (typeof value === "string" && /^[A-Za-z]{2,40}$/.test(value))
376613
376645
  return value;
376614
376646
  }
376615
376647
  return "";
376616
376648
  }
376617
376649
  function safeExplicitRetryable(error) {
376618
- for (const record8 of safeErrorObjects(error)) {
376619
- if (typeof record8["retryable"] === "boolean")
376620
- return record8["retryable"];
376650
+ for (const record9 of safeErrorObjects(error)) {
376651
+ if (typeof record9["retryable"] === "boolean")
376652
+ return record9["retryable"];
376621
376653
  }
376622
376654
  return void 0;
376623
376655
  }
@@ -376833,21 +376865,21 @@ function parseMemoryCompilationProposal(value) {
376833
376865
  };
376834
376866
  }
376835
376867
  async function analyzeMemoryDelta(backend, input) {
376836
- const candidatePayload = input.candidates.map((record8) => ({
376837
- id: record8.id,
376838
- kind: record8.kind,
376839
- authority: record8.authority,
376840
- trustClass: record8.trustClass,
376868
+ const candidatePayload = input.candidates.map((record9) => ({
376869
+ id: record9.id,
376870
+ kind: record9.kind,
376871
+ authority: record9.authority,
376872
+ trustClass: record9.trustClass,
376841
376873
  // For canonical artifacts this is the hash a trusted resolver can reopen,
376842
376874
  // not the ledger's epoch-scoped record identity hash.
376843
- contentHash: isArtifactRecord(record8) ? canonicalArtifactContentHash(record8) : record8.contentHash,
376844
- provenance: record8.provenance,
376845
- validFrom: record8.validFrom,
376846
- validUntil: record8.validUntil ?? null,
376875
+ contentHash: isArtifactRecord(record9) ? canonicalArtifactContentHash(record9) : record9.contentHash,
376876
+ provenance: record9.provenance,
376877
+ validFrom: record9.validFrom,
376878
+ validUntil: record9.validUntil ?? null,
376847
376879
  // This is intentionally the real evidence candidate, not a wrapper or
376848
376880
  // structural preview. The system instruction below makes its untrusted
376849
376881
  // status explicit regardless of text that appears inside it.
376850
- body: record8.body
376882
+ body: record9.body
376851
376883
  }));
376852
376884
  const prompt = [
376853
376885
  "You are an isolated, non-mutating memory compiler for a coding agent.",
@@ -376906,34 +376938,34 @@ function compilerBodyPreviewBudget(candidateCount) {
376906
376938
  return Math.min(MEMORY_COMPILER_BODY_PREVIEW_MAX_CHARS, Math.max(MEMORY_COMPILER_BODY_PREVIEW_MIN_CHARS, Math.floor(MEMORY_COMPILER_BODY_PREVIEW_TOTAL_CHARS / Math.max(1, candidateCount))));
376907
376939
  }
376908
376940
  async function analyzeMemoryCompilationPlanWithOutcome(backend, input) {
376909
- const protectedRecords = input.candidates.filter((record8) => record8.authority === "system" || record8.authority === "user");
376910
- const mutableRecords = input.candidates.filter((record8) => record8.authority !== "system" && record8.authority !== "user");
376911
- const newestUserId = [...protectedRecords].reverse().find((record8) => record8.authority === "user")?.id;
376941
+ const protectedRecords = input.candidates.filter((record9) => record9.authority === "system" || record9.authority === "user");
376942
+ const mutableRecords = input.candidates.filter((record9) => record9.authority !== "system" && record9.authority !== "user");
376943
+ const newestUserId = [...protectedRecords].reverse().find((record9) => record9.authority === "user")?.id;
376912
376944
  const previewChars = compilerBodyPreviewBudget(mutableRecords.length);
376913
- const protectedPayload = protectedRecords.map((record8) => ({
376914
- id: record8.id,
376915
- authority: record8.authority,
376945
+ const protectedPayload = protectedRecords.map((record9) => ({
376946
+ id: record9.id,
376947
+ authority: record9.authority,
376916
376948
  lockedDisposition: "retain_full",
376917
376949
  // The newest user authority orients relevance decisions. Older user and
376918
376950
  // all system bodies stay out of this isolated request: trusted code has
376919
376951
  // already fixed their disposition and the final request retains them.
376920
- ...record8.id === newestUserId ? compilerBodyPreview(record8.body, MEMORY_COMPILER_BODY_PREVIEW_MAX_CHARS) : { bodyOmitted: true }
376952
+ ...record9.id === newestUserId ? compilerBodyPreview(record9.body, MEMORY_COMPILER_BODY_PREVIEW_MAX_CHARS) : { bodyOmitted: true }
376921
376953
  }));
376922
- const candidatePayload = mutableRecords.map((record8) => ({
376923
- id: record8.id,
376924
- kind: record8.kind,
376925
- authority: record8.authority,
376926
- trustClass: record8.trustClass,
376927
- artifactAvailable: durableArtifactReference(record8) !== void 0,
376928
- toolResult: record8.authority === "tool_data",
376929
- estimatedFullTokens: estimatedRecordTokens(record8),
376930
- estimatedFullInputTokens: estimatedConservativeTextTokens(record8.body),
376931
- validUntil: record8.validUntil ?? null,
376954
+ const candidatePayload = mutableRecords.map((record9) => ({
376955
+ id: record9.id,
376956
+ kind: record9.kind,
376957
+ authority: record9.authority,
376958
+ trustClass: record9.trustClass,
376959
+ artifactAvailable: durableArtifactReference(record9) !== void 0,
376960
+ toolResult: record9.authority === "tool_data",
376961
+ estimatedFullTokens: estimatedRecordTokens(record9),
376962
+ estimatedFullInputTokens: estimatedConservativeTextTokens(record9.body),
376963
+ validUntil: record9.validUntil ?? null,
376932
376964
  // The exact body remains in the immutable ledger/artifact store. The
376933
376965
  // compiler only needs enough bounded context to identify obviously stale,
376934
376966
  // duplicate, or reopenable material; omission always defaults to
376935
376967
  // retain_full, so an incomplete preview can never silently delete data.
376936
- ...compilerBodyPreview(record8.body, previewChars)
376968
+ ...compilerBodyPreview(record9.body, previewChars)
376937
376969
  }));
376938
376970
  const targetMaximumTokens = compactionInputTarget(input.budget);
376939
376971
  const requiredMinimumReduction = Math.max(1, (input.budget.compactionInputTokens ?? compactionInputEstimate(input.budget)) - targetMaximumTokens);
@@ -377155,19 +377187,19 @@ function emptyCoverage() {
377155
377187
  unresolvedRequirementIds: []
377156
377188
  };
377157
377189
  }
377158
- function durableArtifactReference(record8) {
377159
- if (!isArtifactRecord(record8))
377190
+ function durableArtifactReference(record9) {
377191
+ if (!isArtifactRecord(record9))
377160
377192
  return void 0;
377161
- const contentHash2 = canonicalArtifactContentHash(record8);
377193
+ const contentHash2 = canonicalArtifactContentHash(record9);
377162
377194
  const artifactUri = `omnius-artifact://sha256/${contentHash2}`;
377163
- if (record8.metadata["artifactReference"] !== artifactUri)
377195
+ if (record9.metadata["artifactReference"] !== artifactUri)
377164
377196
  return void 0;
377165
377197
  return {
377166
377198
  artifactUri,
377167
377199
  contentHash: contentHash2,
377168
- ...record8.provenance.sourceUri ? { sourceUri: record8.provenance.sourceUri } : {},
377169
- ...record8.provenance.sourceRevision ? { sourceRevision: record8.provenance.sourceRevision } : {},
377170
- ...record8.provenance.sourceRange ? { sourceRange: record8.provenance.sourceRange } : {}
377200
+ ...record9.provenance.sourceUri ? { sourceUri: record9.provenance.sourceUri } : {},
377201
+ ...record9.provenance.sourceRevision ? { sourceRevision: record9.provenance.sourceRevision } : {},
377202
+ ...record9.provenance.sourceRange ? { sourceRange: record9.provenance.sourceRange } : {}
377171
377203
  };
377172
377204
  }
377173
377205
  function recordLineCount(content) {
@@ -377194,7 +377226,7 @@ function sliceRecordLines(content, span) {
377194
377226
  const endOffset = span.end === totalLines ? content.length : starts[span.end];
377195
377227
  return startOffset === void 0 || endOffset === void 0 ? null : content.slice(startOffset, endOffset);
377196
377228
  }
377197
- function renderedCandidateContent(candidate, record8) {
377229
+ function renderedCandidateContent(candidate, record9) {
377198
377230
  const artifactHeader = candidate.artifact ? [
377199
377231
  `artifact: ${candidate.artifact.artifactUri}`,
377200
377232
  ...candidate.artifact.sourceUri ? [`source: ${candidate.artifact.sourceUri}`] : [],
@@ -377202,10 +377234,10 @@ function renderedCandidateContent(candidate, record8) {
377202
377234
  ] : [];
377203
377235
  switch (candidate.disposition) {
377204
377236
  case "retain_full":
377205
- return record8.body;
377237
+ return record9.body;
377206
377238
  case "retain_partial": {
377207
377239
  const excerpts = candidate.spans?.map((span) => {
377208
- const content = sliceRecordLines(record8.body, span);
377240
+ const content = sliceRecordLines(record9.body, span);
377209
377241
  return content === null ? null : `lines ${span.start}-${span.end}:
377210
377242
  ${content}`;
377211
377243
  });
@@ -377247,12 +377279,12 @@ ${content}`;
377247
377279
  function estimatedTextTokens(value) {
377248
377280
  return value.length > 0 ? Math.ceil(value.length / 4) + 4 : 0;
377249
377281
  }
377250
- function hydrateProposalChange(change, record8) {
377251
- const artifact = isArtifactRecord(record8) ? durableArtifactReference(record8) : void 0;
377252
- if (isArtifactRecord(record8) && !artifact)
377282
+ function hydrateProposalChange(change, record9) {
377283
+ const artifact = isArtifactRecord(record9) ? durableArtifactReference(record9) : void 0;
377284
+ if (isArtifactRecord(record9) && !artifact)
377253
377285
  return null;
377254
377286
  const base = {
377255
- id: record8.id,
377287
+ id: record9.id,
377256
377288
  rationale: change.rationale,
377257
377289
  renderedTokens: 0,
377258
377290
  coverage: emptyCoverage(),
@@ -377283,24 +377315,24 @@ function hydrateProposalChange(change, record8) {
377283
377315
  case "archive":
377284
377316
  return { ...base, disposition: "archive", archiveReason: change.archiveReason };
377285
377317
  }
377286
- const content = renderedCandidateContent(candidate, record8);
377318
+ const content = renderedCandidateContent(candidate, record9);
377287
377319
  return content === null ? null : { ...candidate, renderedTokens: estimatedTextTokens(content) };
377288
377320
  }
377289
377321
  function hydrateMemoryCompilationProposal(proposal, input, mutableRecords) {
377290
- const recordById = new Map(input.candidates.map((record8) => [record8.id, record8]));
377291
- const mutableIds = new Set(mutableRecords.map((record8) => record8.id));
377322
+ const recordById = new Map(input.candidates.map((record9) => [record9.id, record9]));
377323
+ const mutableIds = new Set(mutableRecords.map((record9) => record9.id));
377292
377324
  const returnedIds = new Set(proposal.changes.map((change) => change.id));
377293
377325
  if (returnedIds.size !== proposal.changes.length) {
377294
377326
  return { plan: null, invalidOutputDetail: "duplicate_candidate_id" };
377295
377327
  }
377296
377328
  for (const id5 of returnedIds) {
377297
- const record8 = recordById.get(id5);
377298
- if (!record8)
377329
+ const record9 = recordById.get(id5);
377330
+ if (!record9)
377299
377331
  return { plan: null, invalidOutputDetail: "unknown_candidate_id" };
377300
377332
  if (!mutableIds.has(id5)) {
377301
377333
  return {
377302
377334
  plan: null,
377303
- invalidOutputDetail: record8.authority === "system" || record8.authority === "user" ? "locked_candidate_id" : "unknown_candidate_id"
377335
+ invalidOutputDetail: record9.authority === "system" || record9.authority === "user" ? "locked_candidate_id" : "unknown_candidate_id"
377304
377336
  };
377305
377337
  }
377306
377338
  }
@@ -377313,15 +377345,15 @@ function hydrateMemoryCompilationProposal(proposal, input, mutableRecords) {
377313
377345
  return { plan: null, invalidOutputDetail: "schema_invalid" };
377314
377346
  }
377315
377347
  const changedById = new Map(proposal.changes.map((change) => [change.id, change]));
377316
- const candidates = input.candidates.map((record8) => {
377317
- const change = changedById.get(record8.id);
377318
- return change ? hydrateProposalChange(change, record8) : trustedRetainFullCandidate(record8, record8.authority === "system" || record8.authority === "user" ? "Trusted host policy preserves system and user authority in full." : "Sparse compiler proposal omitted this candidate; trusted host policy preserves it in full.");
377348
+ const candidates = input.candidates.map((record9) => {
377349
+ const change = changedById.get(record9.id);
377350
+ return change ? hydrateProposalChange(change, record9) : trustedRetainFullCandidate(record9, record9.authority === "system" || record9.authority === "user" ? "Trusted host policy preserves system and user authority in full." : "Sparse compiler proposal omitted this candidate; trusted host policy preserves it in full.");
377319
377351
  });
377320
377352
  if (candidates.some((candidate) => candidate === null)) {
377321
377353
  return { plan: null, invalidOutputDetail: "schema_invalid" };
377322
377354
  }
377323
377355
  const hydrated = candidates;
377324
- const originalCandidateTokens = input.candidates.reduce((total, record8) => total + estimatedRecordTokens(record8), 0);
377356
+ const originalCandidateTokens = input.candidates.reduce((total, record9) => total + estimatedRecordTokens(record9), 0);
377325
377357
  const fixedTokens = Math.max(0, auditInputEstimate(input.budget) - originalCandidateTokens);
377326
377358
  const renderedTokens = hydrated.reduce((total, candidate) => total + candidate.renderedTokens, 0);
377327
377359
  return {
@@ -377338,20 +377370,20 @@ function hydrateMemoryCompilationProposal(proposal, input, mutableRecords) {
377338
377370
  }
377339
377371
  };
377340
377372
  }
377341
- function trustedRetainFullCandidate(record8, rationale = "Trusted host policy preserves this candidate in full.") {
377342
- const contentHash2 = canonicalArtifactContentHash(record8);
377343
- const artifact = isArtifactRecord(record8) ? {
377373
+ function trustedRetainFullCandidate(record9, rationale = "Trusted host policy preserves this candidate in full.") {
377374
+ const contentHash2 = canonicalArtifactContentHash(record9);
377375
+ const artifact = isArtifactRecord(record9) ? {
377344
377376
  artifactUri: `omnius-artifact://sha256/${contentHash2}`,
377345
377377
  contentHash: contentHash2,
377346
- ...record8.provenance.sourceUri ? { sourceUri: record8.provenance.sourceUri } : {},
377347
- ...record8.provenance.sourceRevision ? { sourceRevision: record8.provenance.sourceRevision } : {},
377348
- ...record8.provenance.sourceRange ? { sourceRange: record8.provenance.sourceRange } : {}
377378
+ ...record9.provenance.sourceUri ? { sourceUri: record9.provenance.sourceUri } : {},
377379
+ ...record9.provenance.sourceRevision ? { sourceRevision: record9.provenance.sourceRevision } : {},
377380
+ ...record9.provenance.sourceRange ? { sourceRange: record9.provenance.sourceRange } : {}
377349
377381
  } : void 0;
377350
377382
  return {
377351
- id: record8.id,
377383
+ id: record9.id,
377352
377384
  disposition: "retain_full",
377353
377385
  rationale,
377354
- renderedTokens: estimatedRecordTokens(record8),
377386
+ renderedTokens: estimatedRecordTokens(record9),
377355
377387
  coverage: {
377356
377388
  claimIds: [],
377357
377389
  requirementIds: [],
@@ -377370,7 +377402,7 @@ function hold(reasons3, retainedIds = /* @__PURE__ */ new Set()) {
377370
377402
  };
377371
377403
  }
377372
377404
  function validateMemoryDelta(input) {
377373
- const candidateIds = new Set(input.candidateRecords.map((record8) => record8.id));
377405
+ const candidateIds = new Set(input.candidateRecords.map((record9) => record9.id));
377374
377406
  const retainedIds = new Set(input.delta.retain);
377375
377407
  const archivedIds = new Set(input.delta.archive.map((entry) => entry.id));
377376
377408
  if (input.delta.decision !== "compact")
@@ -377396,11 +377428,11 @@ function validateMemoryDelta(input) {
377396
377428
  }
377397
377429
  if ([...retainedIds].some((id5) => archivedIds.has(id5)))
377398
377430
  return hold(["record cannot be retained and archived together"], retainedIds);
377399
- const candidateById = new Map(input.candidateRecords.map((record8) => [record8.id, record8]));
377431
+ const candidateById = new Map(input.candidateRecords.map((record9) => [record9.id, record9]));
377400
377432
  if (input.delta.unresolvedClaims.some((id5) => candidateById.get(id5)?.kind !== "claim")) {
377401
377433
  return hold(["unresolved claims must reference known claim records"], retainedIds);
377402
377434
  }
377403
- const protectedAuthority = input.candidateRecords.filter((record8) => (record8.authority === "system" || record8.authority === "user") && archivedIds.has(record8.id));
377435
+ const protectedAuthority = input.candidateRecords.filter((record9) => (record9.authority === "system" || record9.authority === "user") && archivedIds.has(record9.id));
377404
377436
  if (protectedAuthority.length > 0)
377405
377437
  return hold(["authority records may not be archived"], retainedIds);
377406
377438
  if (input.delta.supersede.some(({ old, next }) => !candidateIds.has(old) || !candidateIds.has(next) || old === next)) {
@@ -377421,8 +377453,8 @@ function validateMemoryDelta(input) {
377421
377453
  archivedIds
377422
377454
  };
377423
377455
  }
377424
- function estimatedRecordTokens(record8) {
377425
- return record8.body.length > 0 ? Math.ceil(record8.body.length / 4) + 4 : 0;
377456
+ function estimatedRecordTokens(record9) {
377457
+ return record9.body.length > 0 ? Math.ceil(record9.body.length / 4) + 4 : 0;
377426
377458
  }
377427
377459
  function auditInputEstimate(budget) {
377428
377460
  return budget.totalInputTokens ?? Math.max(0, budget.projectedTotalTokens - (budget.outputReservationTokens ?? 0) - (budget.safetyMarginTokens ?? 0));
@@ -377439,10 +377471,10 @@ function compactionInputTarget(budget) {
377439
377471
  function memoryCompilationTargetReachability(input) {
377440
377472
  let candidateTokens = 0;
377441
377473
  let lockedTokens = 0;
377442
- for (const record8 of input.candidateRecords) {
377443
- const tokens3 = estimatedConservativeTextTokens(record8.body);
377474
+ for (const record9 of input.candidateRecords) {
377475
+ const tokens3 = estimatedConservativeTextTokens(record9.body);
377444
377476
  candidateTokens += tokens3;
377445
- if (record8.authority === "system" || record8.authority === "user")
377477
+ if (record9.authority === "system" || record9.authority === "user")
377446
377478
  lockedTokens += tokens3;
377447
377479
  }
377448
377480
  const fixedTokens = Math.max(0, compactionInputEstimate(input.budget) - candidateTokens);
@@ -377465,7 +377497,7 @@ function planHold(input, reasons3, candidates = /* @__PURE__ */ new Map()) {
377465
377497
  reasons: reasons3,
377466
377498
  // A rejected plan can never cause a partial materialization. Preserve the
377467
377499
  // entire candidate set until a new exact request is compiled.
377468
- retainedIds: new Set(input.candidateRecords.map((record8) => record8.id)),
377500
+ retainedIds: new Set(input.candidateRecords.map((record9) => record9.id)),
377469
377501
  archivedIds: /* @__PURE__ */ new Set(),
377470
377502
  candidates
377471
377503
  };
@@ -377473,31 +377505,31 @@ function planHold(input, reasons3, candidates = /* @__PURE__ */ new Map()) {
377473
377505
  function uniqueStrings4(values) {
377474
377506
  return new Set(values).size === values.length;
377475
377507
  }
377476
- function isArtifactRecord(record8) {
377477
- return record8.kind === "artifact" || record8.kind === "artifact_extract";
377508
+ function isArtifactRecord(record9) {
377509
+ return record9.kind === "artifact" || record9.kind === "artifact_extract";
377478
377510
  }
377479
- function canonicalArtifactContentHash(record8) {
377480
- const stored = record8.metadata["artifactContentHash"];
377481
- return typeof stored === "string" && SHA2564.test(stored) ? stored.toLowerCase() : record8.contentHash.toLowerCase();
377511
+ function canonicalArtifactContentHash(record9) {
377512
+ const stored = record9.metadata["artifactContentHash"];
377513
+ return typeof stored === "string" && SHA2564.test(stored) ? stored.toLowerCase() : record9.contentHash.toLowerCase();
377482
377514
  }
377483
- function referenceMatchesRecord(reference2, record8) {
377515
+ function referenceMatchesRecord(reference2, record9) {
377484
377516
  const uri = ARTIFACT_URI.exec(reference2.artifactUri);
377485
377517
  if (!uri || uri[1].toLowerCase() !== reference2.contentHash.toLowerCase())
377486
377518
  return "artifact URI is not bound to its declared content hash";
377487
- if (reference2.contentHash.toLowerCase() !== canonicalArtifactContentHash(record8))
377519
+ if (reference2.contentHash.toLowerCase() !== canonicalArtifactContentHash(record9))
377488
377520
  return "artifact reference hash does not match canonical record content";
377489
- if (record8.provenance.sourceUri && reference2.sourceUri !== record8.provenance.sourceUri)
377521
+ if (record9.provenance.sourceUri && reference2.sourceUri !== record9.provenance.sourceUri)
377490
377522
  return "artifact reference source URI does not match canonical provenance";
377491
- if (record8.provenance.sourceRevision && reference2.sourceRevision !== record8.provenance.sourceRevision)
377523
+ if (record9.provenance.sourceRevision && reference2.sourceRevision !== record9.provenance.sourceRevision)
377492
377524
  return "artifact reference revision does not match canonical provenance";
377493
- const canonicalRange = record8.provenance.sourceRange;
377525
+ const canonicalRange = record9.provenance.sourceRange;
377494
377526
  const referencedRange = reference2.sourceRange;
377495
377527
  if (canonicalRange && referencedRange && (referencedRange.start < canonicalRange.start || referencedRange.end > canonicalRange.end)) {
377496
377528
  return "artifact reference source range exceeds canonical provenance";
377497
377529
  }
377498
377530
  return null;
377499
377531
  }
377500
- function validateCandidateRepresentation(candidate, record8, claimRecords) {
377532
+ function validateCandidateRepresentation(candidate, record9, claimRecords) {
377501
377533
  if (!candidate.rationale.trim())
377502
377534
  return `candidate ${candidate.id} has no rationale`;
377503
377535
  if (!uniqueStrings4(candidate.coverage.claimIds) || !uniqueStrings4(candidate.coverage.requirementIds) || !uniqueStrings4(candidate.coverage.unresolvedRequirementIds)) {
@@ -377509,18 +377541,18 @@ function validateCandidateRepresentation(candidate, record8, claimRecords) {
377509
377541
  if (candidate.coverage.claimIds.some((id5) => claimRecords.get(id5)?.kind !== "claim")) {
377510
377542
  return `candidate ${candidate.id} coverage references an unknown claim`;
377511
377543
  }
377512
- const sourceRange = record8.provenance.sourceRange;
377544
+ const sourceRange = record9.provenance.sourceRange;
377513
377545
  if (candidate.spans?.some((span) => sourceRange && (span.start < sourceRange.start || span.end > sourceRange.end))) {
377514
377546
  return `candidate ${candidate.id} line span exceeds canonical source range`;
377515
377547
  }
377516
- const fullTokens = estimatedRecordTokens(record8);
377548
+ const fullTokens = estimatedRecordTokens(record9);
377517
377549
  if (candidate.renderedTokens > Math.max(fullTokens, 4096) && candidate.disposition !== "compact_summary") {
377518
377550
  return `candidate ${candidate.id} rendered token estimate exceeds bounded representation size`;
377519
377551
  }
377520
- if (isArtifactRecord(record8)) {
377552
+ if (isArtifactRecord(record9)) {
377521
377553
  if (!candidate.artifact)
377522
377554
  return `artifact candidate ${candidate.id} lacks a durable artifact reference`;
377523
- const issue3 = referenceMatchesRecord(candidate.artifact, record8);
377555
+ const issue3 = referenceMatchesRecord(candidate.artifact, record9);
377524
377556
  if (issue3)
377525
377557
  return `candidate ${candidate.id} ${issue3}`;
377526
377558
  } else if (candidate.artifact) {
@@ -377566,7 +377598,7 @@ function validateCandidateRepresentation(candidate, record8, claimRecords) {
377566
377598
  }
377567
377599
  }
377568
377600
  function validateMemoryCompilationPlan(input) {
377569
- const candidateById = new Map(input.candidateRecords.map((record8) => [record8.id, record8]));
377601
+ const candidateById = new Map(input.candidateRecords.map((record9) => [record9.id, record9]));
377570
377602
  const planById = new Map(input.plan.candidates.map((candidate) => [candidate.id, candidate]));
377571
377603
  if (input.plan.schemaVersion !== 2)
377572
377604
  return planHold(input, ["memory compilation plan schema version is unsupported"], planById);
@@ -377586,11 +377618,11 @@ function validateMemoryCompilationPlan(input) {
377586
377618
  if (typeof input.plan.orientation === "string" && input.plan.orientation.length > 4e3)
377587
377619
  return planHold(input, ["orientation exceeds bounded working-set limit"], planById);
377588
377620
  for (const [id5, candidate] of planById) {
377589
- const record8 = candidateById.get(id5);
377590
- const issue3 = validateCandidateRepresentation(candidate, record8, candidateById);
377621
+ const record9 = candidateById.get(id5);
377622
+ const issue3 = validateCandidateRepresentation(candidate, record9, candidateById);
377591
377623
  if (issue3)
377592
377624
  return planHold(input, [issue3], planById);
377593
- if ((record8.authority === "system" || record8.authority === "user") && candidate.disposition !== "retain_full") {
377625
+ if ((record9.authority === "system" || record9.authority === "user") && candidate.disposition !== "retain_full") {
377594
377626
  return planHold(input, [`authority record ${id5} must be retained in full`], planById);
377595
377627
  }
377596
377628
  }
@@ -377599,7 +377631,7 @@ function validateMemoryCompilationPlan(input) {
377599
377631
  if (input.plan.supersede.some(({ old, next }) => !candidateById.has(old) || !candidateById.has(next) || old === next || planById.get(old)?.disposition !== "archive" || planById.get(old)?.archiveReason !== "superseded" || planById.get(next)?.disposition === "archive")) {
377600
377632
  return planHold(input, ["supersession must retire a known superseded record and retain its replacement"], planById);
377601
377633
  }
377602
- const candidateTokens = input.candidateRecords.reduce((total, record8) => total + estimatedRecordTokens(record8), 0);
377634
+ const candidateTokens = input.candidateRecords.reduce((total, record9) => total + estimatedRecordTokens(record9), 0);
377603
377635
  const fixedTokens = Math.max(0, auditInputEstimate(input.budget) - candidateTokens);
377604
377636
  const renderedTokens = [...planById.values()].reduce((total, candidate) => total + candidate.renderedTokens, 0);
377605
377637
  const computedPostCompactionTokens = fixedTokens + renderedTokens;
@@ -377615,7 +377647,7 @@ function validateMemoryCompilationPlan(input) {
377615
377647
  if (archivedIds.size === 0 && [...planById.values()].every((candidate) => candidate.disposition === "retain_full")) {
377616
377648
  return planHold(input, ["compact decision does not change any candidate representation"], planById);
377617
377649
  }
377618
- const conservativeCandidateTokens = input.candidateRecords.reduce((total, record8) => total + estimatedConservativeTextTokens(record8.body), 0);
377650
+ const conservativeCandidateTokens = input.candidateRecords.reduce((total, record9) => total + estimatedConservativeTextTokens(record9.body), 0);
377619
377651
  const conservativeFixedTokens = Math.max(0, compactionInputEstimate(input.budget) - conservativeCandidateTokens);
377620
377652
  const conservativeRenderedTokens = [...planById.values()].reduce((total, candidate) => {
377621
377653
  const content = renderedCandidateContent(candidate, candidateById.get(candidate.id));
@@ -378201,27 +378233,27 @@ function normalizeFailureDiagnosis(value) {
378201
378233
  kind: kind ?? patternKey?.match(/^[^:]+:(.+)$/)?.[1]
378202
378234
  };
378203
378235
  }
378204
- function diagnoseContextDump(record8) {
378236
+ function diagnoseContextDump(record9) {
378205
378237
  const diagnoses = /* @__PURE__ */ new Set();
378206
- if (record8.focusSupervisor?.directive?.requiredNextAction) {
378238
+ if (record9.focusSupervisor?.directive?.requiredNextAction) {
378207
378239
  diagnoses.add("focus-supervisor-active");
378208
378240
  }
378209
- if (record8.focusSupervisor?.lastDecision === "block_tool_call") {
378241
+ if (record9.focusSupervisor?.lastDecision === "block_tool_call") {
378210
378242
  diagnoses.add("focus-supervisor-block");
378211
378243
  }
378212
- if (record8.metrics.rawDiscoveryToolChars > 0 && (record8.metrics.signalToNoise.ratio ?? 999) < 1) {
378244
+ if (record9.metrics.rawDiscoveryToolChars > 0 && (record9.metrics.signalToNoise.ratio ?? 999) < 1) {
378213
378245
  diagnoses.add("raw-discovery-dominates-context");
378214
378246
  }
378215
- if (record8.metrics.estimatedTokens > 1e5) {
378247
+ if (record9.metrics.estimatedTokens > 1e5) {
378216
378248
  diagnoses.add("large-context-window");
378217
378249
  }
378218
- if (hasToolResultBindingMismatch(record8)) {
378250
+ if (hasToolResultBindingMismatch(record9)) {
378219
378251
  diagnoses.add("tool-result-binding-mismatch");
378220
378252
  }
378221
378253
  return [...diagnoses].sort();
378222
378254
  }
378223
- function hasToolResultBindingMismatch(record8) {
378224
- const messages = Array.isArray(record8.request?.["messages"]) ? record8.request["messages"] : [];
378255
+ function hasToolResultBindingMismatch(record9) {
378256
+ const messages = Array.isArray(record9.request?.["messages"]) ? record9.request["messages"] : [];
378225
378257
  if (messages.length === 0)
378226
378258
  return false;
378227
378259
  const callsById = /* @__PURE__ */ new Map();
@@ -378305,13 +378337,13 @@ function summarizeToolEvent(toolName, success, diagnoses, command) {
378305
378337
  parts.push(`command=${trim(command, 180)}`);
378306
378338
  return parts.join(" | ");
378307
378339
  }
378308
- function summarizeContextDump(record8, diagnoses) {
378340
+ function summarizeContextDump(record9, diagnoses) {
378309
378341
  const parts = [
378310
- `context dump ${record8.stage}`,
378311
- `tokens~${record8.metrics.estimatedTokens}`
378342
+ `context dump ${record9.stage}`,
378343
+ `tokens~${record9.metrics.estimatedTokens}`
378312
378344
  ];
378313
- if (record8.focusSupervisor?.directive?.requiredNextAction) {
378314
- parts.push(`required=${record8.focusSupervisor.directive.requiredNextAction}`);
378345
+ if (record9.focusSupervisor?.directive?.requiredNextAction) {
378346
+ parts.push(`required=${record9.focusSupervisor.directive.requiredNextAction}`);
378315
378347
  }
378316
378348
  if (diagnoses.length > 0)
378317
378349
  parts.push(`diagnoses=${diagnoses.join(",")}`);
@@ -378522,7 +378554,7 @@ function shortHash5(value) {
378522
378554
 
378523
378555
  // packages/orchestrator/dist/modelResponseDiagnostics.js
378524
378556
  var MAX_COUNT = 1e9;
378525
- function record7(value) {
378557
+ function record8(value) {
378526
378558
  return value !== null && typeof value === "object" && !Array.isArray(value);
378527
378559
  }
378528
378560
  function count(value) {
@@ -378563,7 +378595,7 @@ function nativeMetrics(value, wire = false) {
378563
378595
  return Object.keys(result).length ? result : void 0;
378564
378596
  }
378565
378597
  function transportMetadata(value) {
378566
- if (!record7(value))
378598
+ if (!record8(value))
378567
378599
  return void 0;
378568
378600
  const physicalRequestId = identifier2(value.physicalRequestId);
378569
378601
  if (!physicalRequestId)
@@ -378632,11 +378664,11 @@ var NativeModelResponseDiagnostics = class {
378632
378664
  }
378633
378665
  observe(frame) {
378634
378666
  try {
378635
- if (!record7(frame))
378667
+ if (!record8(frame))
378636
378668
  return;
378637
378669
  this.value.frameCount = boundedCount(this.value.frameCount + 1);
378638
378670
  const message = frame.message;
378639
- if (record7(message)) {
378671
+ if (record8(message)) {
378640
378672
  this.value.messageFrames = boundedCount(this.value.messageFrames + 1);
378641
378673
  if (typeof message.content === "string")
378642
378674
  this.value.contentChars = boundedCount(this.value.contentChars + message.content.length);
@@ -378676,7 +378708,7 @@ var NativeModelResponseDiagnostics = class {
378676
378708
  function modelResponseDiagnosticReceipt(input) {
378677
378709
  try {
378678
378710
  const value = input.diagnostics;
378679
- if (!record7(value) || value.schema !== "omnius.model-response-diagnostics.v1" || value.transport !== "ollama-native" || value.mode !== "unary" && value.mode !== "stream" || value.logicalRequestId !== input.logicalRequestId || !identifier2(input.runId) || count(input.taskEpoch) === void 0 || count(input.turn) === void 0 || count(input.visibleChars) === void 0 || count(input.normalizedToolCalls) === void 0)
378711
+ if (!record8(value) || value.schema !== "omnius.model-response-diagnostics.v1" || value.transport !== "ollama-native" || value.mode !== "unary" && value.mode !== "stream" || value.logicalRequestId !== input.logicalRequestId || !identifier2(input.runId) || count(input.taskEpoch) === void 0 || count(input.turn) === void 0 || count(input.visibleChars) === void 0 || count(input.normalizedToolCalls) === void 0)
378680
378712
  return void 0;
378681
378713
  const frameCount = count(value.frameCount);
378682
378714
  const messageFrames = count(value.messageFrames);
@@ -378685,8 +378717,8 @@ function modelResponseDiagnosticReceipt(input) {
378685
378717
  const rawToolCallEntries = count(value.rawToolCallEntries);
378686
378718
  if (frameCount === void 0 || messageFrames === void 0 || contentChars === void 0 || thinkingChars === void 0 || rawToolCallEntries === void 0 || messageFrames > frameCount || typeof value.done !== "boolean")
378687
378719
  return void 0;
378688
- const usage = record7(value.usage) && count(value.usage.promptTokens) !== void 0 && count(value.usage.completionTokens) !== void 0 && count(value.usage.totalTokens) !== void 0 ? { promptTokens: value.usage.promptTokens, completionTokens: value.usage.completionTokens, totalTokens: value.usage.totalTokens } : void 0;
378689
- const metrics = value.done && record7(value.nativeMetrics) ? nativeMetrics(value.nativeMetrics) : void 0;
378720
+ const usage = record8(value.usage) && count(value.usage.promptTokens) !== void 0 && count(value.usage.completionTokens) !== void 0 && count(value.usage.totalTokens) !== void 0 ? { promptTokens: value.usage.promptTokens, completionTokens: value.usage.completionTokens, totalTokens: value.usage.totalTokens } : void 0;
378721
+ const metrics = value.done && record8(value.nativeMetrics) ? nativeMetrics(value.nativeMetrics) : void 0;
378690
378722
  const transport = transportMetadata(value.requestTrace);
378691
378723
  if (transport && !value.done)
378692
378724
  delete transport.doneObservedMonotonicMs;
@@ -384689,11 +384721,11 @@ function ollamaNativeFormatFromResponseFormat(value) {
384689
384721
  if (!value || typeof value !== "object" || Array.isArray(value)) {
384690
384722
  return void 0;
384691
384723
  }
384692
- const record8 = value;
384693
- if (record8["type"] === "json_object")
384724
+ const record9 = value;
384725
+ if (record9["type"] === "json_object")
384694
384726
  return "json";
384695
- if (record8["type"] === "json_schema") {
384696
- const jsonSchema = record8["json_schema"];
384727
+ if (record9["type"] === "json_schema") {
384728
+ const jsonSchema = record9["json_schema"];
384697
384729
  if (jsonSchema && typeof jsonSchema === "object" && !Array.isArray(jsonSchema)) {
384698
384730
  const schemaRecord = jsonSchema;
384699
384731
  const nestedSchema = schemaRecord["schema"];
@@ -384706,8 +384738,8 @@ function ollamaNativeFormatFromResponseFormat(value) {
384706
384738
  }
384707
384739
  return "json";
384708
384740
  }
384709
- if (record8["type"] === "object" || record8["properties"] !== void 0) {
384710
- return record8;
384741
+ if (record9["type"] === "object" || record9["properties"] !== void 0) {
384742
+ return record9;
384711
384743
  }
384712
384744
  return void 0;
384713
384745
  }
@@ -388021,7 +388053,7 @@ ${renderTaskExecutionSnapshot(snapshot)}` } : projected;
388021
388053
  const stateDir = this.omniusStateDir();
388022
388054
  const reportEvidenceReference = this._conversationReportEvidence?.persist();
388023
388055
  const reportLedger = this._completionLedger ?? this._conversationReportEvidence?.ledger ?? null;
388024
- const record8 = {
388056
+ const record9 = {
388025
388057
  ...buildCompletionFinalizationRecord({
388026
388058
  runId: this.currentArtifactRunId(),
388027
388059
  taskEpoch: this._taskEpoch,
@@ -388046,16 +388078,16 @@ ${renderTaskExecutionSnapshot(snapshot)}` } : projected;
388046
388078
  }),
388047
388079
  ...reportEvidenceReference ? { reportEvidenceReference } : {}
388048
388080
  };
388049
- const markerPath = completionFinalizationPath(stateDir, record8.runId);
388050
- prepareCompletionFinalization(stateDir, record8);
388081
+ const markerPath = completionFinalizationPath(stateDir, record9.runId);
388082
+ prepareCompletionFinalization(stateDir, record9);
388051
388083
  if (this._completionLedger) {
388052
388084
  this._completionLedger = {
388053
388085
  ...this._completionLedger,
388054
388086
  terminal: {
388055
- receiptId: record8.id,
388087
+ receiptId: record9.id,
388056
388088
  status: input.status,
388057
- committedAtIso: record8.committedAtIso,
388058
- evidenceIds: record8.evidenceIds
388089
+ committedAtIso: record9.committedAtIso,
388090
+ evidenceIds: record9.evidenceIds
388059
388091
  }
388060
388092
  };
388061
388093
  }
@@ -388069,14 +388101,14 @@ ${renderTaskExecutionSnapshot(snapshot)}` } : projected;
388069
388101
  actor: "runner",
388070
388102
  taskEpoch: this._taskEpoch,
388071
388103
  status: boardCanComplete ? "completed" : "archived",
388072
- terminalReceiptId: record8.id,
388104
+ terminalReceiptId: record9.id,
388073
388105
  terminalSummary: input.summary.slice(0, 1200),
388074
388106
  artifactEvidence: [
388075
388107
  {
388076
388108
  kind: "note",
388077
388109
  summary: `terminal ${input.status} committed`,
388078
388110
  ref: markerPath,
388079
- verifies: record8.evidenceIds
388111
+ verifies: record9.evidenceIds
388080
388112
  }
388081
388113
  ]
388082
388114
  });
@@ -388089,34 +388121,34 @@ ${renderTaskExecutionSnapshot(snapshot)}` } : projected;
388089
388121
  turn: this._taskState.toolCallCount,
388090
388122
  toolName: "task_complete",
388091
388123
  args: {
388092
- terminalReceiptId: record8.id,
388124
+ terminalReceiptId: record9.id,
388093
388125
  status: input.status,
388094
388126
  runtime: {
388095
- package: record8.runtimeProvenance.package.name,
388096
- version: record8.runtimeProvenance.package.version,
388097
- packageManifestSha256: record8.runtimeProvenance.package.manifestSha256,
388098
- moduleSha256: record8.runtimeProvenance.module.sha256
388127
+ package: record9.runtimeProvenance.package.name,
388128
+ version: record9.runtimeProvenance.package.version,
388129
+ packageManifestSha256: record9.runtimeProvenance.package.manifestSha256,
388130
+ moduleSha256: record9.runtimeProvenance.module.sha256
388099
388131
  }
388100
388132
  },
388101
388133
  success: input.status === "completed",
388102
- output: `terminal_receipt=${record8.id}
388134
+ output: `terminal_receipt=${record9.id}
388103
388135
  marker=${markerPath}
388104
388136
  readiness_hash=${input.completionReadiness.readinessHash}
388105
388137
  completion_disposition=${input.completionReadiness.disposition}
388106
- verification_audit=${record8.verificationAudit?.status ?? "no_observed_gap"}
388107
- verification_audit_gaps=${record8.verificationAudit?.gaps.map((gap) => `${gap.id}:${gap.source}`).join(",") || "none"}
388138
+ verification_audit=${record9.verificationAudit?.status ?? "no_observed_gap"}
388139
+ verification_audit_gaps=${record9.verificationAudit?.gaps.map((gap) => `${gap.id}:${gap.source}`).join(",") || "none"}
388108
388140
  unresolved=${input.completionReadiness.unresolvedIds.join(",") || "none"}
388109
- evidence=${record8.evidenceIds.join(",") || "none"}
388110
- command_receipts=${record8.commandReceipts.length}
388111
- ` + (record8.commandReceipts.length > 0 ? `command_receipts_summary=${record8.commandReceipts.map((entry) => `${entry.canonicalCommand || entry.command || "n/a"}:${entry.exitCode}`).join(" | ")}
388112
- ` : "command_receipts_summary=none\n") + `runtime_package=${record8.runtimeProvenance.package.name ?? "unknown"}@${record8.runtimeProvenance.package.version ?? "unknown"}
388113
- runtime_package_sha256=${record8.runtimeProvenance.package.manifestSha256 ?? "unknown"}
388114
- runtime_module=${record8.runtimeProvenance.module.path}
388115
- runtime_module_sha256=${record8.runtimeProvenance.module.sha256 ?? "unknown"}`
388141
+ evidence=${record9.evidenceIds.join(",") || "none"}
388142
+ command_receipts=${record9.commandReceipts.length}
388143
+ ` + (record9.commandReceipts.length > 0 ? `command_receipts_summary=${record9.commandReceipts.map((entry) => `${entry.canonicalCommand || entry.command || "n/a"}:${entry.exitCode}`).join(" | ")}
388144
+ ` : "command_receipts_summary=none\n") + `runtime_package=${record9.runtimeProvenance.package.name ?? "unknown"}@${record9.runtimeProvenance.package.version ?? "unknown"}
388145
+ runtime_package_sha256=${record9.runtimeProvenance.package.manifestSha256 ?? "unknown"}
388146
+ runtime_module=${record9.runtimeProvenance.module.path}
388147
+ runtime_module_sha256=${record9.runtimeProvenance.module.sha256 ?? "unknown"}`
388116
388148
  });
388117
- commitTerminalTrajectoryProjection(stateDir, record8, input.trajectoryPayload);
388149
+ commitTerminalTrajectoryProjection(stateDir, record9, input.trajectoryPayload);
388118
388150
  const committed = {
388119
- ...record8,
388151
+ ...record9,
388120
388152
  phase: "committed",
388121
388153
  projections: {
388122
388154
  ledger: "committed",
@@ -388828,7 +388860,7 @@ runtime_module_sha256=${record8.runtimeProvenance.module.sha256 ?? "unknown"}`
388828
388860
  } catch {
388829
388861
  }
388830
388862
  }
388831
- const record8 = ledger.appendRecord({
388863
+ const record9 = ledger.appendRecord({
388832
388864
  id: id5,
388833
388865
  epoch: epoch2,
388834
388866
  kind: isToolArtifact ? "artifact" : "orientation",
@@ -388857,18 +388889,18 @@ runtime_module_sha256=${record8.runtimeProvenance.module.sha256 ?? "unknown"}`
388857
388889
  }
388858
388890
  });
388859
388891
  for (const activeRecord of activeByBodyHash.get(bodyHash) ?? []) {
388860
- if (activeRecord.id === record8.id)
388892
+ if (activeRecord.id === record9.id)
388861
388893
  continue;
388862
388894
  ledger.linkDependency({
388863
388895
  // Working-set closure follows source → target. The durable
388864
388896
  // evidence therefore points to this request-local projection.
388865
388897
  sourceRecordId: activeRecord.id,
388866
- targetRecordId: record8.id,
388898
+ targetRecordId: record9.id,
388867
388899
  relation: "derived_from",
388868
388900
  requiredForActiveWork: true
388869
388901
  });
388870
388902
  }
388871
- candidates.push({ record: record8, messageIndex });
388903
+ candidates.push({ record: record9, messageIndex });
388872
388904
  }
388873
388905
  return candidates;
388874
388906
  } catch {
@@ -389272,16 +389304,16 @@ ${read.content}`;
389272
389304
  const stateFingerprint = _createHash("sha256").update(JSON.stringify({
389273
389305
  requestFingerprint: budget.requestFingerprint,
389274
389306
  workingSetFingerprint: workingSet.fingerprint,
389275
- candidates: candidates.map((record8) => [
389276
- record8.id,
389277
- record8.contentHash,
389278
- record8.validUntil ?? null
389307
+ candidates: candidates.map((record9) => [
389308
+ record9.id,
389309
+ record9.contentHash,
389310
+ record9.validUntil ?? null
389279
389311
  ])
389280
389312
  })).digest("hex");
389281
389313
  const cached = this._memoryCompilerShadowCache.get(stateFingerprint);
389282
389314
  if (cached)
389283
389315
  return { ...cached, cacheHit: true };
389284
- const candidateChars = candidates.reduce((total, record8) => total + record8.body.length, 0);
389316
+ const candidateChars = candidates.reduce((total, record9) => total + record9.body.length, 0);
389285
389317
  const maxCandidateChars = Math.max(32e3, Math.floor(budget.modelContextTokens * 4 * 0.45));
389286
389318
  if (candidates.length === 0 || candidateChars > maxCandidateChars) {
389287
389319
  const audit2 = {
@@ -389290,7 +389322,7 @@ ${read.content}`;
389290
389322
  decision: "hold",
389291
389323
  accepted: false,
389292
389324
  cacheHit: false,
389293
- candidateRecordIds: candidates.map((record8) => record8.id),
389325
+ candidateRecordIds: candidates.map((record9) => record9.id),
389294
389326
  activeRecordIds,
389295
389327
  reason: candidates.length === 0 ? "no current records to classify" : `whole candidate bodies require ${candidateChars} chars; isolated compiler budget is ${maxCandidateChars} chars`
389296
389328
  };
@@ -389314,7 +389346,7 @@ ${read.content}`;
389314
389346
  decision: validation?.appliedDecision ?? "hold",
389315
389347
  accepted: validation?.accepted ?? false,
389316
389348
  cacheHit: false,
389317
- candidateRecordIds: candidates.map((record8) => record8.id),
389349
+ candidateRecordIds: candidates.map((record9) => record9.id),
389318
389350
  activeRecordIds,
389319
389351
  ...validation ? {
389320
389352
  retainedRecordIds: [...validation.retainedIds].sort(),
@@ -389373,7 +389405,7 @@ ${read.content}`;
389373
389405
  return {
389374
389406
  epoch: String(this._taskEpoch),
389375
389407
  rootRecordIds: activeRecordIds.sort(),
389376
- recordIds: materialized.records.map((record8) => record8.id),
389408
+ recordIds: materialized.records.map((record9) => record9.id),
389377
389409
  transactionIds: materialized.transactionIds,
389378
389410
  fingerprint: materialized.fingerprint
389379
389411
  };
@@ -391301,7 +391333,7 @@ ${workflowStatus}` } : {}
391301
391333
  finalRequestFingerprint: exactBudget.requestFingerprint,
391302
391334
  finalProjectionChanged: (compilationAudit.postRequestFingerprint ?? compilationAudit.preRequestFingerprint) !== exactBudget.requestFingerprint
391303
391335
  } : void 0;
391304
- const record8 = recordContextWindowDump({
391336
+ const record9 = recordContextWindowDump({
391305
391337
  source: "agenticRunner",
391306
391338
  stage: stage2,
391307
391339
  agentType,
@@ -391316,8 +391348,8 @@ ${workflowStatus}` } : {}
391316
391348
  focusSupervisor: this._focusSupervisor?.snapshot(),
391317
391349
  requestCompilation: this._referenceContractCompilation(memoryCompilerShadow, planAuditApplies)
391318
391350
  });
391319
- if (record8)
391320
- this._lastOutboundRequestBudget = record8.requestBudget;
391351
+ if (record9)
391352
+ this._lastOutboundRequestBudget = record9.requestBudget;
391321
391353
  else
391322
391354
  this._lastOutboundRequestBudget = exactBudget;
391323
391355
  if (memoryCompilerShadow) {
@@ -391355,14 +391387,14 @@ ${workflowStatus}` } : {}
391355
391387
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
391356
391388
  });
391357
391389
  }
391358
- if (record8) {
391390
+ if (record9) {
391359
391391
  const focusSnapshot = {
391360
- estimatedTokens: record8.metrics.estimatedTokens,
391361
- rawDiscoveryChars: record8.metrics.rawDiscoveryToolChars,
391362
- activeEvidenceChars: record8.metrics.activeEvidenceChars,
391363
- activeFrameChars: record8.metrics.activeContextFrameChars,
391364
- signalToNoiseRatio: record8.metrics.signalToNoise.ratio,
391365
- pressureRatio: this._lastContextPressureSnapshot?.rawRatio ?? (this.options.contextWindowSize ? record8.metrics.estimatedTokens / this.options.contextWindowSize : 0),
391392
+ estimatedTokens: record9.metrics.estimatedTokens,
391393
+ rawDiscoveryChars: record9.metrics.rawDiscoveryToolChars,
391394
+ activeEvidenceChars: record9.metrics.activeEvidenceChars,
391395
+ activeFrameChars: record9.metrics.activeContextFrameChars,
391396
+ signalToNoiseRatio: record9.metrics.signalToNoise.ratio,
391397
+ pressureRatio: this._lastContextPressureSnapshot?.rawRatio ?? (this.options.contextWindowSize ? record9.metrics.estimatedTokens / this.options.contextWindowSize : 0),
391366
391398
  droppedSignals: this._lastContextFrameDiagnostics?.droppedSignals ?? this._lastContextPressureSnapshot?.droppedSignals,
391367
391399
  truncatedSignals: this._lastContextFrameDiagnostics?.truncatedSignals ?? this._lastContextPressureSnapshot?.truncatedSignals
391368
391400
  };
@@ -391374,12 +391406,12 @@ ${workflowStatus}` } : {}
391374
391406
  stateDir: this.omniusStateDir(),
391375
391407
  runId: this.currentArtifactRunId(),
391376
391408
  sessionId: this._sessionId,
391377
- record: record8
391409
+ record: record9
391378
391410
  });
391379
391411
  } catch {
391380
391412
  }
391381
391413
  }
391382
- return record8?.id ?? null;
391414
+ return record9?.id ?? null;
391383
391415
  }
391384
391416
  /** Refresh exact transport fields after validated memory materialization. */
391385
391417
  _refreshCanonicalTransportTrace(request) {
@@ -391671,8 +391703,8 @@ ${workflowStatus}` } : {}
391671
391703
  epoch: epoch2,
391672
391704
  taskId: this._contextMemoryTaskRecordId
391673
391705
  });
391674
- for (const record8 of [action, call2, result])
391675
- ledger.attachTransactionRecord(transaction.id, record8.id);
391706
+ for (const record9 of [action, call2, result])
391707
+ ledger.attachTransactionRecord(transaction.id, record9.id);
391676
391708
  ledger.linkDependency({
391677
391709
  sourceRecordId: action.id,
391678
391710
  targetRecordId: this._contextMemoryTaskRecordId,
@@ -391959,13 +391991,13 @@ ${workflowStatus}` } : {}
391959
391991
  for (const raw of parsed["receipts"].slice(-128)) {
391960
391992
  if (!raw || typeof raw !== "object")
391961
391993
  continue;
391962
- const record8 = raw;
391963
- const transactionId2 = String(record8["transactionId"] ?? "").trim();
391964
- const toolName = String(record8["toolName"] ?? "").trim();
391965
- const artifactLocator = String(record8["artifactLocator"] ?? "").trim();
391966
- const evidenceId = String(record8["evidenceId"] ?? "").trim();
391967
- const summary = String(record8["summary"] ?? "").trim();
391968
- const turn = Number(record8["turn"]);
391994
+ const record9 = raw;
391995
+ const transactionId2 = String(record9["transactionId"] ?? "").trim();
391996
+ const toolName = String(record9["toolName"] ?? "").trim();
391997
+ const artifactLocator = String(record9["artifactLocator"] ?? "").trim();
391998
+ const evidenceId = String(record9["evidenceId"] ?? "").trim();
391999
+ const summary = String(record9["summary"] ?? "").trim();
392000
+ const turn = Number(record9["turn"]);
391969
392001
  if (!transactionId2 || !toolName || !artifactLocator || !evidenceId || !summary || !Number.isFinite(turn)) {
391970
392002
  continue;
391971
392003
  }
@@ -392776,10 +392808,10 @@ ${content}`)].join("\n\n");
392776
392808
  includeSuperseded: false,
392777
392809
  maximumCompressionGeneration: 4,
392778
392810
  limit: 1e4
392779
- }).map((record8) => [
392780
- record8.id,
392781
- record8.bodyHash,
392782
- record8.validUntil
392811
+ }).map((record9) => [
392812
+ record9.id,
392813
+ record9.bodyHash,
392814
+ record9.validUntil
392783
392815
  ]))).digest("hex") : "none";
392784
392816
  const semanticKey = _createHash("sha256").update(JSON.stringify({
392785
392817
  scopeId: this._sessionId,
@@ -392948,17 +392980,17 @@ ${content}`)].join("\n\n");
392948
392980
  if (records.length === 0)
392949
392981
  return [];
392950
392982
  const tokenBudget = Math.max(0, Math.min(physicalInputBudget, Math.floor(defaultTokenBudget)));
392951
- const rendered = records.map((record8) => [
392952
- `[${record8.memoryClass.toUpperCase()} id=${record8.id}${record8.canonicalKey ? ` key=${record8.canonicalKey}` : ""} importance=${record8.importance.toFixed(2)}]`,
392953
- record8.body,
392954
- `provenance=${record8.provenance.map((source) => source.chunkId).join(",")}`
392983
+ const rendered = records.map((record9) => [
392984
+ `[${record9.memoryClass.toUpperCase()} id=${record9.id}${record9.canonicalKey ? ` key=${record9.canonicalKey}` : ""} importance=${record9.importance.toFixed(2)}]`,
392985
+ record9.body,
392986
+ `provenance=${record9.provenance.map((source) => source.chunkId).join(",")}`
392955
392987
  ].join("\n"));
392956
392988
  const tokens3 = Math.ceil(rendered.join("\n\n").length / 4);
392957
392989
  if (tokens3 > tokenBudget) {
392958
392990
  this._appendVirtualMemoryReceipt({
392959
392991
  requestId: this._modelTurnRequestId(turn, "virtual-memory"),
392960
392992
  stage: "capacity_error",
392961
- itemIds: records.map((record8) => record8.id),
392993
+ itemIds: records.map((record9) => record9.id),
392962
392994
  tokenDelta: tokens3,
392963
392995
  tokenBudget,
392964
392996
  reason: "active inference-classified pinned state exceeds its physical allocation",
@@ -392992,7 +393024,7 @@ ${content}`)].join("\n\n");
392992
393024
  stage: "pin",
392993
393025
  operation: "PIN",
392994
393026
  toLevel: "L1",
392995
- itemIds: records.map((record8) => record8.id),
393027
+ itemIds: records.map((record9) => record9.id),
392996
393028
  tokenDelta: tokens3,
392997
393029
  tokenBudget,
392998
393030
  reason: "pin active inference-classified constraints and current plan",
@@ -395702,7 +395734,7 @@ ${modelVisible}` : modelVisible || result.error || displayOutput || "";
395702
395734
  this._objectiveVerificationReceipts.set(verification.evidenceId, verification);
395703
395735
  }
395704
395736
  const verificationOnly = input.toolName === "task_complete" && !deliveryReceipt;
395705
- if (verificationOnly && verificationReceipts.length === 0)
395737
+ if (verificationOnly && verificationReceipts.length === 0 && !isCompletionReviewPendingResult(input.toolName, input.result))
395706
395738
  return;
395707
395739
  const realFileMutation = input.realFileMutation ?? this._isRealProjectMutation(input.toolName, input.result);
395708
395740
  const attemptedTargetPaths = this._extractToolTargetPaths(input.toolName, input.args, input.result);
@@ -396449,7 +396481,9 @@ Respond with a short verification section in this shape (example):
396449
396481
  - next: "what you will do next OR the exact todo_write(...) call to update statuses"
396450
396482
  Do NOT call task_complete until all items are marked completed via todo_write.`;
396451
396483
  }
396452
- buildTaskCompleteToolFailureGuard(detail) {
396484
+ buildTaskCompleteToolFailureGuard(detail, pending) {
396485
+ if (isCompletionReviewPendingV1(pending))
396486
+ return completionReviewPendingGuard(pending);
396453
396487
  const trimmed = detail.trim().slice(0, 4e3);
396454
396488
  return [
396455
396489
  `[TASK_COMPLETE BLOCKED BY VERIFICATION]`,
@@ -396461,6 +396495,9 @@ Do NOT call task_complete until all items are marked completed via todo_write.`;
396461
396495
  `Continue the work loop: inspect the failed evidence, make the smallest targeted fix, then rerun the relevant verification. Use the full available verification spectrum for the artifact you changed: static syntax, build/typecheck, tests, service startup, runtime logs, browser/page errors, console output, network failures, screenshots, accessibility/DOM state, and end-to-end user flow checks where applicable. The exact tools are stack-dependent; the standard is objective runtime evidence, not self-report.`
396462
396496
  ].join("\n");
396463
396497
  }
396498
+ taskCompleteToolFailureStatus(pending) {
396499
+ return isCompletionReviewPendingV1(pending) ? "task_complete review pending; retry the retained completion review" : "task_complete blocked by verification guard";
396500
+ }
396464
396501
  buildMissionCompletionContract(task, context) {
396465
396502
  if (this.usesConversationProfile())
396466
396503
  return "";
@@ -398699,7 +398736,7 @@ ${sections.join("\n")}` : sections.join("\n");
398699
398736
  return;
398700
398737
  try {
398701
398738
  const epoch2 = String(this._taskEpoch);
398702
- const actionOrTask = this._contextMemoryActiveRecordIds.map((id5) => ledger.getRecord(id5)).find((record8) => record8?.kind === "action") ?? (this._contextMemoryTaskRecordId ? ledger.getRecord(this._contextMemoryTaskRecordId) : null);
398739
+ const actionOrTask = this._contextMemoryActiveRecordIds.map((id5) => ledger.getRecord(id5)).find((record9) => record9?.kind === "action") ?? (this._contextMemoryTaskRecordId ? ledger.getRecord(this._contextMemoryTaskRecordId) : null);
398703
398740
  if (!actionOrTask || actionOrTask.epoch !== epoch2)
398704
398741
  return;
398705
398742
  for (const path7 of this._evidenceLedger.renderedFullPathsInLastBlock()) {
@@ -398709,7 +398746,7 @@ ${sections.join("\n")}` : sections.join("\n");
398709
398746
  const artifact = this._contextMemoryArtifactByPath.get(path7);
398710
398747
  const sourceRevision = entry.contentHash ?? `v${entry.readVersion}`;
398711
398748
  const id5 = `materialization:${epoch2}:${_createHash("sha256").update(`${actionOrTask.id}\0${path7}\0${sourceRevision}`).digest("hex").slice(0, 24)}`;
398712
- const record8 = ledger.appendRecord({
398749
+ const record9 = ledger.appendRecord({
398713
398750
  id: id5,
398714
398751
  epoch: epoch2,
398715
398752
  kind: "materialization",
@@ -398735,13 +398772,13 @@ ${sections.join("\n")}` : sections.join("\n");
398735
398772
  });
398736
398773
  ledger.linkDependency({
398737
398774
  sourceRecordId: actionOrTask.id,
398738
- targetRecordId: record8.id,
398775
+ targetRecordId: record9.id,
398739
398776
  relation: "requires",
398740
398777
  requiredForActiveWork: true
398741
398778
  });
398742
398779
  if (artifact?.epoch === epoch2) {
398743
398780
  ledger.linkDependency({
398744
- sourceRecordId: record8.id,
398781
+ sourceRecordId: record9.id,
398745
398782
  targetRecordId: artifact.recordId,
398746
398783
  relation: "derived_from",
398747
398784
  requiredForActiveWork: true
@@ -399139,11 +399176,11 @@ ${chunk.content}`, {
399139
399176
  if (typeof result === "boolean")
399140
399177
  return result;
399141
399178
  if (result && typeof result === "object") {
399142
- const record8 = result;
399143
- if (typeof record8["shouldConsolidate"] === "boolean")
399144
- return record8["shouldConsolidate"];
399145
- if (typeof record8["shouldRun"] === "boolean")
399146
- return record8["shouldRun"];
399179
+ const record9 = result;
399180
+ if (typeof record9["shouldConsolidate"] === "boolean")
399181
+ return record9["shouldConsolidate"];
399182
+ if (typeof record9["shouldRun"] === "boolean")
399183
+ return record9["shouldRun"];
399147
399184
  }
399148
399185
  return Boolean(result);
399149
399186
  } catch {
@@ -401663,7 +401700,7 @@ ${notice}`;
401663
401700
  injectSteeringInput(input) {
401664
401701
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
401665
401702
  const content = this.scrubUserInput(input.content, "steering-input").trim();
401666
- const record8 = {
401703
+ const record9 = {
401667
401704
  ...input,
401668
401705
  inputId: input.inputId.trim() || `steering-${Date.now()}-${++this._steeringSequence}`,
401669
401706
  content,
@@ -401673,23 +401710,23 @@ ${notice}`;
401673
401710
  state: "received",
401674
401711
  taskEpoch: input.taskEpoch ?? (this._taskEpoch || void 0)
401675
401712
  };
401676
- this.pendingSteeringInputs.push(record8);
401677
- this._emitSteeringLifecycle(record8, "received by runner");
401713
+ this.pendingSteeringInputs.push(record9);
401714
+ this._emitSteeringLifecycle(record9, "received by runner");
401678
401715
  if (!content) {
401679
- record8.state = "cancelled";
401680
- this._emitSteeringLifecycle(record8, "empty steering input rejected");
401681
- return this._steeringReceipt(record8);
401716
+ record9.state = "cancelled";
401717
+ this._emitSteeringLifecycle(record9, "empty steering input rejected");
401718
+ return this._steeringReceipt(record9);
401682
401719
  }
401683
- record8.state = "queued";
401684
- this._emitSteeringLifecycle(record8, "queued for next safe turn boundary");
401685
- if (steeringGatesOldPlan(record8.intent)) {
401686
- this._selectActiveSteering(record8, this._currentSteeringTurn);
401720
+ record9.state = "queued";
401721
+ this._emitSteeringLifecycle(record9, "queued for next safe turn boundary");
401722
+ if (steeringGatesOldPlan(record9.intent)) {
401723
+ this._selectActiveSteering(record9, this._currentSteeringTurn);
401687
401724
  }
401688
- if (record8.intent === "redirect" || record8.intent === "replace" || record8.intent === "cancel") {
401689
- this._requestSteeringPreemption(record8);
401725
+ if (record9.intent === "redirect" || record9.intent === "replace" || record9.intent === "cancel") {
401726
+ this._requestSteeringPreemption(record9);
401690
401727
  }
401691
401728
  this._trajectoryDirtyCauses.add("user_steering");
401692
- return this._steeringReceipt(record8);
401729
+ return this._steeringReceipt(record9);
401693
401730
  }
401694
401731
  /**
401695
401732
  * Request safe-boundary preemption for an already accepted typed input.
@@ -401700,16 +401737,16 @@ ${notice}`;
401700
401737
  const normalizedInputId = inputId.trim();
401701
401738
  if (!normalizedInputId)
401702
401739
  return null;
401703
- const record8 = this.pendingSteeringInputs.find((candidate) => candidate.inputId === normalizedInputId);
401704
- if (!record8)
401740
+ const record9 = this.pendingSteeringInputs.find((candidate) => candidate.inputId === normalizedInputId);
401741
+ if (!record9)
401705
401742
  return null;
401706
- if (record8.intent !== "redirect" && record8.intent !== "replace" && record8.intent !== "cancel") {
401743
+ if (record9.intent !== "redirect" && record9.intent !== "replace" && record9.intent !== "cancel") {
401707
401744
  return null;
401708
401745
  }
401709
- if (this._pendingSteeringPreemption?.inputId !== record8.inputId) {
401710
- this._requestSteeringPreemption(record8);
401746
+ if (this._pendingSteeringPreemption?.inputId !== record9.inputId) {
401747
+ this._requestSteeringPreemption(record9);
401711
401748
  }
401712
- return this._steeringReceipt(record8);
401749
+ return this._steeringReceipt(record9);
401713
401750
  }
401714
401751
  /**
401715
401752
  * Promote an already queued steering record to the next immediate safe
@@ -401720,24 +401757,24 @@ ${notice}`;
401720
401757
  const normalizedInputId = inputId.trim();
401721
401758
  if (!normalizedInputId)
401722
401759
  return null;
401723
- const record8 = this.pendingSteeringInputs.find((candidate) => candidate.inputId === normalizedInputId);
401724
- if (!record8 || record8.state !== "queued" && record8.state !== "acknowledged") {
401760
+ const record9 = this.pendingSteeringInputs.find((candidate) => candidate.inputId === normalizedInputId);
401761
+ if (!record9 || record9.state !== "queued" && record9.state !== "acknowledged") {
401725
401762
  return null;
401726
401763
  }
401727
- if (record8.intent === "redirect" || record8.intent === "replace" || record8.intent === "cancel") {
401728
- return this.requestSteeringPreemption(record8.inputId);
401764
+ if (record9.intent === "redirect" || record9.intent === "replace" || record9.intent === "cancel") {
401765
+ return this.requestSteeringPreemption(record9.inputId);
401729
401766
  }
401730
- this._immediateSteeringWakeInputId = record8.inputId;
401731
- record8.state = "acknowledged";
401732
- this._emitSteeringLifecycle(record8, "user promoted queued steering to the next immediate safe boundary");
401733
- this._turnAbortController.abort(new Error(`promoted steering boundary: ${record8.inputId}`));
401767
+ this._immediateSteeringWakeInputId = record9.inputId;
401768
+ record9.state = "acknowledged";
401769
+ this._emitSteeringLifecycle(record9, "user promoted queued steering to the next immediate safe boundary");
401770
+ this._turnAbortController.abort(new Error(`promoted steering boundary: ${record9.inputId}`));
401734
401771
  const shellTool = this.tools.get("shell");
401735
401772
  if (shellTool && typeof shellTool.killAll === "function") {
401736
401773
  shellTool.killAll();
401737
401774
  }
401738
401775
  this._turnAbortController = new AbortController();
401739
401776
  this._setBackendTurnAbortSignal(this._turnAbortController.signal);
401740
- return this._steeringReceipt(record8);
401777
+ return this._steeringReceipt(record9);
401741
401778
  }
401742
401779
  /** Inject bounded runtime guidance without treating it as user steering. */
401743
401780
  injectRuntimeGuidance(content) {
@@ -402028,7 +402065,7 @@ ${notice}`;
402028
402065
  throw new Error("Conflicting native amendment intake");
402029
402066
  return existing.promise;
402030
402067
  }
402031
- const steering = this.pendingSteeringInputs.find((record8) => record8.inputId === authority.inputId && !["superseded", "cancelled"].includes(record8.state));
402068
+ const steering = this.pendingSteeringInputs.find((record9) => record9.inputId === authority.inputId && !["superseded", "cancelled"].includes(record9.state));
402032
402069
  if (!steering || !this.options.taskNativeScope || !this.options.expectedOutcomeContract || !this._completionLedger)
402033
402070
  throw new Error("Native amendment requires an existing authenticated human steering intake");
402034
402071
  const rebased = this._rebaseNativeTaskRequirementAmendmentPlan(authority);
@@ -402074,8 +402111,8 @@ ${notice}`;
402074
402111
  }
402075
402112
  return rebased;
402076
402113
  }
402077
- _applyNativeTaskRequirementAmendmentAtBoundary(record8) {
402078
- const pending = this._pendingNativeRequirementAmendments.get(record8.inputId);
402114
+ _applyNativeTaskRequirementAmendmentAtBoundary(record9) {
402115
+ const pending = this._pendingNativeRequirementAmendments.get(record9.inputId);
402079
402116
  if (!pending)
402080
402117
  return;
402081
402118
  try {
@@ -402085,7 +402122,7 @@ ${notice}`;
402085
402122
  priorExpectedOutcome: this.options.expectedOutcomeContract,
402086
402123
  priorScope: this.options.taskNativeScope,
402087
402124
  amendment: pending.authority,
402088
- steering: record8
402125
+ steering: record9
402089
402126
  });
402090
402127
  const path7 = this._objectiveLedgerPath ?? _pathJoin(this.omniusStateDir(), "completion-ledgers", `${this.currentArtifactRunId()}.json`);
402091
402128
  saveCompletionLedger(path7, next);
@@ -402103,8 +402140,8 @@ ${notice}`;
402103
402140
  this._trajectoryReviewSequence++;
402104
402141
  this._recoveryReviewSequence++;
402105
402142
  this._initializeTaskObjective(this._taskObjectiveContract.goal);
402106
- const hold2 = this._nativeRequirementInterpretationHolds.get(record8.inputId);
402107
- this._nativeRequirementInterpretationHolds.delete(record8.inputId);
402143
+ const hold2 = this._nativeRequirementInterpretationHolds.get(record9.inputId);
402144
+ this._nativeRequirementInterpretationHolds.delete(record9.inputId);
402108
402145
  hold2?.wake();
402109
402146
  const applied = this._completionLedger.nativeRequirementAmendments.at(-1);
402110
402147
  pending.resolve({
@@ -402116,14 +402153,14 @@ ${notice}`;
402116
402153
  } catch (error) {
402117
402154
  try {
402118
402155
  const current = loadCompletionLedger(this._objectiveLedgerPath ?? _pathJoin(this.omniusStateDir(), "completion-ledgers", `${this.currentArtifactRunId()}.json`));
402119
- if (current.nativeRequirementAmendments?.some((amendment) => amendment.authority.inputId === record8.inputId))
402156
+ if (current.nativeRequirementAmendments?.some((amendment) => amendment.authority.inputId === record9.inputId))
402120
402157
  this._reviewedInterpretationProjectionBlocked = true;
402121
402158
  } catch {
402122
402159
  }
402123
402160
  pending.reject(error);
402124
402161
  throw error;
402125
402162
  } finally {
402126
- this._pendingNativeRequirementAmendments.delete(record8.inputId);
402163
+ this._pendingNativeRequirementAmendments.delete(record9.inputId);
402127
402164
  }
402128
402165
  }
402129
402166
  /** Independent host capability; never exposed as a model tool or human amendment. */
@@ -402539,15 +402576,15 @@ The previous reviewer response failed exact candidate-quote serialization. Host
402539
402576
  /** Retract the last pending user message (Esc cancel).
402540
402577
  * Returns the retracted text, or null if queue is empty or already consumed. */
402541
402578
  retractLastPendingMessage() {
402542
- const record8 = [...this.pendingSteeringInputs].reverse().find((candidate) => candidate.state === "queued" || candidate.state === "acknowledged");
402543
- if (!record8)
402579
+ const record9 = [...this.pendingSteeringInputs].reverse().find((candidate) => candidate.state === "queued" || candidate.state === "acknowledged");
402580
+ if (!record9)
402544
402581
  return null;
402545
- record8.state = "cancelled";
402546
- if (this._pendingSteeringPreemption?.inputId === record8.inputId) {
402582
+ record9.state = "cancelled";
402583
+ if (this._pendingSteeringPreemption?.inputId === record9.inputId) {
402547
402584
  this._pendingSteeringPreemption = null;
402548
402585
  }
402549
- this._emitSteeringLifecycle(record8, "retracted before admission at a safe boundary");
402550
- return record8.content;
402586
+ this._emitSteeringLifecycle(record9, "retracted before admission at a safe boundary");
402587
+ return record9.content;
402551
402588
  }
402552
402589
  /** Abort the current task run through the generation-bound stop lineage. */
402553
402590
  abort() {
@@ -403002,31 +403039,31 @@ The previous reviewer response failed exact candidate-quote serialization. Host
403002
403039
  /** Import receipts only after reopening the immutable issuer stores and
403003
403040
  * matching them to the current host-bound native resource bytes. */
403004
403041
  async _restoreTaskObjectiveContinuation() {
403005
- const record8 = this._taskObjectiveContinuationRecord;
403042
+ const record9 = this._taskObjectiveContinuationRecord;
403006
403043
  let predecessor = this._completionLedger;
403007
403044
  const index = this._artifactReviewSourceIndex;
403008
- if (!record8 || !predecessor)
403045
+ if (!record9 || !predecessor)
403009
403046
  return;
403010
- if (!index && record8.input.resources.length)
403047
+ if (!index && record9.input.resources.length)
403011
403048
  throw new Error("Task objective continuation source index is unavailable");
403012
- const strengthening = record8.input.contractStrengthening;
403049
+ const strengthening = record9.input.contractStrengthening;
403013
403050
  if (strengthening && taskObjectiveContinuationDigest(this.options.taskObjectiveContract) !== strengthening.recipientContractSha256) {
403014
403051
  throw new Error("Validated continuation recipient contract changed before source restoration");
403015
403052
  }
403016
- if (predecessor.runId !== record8.input.predecessor.runId) {
403017
- const bytes3 = _fsReadFileSync(record8.input.predecessor.ledgerPath);
403018
- if (_createHash("sha256").update(bytes3).digest("hex") !== record8.input.predecessor.ledgerSha256)
403053
+ if (predecessor.runId !== record9.input.predecessor.runId) {
403054
+ const bytes3 = _fsReadFileSync(record9.input.predecessor.ledgerPath);
403055
+ if (_createHash("sha256").update(bytes3).digest("hex") !== record9.input.predecessor.ledgerSha256)
403019
403056
  throw new Error("Task objective continuation predecessor changed during reconciliation");
403020
403057
  predecessor = restoreCompletionLedgerSnapshot(JSON.parse(bytes3.toString("utf8")));
403021
403058
  }
403022
403059
  if (index)
403023
- index.withWriteTransaction(() => claimTaskObjectiveContinuation(record8));
403060
+ index.withWriteTransaction(() => claimTaskObjectiveContinuation(record9));
403024
403061
  else
403025
- claimTaskObjectiveContinuation(record8);
403026
- record8.adoptions = [];
403027
- record8.importedEvidence = [];
403062
+ claimTaskObjectiveContinuation(record9);
403063
+ record9.adoptions = [];
403064
+ record9.importedEvidence = [];
403028
403065
  const owner = { scopeId: this._sessionId, runId: this.currentArtifactRunId(), taskEpoch: this._taskEpoch };
403029
- const previousOwner = { ...owner, runId: record8.input.predecessor.runId };
403066
+ const previousOwner = { ...owner, runId: record9.input.predecessor.runId };
403030
403067
  const validCriteria = /* @__PURE__ */ new Set();
403031
403068
  const views = /* @__PURE__ */ new Map();
403032
403069
  const seenSources = /* @__PURE__ */ new Set();
@@ -403039,7 +403076,7 @@ The previous reviewer response failed exact candidate-quote serialization. Host
403039
403076
  const receipt = entry.observation.documentExtraction;
403040
403077
  if (!receipt)
403041
403078
  continue;
403042
- for (const resource of record8.input.resources) {
403079
+ for (const resource of record9.input.resources) {
403043
403080
  if (resource.pathAliases.includes(entry.verifiedSourcePath) || resource.pathAliases.includes(receipt.sourcePath)) {
403044
403081
  if (!resource.sourceSha256 || receipt.documentHash !== resource.sourceSha256)
403045
403082
  conflictingVersions.add(resource.criterionId);
@@ -403058,13 +403095,13 @@ The previous reviewer response failed exact candidate-quote serialization. Host
403058
403095
  const source = evidence2.sources.find((value) => value.sourceId === entry.sourceId);
403059
403096
  if (!source || source.toolName !== "pdf_to_text")
403060
403097
  continue;
403061
- const resources = record8.input.resources.filter((resource) => !conflictingVersions.has(resource.criterionId) && resource.sourceSha256 && resource.sourceSha256 === source.sourceSha256 && resource.pathAliases.includes(entry.verifiedSourcePath) && predecessor.evidence.some((receipt) => receipt.success === true && receipt.toolName === "pdf_to_text" && receipt.objectiveEvidenceKinds?.includes("observation") && receipt.criterionIds?.includes(resource.criterionId) && receipt.targetPaths?.some((path7) => resource.pathAliases.includes(path7))));
403098
+ const resources = record9.input.resources.filter((resource) => !conflictingVersions.has(resource.criterionId) && resource.sourceSha256 && resource.sourceSha256 === source.sourceSha256 && resource.pathAliases.includes(entry.verifiedSourcePath) && predecessor.evidence.some((receipt) => receipt.success === true && receipt.toolName === "pdf_to_text" && receipt.objectiveEvidenceKinds?.includes("observation") && receipt.criterionIds?.includes(resource.criterionId) && receipt.targetPaths?.some((path7) => resource.pathAliases.includes(path7))));
403062
403099
  if (!resources.length)
403063
403100
  continue;
403064
- const adopted = index.adopt({ owner, issuer: index.originalReference(entry), authoritySha256: record8.authoritySha256 });
403101
+ const adopted = index.adopt({ owner, issuer: index.originalReference(entry), authoritySha256: record9.authoritySha256 });
403065
403102
  if (!seenSources.has(adopted.sourceId)) {
403066
403103
  seenSources.add(adopted.sourceId);
403067
- record8.adoptions.push({
403104
+ record9.adoptions.push({
403068
403105
  sourceId: adopted.sourceId,
403069
403106
  issuer: adopted.adoption.issuer,
403070
403107
  criterionIds: resources.map((resource) => resource.criterionId),
@@ -403105,11 +403142,11 @@ criterion=${resource.criterionId}; native=message_id:${resource.messageId}; issu
403105
403142
  if (receipt.kind === "human_input" || receipt.success === true && receipt.role === "mutation" || receipt.receipt)
403106
403143
  return [receipt];
403107
403144
  if (receipt.success === true && receipt.toolName === "pdf_to_text" && receipt.objectiveEvidenceKinds?.includes("observation")) {
403108
- const criterionIds = (receipt.criterionIds ?? []).filter((id5) => validCriteria.has(id5) && record8.input.resources.some((resource) => resource.criterionId === id5 && receipt.targetPaths?.some((path7) => resource.pathAliases.includes(path7))));
403145
+ const criterionIds = (receipt.criterionIds ?? []).filter((id5) => validCriteria.has(id5) && record9.input.resources.some((resource) => resource.criterionId === id5 && receipt.targetPaths?.some((path7) => resource.pathAliases.includes(path7))));
403109
403146
  if (criterionIds.length)
403110
403147
  return [{ ...receipt, criterionIds, role: "observation", objectiveEvidenceKinds: ["observation"] }];
403111
403148
  }
403112
- if (record8.input.scope.admissionKind === "same_native_input_retry" && record8.input.resources.length === 0 && !predecessor.objectiveContract?.requirements && receipt.kind === "tool_result" && receipt.success === true && receipt.role === "observation") {
403149
+ if (record9.input.scope.admissionKind === "same_native_input_retry" && record9.input.resources.length === 0 && !predecessor.objectiveContract?.requirements && receipt.kind === "tool_result" && receipt.success === true && receipt.role === "observation") {
403113
403150
  const history = `[Retained same-native tool observation; historical quoted data, not current source validation]
403114
403151
  issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ?? "not recorded"}
403115
403152
  ` + receipt.summary;
@@ -403120,18 +403157,18 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403120
403157
  return [];
403121
403158
  return [{ ...receipt, success: void 0, progressClass: "control_bookkeeping", objectiveEvidenceKinds: [] }];
403122
403159
  });
403123
- record8.retiredSupportedAnswerReviewEvidenceIds = [...retiredReviewRows];
403124
- record8.importedEvidence = evidence.map((receipt) => ({
403160
+ record9.retiredSupportedAnswerReviewEvidenceIds = [...retiredReviewRows];
403161
+ record9.importedEvidence = evidence.map((receipt) => ({
403125
403162
  evidenceId: receipt.id,
403126
403163
  issuerRunId: predecessor.taskObjectiveContinuation?.importedEvidence.find((entry) => entry.evidenceId === receipt.id)?.issuerRunId ?? predecessor.runId,
403127
403164
  predecessorRunId: predecessor.runId,
403128
- predecessorLedgerSha256: record8.input.predecessor.ledgerSha256,
403165
+ predecessorLedgerSha256: record9.input.predecessor.ledgerSha256,
403129
403166
  criterionIds: [...receipt.criterionIds ?? []]
403130
403167
  }));
403131
403168
  if (strengthening && taskObjectiveContinuationDigest(this.options.taskObjectiveContract) !== strengthening.recipientContractSha256) {
403132
403169
  throw new Error("Validated continuation recipient contract changed before source restoration");
403133
403170
  }
403134
- if (record8.input.scope.admissionKind === "same_native_input_retry" && record8.input.scope.currentInputId === record8.input.scope.originalInputId && !strengthening) {
403171
+ if (record9.input.scope.admissionKind === "same_native_input_retry" && record9.input.scope.currentInputId === record9.input.scope.originalInputId && !strengthening) {
403135
403172
  const binding = {
403136
403173
  runId: predecessor.runId,
403137
403174
  taskEpoch: predecessor.taskEpoch,
@@ -403145,7 +403182,7 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403145
403182
  if (refusal || dispatch)
403146
403183
  this._objectiveRecoveryInherited = {
403147
403184
  predecessorRunId: predecessor.runId,
403148
- predecessorLedgerSha256: record8.input.predecessor.ledgerSha256,
403185
+ predecessorLedgerSha256: record9.input.predecessor.ledgerSha256,
403149
403186
  refusalCount: refusal?.count ?? 0,
403150
403187
  ...dispatch ? { operationSha256: dispatch.operationSha256 } : {}
403151
403188
  };
@@ -403161,7 +403198,7 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403161
403198
  evidence,
403162
403199
  proposedClaims: [],
403163
403200
  status: "open",
403164
- taskObjectiveContinuation: record8
403201
+ taskObjectiveContinuation: record9
403165
403202
  };
403166
403203
  delete restored.terminal;
403167
403204
  delete restored.needsInput;
@@ -403225,20 +403262,20 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403225
403262
  this._objectiveLedgerPath = _pathJoin(dir, `${owner.runId}.json`);
403226
403263
  saveCompletionLedger(this._objectiveLedgerPath, this._completionLedger);
403227
403264
  if (index)
403228
- index.withWriteTransaction(() => commitTaskObjectiveContinuation(record8));
403265
+ index.withWriteTransaction(() => commitTaskObjectiveContinuation(record9));
403229
403266
  else
403230
- commitTaskObjectiveContinuation(record8);
403267
+ commitTaskObjectiveContinuation(record9);
403231
403268
  }
403232
403269
  /** Immutable run key for artifacts; sessionId remains correlation metadata. */
403233
403270
  currentArtifactRunId() {
403234
403271
  return this._activeRunId || this._sessionId;
403235
403272
  }
403236
- _steeringReceipt(record8) {
403273
+ _steeringReceipt(record9) {
403237
403274
  return {
403238
- inputId: record8.inputId,
403239
- intent: record8.intent,
403240
- state: record8.state,
403241
- taskEpoch: record8.taskEpoch,
403275
+ inputId: record9.inputId,
403276
+ intent: record9.intent,
403277
+ state: record9.state,
403278
+ taskEpoch: record9.taskEpoch,
403242
403279
  runId: this._activeRunId || void 0,
403243
403280
  acceptedAt: (/* @__PURE__ */ new Date()).toISOString()
403244
403281
  };
@@ -403261,34 +403298,34 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403261
403298
  };
403262
403299
  }
403263
403300
  }
403264
- _emitSteeringLifecycle(record8, reason) {
403265
- const receipt = this._steeringReceipt(record8);
403301
+ _emitSteeringLifecycle(record9, reason) {
403302
+ const receipt = this._steeringReceipt(record9);
403266
403303
  const reconciliation = this._activeSteering && [
403267
403304
  this._activeSteering.input,
403268
403305
  ...this._activeSteering.relatedInputs ?? []
403269
- ].some((input) => input.inputId === record8.inputId) ? this._activeSteering.reconciliation : void 0;
403306
+ ].some((input) => input.inputId === record9.inputId) ? this._activeSteering.reconciliation : void 0;
403270
403307
  this.emit({
403271
403308
  type: "status",
403272
- content: `Steering ${record8.inputId} ${record8.state}: ${reason}`,
403309
+ content: `Steering ${record9.inputId} ${record9.state}: ${reason}`,
403273
403310
  steering: receipt,
403274
403311
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
403275
403312
  });
403276
403313
  this._onTypedEvent?.({
403277
403314
  type: "steering_lifecycle",
403278
403315
  runId: this.currentArtifactRunId(),
403279
- inputId: record8.inputId,
403280
- intent: record8.intent,
403281
- state: record8.state,
403282
- taskEpoch: record8.taskEpoch,
403316
+ inputId: record9.inputId,
403317
+ intent: record9.intent,
403318
+ state: record9.state,
403319
+ taskEpoch: record9.taskEpoch,
403283
403320
  summary: reason,
403284
403321
  ...reconciliation ? { reconciliation: { ...reconciliation } } : {},
403285
403322
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
403286
403323
  });
403287
403324
  appendSteeringLedgerEntry(this._workingDirectory || process.cwd(), {
403288
403325
  type: "lifecycle",
403289
- packetId: record8.inputId,
403326
+ packetId: record9.inputId,
403290
403327
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
403291
- intake: { ...record8 },
403328
+ intake: { ...record9 },
403292
403329
  runId: this.currentArtifactRunId(),
403293
403330
  taskEpoch: this._taskEpoch,
403294
403331
  primaryInputId: this._activeSteering?.input.inputId,
@@ -403301,11 +403338,11 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403301
403338
  this.backend.setAbortSignal(signal);
403302
403339
  }
403303
403340
  }
403304
- _requestSteeringPreemption(record8) {
403305
- this._pendingSteeringPreemption = record8;
403306
- record8.state = "acknowledged";
403307
- this._emitSteeringLifecycle(record8, "preemption acknowledged");
403308
- this._turnAbortController.abort(new Error(`steering ${record8.intent}: ${record8.inputId}`));
403341
+ _requestSteeringPreemption(record9) {
403342
+ this._pendingSteeringPreemption = record9;
403343
+ record9.state = "acknowledged";
403344
+ this._emitSteeringLifecycle(record9, "preemption acknowledged");
403345
+ this._turnAbortController.abort(new Error(`steering ${record9.intent}: ${record9.inputId}`));
403309
403346
  const shellTool = this.tools.get("shell");
403310
403347
  if (shellTool && typeof shellTool.killAll === "function") {
403311
403348
  shellTool.killAll();
@@ -403314,18 +403351,18 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403314
403351
  this._setBackendTurnAbortSignal(this._turnAbortController.signal);
403315
403352
  }
403316
403353
  _prepareSteeringInputsForRun() {
403317
- const initialInputs = this.pendingSteeringInputs.filter((record8) => record8.state === "queued" || record8.state === "acknowledged");
403318
- this._allowImplicitContinuation = initialInputs.some((record8) => record8.intent === "append" || record8.intent === "clarify") && !initialInputs.some((record8) => record8.intent === "redirect" || record8.intent === "replace" || record8.intent === "cancel");
403319
- for (const record8 of this.pendingSteeringInputs) {
403320
- if (record8.state !== "queued" && record8.state !== "acknowledged")
403354
+ const initialInputs = this.pendingSteeringInputs.filter((record9) => record9.state === "queued" || record9.state === "acknowledged");
403355
+ this._allowImplicitContinuation = initialInputs.some((record9) => record9.intent === "append" || record9.intent === "clarify") && !initialInputs.some((record9) => record9.intent === "redirect" || record9.intent === "replace" || record9.intent === "cancel");
403356
+ for (const record9 of this.pendingSteeringInputs) {
403357
+ if (record9.state !== "queued" && record9.state !== "acknowledged")
403321
403358
  continue;
403322
- if (record8.taskEpoch && record8.taskEpoch !== this._taskEpoch) {
403323
- record8.state = "superseded";
403324
- this._emitSteeringLifecycle(record8, "superseded by a later task run");
403359
+ if (record9.taskEpoch && record9.taskEpoch !== this._taskEpoch) {
403360
+ record9.state = "superseded";
403361
+ this._emitSteeringLifecycle(record9, "superseded by a later task run");
403325
403362
  continue;
403326
403363
  }
403327
- record8.taskEpoch = this._taskEpoch;
403328
- this._emitSteeringLifecycle(record8, "bound to active task epoch");
403364
+ record9.taskEpoch = this._taskEpoch;
403365
+ this._emitSteeringLifecycle(record9, "bound to active task epoch");
403329
403366
  }
403330
403367
  }
403331
403368
  /** Archive prior task-epoch state before its session-backed records are hidden. */
@@ -403417,13 +403454,13 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403417
403454
  delete this._lastVerifierResult;
403418
403455
  }
403419
403456
  /** A media follow-up joins unresolved user authority instead of replacing it. */
403420
- _selectActiveSteering(record8, turn) {
403457
+ _selectActiveSteering(record9, turn) {
403421
403458
  const prior = this._activeSteering;
403422
403459
  if (prior && this._steeringAuthorityRuns.get(prior) === this._activeRunId && prior.input.taskEpoch === this._taskEpoch && !isSteeringScopeResolved(prior)) {
403423
- if ([prior.input, ...prior.relatedInputs ?? []].some((input) => input.inputId === record8.inputId))
403460
+ if ([prior.input, ...prior.relatedInputs ?? []].some((input) => input.inputId === record9.inputId))
403424
403461
  return;
403425
- if (record8.intent !== "replace" && record8.intent !== "redirect" && record8.intent !== "cancel") {
403426
- prior.relatedInputs = [...prior.relatedInputs ?? [], record8];
403462
+ if (record9.intent !== "replace" && record9.intent !== "redirect" && record9.intent !== "cancel") {
403463
+ prior.relatedInputs = [...prior.relatedInputs ?? [], record9];
403427
403464
  prior.reconciliation = void 0;
403428
403465
  prior.requiresReconciliation = true;
403429
403466
  prior.gatesOldPlan = true;
@@ -403436,56 +403473,56 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403436
403473
  }
403437
403474
  }
403438
403475
  this._activeSteering = {
403439
- input: record8,
403476
+ input: record9,
403440
403477
  appliedTurn: turn,
403441
- requiresReconciliation: steeringRequiresReconciliation(record8.intent),
403442
- gatesOldPlan: steeringGatesOldPlan(record8.intent),
403478
+ requiresReconciliation: steeringRequiresReconciliation(record9.intent),
403479
+ gatesOldPlan: steeringGatesOldPlan(record9.intent),
403443
403480
  visibleRequestTurns: []
403444
403481
  };
403445
403482
  this._steeringAuthorityRuns.set(this._activeSteering, this._activeRunId);
403446
403483
  }
403447
- _activateSteering(record8, turn) {
403448
- const requiresReconciliation = steeringRequiresReconciliation(record8.intent);
403449
- const gatesOldPlan = steeringGatesOldPlan(record8.intent);
403484
+ _activateSteering(record9, turn) {
403485
+ const requiresReconciliation = steeringRequiresReconciliation(record9.intent);
403486
+ const gatesOldPlan = steeringGatesOldPlan(record9.intent);
403450
403487
  const prior = this._activeSteering;
403451
- if (prior && prior.input.inputId !== record8.inputId && !isSteeringScopeResolved(prior) && (record8.intent === "redirect" || record8.intent === "replace")) {
403488
+ if (prior && prior.input.inputId !== record9.inputId && !isSteeringScopeResolved(prior) && (record9.intent === "redirect" || record9.intent === "replace")) {
403452
403489
  prior.input.state = "superseded";
403453
- this._emitSteeringLifecycle(prior.input, `superseded by ${record8.intent} ${record8.inputId}`);
403490
+ this._emitSteeringLifecycle(prior.input, `superseded by ${record9.intent} ${record9.inputId}`);
403454
403491
  }
403455
- this._selectActiveSteering(record8, turn);
403456
- record8.taskEpoch = this._taskEpoch;
403492
+ this._selectActiveSteering(record9, turn);
403493
+ record9.taskEpoch = this._taskEpoch;
403457
403494
  const steeringEvidenceChunkIds = this._recordImmutableEvidence({
403458
403495
  source: "user",
403459
- sourceUri: `omnius-run://${this.currentArtifactRunId()}/steering/${record8.inputId}`,
403460
- messageId: record8.inputId,
403496
+ sourceUri: `omnius-run://${this.currentArtifactRunId()}/steering/${record9.inputId}`,
403497
+ messageId: record9.inputId,
403461
403498
  version: `${this._taskEpoch}:${turn}`,
403462
- body: record8.content,
403499
+ body: record9.content,
403463
403500
  metadata: {
403464
403501
  role: "user",
403465
- intent: record8.intent,
403466
- source: record8.source,
403502
+ intent: record9.intent,
403503
+ source: record9.source,
403467
403504
  turn
403468
403505
  }
403469
403506
  });
403470
403507
  this._pendingStructuredMemorySourceIds.push(...steeringEvidenceChunkIds);
403471
403508
  void this._processPendingStructuredMemoryExtraction();
403472
403509
  const ledger = this._contextMemoryLedger;
403473
- if (ledger && !this._contextMemorySteeringRecordIds.has(record8.inputId)) {
403510
+ if (ledger && !this._contextMemorySteeringRecordIds.has(record9.inputId)) {
403474
403511
  try {
403475
403512
  const steering = ledger.appendRecord({
403476
403513
  epoch: String(this._taskEpoch),
403477
403514
  kind: "steering",
403478
403515
  authority: "user",
403479
- body: record8.content,
403516
+ body: record9.content,
403480
403517
  provenance: { producer: "agenticRunner:steering" },
403481
403518
  metadata: {
403482
- inputId: record8.inputId,
403483
- intent: record8.intent,
403484
- source: record8.source,
403519
+ inputId: record9.inputId,
403520
+ intent: record9.intent,
403521
+ source: record9.source,
403485
403522
  turn
403486
403523
  }
403487
403524
  });
403488
- this._contextMemorySteeringRecordIds.set(record8.inputId, steering.id);
403525
+ this._contextMemorySteeringRecordIds.set(record9.inputId, steering.id);
403489
403526
  if (this._contextMemoryTaskRecordId) {
403490
403527
  ledger.linkDependency({
403491
403528
  sourceRecordId: steering.id,
@@ -403499,13 +403536,13 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403499
403536
  steering.id,
403500
403537
  ...this._contextMemoryTaskRecordId ? [this._contextMemoryTaskRecordId] : []
403501
403538
  ];
403502
- this._commitContextMemoryWorkingSet(`steering ${record8.inputId} admitted`);
403539
+ this._commitContextMemoryWorkingSet(`steering ${record9.inputId} admitted`);
403503
403540
  } catch {
403504
403541
  }
403505
403542
  }
403506
403543
  if (requiresReconciliation) {
403507
- record8.state = "reconciliation_required";
403508
- this._emitSteeringLifecycle(record8, gatesOldPlan ? `admitted at turn ${turn}; old-plan actions are gated pending structured reconciliation` : `admitted at turn ${turn}; awaiting structured reconciliation`);
403544
+ record9.state = "reconciliation_required";
403545
+ this._emitSteeringLifecycle(record9, gatesOldPlan ? `admitted at turn ${turn}; old-plan actions are gated pending structured reconciliation` : `admitted at turn ${turn}; awaiting structured reconciliation`);
403509
403546
  }
403510
403547
  }
403511
403548
  _canonicalReadEvidencePayload(canonicalPath2, contentHash2, requestedRange) {
@@ -403529,19 +403566,19 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403529
403566
  }
403530
403567
  async _drainPendingSteeringMessages(messages, turn) {
403531
403568
  this.drainPendingRuntimeGuidance(turn);
403532
- const pending = this.pendingSteeringInputs.filter((record8) => (record8.state === "queued" || record8.state === "acknowledged") && (!record8.taskEpoch || record8.taskEpoch === this._taskEpoch));
403533
- for (const record8 of pending) {
403569
+ const pending = this.pendingSteeringInputs.filter((record9) => (record9.state === "queued" || record9.state === "acknowledged") && (!record9.taskEpoch || record9.taskEpoch === this._taskEpoch));
403570
+ for (const record9 of pending) {
403534
403571
  const replacement = this._pendingSteeringPreemption;
403535
- if (replacement?.intent === "replace" && record8.inputId !== replacement.inputId && this.pendingSteeringInputs.indexOf(record8) < this.pendingSteeringInputs.indexOf(replacement)) {
403536
- record8.state = "superseded";
403537
- this._emitSteeringLifecycle(record8, `superseded before consumption by replacement ${replacement.inputId}`);
403572
+ if (replacement?.intent === "replace" && record9.inputId !== replacement.inputId && this.pendingSteeringInputs.indexOf(record9) < this.pendingSteeringInputs.indexOf(replacement)) {
403573
+ record9.state = "superseded";
403574
+ this._emitSteeringLifecycle(record9, `superseded before consumption by replacement ${replacement.inputId}`);
403538
403575
  continue;
403539
403576
  }
403540
- this._applyNativeTaskRequirementAmendmentAtBoundary(record8);
403577
+ this._applyNativeTaskRequirementAmendmentAtBoundary(record9);
403541
403578
  const historyStart = messages.length;
403542
- await this.appendInjectedUserMessage(record8.content, messages, turn);
403543
- this._activateSteering(record8, turn);
403544
- if (this._immediateSteeringWakeInputId === record8.inputId) {
403579
+ await this.appendInjectedUserMessage(record9.content, messages, turn);
403580
+ this._activateSteering(record9, turn);
403581
+ if (this._immediateSteeringWakeInputId === record9.inputId) {
403545
403582
  this._immediateSteeringWakeInputId = null;
403546
403583
  }
403547
403584
  if (this._activeSteering && this._activeSteering.historyStartIndex === void 0) {
@@ -403549,9 +403586,9 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403549
403586
  }
403550
403587
  }
403551
403588
  for (const inputId of [...this._pendingNativeRequirementAmendments.keys()]) {
403552
- const record8 = this.pendingSteeringInputs.find((record9) => record9.inputId === inputId && !["cancelled", "superseded"].includes(record9.state));
403553
- if (record8)
403554
- this._applyNativeTaskRequirementAmendmentAtBoundary(record8);
403589
+ const record9 = this.pendingSteeringInputs.find((record10) => record10.inputId === inputId && !["cancelled", "superseded"].includes(record10.state));
403590
+ if (record9)
403591
+ this._applyNativeTaskRequirementAmendmentAtBoundary(record9);
403555
403592
  }
403556
403593
  while (this.pendingUserMessages.length > 0) {
403557
403594
  await this.appendInjectedUserMessage(this.pendingUserMessages.shift(), messages, turn);
@@ -403565,20 +403602,20 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403565
403602
  async _applySteeringAtSafeBoundary(messages, turn) {
403566
403603
  this._currentSteeringTurn = turn;
403567
403604
  await this._drainPendingSteeringMessages(messages, turn);
403568
- const record8 = this._pendingSteeringPreemption;
403569
- if (!record8) {
403605
+ const record9 = this._pendingSteeringPreemption;
403606
+ if (!record9) {
403570
403607
  this._checkpointActiveTaskScope(messages);
403571
403608
  return "continue";
403572
403609
  }
403573
- if (record8.intent === "cancel") {
403610
+ if (record9.intent === "cancel") {
403574
403611
  this._pendingSteeringPreemption = null;
403575
- record8.state = "cancelled";
403576
- this._emitSteeringLifecycle(record8, `cancelled active task at turn ${turn}`);
403612
+ record9.state = "cancelled";
403613
+ this._emitSteeringLifecycle(record9, `cancelled active task at turn ${turn}`);
403577
403614
  this.abort();
403578
403615
  return "abort";
403579
403616
  }
403580
403617
  const previousEpoch = this._taskEpoch;
403581
- const prepared = this._preparedTaskScopeBoundary?.inputId === record8.inputId ? this._preparedTaskScopeBoundary : this._prepareTaskScopeBoundary(messages, record8);
403618
+ const prepared = this._preparedTaskScopeBoundary?.inputId === record9.inputId ? this._preparedTaskScopeBoundary : this._prepareTaskScopeBoundary(messages, record9);
403582
403619
  const activeMessages = [...prepared.activeMessages];
403583
403620
  for (const message of messages.slice(prepared.messageCount)) {
403584
403621
  if (message.role === "user" && !activeMessages.some((item) => JSON.stringify(item) === JSON.stringify(message))) {
@@ -403587,7 +403624,7 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403587
403624
  }
403588
403625
  const archiveReference = this._persistTaskScopeBoundary(prepared.boundary, messages);
403589
403626
  this._advanceTaskScopeLifecycle(prepared.boundary);
403590
- this._archiveSupersededTaskState(previousEpoch, record8);
403627
+ this._archiveSupersededTaskState(previousEpoch, record9);
403591
403628
  this._installTaskScopeBoundary(prepared.boundary, archiveReference, turn);
403592
403629
  messages.splice(0, messages.length, ...activeMessages);
403593
403630
  this._activeTaskScopeCheckpoint = null;
@@ -403595,12 +403632,12 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403595
403632
  this._pendingSteeringPreemption = null;
403596
403633
  const active = this._activeSteering;
403597
403634
  for (const input of [
403598
- record8,
403635
+ record9,
403599
403636
  ...active ? [active.input, ...active.relatedInputs ?? []] : []
403600
403637
  ]) {
403601
403638
  input.taskEpoch = this._taskEpoch;
403602
403639
  }
403603
- if (active?.input.inputId === record8.inputId && active.reconciliation?.taskDisposition === "replace") {
403640
+ if (active?.input.inputId === record9.inputId && active.reconciliation?.taskDisposition === "replace") {
403604
403641
  active.gatesOldPlan = false;
403605
403642
  this._taskState.nextAction = active.reconciliation.revisedNextAction;
403606
403643
  this._taskState.steeringConstraints = [
@@ -403608,12 +403645,12 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403608
403645
  ];
403609
403646
  }
403610
403647
  this._checkpointActiveTaskScope(messages);
403611
- this._emitSteeringLifecycle(record8, `epoch transition applied at turn ${turn}; ${previousEpoch} -> ${this._taskEpoch}; archive=${archiveReference}`);
403648
+ this._emitSteeringLifecycle(record9, `epoch transition applied at turn ${turn}; ${previousEpoch} -> ${this._taskEpoch}; archive=${archiveReference}`);
403612
403649
  return "restart";
403613
403650
  }
403614
- _prepareTaskScopeBoundary(messages, record8, reconciliation) {
403615
- const active = this._activeSteering?.input.inputId === record8.inputId ? this._activeSteering : null;
403616
- const inputs = active ? [active.input, ...active.relatedInputs ?? []] : [record8];
403651
+ _prepareTaskScopeBoundary(messages, record9, reconciliation) {
403652
+ const active = this._activeSteering?.input.inputId === record9.inputId ? this._activeSteering : null;
403653
+ const inputs = active ? [active.input, ...active.relatedInputs ?? []] : [record9];
403617
403654
  const authorityMessages = inputs.map((input) => ({
403618
403655
  role: "user",
403619
403656
  content: input.content,
@@ -403632,11 +403669,11 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403632
403669
  sessionId: this._sessionId,
403633
403670
  fromEpoch: this._taskEpoch,
403634
403671
  toEpoch: this._taskEpoch + 1,
403635
- goal: (reconciliation?.replacementGoal ?? record8.content).slice(0, 4e3),
403672
+ goal: (reconciliation?.replacementGoal ?? record9.content).slice(0, 4e3),
403636
403673
  inputIds: inputs.map((input) => input.inputId),
403637
403674
  ...this._activeTaskScopeBoundary ? { priorBoundary: this._activeTaskScopeBoundary } : {}
403638
403675
  }),
403639
- inputId: record8.inputId,
403676
+ inputId: record9.inputId,
403640
403677
  messageCount: messages.length
403641
403678
  };
403642
403679
  }
@@ -407304,7 +407341,7 @@ Respond with the assessment and take the selected evidence-backed action.`;
407304
407341
  const recovered2 = new FailureResolutionTransactionCoordinator({
407305
407342
  failureStore: this._failureStore
407306
407343
  }).recover(this._workboardDir(), this.currentArtifactRunId());
407307
- if (recovered2.some((record8) => record8.state === "committed")) {
407344
+ if (recovered2.some((record9) => record9.state === "committed")) {
407308
407345
  this._workboard = readActiveWorkboardSnapshot(this._workboardDir(), this.currentArtifactRunId()) ?? this._workboard;
407309
407346
  }
407310
407347
  } catch {
@@ -408050,6 +408087,20 @@ ${dynamicProjectContext}`
408050
408087
  const currentTelegramCompletionObjectiveScope = () => {
408051
408088
  return this._telegramCompletionObjectiveScope();
408052
408089
  };
408090
+ const acceptedTaskCompleteArgs = (tc, result, completionTurn) => {
408091
+ const restored = result.completionRestoredPayload;
408092
+ const owner = completionReplyOwners.get(tc.id);
408093
+ if (tc.name !== "task_complete" || result.success !== true || result.completionAdmission !== "accepted" || tc.arguments.resume_review !== true || !isCompletionRestoredPayloadV1(restored) || !owner || owner.runId !== this.currentArtifactRunId() || owner.taskEpoch !== this._taskEpoch || owner.turn !== completionTurn || owner.objectiveScope !== currentTelegramCompletionObjectiveScope() || owner.objectiveFingerprint !== this._objectiveFrontier?.fingerprint)
408094
+ return tc.arguments;
408095
+ return {
408096
+ ...tc.arguments,
408097
+ summary: restored.summary,
408098
+ user_reply: restored.userReply,
408099
+ ...restored.status !== void 0 ? { status: restored.status } : {},
408100
+ ...restored.question !== void 0 ? { question: restored.question } : {},
408101
+ ...restored.missingCriterionIds !== void 0 ? { missing_criterion_ids: [...restored.missingCriterionIds] } : {}
408102
+ };
408103
+ };
408053
408104
  const captureAcceptedCompletionReply = (toolCallId, args, completionTurn) => {
408054
408105
  const owner = completionReplyOwners.get(toolCallId);
408055
408106
  if (this._isTelegramSurface() && (!owner || owner.runId !== this.currentArtifactRunId() || owner.taskEpoch !== this._taskEpoch || owner.turn !== completionTurn || owner.objectiveScope !== currentTelegramCompletionObjectiveScope())) {
@@ -408902,7 +408953,7 @@ ${lastCompletionGateFeedback.trim().slice(0, 4e3)}` : ""
408902
408953
  if (this.aborted || this._pendingSteeringPreemption)
408903
408954
  return null;
408904
408955
  const preparedArgumentError = await prepareToolArguments(tc, this._currentSteeringTurn);
408905
- if (tc.name === "task_complete" && this._isTelegramSurface() && telegramOnlyCompletionCallIds.has(tc.id) && !(typeof tc.arguments?.["user_reply"] === "string" && tc.arguments["user_reply"].trim())) {
408956
+ if (tc.name === "task_complete" && this._isTelegramSurface() && tc.arguments["resume_review"] !== true && telegramOnlyCompletionCallIds.has(tc.id) && !(typeof tc.arguments?.["user_reply"] === "string" && tc.arguments["user_reply"].trim())) {
408906
408957
  const modelText = this._latestModelVisibleAssistantText;
408907
408958
  const assessment = this._currentExpectedOutcomeAssessment();
408908
408959
  const frontier = this._objectiveFrontier;
@@ -410164,6 +410215,11 @@ intent=${_verifierResult.intentBucket}; scope=${_verifierResult.effectScope ?? "
410164
410215
  exactFileReadObservations.set(this._buildToolFingerprint("file_read", tc.arguments), observedIdentity);
410165
410216
  }
410166
410217
  }
410218
+ const completionReviewIsPending = isCompletionReviewPendingResult(tc.name, result);
410219
+ if (completionReviewIsPending) {
410220
+ result = { ...result, runtimeAuthored: true, completionEvidenceFamily: "completion_review_pending" };
410221
+ delete result.failureDiagnosis;
410222
+ }
410167
410223
  if (tc.name === "task_complete" && result.success === false && result.completionAdmission !== "rejected") {
410168
410224
  const diagnostic = String(result.error || result.output || "task_complete returned no diagnostic text").trim().slice(0, 4e3);
410169
410225
  const feedback = `[COMPLETION FEEDBACK — task_complete adapter]
@@ -410254,12 +410310,14 @@ ${diagnostic}`;
410254
410310
  failure: 0,
410255
410311
  lastOutcomeTurn: turn
410256
410312
  };
410257
- if (result.success)
410258
- updated.success++;
410259
- else
410260
- updated.failure++;
410261
- updated.lastOutcomeTurn = turn;
410262
- this._argCohorts.set(cohortKey, updated);
410313
+ if (!completionReviewIsPending) {
410314
+ if (result.success)
410315
+ updated.success++;
410316
+ else
410317
+ updated.failure++;
410318
+ updated.lastOutcomeTurn = turn;
410319
+ this._argCohorts.set(cohortKey, updated);
410320
+ }
410263
410321
  try {
410264
410322
  if (realFileMutation) {
410265
410323
  const paths2 = realMutationPaths.length > 0 ? realMutationPaths : this._extractToolTargetPaths(tc.name, tc.arguments, result);
@@ -410766,7 +410824,7 @@ ${diagnostic}`;
410766
410824
  }
410767
410825
  }
410768
410826
  let failureWorkboardCardId = null;
410769
- if (!result.success && (result.error || result.output || result.llmContent)) {
410827
+ if (!result.success && !completionReviewIsPending && (result.error || result.output || result.llmContent)) {
410770
410828
  const errorText = (result.error || result.output || result.llmContent || "").toString();
410771
410829
  const diagnosis = this._diagnoseToolFailure(tc.name, tc.arguments, result);
410772
410830
  const sig = diagnosis.patternKey;
@@ -411374,7 +411432,7 @@ ${bookkeepingGuidance}`;
411374
411432
 
411375
411433
  ${bookkeepingGuidance}` : bookkeepingGuidance;
411376
411434
  }
411377
- if (!result.success && this.options.modelTier === "small") {
411435
+ if (!result.success && !completionReviewIsPending && this.options.modelTier === "small") {
411378
411436
  const recovery = this.buildRecoveryGuidance(tc.name, result.error ?? "", tc.arguments);
411379
411437
  if (recovery)
411380
411438
  output += "\n\n" + recovery;
@@ -411396,7 +411454,7 @@ ${bookkeepingGuidance}` : bookkeepingGuidance;
411396
411454
  }
411397
411455
  if (result.success) {
411398
411456
  delete result.failureDiagnosis;
411399
- } else if (!this._isPdfTerminalFeedback(result)) {
411457
+ } else if (!completionReviewIsPending && !this._isPdfTerminalFeedback(result)) {
411400
411458
  this._diagnoseToolFailure(tc.name, tc.arguments, result);
411401
411459
  const staleHashRetryGuidance = this._buildStaleHashRetryGuidance(tc.name, tc.arguments, result);
411402
411460
  if (staleHashRetryGuidance) {
@@ -411474,7 +411532,7 @@ Evidence: ${evidencePreview}`.slice(0, 500);
411474
411532
  outcomes.push(result.runtimeAuthored === true && result.completionEvidenceFamily === "negative_observation_recovery_required" ? "held" : progressOnly || result.runtimeAuthored === true || result.noop === true || ["tool_search", "todo_write", "todo_read", "task_complete", "working_notes", "memory_write"].includes(tc.name) ? "control" : "executed");
411475
411533
  this._negativeObservationProposalOutcomes.set(turn, outcomes);
411476
411534
  }
411477
- if (!progressOnly) {
411535
+ if (!progressOnly && !completionReviewIsPending) {
411478
411536
  const canonicalName = resolvedTool?.name ?? tc.name;
411479
411537
  const operationSha256 = taskExecutionDigest({ toolName: canonicalName, args: tc.arguments ?? {} });
411480
411538
  const refusalReason = result.runtimeAuthored === true && result.success === false && ["objective_alternate_action_required", "objective_plateau_review_due"].includes(result.completionEvidenceFamily ?? "") ? result.completionEvidenceFamily.slice("objective_".length) : void 0;
@@ -411594,7 +411652,7 @@ Evidence: ${evidencePreview}`.slice(0, 500);
411594
411652
  }
411595
411653
  }
411596
411654
  this._trackDecomp2(tc, result, turn);
411597
- if (result && result.success === false) {
411655
+ if (result && result.success === false && !completionReviewIsPending) {
411598
411656
  this._runErrorCount++;
411599
411657
  const errMsg = result.error || "";
411600
411658
  if (typeof errMsg === "string" && errMsg.length > 0) {
@@ -412180,7 +412238,10 @@ Then use file_read on individual FILES inside it.`);
412180
412238
  output,
412181
412239
  success: result.success,
412182
412240
  runtimeAuthored: result.runtimeAuthored,
412183
- completionEvidenceFamily: result.completionEvidenceFamily
412241
+ completionEvidenceFamily: result.completionEvidenceFamily,
412242
+ completionAdmission: result.completionAdmission,
412243
+ completionReviewPending: result.completionReviewPending,
412244
+ completionRestoredPayload: result.completionRestoredPayload
412184
412245
  };
412185
412246
  };
412186
412247
  return boundExecuteSingle;
@@ -414443,6 +414504,9 @@ ${transportFailure2}` : transportFailure2;
414443
414504
  error: r.success ? void 0 : r.output,
414444
414505
  runtimeAuthored: r.runtimeAuthored,
414445
414506
  completionEvidenceFamily: r.completionEvidenceFamily,
414507
+ completionAdmission: r.completionAdmission,
414508
+ completionReviewPending: r.completionReviewPending,
414509
+ completionRestoredPayload: r.completionRestoredPayload,
414446
414510
  systemGuidance: r.systemGuidance
414447
414511
  };
414448
414512
  })();
@@ -414473,16 +414537,16 @@ ${transportFailure2}` : transportFailure2;
414473
414537
  if (!sr.result.success) {
414474
414538
  messages.push({
414475
414539
  role: "system",
414476
- content: this.buildTaskCompleteToolFailureGuard(output)
414540
+ content: this.buildTaskCompleteToolFailureGuard(output, sr.result.completionReviewPending)
414477
414541
  });
414478
414542
  this.emit({
414479
414543
  type: "status",
414480
- content: "task_complete blocked by verification guard",
414544
+ content: this.taskCompleteToolFailureStatus(sr.result.completionReviewPending),
414481
414545
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
414482
414546
  });
414483
414547
  continue;
414484
414548
  }
414485
- const taskCompleteArgs = matchTc.arguments;
414549
+ const taskCompleteArgs = acceptedTaskCompleteArgs(matchTc, sr.result, turn);
414486
414550
  const open4 = this.getOpenTodoItems();
414487
414551
  if (open4.length > 0 && !this._shouldBypassTodoCompletionGuardForTaskComplete(taskCompleteArgs)) {
414488
414552
  const guard = this.buildTodoCompletionGuard(open4);
@@ -414547,16 +414611,16 @@ ${transportFailure2}` : transportFailure2;
414547
414611
  if (!r.success) {
414548
414612
  messages.push({
414549
414613
  role: "system",
414550
- content: this.buildTaskCompleteToolFailureGuard(r.output)
414614
+ content: this.buildTaskCompleteToolFailureGuard(r.output, r.completionReviewPending)
414551
414615
  });
414552
414616
  this.emit({
414553
414617
  type: "status",
414554
- content: "task_complete blocked by verification guard",
414618
+ content: this.taskCompleteToolFailureStatus(r.completionReviewPending),
414555
414619
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
414556
414620
  });
414557
414621
  continue;
414558
414622
  }
414559
- const taskCompleteArgs = r.tc.arguments;
414623
+ const taskCompleteArgs = acceptedTaskCompleteArgs(r.tc, r, turn);
414560
414624
  const open4 = this.getOpenTodoItems();
414561
414625
  if (open4.length > 0 && !this._shouldBypassTodoCompletionGuardForTaskComplete(taskCompleteArgs)) {
414562
414626
  const guard = this.buildTodoCompletionGuard(open4);
@@ -414643,7 +414707,11 @@ ${transportFailure2}` : transportFailure2;
414643
414707
  output: cloned.output,
414644
414708
  success: cloned.success,
414645
414709
  runtimeAuthored: cloned.runtimeAuthored,
414646
- completionEvidenceFamily: cloned.completionEvidenceFamily
414710
+ completionEvidenceFamily: cloned.completionEvidenceFamily,
414711
+ completionAdmission: cloned.completionAdmission,
414712
+ completionReviewPending: cloned.completionReviewPending,
414713
+ completionRestoredPayload: cloned.completionRestoredPayload,
414714
+ systemGuidance: cloned.systemGuidance
414647
414715
  };
414648
414716
  }
414649
414717
  }
@@ -414662,16 +414730,16 @@ ${transportFailure2}` : transportFailure2;
414662
414730
  if (!r.success) {
414663
414731
  messages.push({
414664
414732
  role: "system",
414665
- content: this.buildTaskCompleteToolFailureGuard(r.output)
414733
+ content: this.buildTaskCompleteToolFailureGuard(r.output, r.completionReviewPending)
414666
414734
  });
414667
414735
  this.emit({
414668
414736
  type: "status",
414669
- content: "task_complete blocked by verification guard",
414737
+ content: this.taskCompleteToolFailureStatus(r.completionReviewPending),
414670
414738
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
414671
414739
  });
414672
414740
  continue;
414673
414741
  }
414674
- const taskCompleteArgs = r.tc.arguments;
414742
+ const taskCompleteArgs = acceptedTaskCompleteArgs(r.tc, r, turn);
414675
414743
  const open4 = this.getOpenTodoItems();
414676
414744
  if (open4.length > 0 && !this._shouldBypassTodoCompletionGuardForTaskComplete(taskCompleteArgs)) {
414677
414745
  const guard = this.buildTodoCompletionGuard(open4);
@@ -415607,16 +415675,16 @@ ${diagnosis}` : diagnosis;
415607
415675
  if (!r.success) {
415608
415676
  messages.push({
415609
415677
  role: "system",
415610
- content: this.buildTaskCompleteToolFailureGuard(r.output)
415678
+ content: this.buildTaskCompleteToolFailureGuard(r.output, r.completionReviewPending)
415611
415679
  });
415612
415680
  this.emit({
415613
415681
  type: "status",
415614
- content: "task_complete blocked by verification guard",
415682
+ content: this.taskCompleteToolFailureStatus(r.completionReviewPending),
415615
415683
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
415616
415684
  });
415617
415685
  continue;
415618
415686
  }
415619
- const taskCompleteArgs = r.tc.arguments;
415687
+ const taskCompleteArgs = acceptedTaskCompleteArgs(r.tc, r, turn);
415620
415688
  const open4 = this.getOpenTodoItems();
415621
415689
  if (open4.length > 0 && !this._shouldBypassTodoCompletionGuardForTaskComplete(taskCompleteArgs)) {
415622
415690
  const guard = this.buildTodoCompletionGuard(open4);
@@ -423323,28 +423391,28 @@ function brokerAdmissionFailureResponse(err) {
423323
423391
  if (!payload2 || typeof payload2 !== "object" || Array.isArray(payload2)) {
423324
423392
  return null;
423325
423393
  }
423326
- const record8 = payload2;
423327
- const error = record8["error"];
423394
+ const record9 = payload2;
423395
+ const error = record9["error"];
423328
423396
  if (typeof error !== "string" || !error.trim())
423329
423397
  return null;
423330
423398
  const isLegacyError = err.status === 503 && error === BROKER_QUEUE_DEADLINE_ERROR;
423331
423399
  const annotationPrefix = `${BROKER_QUEUE_DEADLINE_ERROR}:`;
423332
423400
  const isAnnotatedError = err.status === 503 && error.startsWith(annotationPrefix);
423333
- const retryable = record8["retryable"];
423334
- const reasonCode = record8["reason_code"];
423335
- const retryAfterMs = record8["retry_after_ms"];
423336
- const logicalRequestId = record8["logical_request_id"];
423337
- const requestId = record8["request_id"];
423338
- const queue = record8["queue"];
423339
- const causeReasonCode = record8["cause_reason_code"];
423340
- const admissionRetained = record8["admission_retained"];
423341
- const resumeTtlMs = record8["resume_ttl_ms"];
423342
- const queuePosition = record8["queue_position"];
423343
- const queueTicket = record8["queue_ticket"];
423401
+ const retryable = record9["retryable"];
423402
+ const reasonCode = record9["reason_code"];
423403
+ const retryAfterMs = record9["retry_after_ms"];
423404
+ const logicalRequestId = record9["logical_request_id"];
423405
+ const requestId = record9["request_id"];
423406
+ const queue = record9["queue"];
423407
+ const causeReasonCode = record9["cause_reason_code"];
423408
+ const admissionRetained = record9["admission_retained"];
423409
+ const resumeTtlMs = record9["resume_ttl_ms"];
423410
+ const queuePosition = record9["queue_position"];
423411
+ const queueTicket = record9["queue_ticket"];
423344
423412
  const responseReasonCode = err.responseHeaders["x-ollama-unify-reason-code"]?.trim() ?? "";
423345
423413
  const responseRetryable = err.responseHeaders["x-ollama-unify-retryable"]?.trim().toLowerCase() ?? "";
423346
423414
  const isLegacyContract = (isLegacyError || isAnnotatedError) && typeof requestId === "string" && requestId.length > 0 && !!queue && typeof queue === "object" && !Array.isArray(queue);
423347
- const isStructuredContract = typeof retryable === "boolean" && typeof reasonCode === "string" && reasonCode.length > 0 && (record8["ok"] === false || responseReasonCode === reasonCode);
423415
+ const isStructuredContract = typeof retryable === "boolean" && typeof reasonCode === "string" && reasonCode.length > 0 && (record9["ok"] === false || responseReasonCode === reasonCode);
423348
423416
  if (!isLegacyContract && !isStructuredContract || requestId !== void 0 && typeof requestId !== "string" || queue !== void 0 && (!queue || typeof queue !== "object" || Array.isArray(queue)) || retryable !== void 0 && typeof retryable !== "boolean" || reasonCode !== void 0 && typeof reasonCode !== "string" || retryAfterMs !== void 0 && (!Number.isFinite(retryAfterMs) || Number(retryAfterMs) < 0) || logicalRequestId !== void 0 && typeof logicalRequestId !== "string" || causeReasonCode !== void 0 && typeof causeReasonCode !== "string" || admissionRetained !== void 0 && typeof admissionRetained !== "boolean" || resumeTtlMs !== void 0 && (!Number.isFinite(resumeTtlMs) || Number(resumeTtlMs) < 0) || queuePosition !== void 0 && (!Number.isInteger(queuePosition) || Number(queuePosition) < 1) || queueTicket !== void 0 && (!Number.isInteger(queueTicket) || Number(queueTicket) < 1) || responseReasonCode && responseReasonCode !== reasonCode || responseRetryable && responseRetryable !== String(retryable).toLowerCase()) {
423349
423417
  return null;
423350
423418
  }
@@ -426880,10 +426948,10 @@ function ownersEqual(left, right) {
426880
426948
  function freezeEvent(state, atMs, owner) {
426881
426949
  return Object.freeze({ state, atMs: timestamp4(atMs), owner });
426882
426950
  }
426883
- function freezeRecord(record8) {
426951
+ function freezeRecord(record9) {
426884
426952
  return Object.freeze({
426885
- ...record8,
426886
- history: Object.freeze([...record8.history])
426953
+ ...record9,
426954
+ history: Object.freeze([...record9.history])
426887
426955
  });
426888
426956
  }
426889
426957
  function decisionsEqual(left, right) {
@@ -426911,49 +426979,49 @@ var TelegramInputOwnershipLedger = class {
426911
426979
  reason: "inputId is already bound to a different immutable target"
426912
426980
  };
426913
426981
  }
426914
- const record8 = freezeRecord({
426982
+ const record9 = freezeRecord({
426915
426983
  target: target2,
426916
426984
  owner,
426917
426985
  lifecycle: "received",
426918
426986
  revision: 0,
426919
426987
  history: Object.freeze([freezeEvent("received", atMs, owner)])
426920
426988
  });
426921
- this.records.set(target2.inputId, record8);
426922
- return { status: "applied", record: record8 };
426989
+ this.records.set(target2.inputId, record9);
426990
+ return { status: "applied", record: record9 };
426923
426991
  }
426924
426992
  claim(targetInput, ownerInput) {
426925
426993
  const bound = this.boundRecord(targetInput);
426926
426994
  if (bound.status !== "applied") return bound;
426927
- const record8 = bound.record;
426995
+ const record9 = bound.record;
426928
426996
  const owner = freezeOwner(ownerInput);
426929
- if (ownersEqual(record8.owner, owner)) {
426930
- return { status: "duplicate", record: record8 };
426997
+ if (ownersEqual(record9.owner, owner)) {
426998
+ return { status: "duplicate", record: record9 };
426931
426999
  }
426932
- if (isTelegramInputTerminalLifecycle(record8.lifecycle)) {
427000
+ if (isTelegramInputTerminalLifecycle(record9.lifecycle)) {
426933
427001
  return {
426934
427002
  status: "terminal",
426935
- record: record8,
427003
+ record: record9,
426936
427004
  reason: "terminal input ownership cannot be transferred"
426937
427005
  };
426938
427006
  }
426939
- if (owner.generation < record8.owner.generation) {
427007
+ if (owner.generation < record9.owner.generation) {
426940
427008
  return {
426941
427009
  status: "stale",
426942
- record: record8,
427010
+ record: record9,
426943
427011
  reason: "owner generation is older than the authoritative claim"
426944
427012
  };
426945
427013
  }
426946
- if (owner.generation === record8.owner.generation) {
427014
+ if (owner.generation === record9.owner.generation) {
426947
427015
  return {
426948
427016
  status: "contradiction",
426949
- record: record8,
427017
+ record: record9,
426950
427018
  reason: "one owner generation cannot name two owners"
426951
427019
  };
426952
427020
  }
426953
427021
  const next = freezeRecord({
426954
- ...record8,
427022
+ ...record9,
426955
427023
  owner,
426956
- revision: record8.revision + 1
427024
+ revision: record9.revision + 1
426957
427025
  });
426958
427026
  this.records.set(targetInput.inputId, next);
426959
427027
  return { status: "applied", record: next };
@@ -426961,30 +427029,30 @@ var TelegramInputOwnershipLedger = class {
426961
427029
  transition(targetInput, ownerInput, nextState, atMs = Date.now()) {
426962
427030
  const authorized = this.authorizedRecord(targetInput, ownerInput);
426963
427031
  if (authorized.status !== "applied") return authorized;
426964
- const record8 = authorized.record;
426965
- if (record8.lifecycle === nextState) {
426966
- return { status: "duplicate", record: record8 };
427032
+ const record9 = authorized.record;
427033
+ if (record9.lifecycle === nextState) {
427034
+ return { status: "duplicate", record: record9 };
426967
427035
  }
426968
- if (isTelegramInputTerminalLifecycle(record8.lifecycle)) {
427036
+ if (isTelegramInputTerminalLifecycle(record9.lifecycle)) {
426969
427037
  return {
426970
427038
  status: "terminal",
426971
- record: record8,
427039
+ record: record9,
426972
427040
  reason: "terminal input lifecycle cannot advance"
426973
427041
  };
426974
427042
  }
426975
- if (!ALLOWED_TRANSITIONS[record8.lifecycle].has(nextState)) {
427043
+ if (!ALLOWED_TRANSITIONS[record9.lifecycle].has(nextState)) {
426976
427044
  return {
426977
427045
  status: "invalid_transition",
426978
- record: record8,
426979
- reason: `${record8.lifecycle} cannot transition to ${nextState}`
427046
+ record: record9,
427047
+ reason: `${record9.lifecycle} cannot transition to ${nextState}`
426980
427048
  };
426981
427049
  }
426982
- return this.storeLifecycle(record8, nextState, atMs);
427050
+ return this.storeLifecycle(record9, nextState, atMs);
426983
427051
  }
426984
427052
  commitDecision(targetInput, ownerInput, decisionInput2, atMs = Date.now()) {
426985
427053
  const bound = this.boundRecord(targetInput);
426986
427054
  if (bound.status !== "applied") return bound;
426987
- const record8 = bound.record;
427055
+ const record9 = bound.record;
426988
427056
  const decision2 = {
426989
427057
  decisionId: nonEmpty(decisionInput2.decisionId, "decisionId"),
426990
427058
  contractFingerprint: nonEmpty(
@@ -426997,55 +427065,55 @@ var TelegramInputOwnershipLedger = class {
426997
427065
  if (decision2.contractVersion !== 2) {
426998
427066
  return {
426999
427067
  status: "invalid_transition",
427000
- record: record8,
427068
+ record: record9,
427001
427069
  reason: "only Telegram turn contract version 2 can be committed"
427002
427070
  };
427003
427071
  }
427004
- if (record8.decision) {
427005
- return decisionsEqual(record8.decision, decision2) ? { status: "duplicate", record: record8 } : {
427072
+ if (record9.decision) {
427073
+ return decisionsEqual(record9.decision, decision2) ? { status: "duplicate", record: record9 } : {
427006
427074
  status: "contradiction",
427007
- record: record8,
427075
+ record: record9,
427008
427076
  reason: "an input can have only one committed decision"
427009
427077
  };
427010
427078
  }
427011
427079
  const authorized = this.authorizedRecord(targetInput, ownerInput);
427012
427080
  if (authorized.status !== "applied") return authorized;
427013
- if (isTelegramInputTerminalLifecycle(record8.lifecycle)) {
427081
+ if (isTelegramInputTerminalLifecycle(record9.lifecycle)) {
427014
427082
  return {
427015
427083
  status: "terminal",
427016
- record: record8,
427084
+ record: record9,
427017
427085
  reason: "a terminal input cannot accept a decision"
427018
427086
  };
427019
427087
  }
427020
- if (!ALLOWED_TRANSITIONS[record8.lifecycle].has("decision_committed")) {
427088
+ if (!ALLOWED_TRANSITIONS[record9.lifecycle].has("decision_committed")) {
427021
427089
  return {
427022
427090
  status: "invalid_transition",
427023
- record: record8,
427024
- reason: `${record8.lifecycle} cannot commit a decision`
427091
+ record: record9,
427092
+ reason: `${record9.lifecycle} cannot commit a decision`
427025
427093
  };
427026
427094
  }
427027
427095
  const committed = Object.freeze({
427028
427096
  ...decision2,
427029
- committedBy: record8.owner,
427097
+ committedBy: record9.owner,
427030
427098
  committedAtMs: timestamp4(atMs)
427031
427099
  });
427032
427100
  const next = freezeRecord({
427033
- ...record8,
427101
+ ...record9,
427034
427102
  decision: committed,
427035
427103
  lifecycle: "decision_committed",
427036
- revision: record8.revision + 1,
427104
+ revision: record9.revision + 1,
427037
427105
  history: [
427038
- ...record8.history,
427039
- freezeEvent("decision_committed", atMs, record8.owner)
427106
+ ...record9.history,
427107
+ freezeEvent("decision_committed", atMs, record9.owner)
427040
427108
  ]
427041
427109
  });
427042
- this.records.set(record8.target.inputId, next);
427110
+ this.records.set(record9.target.inputId, next);
427043
427111
  return { status: "applied", record: next };
427044
427112
  }
427045
427113
  commitDelivery(targetInput, ownerInput, deliveryInput, atMs = Date.now()) {
427046
427114
  const bound = this.boundRecord(targetInput);
427047
427115
  if (bound.status !== "applied") return bound;
427048
- const record8 = bound.record;
427116
+ const record9 = bound.record;
427049
427117
  const delivery = {
427050
427118
  deliveryId: nonEmpty(deliveryInput.deliveryId, "deliveryId"),
427051
427119
  decisionId: nonEmpty(deliveryInput.decisionId, "decisionId"),
@@ -427055,98 +427123,98 @@ var TelegramInputOwnershipLedger = class {
427055
427123
  "transportReceiptId"
427056
427124
  )
427057
427125
  };
427058
- if (record8.delivery) {
427059
- return deliveriesEqual(record8.delivery, delivery) ? { status: "duplicate", record: record8 } : {
427126
+ if (record9.delivery) {
427127
+ return deliveriesEqual(record9.delivery, delivery) ? { status: "duplicate", record: record9 } : {
427060
427128
  status: "contradiction",
427061
- record: record8,
427129
+ record: record9,
427062
427130
  reason: "an input can have only one committed delivery"
427063
427131
  };
427064
427132
  }
427065
427133
  const authorized = this.authorizedRecord(targetInput, ownerInput);
427066
427134
  if (authorized.status !== "applied") return authorized;
427067
- if (isTelegramInputTerminalLifecycle(record8.lifecycle)) {
427135
+ if (isTelegramInputTerminalLifecycle(record9.lifecycle)) {
427068
427136
  return {
427069
427137
  status: "terminal",
427070
- record: record8,
427138
+ record: record9,
427071
427139
  reason: "a terminal input cannot accept a delivery"
427072
427140
  };
427073
427141
  }
427074
- if (!record8.decision || record8.decision.decisionId !== delivery.decisionId) {
427142
+ if (!record9.decision || record9.decision.decisionId !== delivery.decisionId) {
427075
427143
  return {
427076
427144
  status: "invalid_transition",
427077
- record: record8,
427145
+ record: record9,
427078
427146
  reason: "delivery must cite the committed decision"
427079
427147
  };
427080
427148
  }
427081
- if (record8.decision.disposition === "no_reply") {
427149
+ if (record9.decision.disposition === "no_reply") {
427082
427150
  return {
427083
427151
  status: "invalid_transition",
427084
- record: record8,
427152
+ record: record9,
427085
427153
  reason: "a no_reply decision cannot have a delivery"
427086
427154
  };
427087
427155
  }
427088
- if (record8.decision.disposition === "chat_reply" && delivery.kind !== "visible_reply" || record8.decision.disposition === "action" && delivery.kind !== "action_effect") {
427156
+ if (record9.decision.disposition === "chat_reply" && delivery.kind !== "visible_reply" || record9.decision.disposition === "action" && delivery.kind !== "action_effect") {
427089
427157
  return {
427090
427158
  status: "contradiction",
427091
- record: record8,
427159
+ record: record9,
427092
427160
  reason: "delivery kind contradicts the committed disposition"
427093
427161
  };
427094
427162
  }
427095
427163
  const committed = Object.freeze({
427096
427164
  ...delivery,
427097
- committedBy: record8.owner,
427165
+ committedBy: record9.owner,
427098
427166
  committedAtMs: timestamp4(atMs)
427099
427167
  });
427100
427168
  const next = freezeRecord({
427101
- ...record8,
427169
+ ...record9,
427102
427170
  delivery: committed,
427103
427171
  lifecycle: "delivery_committed",
427104
- revision: record8.revision + 1,
427172
+ revision: record9.revision + 1,
427105
427173
  history: [
427106
- ...record8.history,
427107
- freezeEvent("delivery_committed", atMs, record8.owner)
427174
+ ...record9.history,
427175
+ freezeEvent("delivery_committed", atMs, record9.owner)
427108
427176
  ]
427109
427177
  });
427110
- this.records.set(record8.target.inputId, next);
427178
+ this.records.set(record9.target.inputId, next);
427111
427179
  return { status: "applied", record: next };
427112
427180
  }
427113
427181
  complete(targetInput, ownerInput, terminal, atMs = Date.now()) {
427114
427182
  const bound = this.boundRecord(targetInput);
427115
427183
  if (bound.status !== "applied") return bound;
427116
- const record8 = bound.record;
427117
- if (record8.terminal) {
427118
- return record8.terminal === terminal ? { status: "duplicate", record: record8 } : {
427184
+ const record9 = bound.record;
427185
+ if (record9.terminal) {
427186
+ return record9.terminal === terminal ? { status: "duplicate", record: record9 } : {
427119
427187
  status: "contradiction",
427120
- record: record8,
427188
+ record: record9,
427121
427189
  reason: "an input can have only one terminal lifecycle result"
427122
427190
  };
427123
427191
  }
427124
427192
  const authorized = this.authorizedRecord(targetInput, ownerInput);
427125
427193
  if (authorized.status !== "applied") return authorized;
427126
427194
  if (terminal === "consumed") {
427127
- if (!record8.decision) {
427195
+ if (!record9.decision) {
427128
427196
  return {
427129
427197
  status: "invalid_transition",
427130
- record: record8,
427198
+ record: record9,
427131
427199
  reason: "consumed input requires a committed decision"
427132
427200
  };
427133
427201
  }
427134
- if (record8.decision.disposition !== "no_reply" && !record8.delivery) {
427202
+ if (record9.decision.disposition !== "no_reply" && !record9.delivery) {
427135
427203
  return {
427136
427204
  status: "invalid_transition",
427137
- record: record8,
427205
+ record: record9,
427138
427206
  reason: "reply and action decisions require a delivery receipt"
427139
427207
  };
427140
427208
  }
427141
427209
  }
427142
- if (!ALLOWED_TRANSITIONS[record8.lifecycle].has(terminal)) {
427210
+ if (!ALLOWED_TRANSITIONS[record9.lifecycle].has(terminal)) {
427143
427211
  return {
427144
427212
  status: "invalid_transition",
427145
- record: record8,
427146
- reason: `${record8.lifecycle} cannot transition to ${terminal}`
427213
+ record: record9,
427214
+ reason: `${record9.lifecycle} cannot transition to ${terminal}`
427147
427215
  };
427148
427216
  }
427149
- return this.storeLifecycle(record8, terminal, atMs, terminal);
427217
+ return this.storeLifecycle(record9, terminal, atMs, terminal);
427150
427218
  }
427151
427219
  boundRecord(targetInput) {
427152
427220
  const existing = this.records.get(targetInput.inputId);
@@ -427175,40 +427243,40 @@ var TelegramInputOwnershipLedger = class {
427175
427243
  authorizedRecord(targetInput, ownerInput) {
427176
427244
  const bound = this.boundRecord(targetInput);
427177
427245
  if (bound.status !== "applied") return bound;
427178
- const record8 = bound.record;
427246
+ const record9 = bound.record;
427179
427247
  let owner;
427180
427248
  try {
427181
427249
  owner = freezeOwner(ownerInput);
427182
427250
  } catch (error) {
427183
427251
  return {
427184
427252
  status: "contradiction",
427185
- record: record8,
427253
+ record: record9,
427186
427254
  reason: error instanceof Error ? error.message : String(error)
427187
427255
  };
427188
427256
  }
427189
- if (ownersEqual(record8.owner, owner)) return bound;
427190
- if (owner.generation < record8.owner.generation) {
427257
+ if (ownersEqual(record9.owner, owner)) return bound;
427258
+ if (owner.generation < record9.owner.generation) {
427191
427259
  return {
427192
427260
  status: "stale",
427193
- record: record8,
427261
+ record: record9,
427194
427262
  reason: "operation belongs to an older owner generation"
427195
427263
  };
427196
427264
  }
427197
427265
  return {
427198
427266
  status: "contradiction",
427199
- record: record8,
427267
+ record: record9,
427200
427268
  reason: "operation owner does not match the authoritative claim"
427201
427269
  };
427202
427270
  }
427203
- storeLifecycle(record8, state, atMs, terminal) {
427271
+ storeLifecycle(record9, state, atMs, terminal) {
427204
427272
  const next = freezeRecord({
427205
- ...record8,
427273
+ ...record9,
427206
427274
  lifecycle: state,
427207
427275
  terminal,
427208
- revision: record8.revision + 1,
427209
- history: [...record8.history, freezeEvent(state, atMs, record8.owner)]
427276
+ revision: record9.revision + 1,
427277
+ history: [...record9.history, freezeEvent(state, atMs, record9.owner)]
427210
427278
  });
427211
- this.records.set(record8.target.inputId, next);
427279
+ this.records.set(record9.target.inputId, next);
427212
427280
  return { status: "applied", record: next };
427213
427281
  }
427214
427282
  };
@@ -428078,9 +428146,9 @@ function adaptExecutionTool(tool, options = {}) {
428078
428146
  const mapResult = (result, args) => {
428079
428147
  const mapped = mapExecutionToolResult(result);
428080
428148
  if (tool.getHistoryObservationIdentity) {
428081
- const record8 = { args: structuredClone(args), native: result, mapped: { ...mapped } };
428082
- historyObservations.set(mapped, record8);
428083
- if (mapped.executionReceipt) historyObservations.set(mapped.executionReceipt, record8);
428149
+ const record9 = { args: structuredClone(args), native: result, mapped: { ...mapped } };
428150
+ historyObservations.set(mapped, record9);
428151
+ if (mapped.executionReceipt) historyObservations.set(mapped.executionReceipt, record9);
428084
428152
  }
428085
428153
  return mapped;
428086
428154
  };
@@ -428229,9 +428297,9 @@ function adaptExecutionTool(tool, options = {}) {
428229
428297
  }
428230
428298
  if (typeof tool.getHistoryObservationIdentity === "function") {
428231
428299
  adapted.getHistoryObservationIdentity = (args, result) => {
428232
- const record8 = historyObservations.get(result) ?? (result.executionReceipt && historyObservations.get(result.executionReceipt));
428233
- if (!record8 || JSON.stringify(args) !== JSON.stringify(record8.args) || result.success !== record8.mapped.success || result.output !== record8.mapped.output || result.llmContent !== record8.mapped.llmContent || result.error !== record8.mapped.error) return null;
428234
- return tool.getHistoryObservationIdentity(args, record8.native);
428300
+ const record9 = historyObservations.get(result) ?? (result.executionReceipt && historyObservations.get(result.executionReceipt));
428301
+ if (!record9 || JSON.stringify(args) !== JSON.stringify(record9.args) || result.success !== record9.mapped.success || result.output !== record9.mapped.output || result.llmContent !== record9.mapped.llmContent || result.error !== record9.mapped.error) return null;
428302
+ return tool.getHistoryObservationIdentity(args, record9.native);
428235
428303
  };
428236
428304
  }
428237
428305
  return adapted;