omnius 1.0.851 → 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,13 +343033,15 @@ 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"]);
343036
+ var knownUnsupportedKeywords = /* @__PURE__ */ new Set(["uniqueItems", "rootAnyOf", "requiredAllProperties", "oneOf"]);
343037
+ var optionalPropertyName = /^[A-Za-z_][A-Za-z0-9_-]{0,127}$/;
343037
343038
  var InferenceProviderError = class extends Error {
343038
343039
  status;
343039
343040
  reason;
343040
343041
  retryAfterMs;
343041
343042
  unsupportedKeywords;
343042
- constructor(status2, reason, retryAfterMs, unsupportedKeywords = []) {
343043
+ unsupportedOptionalProperty;
343044
+ constructor(status2, reason, retryAfterMs, unsupportedKeywords = [], unsupportedOptionalProperty) {
343043
343045
  const safeStatus = Number.isInteger(status2) && status2 >= 400 && status2 <= 599 ? status2 : 500;
343044
343046
  const safeReason = reasons.has(reason) ? reason : "upstream";
343045
343047
  super(`Inference provider rejected the request (${safeReason}; HTTP ${safeStatus}).`);
@@ -343047,6 +343049,8 @@ var InferenceProviderError = class extends Error {
343047
343049
  this.status = safeStatus;
343048
343050
  this.reason = safeReason;
343049
343051
  this.unsupportedKeywords = Object.freeze(safeReason === "unsupported_schema" && Array.isArray(unsupportedKeywords) ? [...new Set(unsupportedKeywords.filter((keyword) => knownUnsupportedKeywords.has(keyword)))] : []);
343052
+ if (this.unsupportedKeywords.includes("requiredAllProperties") && typeof unsupportedOptionalProperty === "string" && optionalPropertyName.test(unsupportedOptionalProperty))
343053
+ this.unsupportedOptionalProperty = unsupportedOptionalProperty;
343050
343054
  if (typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) && retryAfterMs > 0)
343051
343055
  this.retryAfterMs = Math.min(864e5, Math.ceil(retryAfterMs));
343052
343056
  }
@@ -343093,7 +343097,12 @@ function normalizeInferenceProviderError(value, headers) {
343093
343097
  const fields2 = [detail, response ?? {}, value];
343094
343098
  const codes = fields2.flatMap((field) => [code(field.code), code(field.type)]).filter((item) => item !== void 0);
343095
343099
  const knownStatus = fields2.flatMap((field) => [status(field.status), status(field.status_code), status(field.code)]).find((item) => item !== void 0);
343096
- const unsupportedKeywords = [...new Set(fields2.flatMap((field) => unsupportedGrammarKeywords(field.message)))];
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
+ const unsupportedKeywords = [.../* @__PURE__ */ new Set([
343102
+ ...fields2.flatMap((field) => unsupportedGrammarKeywords(field.message)),
343103
+ ...missingProperty ? ["requiredAllProperties"] : [],
343104
+ ...detail.type === "invalid_request_error" && detail.param === "schema" && detail.message === "'oneOf' is not permitted." ? ["oneOf"] : []
343105
+ ])];
343097
343106
  let reason = "upstream", inferredStatus = 500;
343098
343107
  if (knownStatus === 429 || codes.some((item) => rateCodes.has(item))) {
343099
343108
  reason = "rate";
@@ -343124,7 +343133,7 @@ function normalizeInferenceProviderError(value, headers) {
343124
343133
  }
343125
343134
  }
343126
343135
  if (unsupportedKeywords.length && reason !== "rate" && reason !== "auth")
343127
- return new InferenceProviderError(400, "unsupported_schema", void 0, unsupportedKeywords);
343136
+ return new InferenceProviderError(400, "unsupported_schema", void 0, unsupportedKeywords, missingProperty);
343128
343137
  return new InferenceProviderError(knownStatus ?? inferredStatus, reason, reason === "rate" ? retryAfterMs : void 0);
343129
343138
  }
343130
343139
  function normalizeInferenceHttpSchemaError(httpStatus, responseBody, headers) {
@@ -344148,11 +344157,23 @@ function collectOpenCodeResponsesResponse(response, request, options) {
344148
344157
  }
344149
344158
 
344150
344159
  // packages/orchestrator/dist/provider-schema-adapter.js
344151
- var SUPPORTED_PROVIDER_SCHEMA_ADAPTATIONS = Object.freeze(["uniqueItems", "rootAnyOf"]);
344160
+ var SUPPORTED_PROVIDER_SCHEMA_ADAPTATIONS = Object.freeze(["uniqueItems", "rootAnyOf", "requiredAllProperties", "oneOf"]);
344152
344161
  var object9 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
344162
+ function hasProviderRequiredAllPropertiesConflict(format, missingProperty) {
344163
+ if (format.type !== "json_schema")
344164
+ return false;
344165
+ const wrapper = object9(format.json_schema) ? format.json_schema : format.json_schema === void 0 ? format : void 0;
344166
+ const schema = wrapper?.schema;
344167
+ if (wrapper?.strict !== true || !object9(schema) || schema.type !== "object" || "$ref" in schema || schema.additionalProperties !== false || !object9(schema.properties) || !Array.isArray(schema.required))
344168
+ return false;
344169
+ const properties = schema.properties, required = schema.required, names = Object.keys(properties);
344170
+ if (!names.length || new Set(required).size !== required.length || required.some((name) => typeof name !== "string" || !Object.hasOwn(properties, name)))
344171
+ return false;
344172
+ return missingProperty === void 0 ? names.some((name) => !required.includes(name)) : Object.hasOwn(properties, missingProperty) && !required.includes(missingProperty);
344173
+ }
344153
344174
  function lowerProviderSchema(schema, unsupportedKeywords) {
344154
344175
  const lowered = structuredClone(schema);
344155
- const adaptations = new Set(unsupportedKeywords.filter((keyword) => keyword === "uniqueItems"));
344176
+ const adaptations = new Set(unsupportedKeywords.filter((keyword) => keyword === "uniqueItems" || keyword === "oneOf"));
344156
344177
  if (adaptations.size === 0)
344157
344178
  return lowered;
344158
344179
  const seen = /* @__PURE__ */ new WeakSet();
@@ -344160,8 +344181,12 @@ function lowerProviderSchema(schema, unsupportedKeywords) {
344160
344181
  if (!object9(value) || seen.has(value))
344161
344182
  return;
344162
344183
  seen.add(value);
344163
- for (const keyword of adaptations)
344164
- 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
+ }
344165
344190
  for (const keyword of ["properties", "patternProperties", "$defs", "definitions", "dependentSchemas", "dependencies"]) {
344166
344191
  if (object9(value[keyword]))
344167
344192
  for (const child of Object.values(value[keyword]))
@@ -344197,17 +344222,17 @@ function lowerProviderSchema(schema, unsupportedKeywords) {
344197
344222
  }
344198
344223
  function lowerResponseSchema(schema, unsupportedKeywords) {
344199
344224
  const lowered = lowerProviderSchema(schema, unsupportedKeywords);
344200
- if (!unsupportedKeywords.includes("rootAnyOf") || lowered.type !== "object" || lowered.additionalProperties !== false || !object9(lowered.properties) || !Array.isArray(lowered.required) || !Array.isArray(lowered.anyOf) || !lowered.anyOf.length)
344225
+ if (!unsupportedKeywords.includes("rootAnyOf") || lowered.type !== "object" || "$ref" in lowered || lowered.additionalProperties !== false || !object9(lowered.properties) || !Array.isArray(lowered.required) || !Array.isArray(lowered.anyOf) || !lowered.anyOf.length)
344201
344226
  return lowered;
344202
344227
  const properties = lowered.properties, required = lowered.required;
344203
344228
  const names = Object.keys(properties);
344204
- if (!names.length || names.some((name) => !required.includes(name)) || required.some((name) => typeof name !== "string" || !Object.hasOwn(properties, name)))
344229
+ if (!names.length || new Set(required).size !== required.length || required.some((name) => typeof name !== "string" || !Object.hasOwn(properties, name)))
344205
344230
  return lowered;
344206
344231
  if (!lowered.anyOf.every((branch) => {
344207
- if (!object9(branch) || branch.type !== "object" || branch.additionalProperties !== false || !object9(branch.properties) || !Array.isArray(branch.required))
344232
+ if (!object9(branch) || "$ref" in branch || branch.type !== "object" || branch.additionalProperties !== false || !object9(branch.properties) || !Array.isArray(branch.required))
344208
344233
  return false;
344209
344234
  const branchProperties = branch.properties, branchRequired = branch.required;
344210
- return names.every((name) => Object.hasOwn(branchProperties, name) && branchRequired.includes(name)) && Object.keys(branchProperties).every((name) => names.includes(name));
344235
+ return new Set(branchRequired).size === branchRequired.length && branchRequired.every((name) => typeof name === "string" && Object.hasOwn(branchProperties, name)) && required.every((name) => branchRequired.includes(name)) && names.every((name) => Object.hasOwn(branchProperties, name)) && Object.keys(branchProperties).every((name) => names.includes(name));
344211
344236
  }))
344212
344237
  return lowered;
344213
344238
  delete lowered.anyOf;
@@ -344235,6 +344260,7 @@ var DEFAULTS = Object.freeze({
344235
344260
  providers: [],
344236
344261
  // The verified full native-tool packet takes ~26s on a healthy community route.
344237
344262
  requestTimeoutMs: 45e3,
344263
+ requestTimeoutMsSource: "default",
344238
344264
  totalTimeoutMs: 12e4,
344239
344265
  localTimeoutMs: 2e4
344240
344266
  });
@@ -344341,6 +344367,8 @@ function loadRemoteInferencePolicy(options = {}) {
344341
344367
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 100 || value > maximum)
344342
344368
  return disabled();
344343
344369
  result[field] = value;
344370
+ if (field === "requestTimeoutMs")
344371
+ result.requestTimeoutMsSource = "explicit";
344344
344372
  }
344345
344373
  }
344346
344374
  if (selected["providers"] !== void 0) {
@@ -344965,7 +344993,7 @@ function safeFailure(error, request, route) {
344965
344993
  const status2 = errorStatus(error);
344966
344994
  const chain = errorChain(error);
344967
344995
  const upstream429 = status2 === 429 && chain.some((value) => value instanceof InferenceProviderError && value.reason === "upstream");
344968
- const category = upstream429 ? "upstream_unavailable" : status2 === 429 ? "rate_limit" : status2 === 401 || status2 === 403 ? "authentication" : status2 !== void 0 && status2 >= 400 && status2 < 500 ? "request_rejected" : status2 !== void 0 && status2 >= 500 ? "upstream_unavailable" : chain.some((value) => value instanceof AttemptTimeout || object12(value) && (value.name === "TimeoutError" || value.name === "AbortError" || value.code === "ETIMEDOUT")) ? "timeout" : chain.some((value) => value instanceof EmptyInferenceResponse) ? "empty_response" : chain.some((value) => value instanceof SyntaxError || value instanceof InvalidInferenceResponse || value instanceof ExpectedInferenceResponseError || object12(value) && value.name === "OpenAIChatResponseError") ? "invalid_response" : "transport";
344996
+ const category = upstream429 ? "upstream_unavailable" : status2 === 429 ? "rate_limit" : status2 === 401 || status2 === 403 ? "authentication" : status2 !== void 0 && status2 >= 400 && status2 < 500 ? "request_rejected" : status2 !== void 0 && status2 >= 500 ? "upstream_unavailable" : chain.some((value) => value instanceof AttemptTimeout || object12(value) && (value.name === "TimeoutError" || value.name === "AbortError" || value.code === "ETIMEDOUT") || value instanceof Error && /^stream timeout: no response or chunk within [0-9]+s$/.test(value.message)) ? "timeout" : chain.some((value) => value instanceof EmptyInferenceResponse) ? "empty_response" : chain.some((value) => value instanceof SyntaxError || value instanceof InvalidInferenceResponse || value instanceof ExpectedInferenceResponseError || object12(value) && value.name === "OpenAIChatResponseError") ? "invalid_response" : "transport";
344969
344997
  const validation = chain.find((value) => value instanceof ExpectedInferenceResponseError);
344970
344998
  const providerSchemaError = chain.find((value) => value instanceof InferenceProviderError && value.reason === "unsupported_schema");
344971
344999
  const malformedEnvelope = chain.some((value) => object12(value) && value.name === "OpenAIChatResponseError");
@@ -345258,7 +345286,7 @@ var RemoteInferenceFallback = class _RemoteInferenceFallback {
345258
345286
  if (!remote.chatCompletionStream)
345259
345287
  throw new Error("Remote streaming unavailable.");
345260
345288
  this.recordRoute(candidate, bounded3);
345261
- yield* remote.chatCompletionStream(this.remoteRequest(bounded3, candidate));
345289
+ yield* remote.chatCompletionStream(this.remoteRequest(bounded3, candidate, deadline));
345262
345290
  }.bind(this);
345263
345291
  const streamBudget = Math.min(deadline - this.now(), request.timeoutMs > 0 ? request.timeoutMs : Infinity);
345264
345292
  const raw = this.requireUsableStream(this.boundedStream(request, streamBudget, factory), request);
@@ -345503,8 +345531,14 @@ var RemoteInferenceFallback = class _RemoteInferenceFallback {
345503
345531
  model: route.model,
345504
345532
  kind: route.keyless ? "keyless" : "configured"
345505
345533
  });
345506
- request.onInferenceRoute?.({ ...this.lastRoute });
345507
- this.options.onRoute?.({ providerId: this.lastRoute.providerId, model: this.lastRoute.model });
345534
+ try {
345535
+ request.onInferenceRoute?.({ ...this.lastRoute });
345536
+ } catch {
345537
+ }
345538
+ try {
345539
+ this.options.onRoute?.({ providerId: this.lastRoute.providerId, model: this.lastRoute.model });
345540
+ } catch {
345541
+ }
345508
345542
  this.lifecycle(request, "selected", route);
345509
345543
  }
345510
345544
  lifecycle(request, phase, route, error) {
@@ -345512,7 +345546,7 @@ var RemoteInferenceFallback = class _RemoteInferenceFallback {
345512
345546
  if (!request.onInferenceRouteLifecycle)
345513
345547
  return;
345514
345548
  const format = request.responseFormat ?? request.response_format;
345515
- const promptOnly = route?.nativeStructuredOutput === false && (format?.type === "json_schema" || format?.type === "json_object");
345549
+ const promptOnly = route?.nativeStructuredOutput === false && (format?.type === "json_schema" || format?.type === "json_object") || Boolean(route && format && this.schemaRestrictions(route).includes("requiredAllProperties") && hasProviderRequiredAllPropertiesConflict(format));
345516
345550
  const receipt = {
345517
345551
  location: route ? "remote" : "local",
345518
345552
  phase,
@@ -345613,8 +345647,11 @@ var RemoteInferenceFallback = class _RemoteInferenceFallback {
345613
345647
  return false;
345614
345648
  const keywords = [.../* @__PURE__ */ new Set([...previous, ...added])];
345615
345649
  const format = request.responseFormat ?? request.response_format;
345616
- const changesFormat = format && JSON.stringify(lowerProviderResponseFormat(format, keywords)) !== JSON.stringify(format);
345617
- const changesTools = request.tools.some((tool) => JSON.stringify(lowerProviderSchema(tool.function.parameters, keywords)) !== JSON.stringify(tool.function.parameters));
345650
+ const newPromptOnly = route.nativeStructuredOutput !== false && added.includes("requiredAllProperties") && format && failure.unsupportedOptionalProperty !== void 0 && hasProviderRequiredAllPropertiesConflict(format, failure.unsupportedOptionalProperty);
345651
+ if (added.includes("requiredAllProperties") && !newPromptOnly)
345652
+ return false;
345653
+ const changesFormat = newPromptOnly || format && JSON.stringify(lowerProviderResponseFormat(format, keywords)) !== JSON.stringify(lowerProviderResponseFormat(format, previous));
345654
+ const changesTools = request.tools.some((tool) => JSON.stringify(lowerProviderSchema(tool.function.parameters, keywords)) !== JSON.stringify(lowerProviderSchema(tool.function.parameters, previous)));
345618
345655
  if (!changesFormat && !changesTools)
345619
345656
  return false;
345620
345657
  if (nativeSchemaRestrictions.size >= 256)
@@ -345627,7 +345664,7 @@ var RemoteInferenceFallback = class _RemoteInferenceFallback {
345627
345664
  const keywords = this.schemaRestrictions(route);
345628
345665
  const format = request.responseFormat ?? request.response_format;
345629
345666
  const structured = format?.type === "json_schema" || format?.type === "json_object";
345630
- const promptOnly = route.nativeStructuredOutput === false && structured;
345667
+ const promptOnly = route.nativeStructuredOutput === false && structured || keywords.includes("requiredAllProperties") && format !== void 0 && hasProviderRequiredAllPropertiesConflict(format);
345631
345668
  if (!keywords.length && !structured)
345632
345669
  return request;
345633
345670
  const loweredFormat = format ? lowerProviderResponseFormat(format, keywords) : void 0;
@@ -345640,7 +345677,8 @@ var RemoteInferenceFallback = class _RemoteInferenceFallback {
345640
345677
  const instructions = formatExpectedInferenceInstructions(request) + [
345641
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." : "",
345642
345679
  keywords.includes("uniqueItems") ? "The provider's native grammar cannot express uniqueItems. The unchanged host contract still requires those arrays to contain no duplicates." : "",
345643
- 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." : ""
345644
345682
  ].filter(Boolean).map((line) => `
345645
345683
  ${line}`).join("");
345646
345684
  const { responseFormat: _camelFormat, response_format: _snakeFormat, ...withoutNativeFormat } = request;
@@ -345659,7 +345697,7 @@ ${line}`).join("");
345659
345697
  }) } : {}
345660
345698
  };
345661
345699
  }
345662
- remoteRequest(request, route) {
345700
+ remoteRequest(request, route, streamDeadline) {
345663
345701
  const prepared = this.prepareModelContract(request, route);
345664
345702
  const { numCtx: _numCtx, num_ctx: _num_ctx, localAdmissionFailure: _failure, ...host } = prepared;
345665
345703
  const wire = this.scrubber(route)({
@@ -345670,6 +345708,8 @@ ${line}`).join("");
345670
345708
  responseFormat: prepared.responseFormat,
345671
345709
  response_format: prepared.response_format
345672
345710
  });
345711
+ const nativeIdle = streamDeadline !== void 0 && (request.nativePlanningStreamIdleTimeoutMs === 9e4 || request.structuredReviewStreamIdleTimeoutMs === 9e4) && this.policy.requestTimeoutMsSource === "default";
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);
345673
345713
  return {
345674
345714
  ...host,
345675
345715
  ...wire,
@@ -345683,7 +345723,7 @@ ${line}`).join("");
345683
345723
  remoteClientIdentity: route.keyless?.clientIdentity === "opencode" && route.baseUrl === OPENCODE_INFERENCE_BASE_URL ? "opencode" : void 0,
345684
345724
  remoteOpenCodeApiShape: route.openCodeApiShape,
345685
345725
  ...route.keyless?.directAnswer ? { chatTemplateKwargs: { enable_thinking: false } } : {},
345686
- timeoutMs: Math.min(request.timeoutMs, this.policy.requestTimeoutMs)
345726
+ timeoutMs
345687
345727
  };
345688
345728
  }
345689
345729
  compatible(request, route, includeCooling = false) {
@@ -346497,40 +346537,40 @@ function cleanId(value, max = 240) {
346497
346537
  function normalizeExpectedOutcomeContractV1(value) {
346498
346538
  if (!value || typeof value !== "object" || Array.isArray(value))
346499
346539
  return null;
346500
- const record8 = value;
346501
- if (record8["schema"] !== "omnius.expected-outcome-contract.v1")
346540
+ const record9 = value;
346541
+ if (record9["schema"] !== "omnius.expected-outcome-contract.v1")
346502
346542
  return null;
346503
- const route = record8["route"];
346504
- const continuity = record8["continuity"];
346505
- const planningMode = record8["planningMode"];
346543
+ const route = record9["route"];
346544
+ const continuity = record9["continuity"];
346545
+ const planningMode = record9["planningMode"];
346506
346546
  if (!ROUTES.has(route) || !CONTINUITIES.has(continuity))
346507
346547
  return null;
346508
346548
  if (!PLANNING_MODES.has(planningMode))
346509
346549
  return null;
346510
- const confidence2 = record8["confidence"];
346511
- const reason = cleanId(record8["reason"], 1e3);
346512
- 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"])) {
346513
346553
  return null;
346514
346554
  }
346515
346555
  const citedEvidenceIds = [
346516
- ...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)))
346517
346557
  ].slice(0, 64);
346518
- if (citedEvidenceIds.length !== record8["citedEvidenceIds"].length)
346558
+ if (citedEvidenceIds.length !== record9["citedEvidenceIds"].length)
346519
346559
  return null;
346520
- const outcome = record8["outcome"];
346560
+ const outcome = record9["outcome"];
346521
346561
  if (!OUTCOMES.has(outcome))
346522
346562
  return null;
346523
- if (!Array.isArray(record8["requiredEffects"]))
346563
+ if (!Array.isArray(record9["requiredEffects"]))
346524
346564
  return null;
346525
346565
  const requiredEffects = [
346526
- ...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)))
346527
346567
  ];
346528
- if (requiredEffects.length !== record8["requiredEffects"].length || !requiredEffects.includes(CORE_EFFECT[outcome])) {
346568
+ if (requiredEffects.length !== record9["requiredEffects"].length || !requiredEffects.includes(CORE_EFFECT[outcome])) {
346529
346569
  return null;
346530
346570
  }
346531
- const activeScopeId = cleanId(record8["activeScopeId"], 500);
346532
- const inputId = cleanId(record8["inputId"]);
346533
- const decisionId = cleanId(record8["decisionId"]);
346571
+ const activeScopeId = cleanId(record9["activeScopeId"], 500);
346572
+ const inputId = cleanId(record9["inputId"]);
346573
+ const decisionId = cleanId(record9["decisionId"]);
346534
346574
  return {
346535
346575
  schema: "omnius.expected-outcome-contract.v1",
346536
346576
  route,
@@ -346570,17 +346610,17 @@ function expectedOutcomeAllowsTextOnlyCompletion(contract) {
346570
346610
  function normalizeCompletionDeliveryReceipt(value) {
346571
346611
  if (!value || typeof value !== "object" || Array.isArray(value))
346572
346612
  return null;
346573
- const record8 = value;
346574
- if (record8["schema"] !== "omnius.completion-delivery-receipt.v1")
346613
+ const record9 = value;
346614
+ if (record9["schema"] !== "omnius.completion-delivery-receipt.v1")
346575
346615
  return null;
346576
- const provider = cleanId(record8["provider"], 120);
346577
- const target2 = cleanId(record8["target"], 500);
346578
- const receiptId = cleanId(record8["receiptId"], 500);
346579
- 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);
346580
346620
  if (!provider || !target2 || !receiptId || !deliveredAtIso)
346581
346621
  return null;
346582
- const artifactPaths = Array.isArray(record8["artifactPaths"]) ? [
346583
- ...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))
346584
346624
  ].slice(0, 32) : void 0;
346585
346625
  return {
346586
346626
  schema: "omnius.completion-delivery-receipt.v1",
@@ -346913,10 +346953,10 @@ function normalizeTaskObjectiveContractV1(value) {
346913
346953
  const raw = input["deliveryTarget"];
346914
346954
  if (!raw || typeof raw !== "object" || Array.isArray(raw))
346915
346955
  return null;
346916
- const record8 = raw;
346917
- const surface = clean(record8["surface"], 120);
346918
- const targetId = clean(record8["targetId"], 500);
346919
- 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);
346920
346960
  if (!surface || !targetId)
346921
346961
  return null;
346922
346962
  deliveryTarget = { surface, targetId, ...threadId ? { threadId } : {} };
@@ -347777,21 +347817,21 @@ function prepareReviewedObjectiveInterpretationRevisionV1(input) {
347777
347817
  };
347778
347818
  return { ...body, id: `interpretation:${taskExecutionDigest(body)}` };
347779
347819
  }
347780
- function revisedLedger(ledger, record8) {
347820
+ function revisedLedger(ledger, record9) {
347781
347821
  const next = {
347782
347822
  ...structuredClone(ledger),
347783
- objectiveContract: structuredClone(record8.nextContract),
347784
- reviewedInterpretation: structuredClone(record8),
347823
+ objectiveContract: structuredClone(record9.nextContract),
347824
+ reviewedInterpretation: structuredClone(record9),
347785
347825
  status: "open",
347786
347826
  updatedAtIso: (/* @__PURE__ */ new Date()).toISOString()
347787
347827
  };
347788
347828
  delete next.terminal;
347789
347829
  delete next.objectiveFrontier;
347790
347830
  delete next.objectiveConvergence;
347791
- if (record8.nextWorkPlan)
347792
- next.workPlan = structuredClone(record8.nextWorkPlan);
347831
+ if (record9.nextWorkPlan)
347832
+ next.workPlan = structuredClone(record9.nextWorkPlan);
347793
347833
  else if (next.workPlan) {
347794
- 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 });
347795
347835
  if (rebound)
347796
347836
  next.workPlan = rebound;
347797
347837
  else
@@ -347835,21 +347875,21 @@ function commitReviewedObjectiveInterpretationRevisionV1(input) {
347835
347875
  const raw = readFileSync24(input.ledgerPath, "utf8");
347836
347876
  if (sha6(raw) !== input.expectedLedgerSha256)
347837
347877
  throw new Error("Reviewed interpretation ledger compare-and-swap failed");
347838
- const ledger = restoreCompletionLedgerSnapshot(JSON.parse(raw)), record8 = input.prepare(ledger);
347839
- prepared = record8;
347840
- 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)
347841
347881
  throw new Error("Reviewed interpretation prior bytes changed");
347842
- const next = revisedLedger(ledger, record8), nextRaw = encoded(next);
347882
+ const next = revisedLedger(ledger, record9), nextRaw = encoded(next);
347843
347883
  const transaction = {
347844
347884
  schema: "omnius.reviewed-objective-interpretation-transaction.v1",
347845
- record: record8,
347885
+ record: record9,
347846
347886
  nextLedger: next,
347847
347887
  nextLedgerSha256: sha6(nextRaw)
347848
347888
  };
347849
347889
  writeAtomic(recordPath, encoded(transaction));
347850
347890
  input.persistenceFaultForTest?.("committed_before_projection");
347851
347891
  writeAtomic(input.ledgerPath, nextRaw);
347852
- return { record: record8, ledger: next, recordPath };
347892
+ return { record: record9, ledger: next, recordPath };
347853
347893
  } catch (error) {
347854
347894
  let committed = false;
347855
347895
  try {
@@ -347915,36 +347955,36 @@ function reconcileReviewedObjectiveInterpretationRevisionV1(ledgerPath, expected
347915
347955
 
347916
347956
  // packages/orchestrator/dist/nativeRequirementAmendment.js
347917
347957
  var hash11 = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
347918
- function validateNativeTaskRequirementAmendmentRecordV1(record8, evidence) {
347958
+ function validateNativeTaskRequirementAmendmentRecordV1(record9, evidence) {
347919
347959
  try {
347920
- const { id: id5, ...body } = record8, a = record8.authority, r = a.review;
347921
- const old = normalizeTaskObjectiveContractV1(record8.priorContract), next = normalizeTaskObjectiveContractV1(a.nextContract);
347922
- const oldOutcome = normalizeExpectedOutcomeContractV1(record8.priorExpectedOutcome), outcome = normalizeExpectedOutcomeContractV1(a.nextExpectedOutcome);
347923
- 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({
347924
347964
  requirements: next.requirements,
347925
347965
  evidence: a.nativeEvidence,
347926
347966
  nativeScopeSha256: a.scope.nativeScopeSha256,
347927
347967
  nativeEvidenceSnapshotSha256: r.nativeEvidenceSnapshotSha256
347928
- }) && 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);
347929
- 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.
347930
347970
  !prior.externalEffectReceipt && !prior.deliveryReceipt && !prior.receipt && prior.role !== "mutation" && current.progressClass === "control_bookkeeping" && current.success === void 0 && !current.objectiveEvidenceKinds?.length))))
347931
347971
  return false;
347932
347972
  const priorLedger = createCompletionLedger({
347933
- runId: record8.priorScope.nativeRunnerRunId,
347934
- taskEpoch: record8.priorScope.taskEpoch,
347973
+ runId: record9.priorScope.nativeRunnerRunId,
347974
+ taskEpoch: record9.priorScope.taskEpoch,
347935
347975
  goal: old.goal,
347936
347976
  objectiveContract: old
347937
347977
  });
347938
- priorLedger.evidence = structuredClone(record8.priorEvidence);
347939
- priorLedger.workPlan = structuredClone(record8.priorWorkPlan);
347978
+ priorLedger.evidence = structuredClone(record9.priorEvidence);
347979
+ priorLedger.workPlan = structuredClone(record9.priorWorkPlan);
347940
347980
  const replay = applyNativeTaskRequirementAmendmentInternal({
347941
347981
  ledger: priorLedger,
347942
347982
  priorExpectedOutcome: oldOutcome,
347943
- priorScope: record8.priorScope,
347983
+ priorScope: record9.priorScope,
347944
347984
  amendment: a,
347945
347985
  steering: { inputId: a.inputId, source: "telegram", taskEpoch: a.scope.taskEpoch, intent: "append" }
347946
347986
  }, false);
347947
- return replay.nativeRequirementAmendments?.at(-1)?.id === record8.id;
347987
+ return replay.nativeRequirementAmendments?.at(-1)?.id === record9.id;
347948
347988
  } catch {
347949
347989
  return false;
347950
347990
  }
@@ -349206,7 +349246,7 @@ function restoreCompletionLedgerSnapshot(value) {
349206
349246
  throw new Error("Unsupported completion ledger schema");
349207
349247
  }
349208
349248
  parsed.schema = COMPLETION_LEDGER_SCHEMA;
349209
- 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))))
349210
349250
  throw new Error("Invalid persisted native requirement amendment authority");
349211
349251
  if (parsed.objectiveContract) {
349212
349252
  const contract = normalizeTaskObjectiveContractV1(parsed.objectiveContract);
@@ -349466,11 +349506,11 @@ function validateContinuationStrengthening(input) {
349466
349506
  ].some((receipt) => receipt.criterionId === proof.criterionId || receipt.supportedAnswer !== void 0)))
349467
349507
  throw new Error("Task objective strengthening cannot inherit a seeded answer review");
349468
349508
  }
349469
- function claimPath(record8) {
349470
- 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`;
349471
349511
  }
349472
- function withContinuationClaimLock(record8, operation) {
349473
- const path7 = `${claimPath(record8)}.lock`;
349512
+ function withContinuationClaimLock(record9, operation) {
349513
+ const path7 = `${claimPath(record9)}.lock`;
349474
349514
  const token5 = JSON.stringify({ pid: process.pid, nonce: Math.random().toString(16).slice(2) });
349475
349515
  let fd;
349476
349516
  try {
@@ -349504,14 +349544,14 @@ function withContinuationClaimLock(record8, operation) {
349504
349544
  unlinkSync9(path7);
349505
349545
  }
349506
349546
  }
349507
- function readClaim(record8) {
349508
- const claim = JSON.parse(readFileSync26(claimPath(record8), "utf8"));
349509
- 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))
349510
349550
  throw new Error("Task objective predecessor belongs to a different admitted recipient");
349511
349551
  return claim;
349512
349552
  }
349513
- function writeClaim(record8, claim, exclusive = false) {
349514
- 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`;
349515
349555
  const fd = openSync7(temporary, "wx", 384);
349516
349556
  try {
349517
349557
  try {
@@ -349539,57 +349579,57 @@ function writeClaim(record8, claim, exclusive = false) {
349539
349579
  throw error;
349540
349580
  }
349541
349581
  }
349542
- function claimTaskObjectiveContinuation(record8) {
349543
- return withContinuationClaimLock(record8, () => claimTaskObjectiveContinuationLocked(record8));
349582
+ function claimTaskObjectiveContinuation(record9) {
349583
+ return withContinuationClaimLock(record9, () => claimTaskObjectiveContinuationLocked(record9));
349544
349584
  }
349545
- function claimTaskObjectiveContinuationLocked(record8) {
349546
- const path7 = claimPath(record8);
349585
+ function claimTaskObjectiveContinuationLocked(record9) {
349586
+ const path7 = claimPath(record9);
349547
349587
  const claim = {
349548
349588
  schema: "omnius.task-objective-continuation-claim.v1",
349549
- predecessorLedgerSha256: record8.input.predecessor.ledgerSha256,
349550
- authoritySha256: record8.authoritySha256,
349551
- recipientBridgeRunId: record8.input.scope.recipientBridgeRunId,
349552
- currentGeneration: record8.input.scope.currentGeneration,
349553
- 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,
349554
349594
  phase: "pending"
349555
349595
  };
349556
349596
  if (existsSync27(path7)) {
349557
- const old = readClaim(record8);
349558
- if (old.recipientRunId === record8.recipientRunId)
349597
+ const old = readClaim(record9);
349598
+ if (old.recipientRunId === record9.recipientRunId)
349559
349599
  return;
349560
349600
  if (old.phase === "inference_started")
349561
349601
  throw new Error("Task objective continuation requires recipient interruption reconciliation");
349562
- writeClaim(record8, claim);
349602
+ writeClaim(record9, claim);
349563
349603
  } else {
349564
- writeClaim(record8, claim, true);
349604
+ writeClaim(record9, claim, true);
349565
349605
  }
349566
349606
  }
349567
- function commitTaskObjectiveContinuation(record8) {
349568
- return withContinuationClaimLock(record8, () => commitTaskObjectiveContinuationLocked(record8));
349607
+ function commitTaskObjectiveContinuation(record9) {
349608
+ return withContinuationClaimLock(record9, () => commitTaskObjectiveContinuationLocked(record9));
349569
349609
  }
349570
- function commitTaskObjectiveContinuationLocked(record8) {
349571
- const claim = readClaim(record8);
349572
- if (claim.recipientRunId !== record8.recipientRunId)
349610
+ function commitTaskObjectiveContinuationLocked(record9) {
349611
+ const claim = readClaim(record9);
349612
+ if (claim.recipientRunId !== record9.recipientRunId)
349573
349613
  throw new Error("Task objective continuation recipient was superseded");
349574
- const recordSha256 = taskObjectiveContinuationDigest(record8);
349614
+ const recordSha256 = taskObjectiveContinuationDigest(record9);
349575
349615
  if (claim.phase !== "pending" && claim.recordSha256 !== recordSha256)
349576
349616
  throw new Error("Task objective continuation committed proof changed");
349577
- 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 });
349578
349618
  }
349579
- function startTaskObjectiveContinuationInference(record8) {
349580
- return withContinuationClaimLock(record8, () => startTaskObjectiveContinuationInferenceLocked(record8));
349619
+ function startTaskObjectiveContinuationInference(record9) {
349620
+ return withContinuationClaimLock(record9, () => startTaskObjectiveContinuationInferenceLocked(record9));
349581
349621
  }
349582
- function startTaskObjectiveContinuationInferenceLocked(record8) {
349583
- const claim = readClaim(record8);
349584
- 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))
349585
349625
  throw new Error("Task objective continuation source restoration is not committed for this recipient");
349586
349626
  if (claim.phase === "committed")
349587
- writeClaim(record8, { ...claim, phase: "inference_started" });
349627
+ writeClaim(record9, { ...claim, phase: "inference_started" });
349588
349628
  }
349589
- function committedClaim(record8) {
349629
+ function committedClaim(record9) {
349590
349630
  try {
349591
- const claim = readClaim(record8);
349592
- 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);
349593
349633
  } catch {
349594
349634
  return false;
349595
349635
  }
@@ -349660,7 +349700,7 @@ function admitTaskObjectiveContinuation(input) {
349660
349700
  }) !== seed.manifestSha256)
349661
349701
  throw new Error("Task objective continuation manifest changed");
349662
349702
  validateContinuationStrengthening({ seed, prior, recipient: input.contract, ledger });
349663
- const record8 = {
349703
+ const record9 = {
349664
349704
  schema: "omnius.task-objective-continuation-record.v1",
349665
349705
  recipientRunId: input.recipientRunId,
349666
349706
  taskEpoch: p.taskEpoch,
@@ -349670,28 +349710,28 @@ function admitTaskObjectiveContinuation(input) {
349670
349710
  importedEvidence: [],
349671
349711
  maximumInheritedEvidenceOrdinal: Math.max(0, ledger.taskObjectiveContinuation?.maximumInheritedEvidenceOrdinal ?? 0, ...ledger.evidence.map((entry) => /^ev_(\d+)$/.test(entry.id) ? Number(entry.id.slice(3)) : 0))
349672
349712
  };
349673
- admittedRecords.add(record8);
349674
- return { ledger, record: record8 };
349713
+ admittedRecords.add(record9);
349714
+ return { ledger, record: record9 };
349675
349715
  }
349676
349716
  function taskObjectiveContinuationAuthorizesEvidence(ledger, entry) {
349677
349717
  let current = ledger, row2 = entry;
349678
349718
  const seen = /* @__PURE__ */ new Set();
349679
349719
  for (; ; ) {
349680
349720
  try {
349681
- const record8 = current?.taskObjectiveContinuation, contract = current?.objectiveContract;
349682
- 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)
349683
349723
  return false;
349684
349724
  const policy = { ...contract, criteria: contract.criteria.map((criterion) => ({ ...criterion, status: "open" })) };
349685
- if (taskObjectiveContinuationDigest(policy) !== (record8.input.contractStrengthening?.recipientContractSha256 ?? record8.input.objective.contractSha256))
349725
+ if (taskObjectiveContinuationDigest(policy) !== (record9.input.contractStrengthening?.recipientContractSha256 ?? record9.input.objective.contractSha256))
349686
349726
  return false;
349687
- const claim = readClaim(record8);
349688
- 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)))
349689
349729
  return false;
349690
- const predecessor = record8.input.predecessor;
349730
+ const predecessor = record9.input.predecessor;
349691
349731
  if (seen.has(predecessor.ledgerPath))
349692
349732
  return false;
349693
349733
  seen.add(predecessor.ledgerPath);
349694
- const imported = record8.importedEvidence.find((item) => item.evidenceId === row2.id);
349734
+ const imported = record9.importedEvidence.find((item) => item.evidenceId === row2.id);
349695
349735
  if (!imported || imported.predecessorRunId !== predecessor.runId || imported.predecessorLedgerSha256 !== predecessor.ledgerSha256 || imported.issuerRunId !== row2.workOperation?.runId || taskObjectiveContinuationDigest(imported.criterionIds) !== taskObjectiveContinuationDigest(row2.criterionIds ?? []))
349696
349736
  return false;
349697
349737
  const bytes3 = readFileSync26(predecessor.ledgerPath);
@@ -349714,11 +349754,11 @@ function taskObjectiveContinuationAuthorizesSource(ledger, entry) {
349714
349754
  try {
349715
349755
  if (entry.adoption?.schema !== "omnius.artifact-review-source-adoption.v1")
349716
349756
  return false;
349717
- const record8 = ledger?.taskObjectiveContinuation;
349718
- 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))
349719
349759
  return false;
349720
- const adopted = record8.adoptions.find((value) => value.sourceId === entry.sourceId && taskObjectiveContinuationDigest(value.issuer) === taskObjectiveContinuationDigest(entry.adoption.issuer));
349721
- 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;
349722
349762
  } catch {
349723
349763
  return false;
349724
349764
  }
@@ -349837,37 +349877,37 @@ function checkOutcome(entry) {
349837
349877
  return "unverified";
349838
349878
  return entry.role === "verification" ? "passed" : "exit_zero";
349839
349879
  }
349840
- function acceptedHostVerification(entry, ledger, record8) {
349880
+ function acceptedHostVerification(entry, ledger, record9) {
349841
349881
  const receipt = normalizeVerificationReceiptV1(entry.verificationReceipt);
349842
- const contract = record8.taskObjectiveContract, frontier = record8.objectiveFrontier;
349843
- 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)))
349844
349884
  return null;
349845
349885
  const criterion = contract.criteria.find((item) => item.id === receipt.criterionId);
349846
349886
  const accepted = frontier.criteria.find((item) => item.id === receipt.criterionId);
349847
349887
  const snapshot = ledger.evidence.find((item) => item.id === receipt.artifactEvidenceId);
349848
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))
349849
349889
  return null;
349850
- 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);
349851
349891
  if (![snapshotAt, checkedAt, committedAt].every(Number.isFinite) || snapshotAt > checkedAt || checkedAt > committedAt)
349852
349892
  return null;
349853
349893
  return { receipt, snapshot };
349854
349894
  }
349855
349895
  function buildTerminalTaskReport(input) {
349856
- const { record: record8, ledger } = input;
349857
- if (record8.phase !== "committed")
349896
+ const { record: record9, ledger } = input;
349897
+ if (record9.phase !== "committed")
349858
349898
  throw new Error("terminal_task_report_requires_committed_receipt");
349859
- 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);
349860
349900
  const evidence = matches ? ledger.evidence.filter((entry) => classifyCompletionProgress(entry) !== "control_bookkeeping") : [];
349861
349901
  const objective = matches ? ledger.objectiveContract : void 0, frontier = matches ? ledger.objectiveFrontier : void 0;
349862
- 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));
349863
349903
  const changes = /* @__PURE__ */ new Map();
349864
349904
  const observations = [];
349865
349905
  const checks = [];
349866
349906
  const limits = /* @__PURE__ */ new Map();
349867
349907
  const nextSteps = /* @__PURE__ */ new Set();
349868
349908
  const limit2 = (id5, source, detail) => limits.set(id5, { id: id5, source, detail: text8(detail, 500) });
349869
- const failure = record8.runtimeFailure;
349870
- 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");
349871
349911
  const currentAdmissionFailure = currentFailureScope && failure && failure.code === "context_admission_failed" && failure.phase === "before_transport" && failure.contextAdmission.decision === "reject";
349872
349912
  const currentEmptyResponseFailure = currentFailureScope && failure && failure.code === "model_empty_response_stall" && failure.phase === "after_transport" && Number.isSafeInteger(failure.consecutiveEmptyResponses) && failure.consecutiveEmptyResponses >= 6;
349873
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;
@@ -349891,7 +349931,7 @@ function buildTerminalTaskReport(input) {
349891
349931
  }
349892
349932
  if (input.workflow) {
349893
349933
  const workflow = input.workflow;
349894
- 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)) {
349895
349935
  limit2("workflow_scope", "evidence_scope", "The feature workflow summary did not match this run and task epoch; its contents were excluded.");
349896
349936
  nextSteps.add("Reconstruct the current feature workflow from its saved checkpoint before repeating work.");
349897
349937
  } else if (!workflow.complete) {
@@ -349922,7 +349962,7 @@ function buildTerminalTaskReport(input) {
349922
349962
  }
349923
349963
  if (entry.receipt || entry.role === "verification") {
349924
349964
  const hostCheck = entry.toolName === "host_terminal_verifier" && !entry.receipt;
349925
- const hostVerification = hostCheck && ledger ? acceptedHostVerification(entry, ledger, record8) : null;
349965
+ const hostVerification = hostCheck && ledger ? acceptedHostVerification(entry, ledger, record9) : null;
349926
349966
  const identity4 = commandIdentity(entry);
349927
349967
  let freshness = "current";
349928
349968
  if (identity4 && latestCommands.get(identity4) > index)
@@ -349976,7 +350016,7 @@ function buildTerminalTaskReport(input) {
349976
350016
  nextSteps.add(`Inspect the ${toolName} result and finish any unrun work before relying on the recorded checks.`);
349977
350017
  }
349978
350018
  });
349979
- for (const gap of record8.verificationAudit.gaps) {
350019
+ for (const gap of record9.verificationAudit.gaps) {
349980
350020
  const entry = evidence.find((item) => item.id === gap.source);
349981
350021
  const check = entry && checks.find((item) => item.evidenceId === entry.id);
349982
350022
  if (check && limits.has(`check:${entry.id}`))
@@ -349994,7 +350034,7 @@ function buildTerminalTaskReport(input) {
349994
350034
  detail = "A recorded evidence gap remains unresolved; inspect the current run evidence.";
349995
350035
  limit2(`audit:${gap.id}`, gap.source, detail);
349996
350036
  }
349997
- for (const obligation2 of record8.completionReadiness?.obligations ?? []) {
350037
+ for (const obligation2 of record9.completionReadiness?.obligations ?? []) {
349998
350038
  if (obligation2.status !== "satisfied") {
349999
350039
  limit2(`obligation:${obligation2.id}`, obligation2.kind, `${obligation2.kind.replace(/_/g, " ")} ${obligation2.sourceId}: ${obligation2.status} (${obligation2.reasonCode.replace(/_/g, " ")}).`);
350000
350040
  nextSteps.add(`Resolve the ${obligation2.status} ${obligation2.kind.replace(/_/g, " ")}: ${text8(obligation2.sourceId, 250)}.`);
@@ -350010,13 +350050,13 @@ function buildTerminalTaskReport(input) {
350010
350050
  const body = {
350011
350051
  schema: "omnius.terminal-task-report.v1",
350012
350052
  source: "host_terminal_receipt",
350013
- runId: record8.runId,
350014
- ...record8.taskEpoch !== void 0 ? { taskEpoch: record8.taskEpoch } : {},
350015
- terminalReceiptId: record8.id,
350016
- status: record8.status,
350017
- ...record8.readinessHash ? { readinessHash: record8.readinessHash } : {},
350018
- ledgerSnapshotHash: hash13(matches ? { runId: ledger.runId, taskEpoch: ledger.taskEpoch, updatedAtIso: ledger.updatedAtIso, evidence: ledger.evidence, audit: record8.verificationAudit, readinessHash: record8.readinessHash } : null),
350019
- 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,
350020
350060
  changes: [...changes.values()].slice(-CAP),
350021
350061
  checks: checks.slice(-CAP),
350022
350062
  observations: observations.slice(-CAP),
@@ -350577,7 +350617,7 @@ async function buildLiveVirtualContextProjection(input) {
350577
350617
  includeSuperseded: false,
350578
350618
  maximumCompressionGeneration: 4,
350579
350619
  limit: 1e4
350580
- }).map((record8) => [record8.id, record8.bodyHash, record8.validUntil]))).digest("hex") : "none";
350620
+ }).map((record9) => [record9.id, record9.bodyHash, record9.validUntil]))).digest("hex") : "none";
350581
350621
  const signature = projectionSignature({
350582
350622
  query,
350583
350623
  scopeId: input.scopeId,
@@ -350949,7 +350989,7 @@ async function extractStructuredMemoriesWithInference(input) {
350949
350989
  includeExpired: false,
350950
350990
  limit: 24
350951
350991
  });
350952
- const existingIds = new Set(existing.map((record8) => record8.id));
350992
+ const existingIds = new Set(existing.map((record9) => record9.id));
350953
350993
  const raw = await input.infer({
350954
350994
  system: EXTRACTION_SYSTEM,
350955
350995
  input: {
@@ -350961,13 +351001,13 @@ async function extractStructuredMemoriesWithInference(input) {
350961
351001
  char_end: span.charEnd,
350962
351002
  text: span.text
350963
351003
  })),
350964
- existing_active_memories: existing.map((record8) => ({
350965
- id: record8.id,
350966
- memory_class: record8.memoryClass,
350967
- canonical_key: record8.canonicalKey,
350968
- body: record8.body.slice(0, 500),
350969
- valid_from: record8.validFrom,
350970
- 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)
350971
351011
  })),
350972
351012
  output_schema: {
350973
351013
  memories: [{
@@ -351056,7 +351096,7 @@ async function extractStructuredMemoriesWithInference(input) {
351056
351096
  }
351057
351097
  const effectiveTtl = ttl !== void 0 ? Math.floor(ttl) : memoryClass === "current_plan" ? 7 * 24 * 60 * 60 : void 0;
351058
351098
  try {
351059
- const record8 = {
351099
+ const record9 = {
351060
351100
  ...input.recordIdPrefix ? { id: `${input.recordIdPrefix}:${batch.index}:${index}` } : {},
351061
351101
  ...input.validFrom ? { validFrom: input.validFrom } : {},
351062
351102
  scopeId: input.scopeId,
@@ -351073,10 +351113,10 @@ async function extractStructuredMemoriesWithInference(input) {
351073
351113
  metadata: { producer: "inference-structured-memory-v1", batch: batchIndex + 1 }
351074
351114
  };
351075
351115
  if (input.commitBatch)
351076
- records.push(record8);
351116
+ records.push(record9);
351077
351117
  else {
351078
351118
  assertCurrent();
351079
- written.push(input.memoryStore.append(record8));
351119
+ written.push(input.memoryStore.append(record9));
351080
351120
  }
351081
351121
  } catch (error) {
351082
351122
  rejected.push(`${label}: ${error instanceof Error ? error.message : String(error)}`);
@@ -351288,10 +351328,10 @@ function validateRelease(release) {
351288
351328
  const operations2 = /* @__PURE__ */ new Set();
351289
351329
  const routing = json3(delivery.records[0].expectedRouting);
351290
351330
  for (const reference2 of delivery.records) {
351291
- const record8 = reopen(reference2), expected = reference2.expectedRouting;
351292
- 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}`)
351293
351333
  throw new InvalidExtraction("Structured extraction provider acknowledgement is missing or foreign");
351294
- operations2.add(record8.outboundOperationId);
351334
+ operations2.add(record9.outboundOperationId);
351295
351335
  }
351296
351336
  }
351297
351337
  var StructuredMemoryExtractionQueue = class {
@@ -351585,7 +351625,7 @@ var StructuredMemoryExtractionQueue = class {
351585
351625
  requestId,
351586
351626
  raw,
351587
351627
  rawSha256: sha10(raw),
351588
- writtenIds: written.map((record8) => record8.id),
351628
+ writtenIds: written.map((record9) => record9.id),
351589
351629
  rejected
351590
351630
  }),
351591
351631
  queueEmbedding: false,
@@ -353491,6 +353531,29 @@ function reopenSourceReviewWebReads(input) {
353491
353531
  return reads;
353492
353532
  }
353493
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
+
353494
353557
  // packages/orchestrator/dist/contextBudget.js
353495
353558
  import { freemem as freemem2, totalmem as totalmem3 } from "node:os";
353496
353559
  var TIER_BASE = {
@@ -353739,11 +353802,11 @@ function recoveryMaterialDigest(value) {
353739
353802
 
353740
353803
  // packages/orchestrator/dist/desktop-verification.js
353741
353804
  var id4 = (value, limit2 = 200) => typeof value === "string" && value.length > 0 && value.length <= limit2;
353742
- var record6 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
353805
+ var record7 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
353743
353806
  function desktopVerificationScope(tool) {
353744
353807
  try {
353745
353808
  const scope = tool.getDesktopVerificationScope?.();
353746
- 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)))
353747
353810
  return void 0;
353748
353811
  return {
353749
353812
  desktopSessionId: scope.desktopSessionId,
@@ -353754,7 +353817,7 @@ function desktopVerificationScope(tool) {
353754
353817
  }
353755
353818
  }
353756
353819
  function desktopVerificationReceipt(value) {
353757
- 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)))
353758
353821
  return void 0;
353759
353822
  const fields2 = value.kind === "native_observation" ? ["schema", "kind", "desktopSessionId", "nativeSessionId", "revision"] : value.kind === "input_dispatch" ? ["schema", "kind", "desktopSessionId", "dispatchId", "inputKind", "windowId"] : [];
353760
353823
  if (Object.keys(value).some((key) => !fields2.includes(key)))
@@ -354626,20 +354689,20 @@ function validateRanges(ranges) {
354626
354689
  });
354627
354690
  }
354628
354691
  function normalizeRecords(records) {
354629
- return records.map((record8) => {
354630
- if (!record8 || typeof record8 !== "object")
354692
+ return records.map((record9) => {
354693
+ if (!record9 || typeof record9 !== "object")
354631
354694
  throw new Error("artifact manifest record is malformed");
354632
- if (record8.fidelity !== "full")
354695
+ if (record9.fidelity !== "full")
354633
354696
  throw new Error("artifact manifest record fidelity must be full");
354634
- if (typeof record8.recordedAt !== "string" || Number.isNaN(Date.parse(record8.recordedAt))) {
354697
+ if (typeof record9.recordedAt !== "string" || Number.isNaN(Date.parse(record9.recordedAt))) {
354635
354698
  throw new Error("artifact manifest record timestamp is invalid");
354636
354699
  }
354637
354700
  return {
354638
- path: validateMetadataText(record8.path, MAX_PROVENANCE_PATH_CHARS, "artifact provenance path"),
354639
- revision: validateMetadataText(record8.revision, MAX_REVISION_CHARS, "artifact provenance revision"),
354640
- 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),
354641
354704
  fidelity: "full",
354642
- recordedAt: record8.recordedAt
354705
+ recordedAt: record9.recordedAt
354643
354706
  };
354644
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));
354645
354708
  }
@@ -354766,7 +354829,7 @@ var ContentAddressedArtifactStore = class {
354766
354829
  atomicWrite(objectPath, input.content);
354767
354830
  }
354768
354831
  const existingManifest = existsSync30(manifestPath) ? this.readManifestByHash(hash17) : void 0;
354769
- const record8 = {
354832
+ const record9 = {
354770
354833
  path: path7,
354771
354834
  revision,
354772
354835
  ranges,
@@ -354774,7 +354837,7 @@ var ContentAddressedArtifactStore = class {
354774
354837
  recordedAt: (/* @__PURE__ */ new Date()).toISOString()
354775
354838
  };
354776
354839
  const records = existingManifest?.records ?? [];
354777
- 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));
354778
354841
  if (!alreadyRecorded && records.length >= this.maxManifestRecords) {
354779
354842
  throw new Error(`artifact manifest exceeds configured ${this.maxManifestRecords}-record limit`);
354780
354843
  }
@@ -354791,7 +354854,7 @@ var ContentAddressedArtifactStore = class {
354791
354854
  throw new Error("artifact manifest conflicts with the canonical object");
354792
354855
  }
354793
354856
  if (!alreadyRecorded) {
354794
- manifest.records = normalizeRecords([...records, record8]);
354857
+ manifest.records = normalizeRecords([...records, record9]);
354795
354858
  atomicWrite(manifestPath, `${JSON.stringify(manifest, null, 2)}
354796
354859
  `);
354797
354860
  } else if (!existsSync30(manifestPath)) {
@@ -355193,24 +355256,24 @@ function deriveFeatureWorkflowStatus(plan, state, board, workspaceRevision) {
355193
355256
  const gaps = [];
355194
355257
  for (const compiled of compileFeatureWorkflow(plan).cards) {
355195
355258
  const card = plan.cards.find((c) => featureWorkflowCardId(plan, c.id) === compiled.id);
355196
- const record8 = state.results[card.id];
355259
+ const record9 = state.results[card.id];
355197
355260
  const boardCard = board.cards.find((c) => c.id === compiled.id);
355198
355261
  let reason = !boardCard || boardCard.status !== "verified" ? "workboard_not_verified" : "";
355199
355262
  if (Object.values(state.operations).some((op) => op.binding.cardId === card.id))
355200
355263
  reason = "host_operation_pending";
355201
- if (record8?.binding.kind === "verification" && !record8.success)
355264
+ if (record9?.binding.kind === "verification" && !record9.success)
355202
355265
  reason = "verification_failed";
355203
355266
  if (Object.values(state.operations).some((op) => op.binding.cardId === card.id && op.state === "interrupted"))
355204
355267
  reason = "interrupted_operation_requires_host_reconciliation";
355205
- if (!reason && (!record8?.success || record8.binding.cardContract !== featureWorkflowCardContract(plan, card)))
355268
+ if (!reason && (!record9?.success || record9.binding.cardContract !== featureWorkflowCardContract(plan, card)))
355206
355269
  reason = "host_receipt_missing_or_stale";
355207
- 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)))
355208
355271
  reason = "input_artifact_changed";
355209
355272
  if (!reason && plan.slots.some((s) => s.cardId === card.id && (!state.slots[s.id] || state.slots[s.id].cardContract !== featureWorkflowCardContract(plan, card))))
355210
355273
  reason = "output_artifact_missing_or_stale";
355211
- 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))
355212
355275
  reason = "integrated_revision_changed";
355213
- if (!reason && card.role === "reviewer" && record8?.reviewDisposition !== "approved")
355276
+ if (!reason && card.role === "reviewer" && record9?.reviewDisposition !== "approved")
355214
355277
  reason = "independent_review_missing";
355215
355278
  if (!reason && featureWorkflowDependencies(plan, card).some((id5) => !valid.has(id5)))
355216
355279
  reason = "prerequisite_unverified";
@@ -355218,7 +355281,7 @@ function deriveFeatureWorkflowStatus(plan, state, board, workspaceRevision) {
355218
355281
  gaps.push({
355219
355282
  cardId: card.id,
355220
355283
  reason,
355221
- ...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) } : {}
355222
355285
  });
355223
355286
  else
355224
355287
  valid.add(card.id);
@@ -355661,8 +355724,8 @@ var FeatureWorkflowController = class {
355661
355724
  fail3("checkpoint_result_mismatch");
355662
355725
  this.validateInputBindings(result.binding);
355663
355726
  const receipt = JSON.parse(this.store.read(result.receiptReference).content);
355664
- const { receiptReference: _ref, ...record8 } = result;
355665
- if (!equal(receipt.record, record8))
355727
+ const { receiptReference: _ref, ...record9 } = result;
355728
+ if (!equal(receipt.record, record9))
355666
355729
  fail3("checkpoint_receipt_mismatch");
355667
355730
  if (result.childReportReference) {
355668
355731
  const body = this.store.read(result.childReportReference).content;
@@ -355703,20 +355766,20 @@ var FeatureWorkflowController = class {
355703
355766
  const workspaceRevision = featureWorkflowWorkspaceRevision(this.options.workingDir, plan);
355704
355767
  for (const compiled of compileFeatureWorkflow(plan).cards) {
355705
355768
  const card = plan.cards.find((c) => featureWorkflowCardId(plan, c.id) === compiled.id);
355706
- const record8 = state.results[card.id];
355707
- 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))
355708
355771
  continue;
355709
- if (!equal(record8.binding.inputSlots, currentInputReferences(plan, card, state.slots)))
355772
+ if (!equal(record9.binding.inputSlots, currentInputReferences(plan, card, state.slots)))
355710
355773
  continue;
355711
- 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))
355712
355775
  continue;
355713
- 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))
355714
355777
  continue;
355715
355778
  const board = this.board();
355716
355779
  if (featureWorkflowDependencies(plan, card).some((id5) => board.cards.find((c) => c.id === featureWorkflowCardId(plan, id5))?.status !== "verified"))
355717
355780
  continue;
355718
355781
  if (board.cards.find((c) => c.id === compiled.id)?.status !== "verified")
355719
- this.applyResultToBoard(card, record8);
355782
+ this.applyResultToBoard(card, record9);
355720
355783
  }
355721
355784
  }
355722
355785
  interruptedOperations() {
@@ -356067,7 +356130,7 @@ var FeatureWorkflowController = class {
356067
356130
  }
356068
356131
  if (!successful && blockers.length === 0)
356069
356132
  blockers.push("The host operation failed; inspect its receipt and retry the remaining bounded work.");
356070
- const record8 = {
356133
+ const record9 = {
356071
356134
  binding: clone(binding),
356072
356135
  actorId,
356073
356136
  success: successful,
@@ -356080,8 +356143,8 @@ var FeatureWorkflowController = class {
356080
356143
  mutationSequence: state.mutationSequence,
356081
356144
  workspaceRevision
356082
356145
  };
356083
- const receiptReference = this.writeBody(JSON.stringify({ record: record8, observedArtifacts: stagedSlots }), `feature-workflow/${plan.id}/receipt/${binding.parentOperationId}`);
356084
- 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 };
356085
356148
  delete state.operations[binding.parentOperationId];
356086
356149
  state.recentSettlements.push({
356087
356150
  operationId: binding.parentOperationId,
@@ -356094,17 +356157,17 @@ var FeatureWorkflowController = class {
356094
356157
  this.persist();
356095
356158
  return this.status();
356096
356159
  }
356097
- applyResultToBoard(card, record8) {
356160
+ applyResultToBoard(card, record9) {
356098
356161
  const state = this.requireState();
356099
356162
  const cardId = featureWorkflowCardId(this.acceptedPlan, card.id);
356100
356163
  const evidence = {
356101
- id: `workflow:${hash15(record8.binding.parentOperationId)}`,
356164
+ id: `workflow:${hash15(record9.binding.parentOperationId)}`,
356102
356165
  kind: "tool_result",
356103
- summary: `${card.phase} host operation ${record8.success ? "completed" : "requires more work"}`,
356104
- ref: record8.receiptReference,
356105
- 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"
356106
356169
  };
356107
- if (record8.commandReceipt)
356170
+ if (record9.commandReceipt)
356108
356171
  attachTrustedWorkboardCommandEvidence(this.boardDir, {
356109
356172
  runId: state.boardRunId,
356110
356173
  cardId,
@@ -356114,7 +356177,7 @@ var FeatureWorkflowController = class {
356114
356177
  command: card.verifier?.command,
356115
356178
  tool: "terminal"
356116
356179
  },
356117
- receipt: record8.commandReceipt
356180
+ receipt: record9.commandReceipt
356118
356181
  });
356119
356182
  else
356120
356183
  attachWorkboardEvidence(this.boardDir, {
@@ -356123,7 +356186,7 @@ var FeatureWorkflowController = class {
356123
356186
  actor: "feature-workflow",
356124
356187
  evidence
356125
356188
  });
356126
- if (!record8.success) {
356189
+ if (!record9.success) {
356127
356190
  completeWorkboardCard(this.boardDir, {
356128
356191
  runId: state.boardRunId,
356129
356192
  cardId,
@@ -356140,7 +356203,7 @@ var FeatureWorkflowController = class {
356140
356203
  cardId,
356141
356204
  outcome: "completed",
356142
356205
  actor: "feature-workflow",
356143
- notes: record8.receiptReference
356206
+ notes: record9.receiptReference
356144
356207
  });
356145
356208
  if (!completed.accepted)
356146
356209
  fail3(`board_completion_${completed.code}`);
@@ -356149,8 +356212,8 @@ var FeatureWorkflowController = class {
356149
356212
  runId: state.boardRunId,
356150
356213
  cardId,
356151
356214
  outcome: "verified",
356152
- actor: `feature-workflow:receipt:${record8.receiptReference}`,
356153
- notes: record8.receiptReference
356215
+ actor: `feature-workflow:receipt:${record9.receiptReference}`,
356216
+ notes: record9.receiptReference
356154
356217
  });
356155
356218
  if (!verified.accepted)
356156
356219
  fail3(`board_verification_${verified.code}`);
@@ -356599,28 +356662,28 @@ function cloneSnapshot(value) {
356599
356662
  function isSnapshot(value) {
356600
356663
  if (!isRecord3(value))
356601
356664
  return false;
356602
- const record8 = value;
356603
- const pending = record8["pendingAcknowledgements"];
356604
- const ambiguous = record8["ambiguousEffects"];
356605
- const childLineage = record8["childLineage"];
356606
- 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;
356607
356670
  if (!baseValid)
356608
356671
  return false;
356609
- const owner = record8["owner"];
356672
+ const owner = record9["owner"];
356610
356673
  const acknowledgements = pending;
356611
356674
  const acknowledgementById = new Map(acknowledgements.map((entry) => [entry.id, entry]));
356612
356675
  if (acknowledgements.some((entry) => entry.generation !== owner.generation)) {
356613
356676
  return false;
356614
356677
  }
356615
- const phase = record8["phase"];
356678
+ const phase = record9["phase"];
356616
356679
  const resumablePhases = /* @__PURE__ */ new Set([
356617
356680
  "pausing",
356618
356681
  "paused",
356619
356682
  "resuming"
356620
356683
  ]);
356621
- if (record8["resumable"] !== resumablePhases.has(phase))
356684
+ if (record9["resumable"] !== resumablePhases.has(phase))
356622
356685
  return false;
356623
- if (phase !== "stopped" && !isNonEmptyString(record8["runId"]))
356686
+ if (phase !== "stopped" && !isNonEmptyString(record9["runId"]))
356624
356687
  return false;
356625
356688
  if ((TERMINAL_PHASES.has(phase) || phase === "paused" || phase === "resuming") && acknowledgements.some((entry) => entry.status === "pending")) {
356626
356689
  return false;
@@ -357881,21 +357944,21 @@ var TypedModelOutputStream = class {
357881
357944
  if (prefix.trim())
357882
357945
  appendVisible(prefix);
357883
357946
  if (reservedMarker === LEGACY_STEERING_GATE_MARKER) {
357884
- const record8 = consumeLegacySteeringGate(this.buffer.slice(reservedAt), final);
357885
- if (record8 === "pending") {
357947
+ const record9 = consumeLegacySteeringGate(this.buffer.slice(reservedAt), final);
357948
+ if (record9 === "pending") {
357886
357949
  this.buffer = this.buffer.slice(reservedAt);
357887
357950
  break;
357888
357951
  }
357889
- if (record8) {
357952
+ if (record9) {
357890
357953
  const region2 = {
357891
357954
  kind: "internal_contract_echo",
357892
357955
  visibility: "internal_control",
357893
- raw: record8.raw,
357956
+ raw: record9.raw,
357894
357957
  value: { marker: reservedMarker }
357895
357958
  };
357896
357959
  regions.push(region2);
357897
357960
  this.options.onRegion?.(region2);
357898
- this.buffer = record8.remainder;
357961
+ this.buffer = record9.remainder;
357899
357962
  this.separatorAfterRegion = this.hasVisibleContent;
357900
357963
  continue;
357901
357964
  }
@@ -359945,8 +360008,8 @@ function deepEqual(left, right) {
359945
360008
  return value.map(canonical9);
359946
360009
  if (!value || typeof value !== "object")
359947
360010
  return value;
359948
- const record8 = value;
359949
- 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])]));
359950
360013
  };
359951
360014
  return JSON.stringify(canonical9(left)) === JSON.stringify(canonical9(right));
359952
360015
  }
@@ -362330,33 +362393,33 @@ function atomicWriteJson(path7, value) {
362330
362393
  `, "utf8");
362331
362394
  renameSync16(tmp, path7);
362332
362395
  }
362333
- function prepareCompletionFinalization(stateDir, record8) {
362334
- const path7 = completionFinalizationPreparePath(stateDir, record8.runId);
362396
+ function prepareCompletionFinalization(stateDir, record9) {
362397
+ const path7 = completionFinalizationPreparePath(stateDir, record9.runId);
362335
362398
  mkdirSync28(join44(stateDir, "completion-finalizations"), { recursive: true });
362336
- atomicWriteJson(path7, { ...record8, phase: "prepared" });
362399
+ atomicWriteJson(path7, { ...record9, phase: "prepared" });
362337
362400
  return path7;
362338
362401
  }
362339
- function commitCompletionFinalization(stateDir, record8) {
362340
- const path7 = completionFinalizationPath(stateDir, record8.runId);
362402
+ function commitCompletionFinalization(stateDir, record9) {
362403
+ const path7 = completionFinalizationPath(stateDir, record9.runId);
362341
362404
  mkdirSync28(join44(stateDir, "completion-finalizations"), { recursive: true });
362342
- atomicWriteJson(path7, { ...record8, phase: "committed" });
362405
+ atomicWriteJson(path7, { ...record9, phase: "committed" });
362343
362406
  try {
362344
- unlinkSync14(completionFinalizationPreparePath(stateDir, record8.runId));
362407
+ unlinkSync14(completionFinalizationPreparePath(stateDir, record9.runId));
362345
362408
  } catch {
362346
362409
  }
362347
362410
  return path7;
362348
362411
  }
362349
- function commitTerminalTrajectoryProjection(stateDir, record8, payload2) {
362412
+ function commitTerminalTrajectoryProjection(stateDir, record9, payload2) {
362350
362413
  const dir = join44(stateDir, "terminal-trajectories");
362351
- 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);
362352
362415
  const path7 = join44(dir, `${safeRunId}.json`);
362353
362416
  mkdirSync28(dir, { recursive: true });
362354
362417
  const projection = {
362355
362418
  schema: "omnius.terminal-trajectory.v1",
362356
- terminalReceiptId: record8.id,
362357
- runId: record8.runId,
362358
- status: record8.status,
362359
- committedAtIso: record8.committedAtIso,
362419
+ terminalReceiptId: record9.id,
362420
+ runId: record9.runId,
362421
+ status: record9.status,
362422
+ committedAtIso: record9.committedAtIso,
362360
362423
  payload: payload2
362361
362424
  };
362362
362425
  atomicWriteJson(path7, projection);
@@ -362935,14 +362998,14 @@ function receiptDigest(input) {
362935
362998
  function validateOverrideReceipt(value) {
362936
362999
  if (!value || typeof value !== "object" || Array.isArray(value))
362937
363000
  return null;
362938
- const record8 = value;
362939
- if (record8["schema"] !== COMPLETION_OVERRIDE_SCHEMA)
363001
+ const record9 = value;
363002
+ if (record9["schema"] !== COMPLETION_OVERRIDE_SCHEMA)
362940
363003
  return null;
362941
- const runId = bounded2(record8["runId"], 500);
362942
- const readinessHash = bounded2(record8["readinessHash"], 64).toLowerCase();
362943
- const reason = bounded2(record8["reason"], 2e3);
362944
- const persistedAtIso = bounded2(record8["persistedAtIso"], 80);
362945
- 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);
362946
363009
  if (!runId || !SHA2562.test(readinessHash) || !reason || !validIso2(persistedAtIso)) {
362947
363010
  return null;
362948
363011
  }
@@ -368467,9 +368530,9 @@ function loadBoundaryRecords(omniusDir) {
368467
368530
  try {
368468
368531
  const parsed = JSON.parse(lines[i]);
368469
368532
  if (parsed && parsed.v === 1 && parsed.handoff && typeof parsed.recordedAt === "number") {
368470
- const record8 = parsed;
368471
- if (shouldPersistTaskHandoff(record8.handoff))
368472
- records.push(record8);
368533
+ const record9 = parsed;
368534
+ if (shouldPersistTaskHandoff(record9.handoff))
368535
+ records.push(record9);
368473
368536
  }
368474
368537
  } catch {
368475
368538
  }
@@ -371093,8 +371156,8 @@ function stableValueKey(value) {
371093
371156
  hash17 = (hash17 << 5) + hash17 + raw.charCodeAt(i) | 0;
371094
371157
  return `{size:${raw.length},hash:${Math.abs(hash17).toString(36)}}`;
371095
371158
  }
371096
- const record8 = value;
371097
- 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(",")}}`;
371098
371161
  }
371099
371162
  var StreamingToolExecutor = class {
371100
371163
  tools = /* @__PURE__ */ new Map();
@@ -371311,7 +371374,10 @@ var StreamingToolExecutor = class {
371311
371374
  return {
371312
371375
  success: prior.result.success,
371313
371376
  output: prior.result.output ? `${prefix}${prior.result.output}` : prior.result.output,
371314
- error: prior.result.error
371377
+ error: prior.result.error,
371378
+ completionAdmission: prior.result.completionAdmission,
371379
+ completionReviewPending: prior.result.completionReviewPending,
371380
+ completionRestoredPayload: prior.result.completionRestoredPayload
371315
371381
  };
371316
371382
  }
371317
371383
  mirrorPriorEquivalent(entry) {
@@ -373047,7 +373113,7 @@ function encodeRepeatedCompletedObservations(history, makeMessage) {
373047
373113
  continue;
373048
373114
  }
373049
373115
  const latest = run.at(-1);
373050
- const record8 = {
373116
+ const record9 = {
373051
373117
  schema: "omnius.repeated-completed-observations.v1",
373052
373118
  count: run.length,
373053
373119
  latestTransactionId: latest.call.transactionId,
@@ -373064,7 +373130,7 @@ function encodeRepeatedCompletedObservations(history, makeMessage) {
373064
373130
  const summary = {
373065
373131
  id: `repeated-observations:${latest.call.transactionId}`,
373066
373132
  message: makeMessage(`[REPEATED COMPLETED OBSERVATIONS v1]
373067
- ${JSON.stringify(record8)}`),
373133
+ ${JSON.stringify(record9)}`),
373068
373134
  kind: "stable",
373069
373135
  ordinal: latest.result.ordinal + 0.125,
373070
373136
  turn: latest.result.turn,
@@ -373718,8 +373784,8 @@ function stable5(value) {
373718
373784
  }
373719
373785
  if (Array.isArray(value))
373720
373786
  return `[${value.map(stable5).join(",")}]`;
373721
- const record8 = value;
373722
- 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(",")}}`;
373723
373789
  }
373724
373790
  function keyedDigest(value, key) {
373725
373791
  return createHmac("sha256", key).update(stable5(value)).digest("hex");
@@ -373927,15 +373993,15 @@ var FailureResolutionTransactionCoordinator = class {
373927
373993
  this.now = options.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
373928
373994
  }
373929
373995
  resolve(input) {
373930
- const record8 = this.prepare(input);
373931
- return this.advance(input.workingDir, record8);
373996
+ const record9 = this.prepare(input);
373997
+ return this.advance(input.workingDir, record9);
373932
373998
  }
373933
373999
  recover(workingDir, runId) {
373934
374000
  const directory = failureResolutionTransactionDirectory(workingDir, runId);
373935
374001
  if (!existsSync51(directory))
373936
374002
  return [];
373937
374003
  const records = readdirSync17(directory).filter((name) => name.endsWith(".json")).sort().map((name) => readResolutionRecord(join60(directory, name)));
373938
- return records.map((record8) => this.advance(workingDir, record8));
374004
+ return records.map((record9) => this.advance(workingDir, record9));
373939
374005
  }
373940
374006
  prepare(input) {
373941
374007
  const runId = normalizeWorkboardRunId(input.runId);
@@ -374000,7 +374066,7 @@ var FailureResolutionTransactionCoordinator = class {
374000
374066
  }
374001
374067
  return existing;
374002
374068
  }
374003
- const record8 = {
374069
+ const record9 = {
374004
374070
  schema: FAILURE_RESOLUTION_TRANSACTION_SCHEMA,
374005
374071
  id: id5,
374006
374072
  state: "prepared",
@@ -374008,45 +374074,45 @@ var FailureResolutionTransactionCoordinator = class {
374008
374074
  preparedAt,
374009
374075
  updatedAt: preparedAt
374010
374076
  };
374011
- writeResolutionRecord(input.workingDir, record8);
374012
- return record8;
374077
+ writeResolutionRecord(input.workingDir, record9);
374078
+ return record9;
374013
374079
  }
374014
374080
  advance(workingDir, input) {
374015
- let record8 = cloneRecord(input);
374016
- if (record8.state === "committed")
374017
- return record8;
374081
+ let record9 = cloneRecord(input);
374082
+ if (record9.state === "committed")
374083
+ return record9;
374018
374084
  this.crashHook?.("before_failure_store");
374019
- for (const failureId of record8.receipt.failureIds) {
374085
+ for (const failureId of record9.receipt.failureIds) {
374020
374086
  const failure = this.failureStore.getById(failureId);
374021
374087
  if (!failure) {
374022
374088
  throw new Error(`failure resolution store record '${failureId}' disappeared`);
374023
374089
  }
374024
374090
  if (!failure.resolved) {
374025
- this.failureStore.markResolved(failureId, record8.receipt.committedAt);
374091
+ this.failureStore.markResolved(failureId, record9.receipt.committedAt);
374026
374092
  }
374027
374093
  }
374028
374094
  this.crashHook?.("after_failure_store");
374029
- record8 = {
374030
- ...record8,
374031
- failureStoreCommittedAt: record8.failureStoreCommittedAt ?? this.now(),
374095
+ record9 = {
374096
+ ...record9,
374097
+ failureStoreCommittedAt: record9.failureStoreCommittedAt ?? this.now(),
374032
374098
  updatedAt: this.now()
374033
374099
  };
374034
- writeResolutionRecord(workingDir, record8);
374100
+ writeResolutionRecord(workingDir, record9);
374035
374101
  this.crashHook?.("before_workboard");
374036
374102
  commitWorkboardFailureResolution(workingDir, {
374037
- runId: record8.receipt.runId,
374103
+ runId: record9.receipt.runId,
374038
374104
  actor: "runner",
374039
- receipt: record8.receipt
374105
+ receipt: record9.receipt
374040
374106
  });
374041
374107
  this.crashHook?.("after_workboard");
374042
- record8 = {
374043
- ...record8,
374108
+ record9 = {
374109
+ ...record9,
374044
374110
  state: "committed",
374045
- workboardCommittedAt: record8.workboardCommittedAt ?? this.now(),
374111
+ workboardCommittedAt: record9.workboardCommittedAt ?? this.now(),
374046
374112
  updatedAt: this.now()
374047
374113
  };
374048
- writeResolutionRecord(workingDir, record8);
374049
- return record8;
374114
+ writeResolutionRecord(workingDir, record9);
374115
+ return record9;
374050
374116
  }
374051
374117
  };
374052
374118
  function failureResolutionTransactionDirectory(workingDir, runId) {
@@ -374056,14 +374122,14 @@ function failureResolutionTransactionPath(workingDir, runId, transaction) {
374056
374122
  const safeTransaction = requiredString(transaction, "transaction id").replace(/[^a-zA-Z0-9_.-]/g, "_").slice(0, 160);
374057
374123
  return join60(failureResolutionTransactionDirectory(workingDir, runId), `${safeTransaction}.json`);
374058
374124
  }
374059
- function writeResolutionRecord(workingDir, record8) {
374060
- const path7 = failureResolutionTransactionPath(workingDir, record8.receipt.runId, record8.id);
374061
- 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), {
374062
374128
  recursive: true
374063
374129
  });
374064
374130
  const temporary = `${path7}.tmp.${process.pid}.${Date.now()}`;
374065
374131
  try {
374066
- writeFileSync33(temporary, `${JSON.stringify(record8, null, 2)}
374132
+ writeFileSync33(temporary, `${JSON.stringify(record9, null, 2)}
374067
374133
  `, "utf8");
374068
374134
  renameSync20(temporary, path7);
374069
374135
  } catch (error) {
@@ -374081,8 +374147,8 @@ function readResolutionRecord(path7) {
374081
374147
  }
374082
374148
  return cloneRecord(parsed);
374083
374149
  }
374084
- function cloneRecord(record8) {
374085
- return JSON.parse(JSON.stringify(record8));
374150
+ function cloneRecord(record9) {
374151
+ return JSON.parse(JSON.stringify(record9));
374086
374152
  }
374087
374153
  function transactionId(value) {
374088
374154
  return createHash88("sha256").update(stableJson4(value)).digest("hex").slice(0, 32);
@@ -374542,10 +374608,10 @@ function hasAssistantPayload(message) {
374542
374608
  const text12 = messageText(message.content).trim();
374543
374609
  if (text12 && !/^(null|undefined)$/i.test(text12))
374544
374610
  return true;
374545
- const record8 = message;
374546
- 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)
374547
374613
  return true;
374548
- return Boolean(record8["function_call"]);
374614
+ return Boolean(record9["function_call"]);
374549
374615
  }
374550
374616
  function staleToolFailureKey(content) {
374551
374617
  const text12 = content.replace(/\s+/g, " ").trim();
@@ -375369,9 +375435,9 @@ function canonical7(value) {
375369
375435
  return `[${value.map((item) => item === void 0 || typeof item === "function" || typeof item === "symbol" ? "null" : canonical7(item)).join(",")}]`;
375370
375436
  }
375371
375437
  if (typeof value === "object") {
375372
- const record8 = value;
375373
- return `{${Object.keys(record8).sort().flatMap((key) => {
375374
- const child = record8[key];
375438
+ const record9 = value;
375439
+ return `{${Object.keys(record9).sort().flatMap((key) => {
375440
+ const child = record9[key];
375375
375441
  if (child === void 0 || typeof child === "function" || typeof child === "symbol")
375376
375442
  return [];
375377
375443
  return [`${JSON.stringify(key)}:${canonical7(child)}`];
@@ -375518,7 +375584,7 @@ function recordContextWindowDump(input) {
375518
375584
  request: input.request
375519
375585
  });
375520
375586
  const storedRequest = redactContextDumpRequest(input.request);
375521
- const record8 = {
375587
+ const record9 = {
375522
375588
  schemaVersion: 1,
375523
375589
  id: id5,
375524
375590
  timestamp: timestamp5,
@@ -375544,20 +375610,20 @@ function recordContextWindowDump(input) {
375544
375610
  try {
375545
375611
  mkdirSync39(dir, { recursive: true, mode: 448 });
375546
375612
  chmodSync2(dir, 448);
375547
- const filePath = join61(dir, `${record8.id}.json`);
375548
- const payload2 = JSON.stringify(record8, null, 2);
375613
+ const filePath = join61(dir, `${record9.id}.json`);
375614
+ const payload2 = JSON.stringify(record9, null, 2);
375549
375615
  writePrivateFileAtomic(filePath, payload2);
375550
- writePrivateFileAtomic(join61(dir, `latest-${record8.agentType}.json`), payload2);
375616
+ writePrivateFileAtomic(join61(dir, `latest-${record9.agentType}.json`), payload2);
375551
375617
  writePrivateFileAtomic(join61(dir, "latest.json"), payload2);
375552
375618
  const indexPath = join61(dir, "index.jsonl");
375553
- 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 });
375554
375620
  chmodSync2(indexPath, 384);
375555
375621
  rotatePrivateIndex(indexPath);
375556
375622
  maybePruneOldDumpFiles(dir);
375557
375623
  } catch {
375558
375624
  return null;
375559
375625
  }
375560
- return record8;
375626
+ return record9;
375561
375627
  }
375562
375628
  function analyzeContextWindowDumpRequest(request) {
375563
375629
  const messages = Array.isArray(request["messages"]) ? request["messages"] : [];
@@ -375715,10 +375781,10 @@ function buildContextAccounting(request, metrics) {
375715
375781
  };
375716
375782
  const messages = Array.isArray(request["messages"]) ? request["messages"] : [];
375717
375783
  for (const message of messages) {
375718
- const record8 = message && typeof message === "object" ? message : {};
375719
- const role = typeof record8["role"] === "string" ? record8["role"] : "unknown";
375720
- const extracted = textAndImagesFromContent(record8["content"]);
375721
- 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;
375722
375788
  add(contextSourceForMessage(role, extracted.textWithoutImages), extracted.textWithoutImages.length + toolCallChars);
375723
375789
  }
375724
375790
  if (metrics.toolSchemaChars > 0)
@@ -375826,8 +375892,8 @@ function isRawDiscoveryToolResult(text12) {
375826
375892
  return false;
375827
375893
  return !text12.includes("[DISCOVERY COMPACTED") && !text12.includes("[DISCOVERY BOUNDED") && !text12.includes("[STOP RE-READING") && !/^\[BRANCH-EXTRACT(?:\s+v\d+)?\]/m.test(text12);
375828
375894
  }
375829
- function toSummary(record8, path7) {
375830
- const { request: _request, requestCompilation, requestBudget, ...summary } = record8;
375895
+ function toSummary(record9, path7) {
375896
+ const { request: _request, requestCompilation, requestBudget, ...summary } = record9;
375831
375897
  return {
375832
375898
  ...summary,
375833
375899
  ...requestCompilation ? {
@@ -376544,20 +376610,20 @@ function safeErrorObjects(error) {
376544
376610
  let current = error;
376545
376611
  while (current && typeof current === "object" && !seen.has(current) && result.length < 4) {
376546
376612
  seen.add(current);
376547
- const record8 = current;
376548
- result.push(record8);
376549
- const responseJson = record8["responseJson"];
376550
- 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) {
376551
376617
  seen.add(responseJson);
376552
376618
  result.push(responseJson);
376553
376619
  }
376554
- current = record8["cause"];
376620
+ current = record9["cause"];
376555
376621
  }
376556
376622
  return result;
376557
376623
  }
376558
376624
  function safeErrorNumber(error, key) {
376559
- for (const record8 of safeErrorObjects(error)) {
376560
- const value = record8[key];
376625
+ for (const record9 of safeErrorObjects(error)) {
376626
+ const value = record9[key];
376561
376627
  if (typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 599) {
376562
376628
  return value;
376563
376629
  }
@@ -376565,25 +376631,25 @@ function safeErrorNumber(error, key) {
376565
376631
  return void 0;
376566
376632
  }
376567
376633
  function safeErrorCode(error) {
376568
- for (const record8 of safeErrorObjects(error)) {
376569
- const value = record8["code"];
376634
+ for (const record9 of safeErrorObjects(error)) {
376635
+ const value = record9["code"];
376570
376636
  if (typeof value === "string" && /^[A-Z0-9_]{2,40}$/.test(value))
376571
376637
  return value;
376572
376638
  }
376573
376639
  return "";
376574
376640
  }
376575
376641
  function safeErrorName(error) {
376576
- for (const record8 of safeErrorObjects(error)) {
376577
- const value = record8["name"];
376642
+ for (const record9 of safeErrorObjects(error)) {
376643
+ const value = record9["name"];
376578
376644
  if (typeof value === "string" && /^[A-Za-z]{2,40}$/.test(value))
376579
376645
  return value;
376580
376646
  }
376581
376647
  return "";
376582
376648
  }
376583
376649
  function safeExplicitRetryable(error) {
376584
- for (const record8 of safeErrorObjects(error)) {
376585
- if (typeof record8["retryable"] === "boolean")
376586
- return record8["retryable"];
376650
+ for (const record9 of safeErrorObjects(error)) {
376651
+ if (typeof record9["retryable"] === "boolean")
376652
+ return record9["retryable"];
376587
376653
  }
376588
376654
  return void 0;
376589
376655
  }
@@ -376799,21 +376865,21 @@ function parseMemoryCompilationProposal(value) {
376799
376865
  };
376800
376866
  }
376801
376867
  async function analyzeMemoryDelta(backend, input) {
376802
- const candidatePayload = input.candidates.map((record8) => ({
376803
- id: record8.id,
376804
- kind: record8.kind,
376805
- authority: record8.authority,
376806
- 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,
376807
376873
  // For canonical artifacts this is the hash a trusted resolver can reopen,
376808
376874
  // not the ledger's epoch-scoped record identity hash.
376809
- contentHash: isArtifactRecord(record8) ? canonicalArtifactContentHash(record8) : record8.contentHash,
376810
- provenance: record8.provenance,
376811
- validFrom: record8.validFrom,
376812
- 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,
376813
376879
  // This is intentionally the real evidence candidate, not a wrapper or
376814
376880
  // structural preview. The system instruction below makes its untrusted
376815
376881
  // status explicit regardless of text that appears inside it.
376816
- body: record8.body
376882
+ body: record9.body
376817
376883
  }));
376818
376884
  const prompt = [
376819
376885
  "You are an isolated, non-mutating memory compiler for a coding agent.",
@@ -376872,34 +376938,34 @@ function compilerBodyPreviewBudget(candidateCount) {
376872
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))));
376873
376939
  }
376874
376940
  async function analyzeMemoryCompilationPlanWithOutcome(backend, input) {
376875
- const protectedRecords = input.candidates.filter((record8) => record8.authority === "system" || record8.authority === "user");
376876
- const mutableRecords = input.candidates.filter((record8) => record8.authority !== "system" && record8.authority !== "user");
376877
- 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;
376878
376944
  const previewChars = compilerBodyPreviewBudget(mutableRecords.length);
376879
- const protectedPayload = protectedRecords.map((record8) => ({
376880
- id: record8.id,
376881
- authority: record8.authority,
376945
+ const protectedPayload = protectedRecords.map((record9) => ({
376946
+ id: record9.id,
376947
+ authority: record9.authority,
376882
376948
  lockedDisposition: "retain_full",
376883
376949
  // The newest user authority orients relevance decisions. Older user and
376884
376950
  // all system bodies stay out of this isolated request: trusted code has
376885
376951
  // already fixed their disposition and the final request retains them.
376886
- ...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 }
376887
376953
  }));
376888
- const candidatePayload = mutableRecords.map((record8) => ({
376889
- id: record8.id,
376890
- kind: record8.kind,
376891
- authority: record8.authority,
376892
- trustClass: record8.trustClass,
376893
- artifactAvailable: durableArtifactReference(record8) !== void 0,
376894
- toolResult: record8.authority === "tool_data",
376895
- estimatedFullTokens: estimatedRecordTokens(record8),
376896
- estimatedFullInputTokens: estimatedConservativeTextTokens(record8.body),
376897
- 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,
376898
376964
  // The exact body remains in the immutable ledger/artifact store. The
376899
376965
  // compiler only needs enough bounded context to identify obviously stale,
376900
376966
  // duplicate, or reopenable material; omission always defaults to
376901
376967
  // retain_full, so an incomplete preview can never silently delete data.
376902
- ...compilerBodyPreview(record8.body, previewChars)
376968
+ ...compilerBodyPreview(record9.body, previewChars)
376903
376969
  }));
376904
376970
  const targetMaximumTokens = compactionInputTarget(input.budget);
376905
376971
  const requiredMinimumReduction = Math.max(1, (input.budget.compactionInputTokens ?? compactionInputEstimate(input.budget)) - targetMaximumTokens);
@@ -377121,19 +377187,19 @@ function emptyCoverage() {
377121
377187
  unresolvedRequirementIds: []
377122
377188
  };
377123
377189
  }
377124
- function durableArtifactReference(record8) {
377125
- if (!isArtifactRecord(record8))
377190
+ function durableArtifactReference(record9) {
377191
+ if (!isArtifactRecord(record9))
377126
377192
  return void 0;
377127
- const contentHash2 = canonicalArtifactContentHash(record8);
377193
+ const contentHash2 = canonicalArtifactContentHash(record9);
377128
377194
  const artifactUri = `omnius-artifact://sha256/${contentHash2}`;
377129
- if (record8.metadata["artifactReference"] !== artifactUri)
377195
+ if (record9.metadata["artifactReference"] !== artifactUri)
377130
377196
  return void 0;
377131
377197
  return {
377132
377198
  artifactUri,
377133
377199
  contentHash: contentHash2,
377134
- ...record8.provenance.sourceUri ? { sourceUri: record8.provenance.sourceUri } : {},
377135
- ...record8.provenance.sourceRevision ? { sourceRevision: record8.provenance.sourceRevision } : {},
377136
- ...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 } : {}
377137
377203
  };
377138
377204
  }
377139
377205
  function recordLineCount(content) {
@@ -377160,7 +377226,7 @@ function sliceRecordLines(content, span) {
377160
377226
  const endOffset = span.end === totalLines ? content.length : starts[span.end];
377161
377227
  return startOffset === void 0 || endOffset === void 0 ? null : content.slice(startOffset, endOffset);
377162
377228
  }
377163
- function renderedCandidateContent(candidate, record8) {
377229
+ function renderedCandidateContent(candidate, record9) {
377164
377230
  const artifactHeader = candidate.artifact ? [
377165
377231
  `artifact: ${candidate.artifact.artifactUri}`,
377166
377232
  ...candidate.artifact.sourceUri ? [`source: ${candidate.artifact.sourceUri}`] : [],
@@ -377168,10 +377234,10 @@ function renderedCandidateContent(candidate, record8) {
377168
377234
  ] : [];
377169
377235
  switch (candidate.disposition) {
377170
377236
  case "retain_full":
377171
- return record8.body;
377237
+ return record9.body;
377172
377238
  case "retain_partial": {
377173
377239
  const excerpts = candidate.spans?.map((span) => {
377174
- const content = sliceRecordLines(record8.body, span);
377240
+ const content = sliceRecordLines(record9.body, span);
377175
377241
  return content === null ? null : `lines ${span.start}-${span.end}:
377176
377242
  ${content}`;
377177
377243
  });
@@ -377213,12 +377279,12 @@ ${content}`;
377213
377279
  function estimatedTextTokens(value) {
377214
377280
  return value.length > 0 ? Math.ceil(value.length / 4) + 4 : 0;
377215
377281
  }
377216
- function hydrateProposalChange(change, record8) {
377217
- const artifact = isArtifactRecord(record8) ? durableArtifactReference(record8) : void 0;
377218
- if (isArtifactRecord(record8) && !artifact)
377282
+ function hydrateProposalChange(change, record9) {
377283
+ const artifact = isArtifactRecord(record9) ? durableArtifactReference(record9) : void 0;
377284
+ if (isArtifactRecord(record9) && !artifact)
377219
377285
  return null;
377220
377286
  const base = {
377221
- id: record8.id,
377287
+ id: record9.id,
377222
377288
  rationale: change.rationale,
377223
377289
  renderedTokens: 0,
377224
377290
  coverage: emptyCoverage(),
@@ -377249,24 +377315,24 @@ function hydrateProposalChange(change, record8) {
377249
377315
  case "archive":
377250
377316
  return { ...base, disposition: "archive", archiveReason: change.archiveReason };
377251
377317
  }
377252
- const content = renderedCandidateContent(candidate, record8);
377318
+ const content = renderedCandidateContent(candidate, record9);
377253
377319
  return content === null ? null : { ...candidate, renderedTokens: estimatedTextTokens(content) };
377254
377320
  }
377255
377321
  function hydrateMemoryCompilationProposal(proposal, input, mutableRecords) {
377256
- const recordById = new Map(input.candidates.map((record8) => [record8.id, record8]));
377257
- 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));
377258
377324
  const returnedIds = new Set(proposal.changes.map((change) => change.id));
377259
377325
  if (returnedIds.size !== proposal.changes.length) {
377260
377326
  return { plan: null, invalidOutputDetail: "duplicate_candidate_id" };
377261
377327
  }
377262
377328
  for (const id5 of returnedIds) {
377263
- const record8 = recordById.get(id5);
377264
- if (!record8)
377329
+ const record9 = recordById.get(id5);
377330
+ if (!record9)
377265
377331
  return { plan: null, invalidOutputDetail: "unknown_candidate_id" };
377266
377332
  if (!mutableIds.has(id5)) {
377267
377333
  return {
377268
377334
  plan: null,
377269
- 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"
377270
377336
  };
377271
377337
  }
377272
377338
  }
@@ -377279,15 +377345,15 @@ function hydrateMemoryCompilationProposal(proposal, input, mutableRecords) {
377279
377345
  return { plan: null, invalidOutputDetail: "schema_invalid" };
377280
377346
  }
377281
377347
  const changedById = new Map(proposal.changes.map((change) => [change.id, change]));
377282
- const candidates = input.candidates.map((record8) => {
377283
- const change = changedById.get(record8.id);
377284
- 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.");
377285
377351
  });
377286
377352
  if (candidates.some((candidate) => candidate === null)) {
377287
377353
  return { plan: null, invalidOutputDetail: "schema_invalid" };
377288
377354
  }
377289
377355
  const hydrated = candidates;
377290
- const originalCandidateTokens = input.candidates.reduce((total, record8) => total + estimatedRecordTokens(record8), 0);
377356
+ const originalCandidateTokens = input.candidates.reduce((total, record9) => total + estimatedRecordTokens(record9), 0);
377291
377357
  const fixedTokens = Math.max(0, auditInputEstimate(input.budget) - originalCandidateTokens);
377292
377358
  const renderedTokens = hydrated.reduce((total, candidate) => total + candidate.renderedTokens, 0);
377293
377359
  return {
@@ -377304,20 +377370,20 @@ function hydrateMemoryCompilationProposal(proposal, input, mutableRecords) {
377304
377370
  }
377305
377371
  };
377306
377372
  }
377307
- function trustedRetainFullCandidate(record8, rationale = "Trusted host policy preserves this candidate in full.") {
377308
- const contentHash2 = canonicalArtifactContentHash(record8);
377309
- 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) ? {
377310
377376
  artifactUri: `omnius-artifact://sha256/${contentHash2}`,
377311
377377
  contentHash: contentHash2,
377312
- ...record8.provenance.sourceUri ? { sourceUri: record8.provenance.sourceUri } : {},
377313
- ...record8.provenance.sourceRevision ? { sourceRevision: record8.provenance.sourceRevision } : {},
377314
- ...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 } : {}
377315
377381
  } : void 0;
377316
377382
  return {
377317
- id: record8.id,
377383
+ id: record9.id,
377318
377384
  disposition: "retain_full",
377319
377385
  rationale,
377320
- renderedTokens: estimatedRecordTokens(record8),
377386
+ renderedTokens: estimatedRecordTokens(record9),
377321
377387
  coverage: {
377322
377388
  claimIds: [],
377323
377389
  requirementIds: [],
@@ -377336,7 +377402,7 @@ function hold(reasons3, retainedIds = /* @__PURE__ */ new Set()) {
377336
377402
  };
377337
377403
  }
377338
377404
  function validateMemoryDelta(input) {
377339
- const candidateIds = new Set(input.candidateRecords.map((record8) => record8.id));
377405
+ const candidateIds = new Set(input.candidateRecords.map((record9) => record9.id));
377340
377406
  const retainedIds = new Set(input.delta.retain);
377341
377407
  const archivedIds = new Set(input.delta.archive.map((entry) => entry.id));
377342
377408
  if (input.delta.decision !== "compact")
@@ -377362,11 +377428,11 @@ function validateMemoryDelta(input) {
377362
377428
  }
377363
377429
  if ([...retainedIds].some((id5) => archivedIds.has(id5)))
377364
377430
  return hold(["record cannot be retained and archived together"], retainedIds);
377365
- const candidateById = new Map(input.candidateRecords.map((record8) => [record8.id, record8]));
377431
+ const candidateById = new Map(input.candidateRecords.map((record9) => [record9.id, record9]));
377366
377432
  if (input.delta.unresolvedClaims.some((id5) => candidateById.get(id5)?.kind !== "claim")) {
377367
377433
  return hold(["unresolved claims must reference known claim records"], retainedIds);
377368
377434
  }
377369
- 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));
377370
377436
  if (protectedAuthority.length > 0)
377371
377437
  return hold(["authority records may not be archived"], retainedIds);
377372
377438
  if (input.delta.supersede.some(({ old, next }) => !candidateIds.has(old) || !candidateIds.has(next) || old === next)) {
@@ -377387,8 +377453,8 @@ function validateMemoryDelta(input) {
377387
377453
  archivedIds
377388
377454
  };
377389
377455
  }
377390
- function estimatedRecordTokens(record8) {
377391
- 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;
377392
377458
  }
377393
377459
  function auditInputEstimate(budget) {
377394
377460
  return budget.totalInputTokens ?? Math.max(0, budget.projectedTotalTokens - (budget.outputReservationTokens ?? 0) - (budget.safetyMarginTokens ?? 0));
@@ -377405,10 +377471,10 @@ function compactionInputTarget(budget) {
377405
377471
  function memoryCompilationTargetReachability(input) {
377406
377472
  let candidateTokens = 0;
377407
377473
  let lockedTokens = 0;
377408
- for (const record8 of input.candidateRecords) {
377409
- const tokens3 = estimatedConservativeTextTokens(record8.body);
377474
+ for (const record9 of input.candidateRecords) {
377475
+ const tokens3 = estimatedConservativeTextTokens(record9.body);
377410
377476
  candidateTokens += tokens3;
377411
- if (record8.authority === "system" || record8.authority === "user")
377477
+ if (record9.authority === "system" || record9.authority === "user")
377412
377478
  lockedTokens += tokens3;
377413
377479
  }
377414
377480
  const fixedTokens = Math.max(0, compactionInputEstimate(input.budget) - candidateTokens);
@@ -377431,7 +377497,7 @@ function planHold(input, reasons3, candidates = /* @__PURE__ */ new Map()) {
377431
377497
  reasons: reasons3,
377432
377498
  // A rejected plan can never cause a partial materialization. Preserve the
377433
377499
  // entire candidate set until a new exact request is compiled.
377434
- retainedIds: new Set(input.candidateRecords.map((record8) => record8.id)),
377500
+ retainedIds: new Set(input.candidateRecords.map((record9) => record9.id)),
377435
377501
  archivedIds: /* @__PURE__ */ new Set(),
377436
377502
  candidates
377437
377503
  };
@@ -377439,31 +377505,31 @@ function planHold(input, reasons3, candidates = /* @__PURE__ */ new Map()) {
377439
377505
  function uniqueStrings4(values) {
377440
377506
  return new Set(values).size === values.length;
377441
377507
  }
377442
- function isArtifactRecord(record8) {
377443
- return record8.kind === "artifact" || record8.kind === "artifact_extract";
377508
+ function isArtifactRecord(record9) {
377509
+ return record9.kind === "artifact" || record9.kind === "artifact_extract";
377444
377510
  }
377445
- function canonicalArtifactContentHash(record8) {
377446
- const stored = record8.metadata["artifactContentHash"];
377447
- 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();
377448
377514
  }
377449
- function referenceMatchesRecord(reference2, record8) {
377515
+ function referenceMatchesRecord(reference2, record9) {
377450
377516
  const uri = ARTIFACT_URI.exec(reference2.artifactUri);
377451
377517
  if (!uri || uri[1].toLowerCase() !== reference2.contentHash.toLowerCase())
377452
377518
  return "artifact URI is not bound to its declared content hash";
377453
- if (reference2.contentHash.toLowerCase() !== canonicalArtifactContentHash(record8))
377519
+ if (reference2.contentHash.toLowerCase() !== canonicalArtifactContentHash(record9))
377454
377520
  return "artifact reference hash does not match canonical record content";
377455
- if (record8.provenance.sourceUri && reference2.sourceUri !== record8.provenance.sourceUri)
377521
+ if (record9.provenance.sourceUri && reference2.sourceUri !== record9.provenance.sourceUri)
377456
377522
  return "artifact reference source URI does not match canonical provenance";
377457
- if (record8.provenance.sourceRevision && reference2.sourceRevision !== record8.provenance.sourceRevision)
377523
+ if (record9.provenance.sourceRevision && reference2.sourceRevision !== record9.provenance.sourceRevision)
377458
377524
  return "artifact reference revision does not match canonical provenance";
377459
- const canonicalRange = record8.provenance.sourceRange;
377525
+ const canonicalRange = record9.provenance.sourceRange;
377460
377526
  const referencedRange = reference2.sourceRange;
377461
377527
  if (canonicalRange && referencedRange && (referencedRange.start < canonicalRange.start || referencedRange.end > canonicalRange.end)) {
377462
377528
  return "artifact reference source range exceeds canonical provenance";
377463
377529
  }
377464
377530
  return null;
377465
377531
  }
377466
- function validateCandidateRepresentation(candidate, record8, claimRecords) {
377532
+ function validateCandidateRepresentation(candidate, record9, claimRecords) {
377467
377533
  if (!candidate.rationale.trim())
377468
377534
  return `candidate ${candidate.id} has no rationale`;
377469
377535
  if (!uniqueStrings4(candidate.coverage.claimIds) || !uniqueStrings4(candidate.coverage.requirementIds) || !uniqueStrings4(candidate.coverage.unresolvedRequirementIds)) {
@@ -377475,18 +377541,18 @@ function validateCandidateRepresentation(candidate, record8, claimRecords) {
377475
377541
  if (candidate.coverage.claimIds.some((id5) => claimRecords.get(id5)?.kind !== "claim")) {
377476
377542
  return `candidate ${candidate.id} coverage references an unknown claim`;
377477
377543
  }
377478
- const sourceRange = record8.provenance.sourceRange;
377544
+ const sourceRange = record9.provenance.sourceRange;
377479
377545
  if (candidate.spans?.some((span) => sourceRange && (span.start < sourceRange.start || span.end > sourceRange.end))) {
377480
377546
  return `candidate ${candidate.id} line span exceeds canonical source range`;
377481
377547
  }
377482
- const fullTokens = estimatedRecordTokens(record8);
377548
+ const fullTokens = estimatedRecordTokens(record9);
377483
377549
  if (candidate.renderedTokens > Math.max(fullTokens, 4096) && candidate.disposition !== "compact_summary") {
377484
377550
  return `candidate ${candidate.id} rendered token estimate exceeds bounded representation size`;
377485
377551
  }
377486
- if (isArtifactRecord(record8)) {
377552
+ if (isArtifactRecord(record9)) {
377487
377553
  if (!candidate.artifact)
377488
377554
  return `artifact candidate ${candidate.id} lacks a durable artifact reference`;
377489
- const issue3 = referenceMatchesRecord(candidate.artifact, record8);
377555
+ const issue3 = referenceMatchesRecord(candidate.artifact, record9);
377490
377556
  if (issue3)
377491
377557
  return `candidate ${candidate.id} ${issue3}`;
377492
377558
  } else if (candidate.artifact) {
@@ -377532,7 +377598,7 @@ function validateCandidateRepresentation(candidate, record8, claimRecords) {
377532
377598
  }
377533
377599
  }
377534
377600
  function validateMemoryCompilationPlan(input) {
377535
- const candidateById = new Map(input.candidateRecords.map((record8) => [record8.id, record8]));
377601
+ const candidateById = new Map(input.candidateRecords.map((record9) => [record9.id, record9]));
377536
377602
  const planById = new Map(input.plan.candidates.map((candidate) => [candidate.id, candidate]));
377537
377603
  if (input.plan.schemaVersion !== 2)
377538
377604
  return planHold(input, ["memory compilation plan schema version is unsupported"], planById);
@@ -377552,11 +377618,11 @@ function validateMemoryCompilationPlan(input) {
377552
377618
  if (typeof input.plan.orientation === "string" && input.plan.orientation.length > 4e3)
377553
377619
  return planHold(input, ["orientation exceeds bounded working-set limit"], planById);
377554
377620
  for (const [id5, candidate] of planById) {
377555
- const record8 = candidateById.get(id5);
377556
- const issue3 = validateCandidateRepresentation(candidate, record8, candidateById);
377621
+ const record9 = candidateById.get(id5);
377622
+ const issue3 = validateCandidateRepresentation(candidate, record9, candidateById);
377557
377623
  if (issue3)
377558
377624
  return planHold(input, [issue3], planById);
377559
- if ((record8.authority === "system" || record8.authority === "user") && candidate.disposition !== "retain_full") {
377625
+ if ((record9.authority === "system" || record9.authority === "user") && candidate.disposition !== "retain_full") {
377560
377626
  return planHold(input, [`authority record ${id5} must be retained in full`], planById);
377561
377627
  }
377562
377628
  }
@@ -377565,7 +377631,7 @@ function validateMemoryCompilationPlan(input) {
377565
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")) {
377566
377632
  return planHold(input, ["supersession must retire a known superseded record and retain its replacement"], planById);
377567
377633
  }
377568
- const candidateTokens = input.candidateRecords.reduce((total, record8) => total + estimatedRecordTokens(record8), 0);
377634
+ const candidateTokens = input.candidateRecords.reduce((total, record9) => total + estimatedRecordTokens(record9), 0);
377569
377635
  const fixedTokens = Math.max(0, auditInputEstimate(input.budget) - candidateTokens);
377570
377636
  const renderedTokens = [...planById.values()].reduce((total, candidate) => total + candidate.renderedTokens, 0);
377571
377637
  const computedPostCompactionTokens = fixedTokens + renderedTokens;
@@ -377581,7 +377647,7 @@ function validateMemoryCompilationPlan(input) {
377581
377647
  if (archivedIds.size === 0 && [...planById.values()].every((candidate) => candidate.disposition === "retain_full")) {
377582
377648
  return planHold(input, ["compact decision does not change any candidate representation"], planById);
377583
377649
  }
377584
- 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);
377585
377651
  const conservativeFixedTokens = Math.max(0, compactionInputEstimate(input.budget) - conservativeCandidateTokens);
377586
377652
  const conservativeRenderedTokens = [...planById.values()].reduce((total, candidate) => {
377587
377653
  const content = renderedCandidateContent(candidate, candidateById.get(candidate.id));
@@ -378167,27 +378233,27 @@ function normalizeFailureDiagnosis(value) {
378167
378233
  kind: kind ?? patternKey?.match(/^[^:]+:(.+)$/)?.[1]
378168
378234
  };
378169
378235
  }
378170
- function diagnoseContextDump(record8) {
378236
+ function diagnoseContextDump(record9) {
378171
378237
  const diagnoses = /* @__PURE__ */ new Set();
378172
- if (record8.focusSupervisor?.directive?.requiredNextAction) {
378238
+ if (record9.focusSupervisor?.directive?.requiredNextAction) {
378173
378239
  diagnoses.add("focus-supervisor-active");
378174
378240
  }
378175
- if (record8.focusSupervisor?.lastDecision === "block_tool_call") {
378241
+ if (record9.focusSupervisor?.lastDecision === "block_tool_call") {
378176
378242
  diagnoses.add("focus-supervisor-block");
378177
378243
  }
378178
- if (record8.metrics.rawDiscoveryToolChars > 0 && (record8.metrics.signalToNoise.ratio ?? 999) < 1) {
378244
+ if (record9.metrics.rawDiscoveryToolChars > 0 && (record9.metrics.signalToNoise.ratio ?? 999) < 1) {
378179
378245
  diagnoses.add("raw-discovery-dominates-context");
378180
378246
  }
378181
- if (record8.metrics.estimatedTokens > 1e5) {
378247
+ if (record9.metrics.estimatedTokens > 1e5) {
378182
378248
  diagnoses.add("large-context-window");
378183
378249
  }
378184
- if (hasToolResultBindingMismatch(record8)) {
378250
+ if (hasToolResultBindingMismatch(record9)) {
378185
378251
  diagnoses.add("tool-result-binding-mismatch");
378186
378252
  }
378187
378253
  return [...diagnoses].sort();
378188
378254
  }
378189
- function hasToolResultBindingMismatch(record8) {
378190
- 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"] : [];
378191
378257
  if (messages.length === 0)
378192
378258
  return false;
378193
378259
  const callsById = /* @__PURE__ */ new Map();
@@ -378271,13 +378337,13 @@ function summarizeToolEvent(toolName, success, diagnoses, command) {
378271
378337
  parts.push(`command=${trim(command, 180)}`);
378272
378338
  return parts.join(" | ");
378273
378339
  }
378274
- function summarizeContextDump(record8, diagnoses) {
378340
+ function summarizeContextDump(record9, diagnoses) {
378275
378341
  const parts = [
378276
- `context dump ${record8.stage}`,
378277
- `tokens~${record8.metrics.estimatedTokens}`
378342
+ `context dump ${record9.stage}`,
378343
+ `tokens~${record9.metrics.estimatedTokens}`
378278
378344
  ];
378279
- if (record8.focusSupervisor?.directive?.requiredNextAction) {
378280
- parts.push(`required=${record8.focusSupervisor.directive.requiredNextAction}`);
378345
+ if (record9.focusSupervisor?.directive?.requiredNextAction) {
378346
+ parts.push(`required=${record9.focusSupervisor.directive.requiredNextAction}`);
378281
378347
  }
378282
378348
  if (diagnoses.length > 0)
378283
378349
  parts.push(`diagnoses=${diagnoses.join(",")}`);
@@ -378488,7 +378554,7 @@ function shortHash5(value) {
378488
378554
 
378489
378555
  // packages/orchestrator/dist/modelResponseDiagnostics.js
378490
378556
  var MAX_COUNT = 1e9;
378491
- function record7(value) {
378557
+ function record8(value) {
378492
378558
  return value !== null && typeof value === "object" && !Array.isArray(value);
378493
378559
  }
378494
378560
  function count(value) {
@@ -378529,7 +378595,7 @@ function nativeMetrics(value, wire = false) {
378529
378595
  return Object.keys(result).length ? result : void 0;
378530
378596
  }
378531
378597
  function transportMetadata(value) {
378532
- if (!record7(value))
378598
+ if (!record8(value))
378533
378599
  return void 0;
378534
378600
  const physicalRequestId = identifier2(value.physicalRequestId);
378535
378601
  if (!physicalRequestId)
@@ -378598,11 +378664,11 @@ var NativeModelResponseDiagnostics = class {
378598
378664
  }
378599
378665
  observe(frame) {
378600
378666
  try {
378601
- if (!record7(frame))
378667
+ if (!record8(frame))
378602
378668
  return;
378603
378669
  this.value.frameCount = boundedCount(this.value.frameCount + 1);
378604
378670
  const message = frame.message;
378605
- if (record7(message)) {
378671
+ if (record8(message)) {
378606
378672
  this.value.messageFrames = boundedCount(this.value.messageFrames + 1);
378607
378673
  if (typeof message.content === "string")
378608
378674
  this.value.contentChars = boundedCount(this.value.contentChars + message.content.length);
@@ -378642,7 +378708,7 @@ var NativeModelResponseDiagnostics = class {
378642
378708
  function modelResponseDiagnosticReceipt(input) {
378643
378709
  try {
378644
378710
  const value = input.diagnostics;
378645
- 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)
378646
378712
  return void 0;
378647
378713
  const frameCount = count(value.frameCount);
378648
378714
  const messageFrames = count(value.messageFrames);
@@ -378651,8 +378717,8 @@ function modelResponseDiagnosticReceipt(input) {
378651
378717
  const rawToolCallEntries = count(value.rawToolCallEntries);
378652
378718
  if (frameCount === void 0 || messageFrames === void 0 || contentChars === void 0 || thinkingChars === void 0 || rawToolCallEntries === void 0 || messageFrames > frameCount || typeof value.done !== "boolean")
378653
378719
  return void 0;
378654
- 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;
378655
- 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;
378656
378722
  const transport = transportMetadata(value.requestTrace);
378657
378723
  if (transport && !value.done)
378658
378724
  delete transport.doneObservedMonotonicMs;
@@ -384655,11 +384721,11 @@ function ollamaNativeFormatFromResponseFormat(value) {
384655
384721
  if (!value || typeof value !== "object" || Array.isArray(value)) {
384656
384722
  return void 0;
384657
384723
  }
384658
- const record8 = value;
384659
- if (record8["type"] === "json_object")
384724
+ const record9 = value;
384725
+ if (record9["type"] === "json_object")
384660
384726
  return "json";
384661
- if (record8["type"] === "json_schema") {
384662
- const jsonSchema = record8["json_schema"];
384727
+ if (record9["type"] === "json_schema") {
384728
+ const jsonSchema = record9["json_schema"];
384663
384729
  if (jsonSchema && typeof jsonSchema === "object" && !Array.isArray(jsonSchema)) {
384664
384730
  const schemaRecord = jsonSchema;
384665
384731
  const nestedSchema = schemaRecord["schema"];
@@ -384672,8 +384738,8 @@ function ollamaNativeFormatFromResponseFormat(value) {
384672
384738
  }
384673
384739
  return "json";
384674
384740
  }
384675
- if (record8["type"] === "object" || record8["properties"] !== void 0) {
384676
- return record8;
384741
+ if (record9["type"] === "object" || record9["properties"] !== void 0) {
384742
+ return record9;
384677
384743
  }
384678
384744
  return void 0;
384679
384745
  }
@@ -387987,7 +388053,7 @@ ${renderTaskExecutionSnapshot(snapshot)}` } : projected;
387987
388053
  const stateDir = this.omniusStateDir();
387988
388054
  const reportEvidenceReference = this._conversationReportEvidence?.persist();
387989
388055
  const reportLedger = this._completionLedger ?? this._conversationReportEvidence?.ledger ?? null;
387990
- const record8 = {
388056
+ const record9 = {
387991
388057
  ...buildCompletionFinalizationRecord({
387992
388058
  runId: this.currentArtifactRunId(),
387993
388059
  taskEpoch: this._taskEpoch,
@@ -388012,16 +388078,16 @@ ${renderTaskExecutionSnapshot(snapshot)}` } : projected;
388012
388078
  }),
388013
388079
  ...reportEvidenceReference ? { reportEvidenceReference } : {}
388014
388080
  };
388015
- const markerPath = completionFinalizationPath(stateDir, record8.runId);
388016
- prepareCompletionFinalization(stateDir, record8);
388081
+ const markerPath = completionFinalizationPath(stateDir, record9.runId);
388082
+ prepareCompletionFinalization(stateDir, record9);
388017
388083
  if (this._completionLedger) {
388018
388084
  this._completionLedger = {
388019
388085
  ...this._completionLedger,
388020
388086
  terminal: {
388021
- receiptId: record8.id,
388087
+ receiptId: record9.id,
388022
388088
  status: input.status,
388023
- committedAtIso: record8.committedAtIso,
388024
- evidenceIds: record8.evidenceIds
388089
+ committedAtIso: record9.committedAtIso,
388090
+ evidenceIds: record9.evidenceIds
388025
388091
  }
388026
388092
  };
388027
388093
  }
@@ -388035,14 +388101,14 @@ ${renderTaskExecutionSnapshot(snapshot)}` } : projected;
388035
388101
  actor: "runner",
388036
388102
  taskEpoch: this._taskEpoch,
388037
388103
  status: boardCanComplete ? "completed" : "archived",
388038
- terminalReceiptId: record8.id,
388104
+ terminalReceiptId: record9.id,
388039
388105
  terminalSummary: input.summary.slice(0, 1200),
388040
388106
  artifactEvidence: [
388041
388107
  {
388042
388108
  kind: "note",
388043
388109
  summary: `terminal ${input.status} committed`,
388044
388110
  ref: markerPath,
388045
- verifies: record8.evidenceIds
388111
+ verifies: record9.evidenceIds
388046
388112
  }
388047
388113
  ]
388048
388114
  });
@@ -388055,34 +388121,34 @@ ${renderTaskExecutionSnapshot(snapshot)}` } : projected;
388055
388121
  turn: this._taskState.toolCallCount,
388056
388122
  toolName: "task_complete",
388057
388123
  args: {
388058
- terminalReceiptId: record8.id,
388124
+ terminalReceiptId: record9.id,
388059
388125
  status: input.status,
388060
388126
  runtime: {
388061
- package: record8.runtimeProvenance.package.name,
388062
- version: record8.runtimeProvenance.package.version,
388063
- packageManifestSha256: record8.runtimeProvenance.package.manifestSha256,
388064
- 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
388065
388131
  }
388066
388132
  },
388067
388133
  success: input.status === "completed",
388068
- output: `terminal_receipt=${record8.id}
388134
+ output: `terminal_receipt=${record9.id}
388069
388135
  marker=${markerPath}
388070
388136
  readiness_hash=${input.completionReadiness.readinessHash}
388071
388137
  completion_disposition=${input.completionReadiness.disposition}
388072
- verification_audit=${record8.verificationAudit?.status ?? "no_observed_gap"}
388073
- 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"}
388074
388140
  unresolved=${input.completionReadiness.unresolvedIds.join(",") || "none"}
388075
- evidence=${record8.evidenceIds.join(",") || "none"}
388076
- command_receipts=${record8.commandReceipts.length}
388077
- ` + (record8.commandReceipts.length > 0 ? `command_receipts_summary=${record8.commandReceipts.map((entry) => `${entry.canonicalCommand || entry.command || "n/a"}:${entry.exitCode}`).join(" | ")}
388078
- ` : "command_receipts_summary=none\n") + `runtime_package=${record8.runtimeProvenance.package.name ?? "unknown"}@${record8.runtimeProvenance.package.version ?? "unknown"}
388079
- runtime_package_sha256=${record8.runtimeProvenance.package.manifestSha256 ?? "unknown"}
388080
- runtime_module=${record8.runtimeProvenance.module.path}
388081
- 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"}`
388082
388148
  });
388083
- commitTerminalTrajectoryProjection(stateDir, record8, input.trajectoryPayload);
388149
+ commitTerminalTrajectoryProjection(stateDir, record9, input.trajectoryPayload);
388084
388150
  const committed = {
388085
- ...record8,
388151
+ ...record9,
388086
388152
  phase: "committed",
388087
388153
  projections: {
388088
388154
  ledger: "committed",
@@ -388794,7 +388860,7 @@ runtime_module_sha256=${record8.runtimeProvenance.module.sha256 ?? "unknown"}`
388794
388860
  } catch {
388795
388861
  }
388796
388862
  }
388797
- const record8 = ledger.appendRecord({
388863
+ const record9 = ledger.appendRecord({
388798
388864
  id: id5,
388799
388865
  epoch: epoch2,
388800
388866
  kind: isToolArtifact ? "artifact" : "orientation",
@@ -388823,18 +388889,18 @@ runtime_module_sha256=${record8.runtimeProvenance.module.sha256 ?? "unknown"}`
388823
388889
  }
388824
388890
  });
388825
388891
  for (const activeRecord of activeByBodyHash.get(bodyHash) ?? []) {
388826
- if (activeRecord.id === record8.id)
388892
+ if (activeRecord.id === record9.id)
388827
388893
  continue;
388828
388894
  ledger.linkDependency({
388829
388895
  // Working-set closure follows source → target. The durable
388830
388896
  // evidence therefore points to this request-local projection.
388831
388897
  sourceRecordId: activeRecord.id,
388832
- targetRecordId: record8.id,
388898
+ targetRecordId: record9.id,
388833
388899
  relation: "derived_from",
388834
388900
  requiredForActiveWork: true
388835
388901
  });
388836
388902
  }
388837
- candidates.push({ record: record8, messageIndex });
388903
+ candidates.push({ record: record9, messageIndex });
388838
388904
  }
388839
388905
  return candidates;
388840
388906
  } catch {
@@ -389238,16 +389304,16 @@ ${read.content}`;
389238
389304
  const stateFingerprint = _createHash("sha256").update(JSON.stringify({
389239
389305
  requestFingerprint: budget.requestFingerprint,
389240
389306
  workingSetFingerprint: workingSet.fingerprint,
389241
- candidates: candidates.map((record8) => [
389242
- record8.id,
389243
- record8.contentHash,
389244
- record8.validUntil ?? null
389307
+ candidates: candidates.map((record9) => [
389308
+ record9.id,
389309
+ record9.contentHash,
389310
+ record9.validUntil ?? null
389245
389311
  ])
389246
389312
  })).digest("hex");
389247
389313
  const cached = this._memoryCompilerShadowCache.get(stateFingerprint);
389248
389314
  if (cached)
389249
389315
  return { ...cached, cacheHit: true };
389250
- const candidateChars = candidates.reduce((total, record8) => total + record8.body.length, 0);
389316
+ const candidateChars = candidates.reduce((total, record9) => total + record9.body.length, 0);
389251
389317
  const maxCandidateChars = Math.max(32e3, Math.floor(budget.modelContextTokens * 4 * 0.45));
389252
389318
  if (candidates.length === 0 || candidateChars > maxCandidateChars) {
389253
389319
  const audit2 = {
@@ -389256,7 +389322,7 @@ ${read.content}`;
389256
389322
  decision: "hold",
389257
389323
  accepted: false,
389258
389324
  cacheHit: false,
389259
- candidateRecordIds: candidates.map((record8) => record8.id),
389325
+ candidateRecordIds: candidates.map((record9) => record9.id),
389260
389326
  activeRecordIds,
389261
389327
  reason: candidates.length === 0 ? "no current records to classify" : `whole candidate bodies require ${candidateChars} chars; isolated compiler budget is ${maxCandidateChars} chars`
389262
389328
  };
@@ -389280,7 +389346,7 @@ ${read.content}`;
389280
389346
  decision: validation?.appliedDecision ?? "hold",
389281
389347
  accepted: validation?.accepted ?? false,
389282
389348
  cacheHit: false,
389283
- candidateRecordIds: candidates.map((record8) => record8.id),
389349
+ candidateRecordIds: candidates.map((record9) => record9.id),
389284
389350
  activeRecordIds,
389285
389351
  ...validation ? {
389286
389352
  retainedRecordIds: [...validation.retainedIds].sort(),
@@ -389339,7 +389405,7 @@ ${read.content}`;
389339
389405
  return {
389340
389406
  epoch: String(this._taskEpoch),
389341
389407
  rootRecordIds: activeRecordIds.sort(),
389342
- recordIds: materialized.records.map((record8) => record8.id),
389408
+ recordIds: materialized.records.map((record9) => record9.id),
389343
389409
  transactionIds: materialized.transactionIds,
389344
389410
  fingerprint: materialized.fingerprint
389345
389411
  };
@@ -391267,7 +391333,7 @@ ${workflowStatus}` } : {}
391267
391333
  finalRequestFingerprint: exactBudget.requestFingerprint,
391268
391334
  finalProjectionChanged: (compilationAudit.postRequestFingerprint ?? compilationAudit.preRequestFingerprint) !== exactBudget.requestFingerprint
391269
391335
  } : void 0;
391270
- const record8 = recordContextWindowDump({
391336
+ const record9 = recordContextWindowDump({
391271
391337
  source: "agenticRunner",
391272
391338
  stage: stage2,
391273
391339
  agentType,
@@ -391282,8 +391348,8 @@ ${workflowStatus}` } : {}
391282
391348
  focusSupervisor: this._focusSupervisor?.snapshot(),
391283
391349
  requestCompilation: this._referenceContractCompilation(memoryCompilerShadow, planAuditApplies)
391284
391350
  });
391285
- if (record8)
391286
- this._lastOutboundRequestBudget = record8.requestBudget;
391351
+ if (record9)
391352
+ this._lastOutboundRequestBudget = record9.requestBudget;
391287
391353
  else
391288
391354
  this._lastOutboundRequestBudget = exactBudget;
391289
391355
  if (memoryCompilerShadow) {
@@ -391321,14 +391387,14 @@ ${workflowStatus}` } : {}
391321
391387
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
391322
391388
  });
391323
391389
  }
391324
- if (record8) {
391390
+ if (record9) {
391325
391391
  const focusSnapshot = {
391326
- estimatedTokens: record8.metrics.estimatedTokens,
391327
- rawDiscoveryChars: record8.metrics.rawDiscoveryToolChars,
391328
- activeEvidenceChars: record8.metrics.activeEvidenceChars,
391329
- activeFrameChars: record8.metrics.activeContextFrameChars,
391330
- signalToNoiseRatio: record8.metrics.signalToNoise.ratio,
391331
- 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),
391332
391398
  droppedSignals: this._lastContextFrameDiagnostics?.droppedSignals ?? this._lastContextPressureSnapshot?.droppedSignals,
391333
391399
  truncatedSignals: this._lastContextFrameDiagnostics?.truncatedSignals ?? this._lastContextPressureSnapshot?.truncatedSignals
391334
391400
  };
@@ -391340,12 +391406,12 @@ ${workflowStatus}` } : {}
391340
391406
  stateDir: this.omniusStateDir(),
391341
391407
  runId: this.currentArtifactRunId(),
391342
391408
  sessionId: this._sessionId,
391343
- record: record8
391409
+ record: record9
391344
391410
  });
391345
391411
  } catch {
391346
391412
  }
391347
391413
  }
391348
- return record8?.id ?? null;
391414
+ return record9?.id ?? null;
391349
391415
  }
391350
391416
  /** Refresh exact transport fields after validated memory materialization. */
391351
391417
  _refreshCanonicalTransportTrace(request) {
@@ -391637,8 +391703,8 @@ ${workflowStatus}` } : {}
391637
391703
  epoch: epoch2,
391638
391704
  taskId: this._contextMemoryTaskRecordId
391639
391705
  });
391640
- for (const record8 of [action, call2, result])
391641
- ledger.attachTransactionRecord(transaction.id, record8.id);
391706
+ for (const record9 of [action, call2, result])
391707
+ ledger.attachTransactionRecord(transaction.id, record9.id);
391642
391708
  ledger.linkDependency({
391643
391709
  sourceRecordId: action.id,
391644
391710
  targetRecordId: this._contextMemoryTaskRecordId,
@@ -391925,13 +391991,13 @@ ${workflowStatus}` } : {}
391925
391991
  for (const raw of parsed["receipts"].slice(-128)) {
391926
391992
  if (!raw || typeof raw !== "object")
391927
391993
  continue;
391928
- const record8 = raw;
391929
- const transactionId2 = String(record8["transactionId"] ?? "").trim();
391930
- const toolName = String(record8["toolName"] ?? "").trim();
391931
- const artifactLocator = String(record8["artifactLocator"] ?? "").trim();
391932
- const evidenceId = String(record8["evidenceId"] ?? "").trim();
391933
- const summary = String(record8["summary"] ?? "").trim();
391934
- 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"]);
391935
392001
  if (!transactionId2 || !toolName || !artifactLocator || !evidenceId || !summary || !Number.isFinite(turn)) {
391936
392002
  continue;
391937
392003
  }
@@ -392742,10 +392808,10 @@ ${content}`)].join("\n\n");
392742
392808
  includeSuperseded: false,
392743
392809
  maximumCompressionGeneration: 4,
392744
392810
  limit: 1e4
392745
- }).map((record8) => [
392746
- record8.id,
392747
- record8.bodyHash,
392748
- record8.validUntil
392811
+ }).map((record9) => [
392812
+ record9.id,
392813
+ record9.bodyHash,
392814
+ record9.validUntil
392749
392815
  ]))).digest("hex") : "none";
392750
392816
  const semanticKey = _createHash("sha256").update(JSON.stringify({
392751
392817
  scopeId: this._sessionId,
@@ -392914,17 +392980,17 @@ ${content}`)].join("\n\n");
392914
392980
  if (records.length === 0)
392915
392981
  return [];
392916
392982
  const tokenBudget = Math.max(0, Math.min(physicalInputBudget, Math.floor(defaultTokenBudget)));
392917
- const rendered = records.map((record8) => [
392918
- `[${record8.memoryClass.toUpperCase()} id=${record8.id}${record8.canonicalKey ? ` key=${record8.canonicalKey}` : ""} importance=${record8.importance.toFixed(2)}]`,
392919
- record8.body,
392920
- `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(",")}`
392921
392987
  ].join("\n"));
392922
392988
  const tokens3 = Math.ceil(rendered.join("\n\n").length / 4);
392923
392989
  if (tokens3 > tokenBudget) {
392924
392990
  this._appendVirtualMemoryReceipt({
392925
392991
  requestId: this._modelTurnRequestId(turn, "virtual-memory"),
392926
392992
  stage: "capacity_error",
392927
- itemIds: records.map((record8) => record8.id),
392993
+ itemIds: records.map((record9) => record9.id),
392928
392994
  tokenDelta: tokens3,
392929
392995
  tokenBudget,
392930
392996
  reason: "active inference-classified pinned state exceeds its physical allocation",
@@ -392958,7 +393024,7 @@ ${content}`)].join("\n\n");
392958
393024
  stage: "pin",
392959
393025
  operation: "PIN",
392960
393026
  toLevel: "L1",
392961
- itemIds: records.map((record8) => record8.id),
393027
+ itemIds: records.map((record9) => record9.id),
392962
393028
  tokenDelta: tokens3,
392963
393029
  tokenBudget,
392964
393030
  reason: "pin active inference-classified constraints and current plan",
@@ -395668,7 +395734,7 @@ ${modelVisible}` : modelVisible || result.error || displayOutput || "";
395668
395734
  this._objectiveVerificationReceipts.set(verification.evidenceId, verification);
395669
395735
  }
395670
395736
  const verificationOnly = input.toolName === "task_complete" && !deliveryReceipt;
395671
- if (verificationOnly && verificationReceipts.length === 0)
395737
+ if (verificationOnly && verificationReceipts.length === 0 && !isCompletionReviewPendingResult(input.toolName, input.result))
395672
395738
  return;
395673
395739
  const realFileMutation = input.realFileMutation ?? this._isRealProjectMutation(input.toolName, input.result);
395674
395740
  const attemptedTargetPaths = this._extractToolTargetPaths(input.toolName, input.args, input.result);
@@ -396415,7 +396481,9 @@ Respond with a short verification section in this shape (example):
396415
396481
  - next: "what you will do next OR the exact todo_write(...) call to update statuses"
396416
396482
  Do NOT call task_complete until all items are marked completed via todo_write.`;
396417
396483
  }
396418
- buildTaskCompleteToolFailureGuard(detail) {
396484
+ buildTaskCompleteToolFailureGuard(detail, pending) {
396485
+ if (isCompletionReviewPendingV1(pending))
396486
+ return completionReviewPendingGuard(pending);
396419
396487
  const trimmed = detail.trim().slice(0, 4e3);
396420
396488
  return [
396421
396489
  `[TASK_COMPLETE BLOCKED BY VERIFICATION]`,
@@ -396427,6 +396495,9 @@ Do NOT call task_complete until all items are marked completed via todo_write.`;
396427
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.`
396428
396496
  ].join("\n");
396429
396497
  }
396498
+ taskCompleteToolFailureStatus(pending) {
396499
+ return isCompletionReviewPendingV1(pending) ? "task_complete review pending; retry the retained completion review" : "task_complete blocked by verification guard";
396500
+ }
396430
396501
  buildMissionCompletionContract(task, context) {
396431
396502
  if (this.usesConversationProfile())
396432
396503
  return "";
@@ -398665,7 +398736,7 @@ ${sections.join("\n")}` : sections.join("\n");
398665
398736
  return;
398666
398737
  try {
398667
398738
  const epoch2 = String(this._taskEpoch);
398668
- 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);
398669
398740
  if (!actionOrTask || actionOrTask.epoch !== epoch2)
398670
398741
  return;
398671
398742
  for (const path7 of this._evidenceLedger.renderedFullPathsInLastBlock()) {
@@ -398675,7 +398746,7 @@ ${sections.join("\n")}` : sections.join("\n");
398675
398746
  const artifact = this._contextMemoryArtifactByPath.get(path7);
398676
398747
  const sourceRevision = entry.contentHash ?? `v${entry.readVersion}`;
398677
398748
  const id5 = `materialization:${epoch2}:${_createHash("sha256").update(`${actionOrTask.id}\0${path7}\0${sourceRevision}`).digest("hex").slice(0, 24)}`;
398678
- const record8 = ledger.appendRecord({
398749
+ const record9 = ledger.appendRecord({
398679
398750
  id: id5,
398680
398751
  epoch: epoch2,
398681
398752
  kind: "materialization",
@@ -398701,13 +398772,13 @@ ${sections.join("\n")}` : sections.join("\n");
398701
398772
  });
398702
398773
  ledger.linkDependency({
398703
398774
  sourceRecordId: actionOrTask.id,
398704
- targetRecordId: record8.id,
398775
+ targetRecordId: record9.id,
398705
398776
  relation: "requires",
398706
398777
  requiredForActiveWork: true
398707
398778
  });
398708
398779
  if (artifact?.epoch === epoch2) {
398709
398780
  ledger.linkDependency({
398710
- sourceRecordId: record8.id,
398781
+ sourceRecordId: record9.id,
398711
398782
  targetRecordId: artifact.recordId,
398712
398783
  relation: "derived_from",
398713
398784
  requiredForActiveWork: true
@@ -399105,11 +399176,11 @@ ${chunk.content}`, {
399105
399176
  if (typeof result === "boolean")
399106
399177
  return result;
399107
399178
  if (result && typeof result === "object") {
399108
- const record8 = result;
399109
- if (typeof record8["shouldConsolidate"] === "boolean")
399110
- return record8["shouldConsolidate"];
399111
- if (typeof record8["shouldRun"] === "boolean")
399112
- 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"];
399113
399184
  }
399114
399185
  return Boolean(result);
399115
399186
  } catch {
@@ -401629,7 +401700,7 @@ ${notice}`;
401629
401700
  injectSteeringInput(input) {
401630
401701
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
401631
401702
  const content = this.scrubUserInput(input.content, "steering-input").trim();
401632
- const record8 = {
401703
+ const record9 = {
401633
401704
  ...input,
401634
401705
  inputId: input.inputId.trim() || `steering-${Date.now()}-${++this._steeringSequence}`,
401635
401706
  content,
@@ -401639,23 +401710,23 @@ ${notice}`;
401639
401710
  state: "received",
401640
401711
  taskEpoch: input.taskEpoch ?? (this._taskEpoch || void 0)
401641
401712
  };
401642
- this.pendingSteeringInputs.push(record8);
401643
- this._emitSteeringLifecycle(record8, "received by runner");
401713
+ this.pendingSteeringInputs.push(record9);
401714
+ this._emitSteeringLifecycle(record9, "received by runner");
401644
401715
  if (!content) {
401645
- record8.state = "cancelled";
401646
- this._emitSteeringLifecycle(record8, "empty steering input rejected");
401647
- return this._steeringReceipt(record8);
401716
+ record9.state = "cancelled";
401717
+ this._emitSteeringLifecycle(record9, "empty steering input rejected");
401718
+ return this._steeringReceipt(record9);
401648
401719
  }
401649
- record8.state = "queued";
401650
- this._emitSteeringLifecycle(record8, "queued for next safe turn boundary");
401651
- if (steeringGatesOldPlan(record8.intent)) {
401652
- 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);
401653
401724
  }
401654
- if (record8.intent === "redirect" || record8.intent === "replace" || record8.intent === "cancel") {
401655
- this._requestSteeringPreemption(record8);
401725
+ if (record9.intent === "redirect" || record9.intent === "replace" || record9.intent === "cancel") {
401726
+ this._requestSteeringPreemption(record9);
401656
401727
  }
401657
401728
  this._trajectoryDirtyCauses.add("user_steering");
401658
- return this._steeringReceipt(record8);
401729
+ return this._steeringReceipt(record9);
401659
401730
  }
401660
401731
  /**
401661
401732
  * Request safe-boundary preemption for an already accepted typed input.
@@ -401666,16 +401737,16 @@ ${notice}`;
401666
401737
  const normalizedInputId = inputId.trim();
401667
401738
  if (!normalizedInputId)
401668
401739
  return null;
401669
- const record8 = this.pendingSteeringInputs.find((candidate) => candidate.inputId === normalizedInputId);
401670
- if (!record8)
401740
+ const record9 = this.pendingSteeringInputs.find((candidate) => candidate.inputId === normalizedInputId);
401741
+ if (!record9)
401671
401742
  return null;
401672
- if (record8.intent !== "redirect" && record8.intent !== "replace" && record8.intent !== "cancel") {
401743
+ if (record9.intent !== "redirect" && record9.intent !== "replace" && record9.intent !== "cancel") {
401673
401744
  return null;
401674
401745
  }
401675
- if (this._pendingSteeringPreemption?.inputId !== record8.inputId) {
401676
- this._requestSteeringPreemption(record8);
401746
+ if (this._pendingSteeringPreemption?.inputId !== record9.inputId) {
401747
+ this._requestSteeringPreemption(record9);
401677
401748
  }
401678
- return this._steeringReceipt(record8);
401749
+ return this._steeringReceipt(record9);
401679
401750
  }
401680
401751
  /**
401681
401752
  * Promote an already queued steering record to the next immediate safe
@@ -401686,24 +401757,24 @@ ${notice}`;
401686
401757
  const normalizedInputId = inputId.trim();
401687
401758
  if (!normalizedInputId)
401688
401759
  return null;
401689
- const record8 = this.pendingSteeringInputs.find((candidate) => candidate.inputId === normalizedInputId);
401690
- 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") {
401691
401762
  return null;
401692
401763
  }
401693
- if (record8.intent === "redirect" || record8.intent === "replace" || record8.intent === "cancel") {
401694
- return this.requestSteeringPreemption(record8.inputId);
401764
+ if (record9.intent === "redirect" || record9.intent === "replace" || record9.intent === "cancel") {
401765
+ return this.requestSteeringPreemption(record9.inputId);
401695
401766
  }
401696
- this._immediateSteeringWakeInputId = record8.inputId;
401697
- record8.state = "acknowledged";
401698
- this._emitSteeringLifecycle(record8, "user promoted queued steering to the next immediate safe boundary");
401699
- 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}`));
401700
401771
  const shellTool = this.tools.get("shell");
401701
401772
  if (shellTool && typeof shellTool.killAll === "function") {
401702
401773
  shellTool.killAll();
401703
401774
  }
401704
401775
  this._turnAbortController = new AbortController();
401705
401776
  this._setBackendTurnAbortSignal(this._turnAbortController.signal);
401706
- return this._steeringReceipt(record8);
401777
+ return this._steeringReceipt(record9);
401707
401778
  }
401708
401779
  /** Inject bounded runtime guidance without treating it as user steering. */
401709
401780
  injectRuntimeGuidance(content) {
@@ -401994,7 +402065,7 @@ ${notice}`;
401994
402065
  throw new Error("Conflicting native amendment intake");
401995
402066
  return existing.promise;
401996
402067
  }
401997
- 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));
401998
402069
  if (!steering || !this.options.taskNativeScope || !this.options.expectedOutcomeContract || !this._completionLedger)
401999
402070
  throw new Error("Native amendment requires an existing authenticated human steering intake");
402000
402071
  const rebased = this._rebaseNativeTaskRequirementAmendmentPlan(authority);
@@ -402040,8 +402111,8 @@ ${notice}`;
402040
402111
  }
402041
402112
  return rebased;
402042
402113
  }
402043
- _applyNativeTaskRequirementAmendmentAtBoundary(record8) {
402044
- const pending = this._pendingNativeRequirementAmendments.get(record8.inputId);
402114
+ _applyNativeTaskRequirementAmendmentAtBoundary(record9) {
402115
+ const pending = this._pendingNativeRequirementAmendments.get(record9.inputId);
402045
402116
  if (!pending)
402046
402117
  return;
402047
402118
  try {
@@ -402051,7 +402122,7 @@ ${notice}`;
402051
402122
  priorExpectedOutcome: this.options.expectedOutcomeContract,
402052
402123
  priorScope: this.options.taskNativeScope,
402053
402124
  amendment: pending.authority,
402054
- steering: record8
402125
+ steering: record9
402055
402126
  });
402056
402127
  const path7 = this._objectiveLedgerPath ?? _pathJoin(this.omniusStateDir(), "completion-ledgers", `${this.currentArtifactRunId()}.json`);
402057
402128
  saveCompletionLedger(path7, next);
@@ -402069,8 +402140,8 @@ ${notice}`;
402069
402140
  this._trajectoryReviewSequence++;
402070
402141
  this._recoveryReviewSequence++;
402071
402142
  this._initializeTaskObjective(this._taskObjectiveContract.goal);
402072
- const hold2 = this._nativeRequirementInterpretationHolds.get(record8.inputId);
402073
- this._nativeRequirementInterpretationHolds.delete(record8.inputId);
402143
+ const hold2 = this._nativeRequirementInterpretationHolds.get(record9.inputId);
402144
+ this._nativeRequirementInterpretationHolds.delete(record9.inputId);
402074
402145
  hold2?.wake();
402075
402146
  const applied = this._completionLedger.nativeRequirementAmendments.at(-1);
402076
402147
  pending.resolve({
@@ -402082,14 +402153,14 @@ ${notice}`;
402082
402153
  } catch (error) {
402083
402154
  try {
402084
402155
  const current = loadCompletionLedger(this._objectiveLedgerPath ?? _pathJoin(this.omniusStateDir(), "completion-ledgers", `${this.currentArtifactRunId()}.json`));
402085
- if (current.nativeRequirementAmendments?.some((amendment) => amendment.authority.inputId === record8.inputId))
402156
+ if (current.nativeRequirementAmendments?.some((amendment) => amendment.authority.inputId === record9.inputId))
402086
402157
  this._reviewedInterpretationProjectionBlocked = true;
402087
402158
  } catch {
402088
402159
  }
402089
402160
  pending.reject(error);
402090
402161
  throw error;
402091
402162
  } finally {
402092
- this._pendingNativeRequirementAmendments.delete(record8.inputId);
402163
+ this._pendingNativeRequirementAmendments.delete(record9.inputId);
402093
402164
  }
402094
402165
  }
402095
402166
  /** Independent host capability; never exposed as a model tool or human amendment. */
@@ -402505,15 +402576,15 @@ The previous reviewer response failed exact candidate-quote serialization. Host
402505
402576
  /** Retract the last pending user message (Esc cancel).
402506
402577
  * Returns the retracted text, or null if queue is empty or already consumed. */
402507
402578
  retractLastPendingMessage() {
402508
- const record8 = [...this.pendingSteeringInputs].reverse().find((candidate) => candidate.state === "queued" || candidate.state === "acknowledged");
402509
- if (!record8)
402579
+ const record9 = [...this.pendingSteeringInputs].reverse().find((candidate) => candidate.state === "queued" || candidate.state === "acknowledged");
402580
+ if (!record9)
402510
402581
  return null;
402511
- record8.state = "cancelled";
402512
- if (this._pendingSteeringPreemption?.inputId === record8.inputId) {
402582
+ record9.state = "cancelled";
402583
+ if (this._pendingSteeringPreemption?.inputId === record9.inputId) {
402513
402584
  this._pendingSteeringPreemption = null;
402514
402585
  }
402515
- this._emitSteeringLifecycle(record8, "retracted before admission at a safe boundary");
402516
- return record8.content;
402586
+ this._emitSteeringLifecycle(record9, "retracted before admission at a safe boundary");
402587
+ return record9.content;
402517
402588
  }
402518
402589
  /** Abort the current task run through the generation-bound stop lineage. */
402519
402590
  abort() {
@@ -402968,31 +403039,31 @@ The previous reviewer response failed exact candidate-quote serialization. Host
402968
403039
  /** Import receipts only after reopening the immutable issuer stores and
402969
403040
  * matching them to the current host-bound native resource bytes. */
402970
403041
  async _restoreTaskObjectiveContinuation() {
402971
- const record8 = this._taskObjectiveContinuationRecord;
403042
+ const record9 = this._taskObjectiveContinuationRecord;
402972
403043
  let predecessor = this._completionLedger;
402973
403044
  const index = this._artifactReviewSourceIndex;
402974
- if (!record8 || !predecessor)
403045
+ if (!record9 || !predecessor)
402975
403046
  return;
402976
- if (!index && record8.input.resources.length)
403047
+ if (!index && record9.input.resources.length)
402977
403048
  throw new Error("Task objective continuation source index is unavailable");
402978
- const strengthening = record8.input.contractStrengthening;
403049
+ const strengthening = record9.input.contractStrengthening;
402979
403050
  if (strengthening && taskObjectiveContinuationDigest(this.options.taskObjectiveContract) !== strengthening.recipientContractSha256) {
402980
403051
  throw new Error("Validated continuation recipient contract changed before source restoration");
402981
403052
  }
402982
- if (predecessor.runId !== record8.input.predecessor.runId) {
402983
- const bytes3 = _fsReadFileSync(record8.input.predecessor.ledgerPath);
402984
- 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)
402985
403056
  throw new Error("Task objective continuation predecessor changed during reconciliation");
402986
403057
  predecessor = restoreCompletionLedgerSnapshot(JSON.parse(bytes3.toString("utf8")));
402987
403058
  }
402988
403059
  if (index)
402989
- index.withWriteTransaction(() => claimTaskObjectiveContinuation(record8));
403060
+ index.withWriteTransaction(() => claimTaskObjectiveContinuation(record9));
402990
403061
  else
402991
- claimTaskObjectiveContinuation(record8);
402992
- record8.adoptions = [];
402993
- record8.importedEvidence = [];
403062
+ claimTaskObjectiveContinuation(record9);
403063
+ record9.adoptions = [];
403064
+ record9.importedEvidence = [];
402994
403065
  const owner = { scopeId: this._sessionId, runId: this.currentArtifactRunId(), taskEpoch: this._taskEpoch };
402995
- const previousOwner = { ...owner, runId: record8.input.predecessor.runId };
403066
+ const previousOwner = { ...owner, runId: record9.input.predecessor.runId };
402996
403067
  const validCriteria = /* @__PURE__ */ new Set();
402997
403068
  const views = /* @__PURE__ */ new Map();
402998
403069
  const seenSources = /* @__PURE__ */ new Set();
@@ -403005,7 +403076,7 @@ The previous reviewer response failed exact candidate-quote serialization. Host
403005
403076
  const receipt = entry.observation.documentExtraction;
403006
403077
  if (!receipt)
403007
403078
  continue;
403008
- for (const resource of record8.input.resources) {
403079
+ for (const resource of record9.input.resources) {
403009
403080
  if (resource.pathAliases.includes(entry.verifiedSourcePath) || resource.pathAliases.includes(receipt.sourcePath)) {
403010
403081
  if (!resource.sourceSha256 || receipt.documentHash !== resource.sourceSha256)
403011
403082
  conflictingVersions.add(resource.criterionId);
@@ -403024,13 +403095,13 @@ The previous reviewer response failed exact candidate-quote serialization. Host
403024
403095
  const source = evidence2.sources.find((value) => value.sourceId === entry.sourceId);
403025
403096
  if (!source || source.toolName !== "pdf_to_text")
403026
403097
  continue;
403027
- 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))));
403028
403099
  if (!resources.length)
403029
403100
  continue;
403030
- 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 });
403031
403102
  if (!seenSources.has(adopted.sourceId)) {
403032
403103
  seenSources.add(adopted.sourceId);
403033
- record8.adoptions.push({
403104
+ record9.adoptions.push({
403034
403105
  sourceId: adopted.sourceId,
403035
403106
  issuer: adopted.adoption.issuer,
403036
403107
  criterionIds: resources.map((resource) => resource.criterionId),
@@ -403071,11 +403142,11 @@ criterion=${resource.criterionId}; native=message_id:${resource.messageId}; issu
403071
403142
  if (receipt.kind === "human_input" || receipt.success === true && receipt.role === "mutation" || receipt.receipt)
403072
403143
  return [receipt];
403073
403144
  if (receipt.success === true && receipt.toolName === "pdf_to_text" && receipt.objectiveEvidenceKinds?.includes("observation")) {
403074
- 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))));
403075
403146
  if (criterionIds.length)
403076
403147
  return [{ ...receipt, criterionIds, role: "observation", objectiveEvidenceKinds: ["observation"] }];
403077
403148
  }
403078
- 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") {
403079
403150
  const history = `[Retained same-native tool observation; historical quoted data, not current source validation]
403080
403151
  issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ?? "not recorded"}
403081
403152
  ` + receipt.summary;
@@ -403086,18 +403157,18 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403086
403157
  return [];
403087
403158
  return [{ ...receipt, success: void 0, progressClass: "control_bookkeeping", objectiveEvidenceKinds: [] }];
403088
403159
  });
403089
- record8.retiredSupportedAnswerReviewEvidenceIds = [...retiredReviewRows];
403090
- record8.importedEvidence = evidence.map((receipt) => ({
403160
+ record9.retiredSupportedAnswerReviewEvidenceIds = [...retiredReviewRows];
403161
+ record9.importedEvidence = evidence.map((receipt) => ({
403091
403162
  evidenceId: receipt.id,
403092
403163
  issuerRunId: predecessor.taskObjectiveContinuation?.importedEvidence.find((entry) => entry.evidenceId === receipt.id)?.issuerRunId ?? predecessor.runId,
403093
403164
  predecessorRunId: predecessor.runId,
403094
- predecessorLedgerSha256: record8.input.predecessor.ledgerSha256,
403165
+ predecessorLedgerSha256: record9.input.predecessor.ledgerSha256,
403095
403166
  criterionIds: [...receipt.criterionIds ?? []]
403096
403167
  }));
403097
403168
  if (strengthening && taskObjectiveContinuationDigest(this.options.taskObjectiveContract) !== strengthening.recipientContractSha256) {
403098
403169
  throw new Error("Validated continuation recipient contract changed before source restoration");
403099
403170
  }
403100
- 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) {
403101
403172
  const binding = {
403102
403173
  runId: predecessor.runId,
403103
403174
  taskEpoch: predecessor.taskEpoch,
@@ -403111,7 +403182,7 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403111
403182
  if (refusal || dispatch)
403112
403183
  this._objectiveRecoveryInherited = {
403113
403184
  predecessorRunId: predecessor.runId,
403114
- predecessorLedgerSha256: record8.input.predecessor.ledgerSha256,
403185
+ predecessorLedgerSha256: record9.input.predecessor.ledgerSha256,
403115
403186
  refusalCount: refusal?.count ?? 0,
403116
403187
  ...dispatch ? { operationSha256: dispatch.operationSha256 } : {}
403117
403188
  };
@@ -403127,7 +403198,7 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403127
403198
  evidence,
403128
403199
  proposedClaims: [],
403129
403200
  status: "open",
403130
- taskObjectiveContinuation: record8
403201
+ taskObjectiveContinuation: record9
403131
403202
  };
403132
403203
  delete restored.terminal;
403133
403204
  delete restored.needsInput;
@@ -403191,20 +403262,20 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403191
403262
  this._objectiveLedgerPath = _pathJoin(dir, `${owner.runId}.json`);
403192
403263
  saveCompletionLedger(this._objectiveLedgerPath, this._completionLedger);
403193
403264
  if (index)
403194
- index.withWriteTransaction(() => commitTaskObjectiveContinuation(record8));
403265
+ index.withWriteTransaction(() => commitTaskObjectiveContinuation(record9));
403195
403266
  else
403196
- commitTaskObjectiveContinuation(record8);
403267
+ commitTaskObjectiveContinuation(record9);
403197
403268
  }
403198
403269
  /** Immutable run key for artifacts; sessionId remains correlation metadata. */
403199
403270
  currentArtifactRunId() {
403200
403271
  return this._activeRunId || this._sessionId;
403201
403272
  }
403202
- _steeringReceipt(record8) {
403273
+ _steeringReceipt(record9) {
403203
403274
  return {
403204
- inputId: record8.inputId,
403205
- intent: record8.intent,
403206
- state: record8.state,
403207
- taskEpoch: record8.taskEpoch,
403275
+ inputId: record9.inputId,
403276
+ intent: record9.intent,
403277
+ state: record9.state,
403278
+ taskEpoch: record9.taskEpoch,
403208
403279
  runId: this._activeRunId || void 0,
403209
403280
  acceptedAt: (/* @__PURE__ */ new Date()).toISOString()
403210
403281
  };
@@ -403227,34 +403298,34 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403227
403298
  };
403228
403299
  }
403229
403300
  }
403230
- _emitSteeringLifecycle(record8, reason) {
403231
- const receipt = this._steeringReceipt(record8);
403301
+ _emitSteeringLifecycle(record9, reason) {
403302
+ const receipt = this._steeringReceipt(record9);
403232
403303
  const reconciliation = this._activeSteering && [
403233
403304
  this._activeSteering.input,
403234
403305
  ...this._activeSteering.relatedInputs ?? []
403235
- ].some((input) => input.inputId === record8.inputId) ? this._activeSteering.reconciliation : void 0;
403306
+ ].some((input) => input.inputId === record9.inputId) ? this._activeSteering.reconciliation : void 0;
403236
403307
  this.emit({
403237
403308
  type: "status",
403238
- content: `Steering ${record8.inputId} ${record8.state}: ${reason}`,
403309
+ content: `Steering ${record9.inputId} ${record9.state}: ${reason}`,
403239
403310
  steering: receipt,
403240
403311
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
403241
403312
  });
403242
403313
  this._onTypedEvent?.({
403243
403314
  type: "steering_lifecycle",
403244
403315
  runId: this.currentArtifactRunId(),
403245
- inputId: record8.inputId,
403246
- intent: record8.intent,
403247
- state: record8.state,
403248
- taskEpoch: record8.taskEpoch,
403316
+ inputId: record9.inputId,
403317
+ intent: record9.intent,
403318
+ state: record9.state,
403319
+ taskEpoch: record9.taskEpoch,
403249
403320
  summary: reason,
403250
403321
  ...reconciliation ? { reconciliation: { ...reconciliation } } : {},
403251
403322
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
403252
403323
  });
403253
403324
  appendSteeringLedgerEntry(this._workingDirectory || process.cwd(), {
403254
403325
  type: "lifecycle",
403255
- packetId: record8.inputId,
403326
+ packetId: record9.inputId,
403256
403327
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
403257
- intake: { ...record8 },
403328
+ intake: { ...record9 },
403258
403329
  runId: this.currentArtifactRunId(),
403259
403330
  taskEpoch: this._taskEpoch,
403260
403331
  primaryInputId: this._activeSteering?.input.inputId,
@@ -403267,11 +403338,11 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403267
403338
  this.backend.setAbortSignal(signal);
403268
403339
  }
403269
403340
  }
403270
- _requestSteeringPreemption(record8) {
403271
- this._pendingSteeringPreemption = record8;
403272
- record8.state = "acknowledged";
403273
- this._emitSteeringLifecycle(record8, "preemption acknowledged");
403274
- 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}`));
403275
403346
  const shellTool = this.tools.get("shell");
403276
403347
  if (shellTool && typeof shellTool.killAll === "function") {
403277
403348
  shellTool.killAll();
@@ -403280,18 +403351,18 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403280
403351
  this._setBackendTurnAbortSignal(this._turnAbortController.signal);
403281
403352
  }
403282
403353
  _prepareSteeringInputsForRun() {
403283
- const initialInputs = this.pendingSteeringInputs.filter((record8) => record8.state === "queued" || record8.state === "acknowledged");
403284
- this._allowImplicitContinuation = initialInputs.some((record8) => record8.intent === "append" || record8.intent === "clarify") && !initialInputs.some((record8) => record8.intent === "redirect" || record8.intent === "replace" || record8.intent === "cancel");
403285
- for (const record8 of this.pendingSteeringInputs) {
403286
- 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")
403287
403358
  continue;
403288
- if (record8.taskEpoch && record8.taskEpoch !== this._taskEpoch) {
403289
- record8.state = "superseded";
403290
- 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");
403291
403362
  continue;
403292
403363
  }
403293
- record8.taskEpoch = this._taskEpoch;
403294
- this._emitSteeringLifecycle(record8, "bound to active task epoch");
403364
+ record9.taskEpoch = this._taskEpoch;
403365
+ this._emitSteeringLifecycle(record9, "bound to active task epoch");
403295
403366
  }
403296
403367
  }
403297
403368
  /** Archive prior task-epoch state before its session-backed records are hidden. */
@@ -403383,13 +403454,13 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403383
403454
  delete this._lastVerifierResult;
403384
403455
  }
403385
403456
  /** A media follow-up joins unresolved user authority instead of replacing it. */
403386
- _selectActiveSteering(record8, turn) {
403457
+ _selectActiveSteering(record9, turn) {
403387
403458
  const prior = this._activeSteering;
403388
403459
  if (prior && this._steeringAuthorityRuns.get(prior) === this._activeRunId && prior.input.taskEpoch === this._taskEpoch && !isSteeringScopeResolved(prior)) {
403389
- if ([prior.input, ...prior.relatedInputs ?? []].some((input) => input.inputId === record8.inputId))
403460
+ if ([prior.input, ...prior.relatedInputs ?? []].some((input) => input.inputId === record9.inputId))
403390
403461
  return;
403391
- if (record8.intent !== "replace" && record8.intent !== "redirect" && record8.intent !== "cancel") {
403392
- prior.relatedInputs = [...prior.relatedInputs ?? [], record8];
403462
+ if (record9.intent !== "replace" && record9.intent !== "redirect" && record9.intent !== "cancel") {
403463
+ prior.relatedInputs = [...prior.relatedInputs ?? [], record9];
403393
403464
  prior.reconciliation = void 0;
403394
403465
  prior.requiresReconciliation = true;
403395
403466
  prior.gatesOldPlan = true;
@@ -403402,56 +403473,56 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403402
403473
  }
403403
403474
  }
403404
403475
  this._activeSteering = {
403405
- input: record8,
403476
+ input: record9,
403406
403477
  appliedTurn: turn,
403407
- requiresReconciliation: steeringRequiresReconciliation(record8.intent),
403408
- gatesOldPlan: steeringGatesOldPlan(record8.intent),
403478
+ requiresReconciliation: steeringRequiresReconciliation(record9.intent),
403479
+ gatesOldPlan: steeringGatesOldPlan(record9.intent),
403409
403480
  visibleRequestTurns: []
403410
403481
  };
403411
403482
  this._steeringAuthorityRuns.set(this._activeSteering, this._activeRunId);
403412
403483
  }
403413
- _activateSteering(record8, turn) {
403414
- const requiresReconciliation = steeringRequiresReconciliation(record8.intent);
403415
- const gatesOldPlan = steeringGatesOldPlan(record8.intent);
403484
+ _activateSteering(record9, turn) {
403485
+ const requiresReconciliation = steeringRequiresReconciliation(record9.intent);
403486
+ const gatesOldPlan = steeringGatesOldPlan(record9.intent);
403416
403487
  const prior = this._activeSteering;
403417
- 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")) {
403418
403489
  prior.input.state = "superseded";
403419
- this._emitSteeringLifecycle(prior.input, `superseded by ${record8.intent} ${record8.inputId}`);
403490
+ this._emitSteeringLifecycle(prior.input, `superseded by ${record9.intent} ${record9.inputId}`);
403420
403491
  }
403421
- this._selectActiveSteering(record8, turn);
403422
- record8.taskEpoch = this._taskEpoch;
403492
+ this._selectActiveSteering(record9, turn);
403493
+ record9.taskEpoch = this._taskEpoch;
403423
403494
  const steeringEvidenceChunkIds = this._recordImmutableEvidence({
403424
403495
  source: "user",
403425
- sourceUri: `omnius-run://${this.currentArtifactRunId()}/steering/${record8.inputId}`,
403426
- messageId: record8.inputId,
403496
+ sourceUri: `omnius-run://${this.currentArtifactRunId()}/steering/${record9.inputId}`,
403497
+ messageId: record9.inputId,
403427
403498
  version: `${this._taskEpoch}:${turn}`,
403428
- body: record8.content,
403499
+ body: record9.content,
403429
403500
  metadata: {
403430
403501
  role: "user",
403431
- intent: record8.intent,
403432
- source: record8.source,
403502
+ intent: record9.intent,
403503
+ source: record9.source,
403433
403504
  turn
403434
403505
  }
403435
403506
  });
403436
403507
  this._pendingStructuredMemorySourceIds.push(...steeringEvidenceChunkIds);
403437
403508
  void this._processPendingStructuredMemoryExtraction();
403438
403509
  const ledger = this._contextMemoryLedger;
403439
- if (ledger && !this._contextMemorySteeringRecordIds.has(record8.inputId)) {
403510
+ if (ledger && !this._contextMemorySteeringRecordIds.has(record9.inputId)) {
403440
403511
  try {
403441
403512
  const steering = ledger.appendRecord({
403442
403513
  epoch: String(this._taskEpoch),
403443
403514
  kind: "steering",
403444
403515
  authority: "user",
403445
- body: record8.content,
403516
+ body: record9.content,
403446
403517
  provenance: { producer: "agenticRunner:steering" },
403447
403518
  metadata: {
403448
- inputId: record8.inputId,
403449
- intent: record8.intent,
403450
- source: record8.source,
403519
+ inputId: record9.inputId,
403520
+ intent: record9.intent,
403521
+ source: record9.source,
403451
403522
  turn
403452
403523
  }
403453
403524
  });
403454
- this._contextMemorySteeringRecordIds.set(record8.inputId, steering.id);
403525
+ this._contextMemorySteeringRecordIds.set(record9.inputId, steering.id);
403455
403526
  if (this._contextMemoryTaskRecordId) {
403456
403527
  ledger.linkDependency({
403457
403528
  sourceRecordId: steering.id,
@@ -403465,13 +403536,13 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403465
403536
  steering.id,
403466
403537
  ...this._contextMemoryTaskRecordId ? [this._contextMemoryTaskRecordId] : []
403467
403538
  ];
403468
- this._commitContextMemoryWorkingSet(`steering ${record8.inputId} admitted`);
403539
+ this._commitContextMemoryWorkingSet(`steering ${record9.inputId} admitted`);
403469
403540
  } catch {
403470
403541
  }
403471
403542
  }
403472
403543
  if (requiresReconciliation) {
403473
- record8.state = "reconciliation_required";
403474
- 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`);
403475
403546
  }
403476
403547
  }
403477
403548
  _canonicalReadEvidencePayload(canonicalPath2, contentHash2, requestedRange) {
@@ -403495,19 +403566,19 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403495
403566
  }
403496
403567
  async _drainPendingSteeringMessages(messages, turn) {
403497
403568
  this.drainPendingRuntimeGuidance(turn);
403498
- const pending = this.pendingSteeringInputs.filter((record8) => (record8.state === "queued" || record8.state === "acknowledged") && (!record8.taskEpoch || record8.taskEpoch === this._taskEpoch));
403499
- 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) {
403500
403571
  const replacement = this._pendingSteeringPreemption;
403501
- if (replacement?.intent === "replace" && record8.inputId !== replacement.inputId && this.pendingSteeringInputs.indexOf(record8) < this.pendingSteeringInputs.indexOf(replacement)) {
403502
- record8.state = "superseded";
403503
- 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}`);
403504
403575
  continue;
403505
403576
  }
403506
- this._applyNativeTaskRequirementAmendmentAtBoundary(record8);
403577
+ this._applyNativeTaskRequirementAmendmentAtBoundary(record9);
403507
403578
  const historyStart = messages.length;
403508
- await this.appendInjectedUserMessage(record8.content, messages, turn);
403509
- this._activateSteering(record8, turn);
403510
- if (this._immediateSteeringWakeInputId === record8.inputId) {
403579
+ await this.appendInjectedUserMessage(record9.content, messages, turn);
403580
+ this._activateSteering(record9, turn);
403581
+ if (this._immediateSteeringWakeInputId === record9.inputId) {
403511
403582
  this._immediateSteeringWakeInputId = null;
403512
403583
  }
403513
403584
  if (this._activeSteering && this._activeSteering.historyStartIndex === void 0) {
@@ -403515,9 +403586,9 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403515
403586
  }
403516
403587
  }
403517
403588
  for (const inputId of [...this._pendingNativeRequirementAmendments.keys()]) {
403518
- const record8 = this.pendingSteeringInputs.find((record9) => record9.inputId === inputId && !["cancelled", "superseded"].includes(record9.state));
403519
- if (record8)
403520
- 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);
403521
403592
  }
403522
403593
  while (this.pendingUserMessages.length > 0) {
403523
403594
  await this.appendInjectedUserMessage(this.pendingUserMessages.shift(), messages, turn);
@@ -403531,20 +403602,20 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403531
403602
  async _applySteeringAtSafeBoundary(messages, turn) {
403532
403603
  this._currentSteeringTurn = turn;
403533
403604
  await this._drainPendingSteeringMessages(messages, turn);
403534
- const record8 = this._pendingSteeringPreemption;
403535
- if (!record8) {
403605
+ const record9 = this._pendingSteeringPreemption;
403606
+ if (!record9) {
403536
403607
  this._checkpointActiveTaskScope(messages);
403537
403608
  return "continue";
403538
403609
  }
403539
- if (record8.intent === "cancel") {
403610
+ if (record9.intent === "cancel") {
403540
403611
  this._pendingSteeringPreemption = null;
403541
- record8.state = "cancelled";
403542
- this._emitSteeringLifecycle(record8, `cancelled active task at turn ${turn}`);
403612
+ record9.state = "cancelled";
403613
+ this._emitSteeringLifecycle(record9, `cancelled active task at turn ${turn}`);
403543
403614
  this.abort();
403544
403615
  return "abort";
403545
403616
  }
403546
403617
  const previousEpoch = this._taskEpoch;
403547
- 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);
403548
403619
  const activeMessages = [...prepared.activeMessages];
403549
403620
  for (const message of messages.slice(prepared.messageCount)) {
403550
403621
  if (message.role === "user" && !activeMessages.some((item) => JSON.stringify(item) === JSON.stringify(message))) {
@@ -403553,7 +403624,7 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403553
403624
  }
403554
403625
  const archiveReference = this._persistTaskScopeBoundary(prepared.boundary, messages);
403555
403626
  this._advanceTaskScopeLifecycle(prepared.boundary);
403556
- this._archiveSupersededTaskState(previousEpoch, record8);
403627
+ this._archiveSupersededTaskState(previousEpoch, record9);
403557
403628
  this._installTaskScopeBoundary(prepared.boundary, archiveReference, turn);
403558
403629
  messages.splice(0, messages.length, ...activeMessages);
403559
403630
  this._activeTaskScopeCheckpoint = null;
@@ -403561,12 +403632,12 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403561
403632
  this._pendingSteeringPreemption = null;
403562
403633
  const active = this._activeSteering;
403563
403634
  for (const input of [
403564
- record8,
403635
+ record9,
403565
403636
  ...active ? [active.input, ...active.relatedInputs ?? []] : []
403566
403637
  ]) {
403567
403638
  input.taskEpoch = this._taskEpoch;
403568
403639
  }
403569
- if (active?.input.inputId === record8.inputId && active.reconciliation?.taskDisposition === "replace") {
403640
+ if (active?.input.inputId === record9.inputId && active.reconciliation?.taskDisposition === "replace") {
403570
403641
  active.gatesOldPlan = false;
403571
403642
  this._taskState.nextAction = active.reconciliation.revisedNextAction;
403572
403643
  this._taskState.steeringConstraints = [
@@ -403574,12 +403645,12 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403574
403645
  ];
403575
403646
  }
403576
403647
  this._checkpointActiveTaskScope(messages);
403577
- 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}`);
403578
403649
  return "restart";
403579
403650
  }
403580
- _prepareTaskScopeBoundary(messages, record8, reconciliation) {
403581
- const active = this._activeSteering?.input.inputId === record8.inputId ? this._activeSteering : null;
403582
- 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];
403583
403654
  const authorityMessages = inputs.map((input) => ({
403584
403655
  role: "user",
403585
403656
  content: input.content,
@@ -403598,11 +403669,11 @@ issuer=${predecessor.runId}; evidence=${receipt.id}; raw_ref=${receipt.rawRef ??
403598
403669
  sessionId: this._sessionId,
403599
403670
  fromEpoch: this._taskEpoch,
403600
403671
  toEpoch: this._taskEpoch + 1,
403601
- goal: (reconciliation?.replacementGoal ?? record8.content).slice(0, 4e3),
403672
+ goal: (reconciliation?.replacementGoal ?? record9.content).slice(0, 4e3),
403602
403673
  inputIds: inputs.map((input) => input.inputId),
403603
403674
  ...this._activeTaskScopeBoundary ? { priorBoundary: this._activeTaskScopeBoundary } : {}
403604
403675
  }),
403605
- inputId: record8.inputId,
403676
+ inputId: record9.inputId,
403606
403677
  messageCount: messages.length
403607
403678
  };
403608
403679
  }
@@ -407270,7 +407341,7 @@ Respond with the assessment and take the selected evidence-backed action.`;
407270
407341
  const recovered2 = new FailureResolutionTransactionCoordinator({
407271
407342
  failureStore: this._failureStore
407272
407343
  }).recover(this._workboardDir(), this.currentArtifactRunId());
407273
- if (recovered2.some((record8) => record8.state === "committed")) {
407344
+ if (recovered2.some((record9) => record9.state === "committed")) {
407274
407345
  this._workboard = readActiveWorkboardSnapshot(this._workboardDir(), this.currentArtifactRunId()) ?? this._workboard;
407275
407346
  }
407276
407347
  } catch {
@@ -408016,6 +408087,20 @@ ${dynamicProjectContext}`
408016
408087
  const currentTelegramCompletionObjectiveScope = () => {
408017
408088
  return this._telegramCompletionObjectiveScope();
408018
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
+ };
408019
408104
  const captureAcceptedCompletionReply = (toolCallId, args, completionTurn) => {
408020
408105
  const owner = completionReplyOwners.get(toolCallId);
408021
408106
  if (this._isTelegramSurface() && (!owner || owner.runId !== this.currentArtifactRunId() || owner.taskEpoch !== this._taskEpoch || owner.turn !== completionTurn || owner.objectiveScope !== currentTelegramCompletionObjectiveScope())) {
@@ -408868,7 +408953,7 @@ ${lastCompletionGateFeedback.trim().slice(0, 4e3)}` : ""
408868
408953
  if (this.aborted || this._pendingSteeringPreemption)
408869
408954
  return null;
408870
408955
  const preparedArgumentError = await prepareToolArguments(tc, this._currentSteeringTurn);
408871
- 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())) {
408872
408957
  const modelText = this._latestModelVisibleAssistantText;
408873
408958
  const assessment = this._currentExpectedOutcomeAssessment();
408874
408959
  const frontier = this._objectiveFrontier;
@@ -410130,6 +410215,11 @@ intent=${_verifierResult.intentBucket}; scope=${_verifierResult.effectScope ?? "
410130
410215
  exactFileReadObservations.set(this._buildToolFingerprint("file_read", tc.arguments), observedIdentity);
410131
410216
  }
410132
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
+ }
410133
410223
  if (tc.name === "task_complete" && result.success === false && result.completionAdmission !== "rejected") {
410134
410224
  const diagnostic = String(result.error || result.output || "task_complete returned no diagnostic text").trim().slice(0, 4e3);
410135
410225
  const feedback = `[COMPLETION FEEDBACK — task_complete adapter]
@@ -410220,12 +410310,14 @@ ${diagnostic}`;
410220
410310
  failure: 0,
410221
410311
  lastOutcomeTurn: turn
410222
410312
  };
410223
- if (result.success)
410224
- updated.success++;
410225
- else
410226
- updated.failure++;
410227
- updated.lastOutcomeTurn = turn;
410228
- 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
+ }
410229
410321
  try {
410230
410322
  if (realFileMutation) {
410231
410323
  const paths2 = realMutationPaths.length > 0 ? realMutationPaths : this._extractToolTargetPaths(tc.name, tc.arguments, result);
@@ -410732,7 +410824,7 @@ ${diagnostic}`;
410732
410824
  }
410733
410825
  }
410734
410826
  let failureWorkboardCardId = null;
410735
- if (!result.success && (result.error || result.output || result.llmContent)) {
410827
+ if (!result.success && !completionReviewIsPending && (result.error || result.output || result.llmContent)) {
410736
410828
  const errorText = (result.error || result.output || result.llmContent || "").toString();
410737
410829
  const diagnosis = this._diagnoseToolFailure(tc.name, tc.arguments, result);
410738
410830
  const sig = diagnosis.patternKey;
@@ -411340,7 +411432,7 @@ ${bookkeepingGuidance}`;
411340
411432
 
411341
411433
  ${bookkeepingGuidance}` : bookkeepingGuidance;
411342
411434
  }
411343
- if (!result.success && this.options.modelTier === "small") {
411435
+ if (!result.success && !completionReviewIsPending && this.options.modelTier === "small") {
411344
411436
  const recovery = this.buildRecoveryGuidance(tc.name, result.error ?? "", tc.arguments);
411345
411437
  if (recovery)
411346
411438
  output += "\n\n" + recovery;
@@ -411362,7 +411454,7 @@ ${bookkeepingGuidance}` : bookkeepingGuidance;
411362
411454
  }
411363
411455
  if (result.success) {
411364
411456
  delete result.failureDiagnosis;
411365
- } else if (!this._isPdfTerminalFeedback(result)) {
411457
+ } else if (!completionReviewIsPending && !this._isPdfTerminalFeedback(result)) {
411366
411458
  this._diagnoseToolFailure(tc.name, tc.arguments, result);
411367
411459
  const staleHashRetryGuidance = this._buildStaleHashRetryGuidance(tc.name, tc.arguments, result);
411368
411460
  if (staleHashRetryGuidance) {
@@ -411440,7 +411532,7 @@ Evidence: ${evidencePreview}`.slice(0, 500);
411440
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");
411441
411533
  this._negativeObservationProposalOutcomes.set(turn, outcomes);
411442
411534
  }
411443
- if (!progressOnly) {
411535
+ if (!progressOnly && !completionReviewIsPending) {
411444
411536
  const canonicalName = resolvedTool?.name ?? tc.name;
411445
411537
  const operationSha256 = taskExecutionDigest({ toolName: canonicalName, args: tc.arguments ?? {} });
411446
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;
@@ -411560,7 +411652,7 @@ Evidence: ${evidencePreview}`.slice(0, 500);
411560
411652
  }
411561
411653
  }
411562
411654
  this._trackDecomp2(tc, result, turn);
411563
- if (result && result.success === false) {
411655
+ if (result && result.success === false && !completionReviewIsPending) {
411564
411656
  this._runErrorCount++;
411565
411657
  const errMsg = result.error || "";
411566
411658
  if (typeof errMsg === "string" && errMsg.length > 0) {
@@ -412146,7 +412238,10 @@ Then use file_read on individual FILES inside it.`);
412146
412238
  output,
412147
412239
  success: result.success,
412148
412240
  runtimeAuthored: result.runtimeAuthored,
412149
- completionEvidenceFamily: result.completionEvidenceFamily
412241
+ completionEvidenceFamily: result.completionEvidenceFamily,
412242
+ completionAdmission: result.completionAdmission,
412243
+ completionReviewPending: result.completionReviewPending,
412244
+ completionRestoredPayload: result.completionRestoredPayload
412150
412245
  };
412151
412246
  };
412152
412247
  return boundExecuteSingle;
@@ -414409,6 +414504,9 @@ ${transportFailure2}` : transportFailure2;
414409
414504
  error: r.success ? void 0 : r.output,
414410
414505
  runtimeAuthored: r.runtimeAuthored,
414411
414506
  completionEvidenceFamily: r.completionEvidenceFamily,
414507
+ completionAdmission: r.completionAdmission,
414508
+ completionReviewPending: r.completionReviewPending,
414509
+ completionRestoredPayload: r.completionRestoredPayload,
414412
414510
  systemGuidance: r.systemGuidance
414413
414511
  };
414414
414512
  })();
@@ -414439,16 +414537,16 @@ ${transportFailure2}` : transportFailure2;
414439
414537
  if (!sr.result.success) {
414440
414538
  messages.push({
414441
414539
  role: "system",
414442
- content: this.buildTaskCompleteToolFailureGuard(output)
414540
+ content: this.buildTaskCompleteToolFailureGuard(output, sr.result.completionReviewPending)
414443
414541
  });
414444
414542
  this.emit({
414445
414543
  type: "status",
414446
- content: "task_complete blocked by verification guard",
414544
+ content: this.taskCompleteToolFailureStatus(sr.result.completionReviewPending),
414447
414545
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
414448
414546
  });
414449
414547
  continue;
414450
414548
  }
414451
- const taskCompleteArgs = matchTc.arguments;
414549
+ const taskCompleteArgs = acceptedTaskCompleteArgs(matchTc, sr.result, turn);
414452
414550
  const open4 = this.getOpenTodoItems();
414453
414551
  if (open4.length > 0 && !this._shouldBypassTodoCompletionGuardForTaskComplete(taskCompleteArgs)) {
414454
414552
  const guard = this.buildTodoCompletionGuard(open4);
@@ -414513,16 +414611,16 @@ ${transportFailure2}` : transportFailure2;
414513
414611
  if (!r.success) {
414514
414612
  messages.push({
414515
414613
  role: "system",
414516
- content: this.buildTaskCompleteToolFailureGuard(r.output)
414614
+ content: this.buildTaskCompleteToolFailureGuard(r.output, r.completionReviewPending)
414517
414615
  });
414518
414616
  this.emit({
414519
414617
  type: "status",
414520
- content: "task_complete blocked by verification guard",
414618
+ content: this.taskCompleteToolFailureStatus(r.completionReviewPending),
414521
414619
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
414522
414620
  });
414523
414621
  continue;
414524
414622
  }
414525
- const taskCompleteArgs = r.tc.arguments;
414623
+ const taskCompleteArgs = acceptedTaskCompleteArgs(r.tc, r, turn);
414526
414624
  const open4 = this.getOpenTodoItems();
414527
414625
  if (open4.length > 0 && !this._shouldBypassTodoCompletionGuardForTaskComplete(taskCompleteArgs)) {
414528
414626
  const guard = this.buildTodoCompletionGuard(open4);
@@ -414609,7 +414707,11 @@ ${transportFailure2}` : transportFailure2;
414609
414707
  output: cloned.output,
414610
414708
  success: cloned.success,
414611
414709
  runtimeAuthored: cloned.runtimeAuthored,
414612
- completionEvidenceFamily: cloned.completionEvidenceFamily
414710
+ completionEvidenceFamily: cloned.completionEvidenceFamily,
414711
+ completionAdmission: cloned.completionAdmission,
414712
+ completionReviewPending: cloned.completionReviewPending,
414713
+ completionRestoredPayload: cloned.completionRestoredPayload,
414714
+ systemGuidance: cloned.systemGuidance
414613
414715
  };
414614
414716
  }
414615
414717
  }
@@ -414628,16 +414730,16 @@ ${transportFailure2}` : transportFailure2;
414628
414730
  if (!r.success) {
414629
414731
  messages.push({
414630
414732
  role: "system",
414631
- content: this.buildTaskCompleteToolFailureGuard(r.output)
414733
+ content: this.buildTaskCompleteToolFailureGuard(r.output, r.completionReviewPending)
414632
414734
  });
414633
414735
  this.emit({
414634
414736
  type: "status",
414635
- content: "task_complete blocked by verification guard",
414737
+ content: this.taskCompleteToolFailureStatus(r.completionReviewPending),
414636
414738
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
414637
414739
  });
414638
414740
  continue;
414639
414741
  }
414640
- const taskCompleteArgs = r.tc.arguments;
414742
+ const taskCompleteArgs = acceptedTaskCompleteArgs(r.tc, r, turn);
414641
414743
  const open4 = this.getOpenTodoItems();
414642
414744
  if (open4.length > 0 && !this._shouldBypassTodoCompletionGuardForTaskComplete(taskCompleteArgs)) {
414643
414745
  const guard = this.buildTodoCompletionGuard(open4);
@@ -415573,16 +415675,16 @@ ${diagnosis}` : diagnosis;
415573
415675
  if (!r.success) {
415574
415676
  messages.push({
415575
415677
  role: "system",
415576
- content: this.buildTaskCompleteToolFailureGuard(r.output)
415678
+ content: this.buildTaskCompleteToolFailureGuard(r.output, r.completionReviewPending)
415577
415679
  });
415578
415680
  this.emit({
415579
415681
  type: "status",
415580
- content: "task_complete blocked by verification guard",
415682
+ content: this.taskCompleteToolFailureStatus(r.completionReviewPending),
415581
415683
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
415582
415684
  });
415583
415685
  continue;
415584
415686
  }
415585
- const taskCompleteArgs = r.tc.arguments;
415687
+ const taskCompleteArgs = acceptedTaskCompleteArgs(r.tc, r, turn);
415586
415688
  const open4 = this.getOpenTodoItems();
415587
415689
  if (open4.length > 0 && !this._shouldBypassTodoCompletionGuardForTaskComplete(taskCompleteArgs)) {
415588
415690
  const guard = this.buildTodoCompletionGuard(open4);
@@ -423289,28 +423391,28 @@ function brokerAdmissionFailureResponse(err) {
423289
423391
  if (!payload2 || typeof payload2 !== "object" || Array.isArray(payload2)) {
423290
423392
  return null;
423291
423393
  }
423292
- const record8 = payload2;
423293
- const error = record8["error"];
423394
+ const record9 = payload2;
423395
+ const error = record9["error"];
423294
423396
  if (typeof error !== "string" || !error.trim())
423295
423397
  return null;
423296
423398
  const isLegacyError = err.status === 503 && error === BROKER_QUEUE_DEADLINE_ERROR;
423297
423399
  const annotationPrefix = `${BROKER_QUEUE_DEADLINE_ERROR}:`;
423298
423400
  const isAnnotatedError = err.status === 503 && error.startsWith(annotationPrefix);
423299
- const retryable = record8["retryable"];
423300
- const reasonCode = record8["reason_code"];
423301
- const retryAfterMs = record8["retry_after_ms"];
423302
- const logicalRequestId = record8["logical_request_id"];
423303
- const requestId = record8["request_id"];
423304
- const queue = record8["queue"];
423305
- const causeReasonCode = record8["cause_reason_code"];
423306
- const admissionRetained = record8["admission_retained"];
423307
- const resumeTtlMs = record8["resume_ttl_ms"];
423308
- const queuePosition = record8["queue_position"];
423309
- 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"];
423310
423412
  const responseReasonCode = err.responseHeaders["x-ollama-unify-reason-code"]?.trim() ?? "";
423311
423413
  const responseRetryable = err.responseHeaders["x-ollama-unify-retryable"]?.trim().toLowerCase() ?? "";
423312
423414
  const isLegacyContract = (isLegacyError || isAnnotatedError) && typeof requestId === "string" && requestId.length > 0 && !!queue && typeof queue === "object" && !Array.isArray(queue);
423313
- 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);
423314
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()) {
423315
423417
  return null;
423316
423418
  }
@@ -426846,10 +426948,10 @@ function ownersEqual(left, right) {
426846
426948
  function freezeEvent(state, atMs, owner) {
426847
426949
  return Object.freeze({ state, atMs: timestamp4(atMs), owner });
426848
426950
  }
426849
- function freezeRecord(record8) {
426951
+ function freezeRecord(record9) {
426850
426952
  return Object.freeze({
426851
- ...record8,
426852
- history: Object.freeze([...record8.history])
426953
+ ...record9,
426954
+ history: Object.freeze([...record9.history])
426853
426955
  });
426854
426956
  }
426855
426957
  function decisionsEqual(left, right) {
@@ -426877,49 +426979,49 @@ var TelegramInputOwnershipLedger = class {
426877
426979
  reason: "inputId is already bound to a different immutable target"
426878
426980
  };
426879
426981
  }
426880
- const record8 = freezeRecord({
426982
+ const record9 = freezeRecord({
426881
426983
  target: target2,
426882
426984
  owner,
426883
426985
  lifecycle: "received",
426884
426986
  revision: 0,
426885
426987
  history: Object.freeze([freezeEvent("received", atMs, owner)])
426886
426988
  });
426887
- this.records.set(target2.inputId, record8);
426888
- return { status: "applied", record: record8 };
426989
+ this.records.set(target2.inputId, record9);
426990
+ return { status: "applied", record: record9 };
426889
426991
  }
426890
426992
  claim(targetInput, ownerInput) {
426891
426993
  const bound = this.boundRecord(targetInput);
426892
426994
  if (bound.status !== "applied") return bound;
426893
- const record8 = bound.record;
426995
+ const record9 = bound.record;
426894
426996
  const owner = freezeOwner(ownerInput);
426895
- if (ownersEqual(record8.owner, owner)) {
426896
- return { status: "duplicate", record: record8 };
426997
+ if (ownersEqual(record9.owner, owner)) {
426998
+ return { status: "duplicate", record: record9 };
426897
426999
  }
426898
- if (isTelegramInputTerminalLifecycle(record8.lifecycle)) {
427000
+ if (isTelegramInputTerminalLifecycle(record9.lifecycle)) {
426899
427001
  return {
426900
427002
  status: "terminal",
426901
- record: record8,
427003
+ record: record9,
426902
427004
  reason: "terminal input ownership cannot be transferred"
426903
427005
  };
426904
427006
  }
426905
- if (owner.generation < record8.owner.generation) {
427007
+ if (owner.generation < record9.owner.generation) {
426906
427008
  return {
426907
427009
  status: "stale",
426908
- record: record8,
427010
+ record: record9,
426909
427011
  reason: "owner generation is older than the authoritative claim"
426910
427012
  };
426911
427013
  }
426912
- if (owner.generation === record8.owner.generation) {
427014
+ if (owner.generation === record9.owner.generation) {
426913
427015
  return {
426914
427016
  status: "contradiction",
426915
- record: record8,
427017
+ record: record9,
426916
427018
  reason: "one owner generation cannot name two owners"
426917
427019
  };
426918
427020
  }
426919
427021
  const next = freezeRecord({
426920
- ...record8,
427022
+ ...record9,
426921
427023
  owner,
426922
- revision: record8.revision + 1
427024
+ revision: record9.revision + 1
426923
427025
  });
426924
427026
  this.records.set(targetInput.inputId, next);
426925
427027
  return { status: "applied", record: next };
@@ -426927,30 +427029,30 @@ var TelegramInputOwnershipLedger = class {
426927
427029
  transition(targetInput, ownerInput, nextState, atMs = Date.now()) {
426928
427030
  const authorized = this.authorizedRecord(targetInput, ownerInput);
426929
427031
  if (authorized.status !== "applied") return authorized;
426930
- const record8 = authorized.record;
426931
- if (record8.lifecycle === nextState) {
426932
- return { status: "duplicate", record: record8 };
427032
+ const record9 = authorized.record;
427033
+ if (record9.lifecycle === nextState) {
427034
+ return { status: "duplicate", record: record9 };
426933
427035
  }
426934
- if (isTelegramInputTerminalLifecycle(record8.lifecycle)) {
427036
+ if (isTelegramInputTerminalLifecycle(record9.lifecycle)) {
426935
427037
  return {
426936
427038
  status: "terminal",
426937
- record: record8,
427039
+ record: record9,
426938
427040
  reason: "terminal input lifecycle cannot advance"
426939
427041
  };
426940
427042
  }
426941
- if (!ALLOWED_TRANSITIONS[record8.lifecycle].has(nextState)) {
427043
+ if (!ALLOWED_TRANSITIONS[record9.lifecycle].has(nextState)) {
426942
427044
  return {
426943
427045
  status: "invalid_transition",
426944
- record: record8,
426945
- reason: `${record8.lifecycle} cannot transition to ${nextState}`
427046
+ record: record9,
427047
+ reason: `${record9.lifecycle} cannot transition to ${nextState}`
426946
427048
  };
426947
427049
  }
426948
- return this.storeLifecycle(record8, nextState, atMs);
427050
+ return this.storeLifecycle(record9, nextState, atMs);
426949
427051
  }
426950
427052
  commitDecision(targetInput, ownerInput, decisionInput2, atMs = Date.now()) {
426951
427053
  const bound = this.boundRecord(targetInput);
426952
427054
  if (bound.status !== "applied") return bound;
426953
- const record8 = bound.record;
427055
+ const record9 = bound.record;
426954
427056
  const decision2 = {
426955
427057
  decisionId: nonEmpty(decisionInput2.decisionId, "decisionId"),
426956
427058
  contractFingerprint: nonEmpty(
@@ -426963,55 +427065,55 @@ var TelegramInputOwnershipLedger = class {
426963
427065
  if (decision2.contractVersion !== 2) {
426964
427066
  return {
426965
427067
  status: "invalid_transition",
426966
- record: record8,
427068
+ record: record9,
426967
427069
  reason: "only Telegram turn contract version 2 can be committed"
426968
427070
  };
426969
427071
  }
426970
- if (record8.decision) {
426971
- return decisionsEqual(record8.decision, decision2) ? { status: "duplicate", record: record8 } : {
427072
+ if (record9.decision) {
427073
+ return decisionsEqual(record9.decision, decision2) ? { status: "duplicate", record: record9 } : {
426972
427074
  status: "contradiction",
426973
- record: record8,
427075
+ record: record9,
426974
427076
  reason: "an input can have only one committed decision"
426975
427077
  };
426976
427078
  }
426977
427079
  const authorized = this.authorizedRecord(targetInput, ownerInput);
426978
427080
  if (authorized.status !== "applied") return authorized;
426979
- if (isTelegramInputTerminalLifecycle(record8.lifecycle)) {
427081
+ if (isTelegramInputTerminalLifecycle(record9.lifecycle)) {
426980
427082
  return {
426981
427083
  status: "terminal",
426982
- record: record8,
427084
+ record: record9,
426983
427085
  reason: "a terminal input cannot accept a decision"
426984
427086
  };
426985
427087
  }
426986
- if (!ALLOWED_TRANSITIONS[record8.lifecycle].has("decision_committed")) {
427088
+ if (!ALLOWED_TRANSITIONS[record9.lifecycle].has("decision_committed")) {
426987
427089
  return {
426988
427090
  status: "invalid_transition",
426989
- record: record8,
426990
- reason: `${record8.lifecycle} cannot commit a decision`
427091
+ record: record9,
427092
+ reason: `${record9.lifecycle} cannot commit a decision`
426991
427093
  };
426992
427094
  }
426993
427095
  const committed = Object.freeze({
426994
427096
  ...decision2,
426995
- committedBy: record8.owner,
427097
+ committedBy: record9.owner,
426996
427098
  committedAtMs: timestamp4(atMs)
426997
427099
  });
426998
427100
  const next = freezeRecord({
426999
- ...record8,
427101
+ ...record9,
427000
427102
  decision: committed,
427001
427103
  lifecycle: "decision_committed",
427002
- revision: record8.revision + 1,
427104
+ revision: record9.revision + 1,
427003
427105
  history: [
427004
- ...record8.history,
427005
- freezeEvent("decision_committed", atMs, record8.owner)
427106
+ ...record9.history,
427107
+ freezeEvent("decision_committed", atMs, record9.owner)
427006
427108
  ]
427007
427109
  });
427008
- this.records.set(record8.target.inputId, next);
427110
+ this.records.set(record9.target.inputId, next);
427009
427111
  return { status: "applied", record: next };
427010
427112
  }
427011
427113
  commitDelivery(targetInput, ownerInput, deliveryInput, atMs = Date.now()) {
427012
427114
  const bound = this.boundRecord(targetInput);
427013
427115
  if (bound.status !== "applied") return bound;
427014
- const record8 = bound.record;
427116
+ const record9 = bound.record;
427015
427117
  const delivery = {
427016
427118
  deliveryId: nonEmpty(deliveryInput.deliveryId, "deliveryId"),
427017
427119
  decisionId: nonEmpty(deliveryInput.decisionId, "decisionId"),
@@ -427021,98 +427123,98 @@ var TelegramInputOwnershipLedger = class {
427021
427123
  "transportReceiptId"
427022
427124
  )
427023
427125
  };
427024
- if (record8.delivery) {
427025
- return deliveriesEqual(record8.delivery, delivery) ? { status: "duplicate", record: record8 } : {
427126
+ if (record9.delivery) {
427127
+ return deliveriesEqual(record9.delivery, delivery) ? { status: "duplicate", record: record9 } : {
427026
427128
  status: "contradiction",
427027
- record: record8,
427129
+ record: record9,
427028
427130
  reason: "an input can have only one committed delivery"
427029
427131
  };
427030
427132
  }
427031
427133
  const authorized = this.authorizedRecord(targetInput, ownerInput);
427032
427134
  if (authorized.status !== "applied") return authorized;
427033
- if (isTelegramInputTerminalLifecycle(record8.lifecycle)) {
427135
+ if (isTelegramInputTerminalLifecycle(record9.lifecycle)) {
427034
427136
  return {
427035
427137
  status: "terminal",
427036
- record: record8,
427138
+ record: record9,
427037
427139
  reason: "a terminal input cannot accept a delivery"
427038
427140
  };
427039
427141
  }
427040
- if (!record8.decision || record8.decision.decisionId !== delivery.decisionId) {
427142
+ if (!record9.decision || record9.decision.decisionId !== delivery.decisionId) {
427041
427143
  return {
427042
427144
  status: "invalid_transition",
427043
- record: record8,
427145
+ record: record9,
427044
427146
  reason: "delivery must cite the committed decision"
427045
427147
  };
427046
427148
  }
427047
- if (record8.decision.disposition === "no_reply") {
427149
+ if (record9.decision.disposition === "no_reply") {
427048
427150
  return {
427049
427151
  status: "invalid_transition",
427050
- record: record8,
427152
+ record: record9,
427051
427153
  reason: "a no_reply decision cannot have a delivery"
427052
427154
  };
427053
427155
  }
427054
- 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") {
427055
427157
  return {
427056
427158
  status: "contradiction",
427057
- record: record8,
427159
+ record: record9,
427058
427160
  reason: "delivery kind contradicts the committed disposition"
427059
427161
  };
427060
427162
  }
427061
427163
  const committed = Object.freeze({
427062
427164
  ...delivery,
427063
- committedBy: record8.owner,
427165
+ committedBy: record9.owner,
427064
427166
  committedAtMs: timestamp4(atMs)
427065
427167
  });
427066
427168
  const next = freezeRecord({
427067
- ...record8,
427169
+ ...record9,
427068
427170
  delivery: committed,
427069
427171
  lifecycle: "delivery_committed",
427070
- revision: record8.revision + 1,
427172
+ revision: record9.revision + 1,
427071
427173
  history: [
427072
- ...record8.history,
427073
- freezeEvent("delivery_committed", atMs, record8.owner)
427174
+ ...record9.history,
427175
+ freezeEvent("delivery_committed", atMs, record9.owner)
427074
427176
  ]
427075
427177
  });
427076
- this.records.set(record8.target.inputId, next);
427178
+ this.records.set(record9.target.inputId, next);
427077
427179
  return { status: "applied", record: next };
427078
427180
  }
427079
427181
  complete(targetInput, ownerInput, terminal, atMs = Date.now()) {
427080
427182
  const bound = this.boundRecord(targetInput);
427081
427183
  if (bound.status !== "applied") return bound;
427082
- const record8 = bound.record;
427083
- if (record8.terminal) {
427084
- 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 } : {
427085
427187
  status: "contradiction",
427086
- record: record8,
427188
+ record: record9,
427087
427189
  reason: "an input can have only one terminal lifecycle result"
427088
427190
  };
427089
427191
  }
427090
427192
  const authorized = this.authorizedRecord(targetInput, ownerInput);
427091
427193
  if (authorized.status !== "applied") return authorized;
427092
427194
  if (terminal === "consumed") {
427093
- if (!record8.decision) {
427195
+ if (!record9.decision) {
427094
427196
  return {
427095
427197
  status: "invalid_transition",
427096
- record: record8,
427198
+ record: record9,
427097
427199
  reason: "consumed input requires a committed decision"
427098
427200
  };
427099
427201
  }
427100
- if (record8.decision.disposition !== "no_reply" && !record8.delivery) {
427202
+ if (record9.decision.disposition !== "no_reply" && !record9.delivery) {
427101
427203
  return {
427102
427204
  status: "invalid_transition",
427103
- record: record8,
427205
+ record: record9,
427104
427206
  reason: "reply and action decisions require a delivery receipt"
427105
427207
  };
427106
427208
  }
427107
427209
  }
427108
- if (!ALLOWED_TRANSITIONS[record8.lifecycle].has(terminal)) {
427210
+ if (!ALLOWED_TRANSITIONS[record9.lifecycle].has(terminal)) {
427109
427211
  return {
427110
427212
  status: "invalid_transition",
427111
- record: record8,
427112
- reason: `${record8.lifecycle} cannot transition to ${terminal}`
427213
+ record: record9,
427214
+ reason: `${record9.lifecycle} cannot transition to ${terminal}`
427113
427215
  };
427114
427216
  }
427115
- return this.storeLifecycle(record8, terminal, atMs, terminal);
427217
+ return this.storeLifecycle(record9, terminal, atMs, terminal);
427116
427218
  }
427117
427219
  boundRecord(targetInput) {
427118
427220
  const existing = this.records.get(targetInput.inputId);
@@ -427141,40 +427243,40 @@ var TelegramInputOwnershipLedger = class {
427141
427243
  authorizedRecord(targetInput, ownerInput) {
427142
427244
  const bound = this.boundRecord(targetInput);
427143
427245
  if (bound.status !== "applied") return bound;
427144
- const record8 = bound.record;
427246
+ const record9 = bound.record;
427145
427247
  let owner;
427146
427248
  try {
427147
427249
  owner = freezeOwner(ownerInput);
427148
427250
  } catch (error) {
427149
427251
  return {
427150
427252
  status: "contradiction",
427151
- record: record8,
427253
+ record: record9,
427152
427254
  reason: error instanceof Error ? error.message : String(error)
427153
427255
  };
427154
427256
  }
427155
- if (ownersEqual(record8.owner, owner)) return bound;
427156
- if (owner.generation < record8.owner.generation) {
427257
+ if (ownersEqual(record9.owner, owner)) return bound;
427258
+ if (owner.generation < record9.owner.generation) {
427157
427259
  return {
427158
427260
  status: "stale",
427159
- record: record8,
427261
+ record: record9,
427160
427262
  reason: "operation belongs to an older owner generation"
427161
427263
  };
427162
427264
  }
427163
427265
  return {
427164
427266
  status: "contradiction",
427165
- record: record8,
427267
+ record: record9,
427166
427268
  reason: "operation owner does not match the authoritative claim"
427167
427269
  };
427168
427270
  }
427169
- storeLifecycle(record8, state, atMs, terminal) {
427271
+ storeLifecycle(record9, state, atMs, terminal) {
427170
427272
  const next = freezeRecord({
427171
- ...record8,
427273
+ ...record9,
427172
427274
  lifecycle: state,
427173
427275
  terminal,
427174
- revision: record8.revision + 1,
427175
- history: [...record8.history, freezeEvent(state, atMs, record8.owner)]
427276
+ revision: record9.revision + 1,
427277
+ history: [...record9.history, freezeEvent(state, atMs, record9.owner)]
427176
427278
  });
427177
- this.records.set(record8.target.inputId, next);
427279
+ this.records.set(record9.target.inputId, next);
427178
427280
  return { status: "applied", record: next };
427179
427281
  }
427180
427282
  };
@@ -428044,9 +428146,9 @@ function adaptExecutionTool(tool, options = {}) {
428044
428146
  const mapResult = (result, args) => {
428045
428147
  const mapped = mapExecutionToolResult(result);
428046
428148
  if (tool.getHistoryObservationIdentity) {
428047
- const record8 = { args: structuredClone(args), native: result, mapped: { ...mapped } };
428048
- historyObservations.set(mapped, record8);
428049
- 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);
428050
428152
  }
428051
428153
  return mapped;
428052
428154
  };
@@ -428195,9 +428297,9 @@ function adaptExecutionTool(tool, options = {}) {
428195
428297
  }
428196
428298
  if (typeof tool.getHistoryObservationIdentity === "function") {
428197
428299
  adapted.getHistoryObservationIdentity = (args, result) => {
428198
- const record8 = historyObservations.get(result) ?? (result.executionReceipt && historyObservations.get(result.executionReceipt));
428199
- 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;
428200
- 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);
428201
428303
  };
428202
428304
  }
428203
428305
  return adapted;