@akagilnc/pi-workflow-roles 0.1.5382 → 0.1.5406

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.
Files changed (51) hide show
  1. package/README.md +2 -0
  2. package/README.zh-CN.md +2 -0
  3. package/dist/acp-host/production-host.js +2523 -1880
  4. package/dist/archivist-record-pointer.js +38 -0
  5. package/dist/compliance-transport.js +5 -0
  6. package/dist/doctor-auditor.js +1 -0
  7. package/dist/engine-detour-usage.js +6 -6
  8. package/dist/headless-host/production-host.js +1097 -454
  9. package/dist/judge-role.js +14 -1
  10. package/dist/migrate-book-topology.js +190 -74
  11. package/dist/navigator-attendance.js +10 -9
  12. package/dist/navigator-invocation-identity.js +18 -0
  13. package/dist/pi/role-turn-host.js +9 -0
  14. package/dist/public-cli/cli.js +1 -0
  15. package/dist/public-cli/instruction-seat-run.js +250 -44
  16. package/dist/public-cli/main.js +929 -323
  17. package/dist/public-cli/post-admission.js +427 -244
  18. package/dist/public-cli/settlement.js +111 -48
  19. package/dist/public-cli/terminal.js +12 -1
  20. package/dist/public-cli/turn-request.js +3 -0
  21. package/dist/receipt-delivery-policy.js +152 -17
  22. package/dist/submission-errors.js +11 -1
  23. package/dist/submission-gate.js +27 -4
  24. package/package.json +1 -1
  25. package/src/archivist-record-pointer.ts +48 -0
  26. package/src/compliance-transport.ts +10 -2
  27. package/src/doctor-auditor.ts +3 -0
  28. package/src/engine-detour-usage.ts +7 -6
  29. package/src/external-host-turn-loop.ts +24 -12
  30. package/src/gatekeeper-role.ts +2 -2
  31. package/src/host-contracts.ts +7 -0
  32. package/src/judge-role.ts +24 -5
  33. package/src/navigator-attendance.ts +17 -12
  34. package/src/navigator-invocation-identity.ts +31 -0
  35. package/src/pi/adapter.ts +33 -8
  36. package/src/pi/role-turn-host.ts +7 -0
  37. package/src/public-cli/cli.ts +1 -0
  38. package/src/public-cli/instruction-seat-run.ts +283 -49
  39. package/src/public-cli/post-admission.ts +556 -324
  40. package/src/public-cli/settlement.ts +112 -50
  41. package/src/public-cli/terminal.ts +16 -4
  42. package/src/public-cli/turn-request.ts +10 -1
  43. package/src/receipt-delivery-policy.ts +209 -17
  44. package/src/role-envelope.ts +5 -1
  45. package/src/role-runtime-dependencies.ts +1 -0
  46. package/src/role-runtime.ts +65 -21
  47. package/src/submission-correctable-error.ts +5 -2
  48. package/src/submission-errors.ts +12 -1
  49. package/src/submission-gate.ts +34 -4
  50. package/src/worker-role.ts +19 -7
  51. package/src/worker-submission-gates.ts +29 -7
@@ -17500,6 +17500,13 @@ function formatTerminalResult(result) {
17500
17500
  `diagnostic ${encodeTerminalField(result.roleOutcome.diagnostic)}`
17501
17501
  );
17502
17502
  }
17503
+ if (result.roleOutcome.kind === "accepted" && result.roleOutcome.decisiveFacts?.directionUnsettled === true) {
17504
+ lines.push("fact directionUnsettled true");
17505
+ const subsequent = result.roleOutcome.decisiveFacts.subsequentAudit;
17506
+ if (typeof subsequent === "string") {
17507
+ lines.push(`fact subsequentAudit ${encodeTerminalField(subsequent)}`);
17508
+ }
17509
+ }
17503
17510
  if (result.roleOutcome.kind === "failure" || result.roleOutcome.kind === "no_receipt" || result.roleOutcome.kind === "audit_escalation" || result.roleOutcome.decisiveFacts?.failedAttempts !== void 0) {
17504
17511
  const facts = result.roleOutcome.kind === "accepted" ? { failedAttempts: result.roleOutcome.decisiveFacts?.failedAttempts } : result.roleOutcome.decisiveFacts ?? {};
17505
17512
  for (const [key, value] of Object.entries(facts)) {
@@ -17558,7 +17565,7 @@ function formatTerminalResult(result) {
17558
17565
  lines.push(`recorded-submission ${encodeTerminalField(rendered)}`);
17559
17566
  }
17560
17567
  } else {
17561
- const payloads = result.roleOutcome.kind === "accepted" || result.roleOutcome.kind === "audit_escalation" ? coalesceSubmissionRows(result.roleOutcome.payloads, result.submissions) : result.submissions ?? [];
17568
+ const payloads = result.roleOutcome.kind === "accepted" || result.roleOutcome.kind === "audit_escalation" ? coalesceSubmissionRows(result.submissions, result.roleOutcome.payloads) : result.submissions ?? [];
17562
17569
  for (let i = payloads.length - 1; i >= 0; i -= 1) {
17563
17570
  const payload = payloads[i];
17564
17571
  const rendered = typeof payload === "string" ? payload : JSON.stringify(payload);
@@ -17574,6 +17581,223 @@ var init_terminal = __esm({
17574
17581
  }
17575
17582
  });
17576
17583
 
17584
+ // src/receipt-delivery-policy.ts
17585
+ function receiptAttemptPointer(runPointer, invocationScopeId) {
17586
+ const scope = invocationScopeId?.trim() ?? "";
17587
+ if (scope.length > 0) return `invocation:${scope}`;
17588
+ return `current:${runPointer}`;
17589
+ }
17590
+ function deliveryLimitFromConfig(value) {
17591
+ return parseAutoResumeLimit(value ?? AUTO_RESUME_LIMIT);
17592
+ }
17593
+ function deliveryTurnsFact(value) {
17594
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
17595
+ throw new TypeError("deliveryTurns must be a non-negative integer");
17596
+ }
17597
+ return value;
17598
+ }
17599
+ function parseNoReceiptLifecycleFacts(input) {
17600
+ if (!isRecord(input) || typeof input.terminalToolCalled !== "boolean" || input.sessionCompletion !== "settled-without-accepted-receipt" || input.acceptedReceipt !== false || typeof input.runPointer !== "string" || input.runPointer.trim() === "" || typeof input.attemptPointer !== "string" || input.attemptPointer.trim() === "" || !Array.isArray(input.rejectedReceipts) || !input.rejectedReceipts.every((item) => isRecord(item) && typeof item.reason === "string")) {
17601
+ throw new TypeError("malformed no-receipt lifecycle facts");
17602
+ }
17603
+ return {
17604
+ terminalToolCalled: input.terminalToolCalled,
17605
+ rejectedReceipts: input.rejectedReceipts.map((item) => ({
17606
+ reason: item.reason,
17607
+ diagnosticAvailable: item.reason.trim() !== ""
17608
+ })),
17609
+ deliveryTurns: deliveryTurnsFact(input.deliveryTurns),
17610
+ sessionCompletion: "settled-without-accepted-receipt",
17611
+ runPointer: input.runPointer,
17612
+ attemptPointer: input.attemptPointer,
17613
+ acceptedReceipt: false
17614
+ };
17615
+ }
17616
+ function noReceiptLifecycleFacts(input) {
17617
+ return {
17618
+ terminalToolCalled: input.terminalToolCalled,
17619
+ rejectedReceipts: input.rejectedReceipts.map(({ reason }) => ({
17620
+ reason,
17621
+ diagnosticAvailable: reason.trim() !== ""
17622
+ })),
17623
+ deliveryTurns: deliveryTurnsFact(input.deliveryTurns),
17624
+ sessionCompletion: "settled-without-accepted-receipt",
17625
+ runPointer: input.runPointer,
17626
+ attemptPointer: input.attemptPointer,
17627
+ acceptedReceipt: false
17628
+ };
17629
+ }
17630
+ function createReceiptDeliveryPolicy(limit) {
17631
+ const deliveryLimit = deliveryLimitFromConfig(limit);
17632
+ let accepted = false;
17633
+ let closed = false;
17634
+ let terminalToolCalled = false;
17635
+ let deliveryTurns = 0;
17636
+ let budgetSpent = 0;
17637
+ const rejectedReceipts = [];
17638
+ const spend = () => {
17639
+ if (budgetSpent < deliveryLimit) budgetSpent += 1;
17640
+ };
17641
+ return {
17642
+ /** The effective ceiling this budget spends (#1132 — never re-read). */
17643
+ limit: deliveryLimit,
17644
+ recordAccepted() {
17645
+ accepted = true;
17646
+ terminalToolCalled = true;
17647
+ },
17648
+ /** Infrastructure owns terminality and must never trigger receipt催交. */
17649
+ stopForInfrastructure() {
17650
+ accepted = true;
17651
+ },
17652
+ /**
17653
+ * Record the rejection this turn already produced.
17654
+ * The fact does not spend a budget. The seam that sends the next prompt
17655
+ * owns that count.
17656
+ */
17657
+ recordRejected(reason) {
17658
+ terminalToolCalled = true;
17659
+ rejectedReceipts.push({ reason, diagnosticAvailable: reason.trim() !== "" });
17660
+ },
17661
+ recordDeliveryRequest() {
17662
+ deliveryTurns += 1;
17663
+ spend();
17664
+ },
17665
+ /**
17666
+ * Stop asking. The issued count stays whatever was actually sent (#1132 —
17667
+ * do not fill the remainder up to the ceiling).
17668
+ */
17669
+ closeBudget() {
17670
+ closed = true;
17671
+ },
17672
+ /**
17673
+ * A nested session settled without an accepted receipt. Close so this layer
17674
+ * does not open another prompt on that session. The issued count stays the
17675
+ * larger of the two seams: a nested zero must not wipe prompts this layer
17676
+ * already sent, and adding the two counts would bill one send twice.
17677
+ */
17678
+ recordNestedNoReceipt(facts) {
17679
+ terminalToolCalled = terminalToolCalled || facts.terminalToolCalled;
17680
+ rejectedReceipts.push(...facts.rejectedReceipts);
17681
+ deliveryTurns = Math.max(deliveryTurns, facts.deliveryTurns);
17682
+ closed = true;
17683
+ },
17684
+ nextAction() {
17685
+ if (accepted) return "accepted";
17686
+ if (closed) return "no-receipt";
17687
+ return budgetSpent < deliveryLimit ? "request-delivery" : "no-receipt";
17688
+ },
17689
+ /** Delivery requests actually issued so far (#1132). */
17690
+ issuedDeliveryRequests() {
17691
+ return deliveryTurns;
17692
+ },
17693
+ /** Current typed delivery facts. No prose. */
17694
+ deliveryState() {
17695
+ return {
17696
+ terminalToolCalled,
17697
+ rejectedReceipts: rejectedReceipts.map((item) => ({ ...item })),
17698
+ deliveryTurns,
17699
+ acceptedReceipt: false
17700
+ };
17701
+ },
17702
+ facts(binding) {
17703
+ return noReceiptLifecycleFacts({ terminalToolCalled, rejectedReceipts: [...rejectedReceipts], deliveryTurns, ...binding });
17704
+ },
17705
+ /**
17706
+ * Continue a public call after the in-memory policy was rebuilt.
17707
+ * Sends already issued spend the same budget; copied rejections keep
17708
+ * the fact and do not spend again.
17709
+ */
17710
+ continueIssued(prior) {
17711
+ for (const receipt of prior.rejectedReceipts) {
17712
+ this.recordRejected(receipt.reason);
17713
+ }
17714
+ if (prior.terminalToolCalled === true) terminalToolCalled = true;
17715
+ for (let index = 0; index < prior.deliveryTurns; index += 1) {
17716
+ this.recordDeliveryRequest();
17717
+ }
17718
+ }
17719
+ };
17720
+ }
17721
+ function entryRecord(entry) {
17722
+ return isRecord(entry) ? entry : void 0;
17723
+ }
17724
+ function customTypeOf(record, message) {
17725
+ return record.customType ?? message?.customType;
17726
+ }
17727
+ function dataOf(record, message) {
17728
+ return record.data ?? message?.details;
17729
+ }
17730
+ function scopeTag(record) {
17731
+ const message = isRecord(record.message) ? record.message : void 0;
17732
+ const customType = customTypeOf(record, message);
17733
+ const data = dataOf(record, message);
17734
+ if ((customType === RECEIPT_DELIVERY_REQUEST_ENTRY || customType === RECEIPT_REJECTION_ENTRY) && isRecord(data) && typeof data.invocationScopeId === "string" && data.invocationScopeId.trim() !== "") {
17735
+ return data.invocationScopeId;
17736
+ }
17737
+ if (customType !== NO_RECEIPT_LIFECYCLE_ENTRY_TYPE) return void 0;
17738
+ try {
17739
+ const facts = parseNoReceiptLifecycleFacts(data);
17740
+ const prefix = "invocation:";
17741
+ if (!facts.attemptPointer.startsWith(prefix)) return void 0;
17742
+ const scope = facts.attemptPointer.slice(prefix.length);
17743
+ return scope.trim() === "" ? void 0 : scope;
17744
+ } catch {
17745
+ return void 0;
17746
+ }
17747
+ }
17748
+ function priorReceiptContinuation(entries, invocationScopeId) {
17749
+ const pointer = receiptAttemptPointer("", invocationScopeId);
17750
+ let entryTurns = 0;
17751
+ let factTurns = 0;
17752
+ let rejectedReceipts = [];
17753
+ let snapshotTerminal = false;
17754
+ for (const entry of entries) {
17755
+ const record = entryRecord(entry);
17756
+ if (record === void 0) continue;
17757
+ const tagged = scopeTag(record);
17758
+ if (tagged !== void 0) {
17759
+ const message = isRecord(record.message) ? record.message : void 0;
17760
+ const customType = customTypeOf(record, message);
17761
+ if (tagged !== invocationScopeId) continue;
17762
+ if (customType === RECEIPT_DELIVERY_REQUEST_ENTRY) entryTurns += 1;
17763
+ if (customType === RECEIPT_REJECTION_ENTRY) {
17764
+ const data = dataOf(record, message);
17765
+ if (isRecord(data) && typeof data.reason === "string") rejectedReceipts.push({ reason: data.reason });
17766
+ }
17767
+ if (customType !== NO_RECEIPT_LIFECYCLE_ENTRY_TYPE) continue;
17768
+ try {
17769
+ const facts = parseNoReceiptLifecycleFacts(dataOf(record, message));
17770
+ if (facts.attemptPointer !== pointer) continue;
17771
+ factTurns = Math.max(factTurns, facts.deliveryTurns);
17772
+ if (facts.rejectedReceipts.length >= rejectedReceipts.length) {
17773
+ rejectedReceipts = facts.rejectedReceipts.map(({ reason }) => ({ reason }));
17774
+ }
17775
+ snapshotTerminal ||= facts.terminalToolCalled;
17776
+ } catch {
17777
+ }
17778
+ continue;
17779
+ }
17780
+ }
17781
+ return {
17782
+ deliveryTurns: Math.max(entryTurns, factTurns),
17783
+ rejectedReceipts,
17784
+ terminalToolCalled: snapshotTerminal || rejectedReceipts.length > 0
17785
+ };
17786
+ }
17787
+ var NO_RECEIPT_LIFECYCLE_ENTRY_TYPE, RECEIPT_DELIVERY_REQUEST_ENTRY, RECEIPT_REJECTION_ENTRY, RECEIPT_DELIVERY_LIMIT_ENV;
17788
+ var init_receipt_delivery_policy = __esm({
17789
+ "src/receipt-delivery-policy.ts"() {
17790
+ "use strict";
17791
+ init_run_lifecycle();
17792
+ init_config2();
17793
+ init_unknown_value();
17794
+ NO_RECEIPT_LIFECYCLE_ENTRY_TYPE = "ak-no-receipt-lifecycle";
17795
+ RECEIPT_DELIVERY_REQUEST_ENTRY = "ak-receipt-delivery-request";
17796
+ RECEIPT_REJECTION_ENTRY = "ak-receipt-rejection";
17797
+ RECEIPT_DELIVERY_LIMIT_ENV = "AK_ROLE_RECEIPT_DELIVERY_LIMIT";
17798
+ }
17799
+ });
17800
+
17577
17801
  // src/session-assistant-usage.ts
17578
17802
  var session_assistant_usage_exports = {};
17579
17803
  __export(session_assistant_usage_exports, {
@@ -17583,10 +17807,10 @@ __export(session_assistant_usage_exports, {
17583
17807
  });
17584
17808
  import { join as join14 } from "node:path";
17585
17809
  async function readAssistantUsageFromSessionFile(sessionFile) {
17586
- const { readFile: readFile22 } = await import("node:fs/promises");
17810
+ const { readFile: readFile23 } = await import("node:fs/promises");
17587
17811
  let text;
17588
17812
  try {
17589
- text = await readFile22(sessionFile, "utf8");
17813
+ text = await readFile23(sessionFile, "utf8");
17590
17814
  } catch (error) {
17591
17815
  if (error?.code === "ENOENT") return void 0;
17592
17816
  throw error;
@@ -18207,6 +18431,8 @@ function createPiRoleTurnHost(config) {
18207
18431
  else env.AK_ROLE_INVOCATION_SCOPE = request.invocationScopeId;
18208
18432
  if (request.host === void 0 || request.host.trim() === "") delete env.AK_ROLE_HOST;
18209
18433
  else env.AK_ROLE_HOST = request.host.trim();
18434
+ if (request.deliveryRequestLimit === void 0) delete env[RECEIPT_DELIVERY_LIMIT_ENV];
18435
+ else env[RECEIPT_DELIVERY_LIMIT_ENV] = String(request.deliveryRequestLimit);
18210
18436
  applyEngineChildEnv(env, request.engine);
18211
18437
  if (typeof process.env.AK_ROLE_AUDITOR_SOURCE_RUN === "string" && process.env.AK_ROLE_AUDITOR_SOURCE_RUN.trim() !== "") {
18212
18438
  env.AK_ROLE_AUDITOR_SOURCE_RUN = process.env.AK_ROLE_AUDITOR_SOURCE_RUN;
@@ -18266,6 +18492,7 @@ var init_role_turn_host = __esm({
18266
18492
  init_engine_detour();
18267
18493
  init_role_activation_flags();
18268
18494
  init_user_dialogue_stdin();
18495
+ init_receipt_delivery_policy();
18269
18496
  init_sitian_facade();
18270
18497
  INTERNAL_ROLE_ENTRYPOINT_RELATIVE2 = "extensions/role-runtime.ts";
18271
18498
  EXPLICIT_INTERNAL_LOAD_PROBE_ARGS = [
@@ -22086,10 +22313,10 @@ function pairGateRounds(volumes) {
22086
22313
  return rounds.sort((a, b) => a.officerStartedAt.localeCompare(b.officerStartedAt)).map((round, index) => ({ ...round, roundIndex: index + 1 }));
22087
22314
  }
22088
22315
  async function resolveOfficerSessionFromPointerFile(pointerPath) {
22089
- const { readFile: readFile22 } = await import("node:fs/promises");
22316
+ const { readFile: readFile23 } = await import("node:fs/promises");
22090
22317
  let raw;
22091
22318
  try {
22092
- raw = JSON.parse(await readFile22(pointerPath, "utf8"));
22319
+ raw = JSON.parse(await readFile23(pointerPath, "utf8"));
22093
22320
  } catch (error) {
22094
22321
  throw new Error(
22095
22322
  `direct officer run pointer unreadable in ${pointerPath}: ${errorText(error)}`,
@@ -22697,9 +22924,7 @@ function runDirectoryFromSessionDirectory(sessionDirectory) {
22697
22924
  function sessionFileFromSessionDirectory(sessionDirectory) {
22698
22925
  return join26(sessionDirectory, "session.jsonl");
22699
22926
  }
22700
- function mintEngineDetourInvocationScope(input) {
22701
- const engine = input.effectiveEngine?.trim();
22702
- if (engine === void 0 || engine.length === 0) return void 0;
22927
+ function mintEngineDetourInvocationScope(_input) {
22703
22928
  return randomUUID3();
22704
22929
  }
22705
22930
  function withEngineDetourInvocationScope(request, invocationScopeId) {
@@ -22902,51 +23127,6 @@ var init_navigator_invocation_identity = __esm({
22902
23127
  }
22903
23128
  });
22904
23129
 
22905
- // src/receipt-delivery-policy.ts
22906
- function parseNoReceiptLifecycleFacts(input) {
22907
- if (!isRecord(input) || typeof input.terminalToolCalled !== "boolean" || input.deliveryTurns !== RECEIPT_DELIVERY_TURN_LIMIT || input.sessionCompletion !== "settled-without-accepted-receipt" || input.acceptedReceipt !== false || typeof input.runPointer !== "string" || input.runPointer.trim() === "" || typeof input.attemptPointer !== "string" || input.attemptPointer.trim() === "" || !Array.isArray(input.rejectedReceipts) || !input.rejectedReceipts.every((item) => isRecord(item) && typeof item.reason === "string")) {
22908
- throw new TypeError("malformed no-receipt lifecycle facts");
22909
- }
22910
- return {
22911
- terminalToolCalled: input.terminalToolCalled,
22912
- rejectedReceipts: input.rejectedReceipts.map((item) => ({
22913
- reason: item.reason,
22914
- diagnosticAvailable: item.reason.trim() !== ""
22915
- })),
22916
- deliveryTurns: RECEIPT_DELIVERY_TURN_LIMIT,
22917
- sessionCompletion: "settled-without-accepted-receipt",
22918
- runPointer: input.runPointer,
22919
- attemptPointer: input.attemptPointer,
22920
- acceptedReceipt: false
22921
- };
22922
- }
22923
- function noReceiptLifecycleFacts(input) {
22924
- if (input.deliveryTurns !== RECEIPT_DELIVERY_TURN_LIMIT) {
22925
- throw new TypeError("no-receipt lifecycle requires an exhausted delivery budget");
22926
- }
22927
- return {
22928
- terminalToolCalled: input.terminalToolCalled,
22929
- rejectedReceipts: input.rejectedReceipts.map(({ reason }) => ({
22930
- reason,
22931
- diagnosticAvailable: reason.trim() !== ""
22932
- })),
22933
- deliveryTurns: RECEIPT_DELIVERY_TURN_LIMIT,
22934
- sessionCompletion: "settled-without-accepted-receipt",
22935
- runPointer: input.runPointer,
22936
- attemptPointer: input.attemptPointer,
22937
- acceptedReceipt: false
22938
- };
22939
- }
22940
- var RECEIPT_DELIVERY_TURN_LIMIT, NO_RECEIPT_LIFECYCLE_ENTRY_TYPE;
22941
- var init_receipt_delivery_policy = __esm({
22942
- "src/receipt-delivery-policy.ts"() {
22943
- "use strict";
22944
- init_unknown_value();
22945
- RECEIPT_DELIVERY_TURN_LIMIT = 2;
22946
- NO_RECEIPT_LIFECYCLE_ENTRY_TYPE = "ak-no-receipt-lifecycle";
22947
- }
22948
- });
22949
-
22950
23130
  // src/public-cli/settlement.ts
22951
23131
  var settlement_exports = {};
22952
23132
  __export(settlement_exports, {
@@ -23089,13 +23269,76 @@ async function attachRecordedSubmissions(admitted, terminal, scope) {
23089
23269
  if (errorPath !== void 0) privateFailureErrorPaths.set(result, errorPath);
23090
23270
  return result;
23091
23271
  }
23092
- async function settleHostEndedNoReceipt(admitted, authority, scope) {
23272
+ function lifecycleFactsFromEntry(entry) {
23273
+ const customType = entry.customType ?? entry.message?.customType;
23274
+ if (customType !== NO_RECEIPT_LIFECYCLE_ENTRY_TYPE) return void 0;
23275
+ return entry.data ?? entry.message?.details;
23276
+ }
23277
+ async function readCurrentAttemptNoReceiptFacts(admitted, authority, scope) {
23278
+ const { sessionFile } = coordinatesFromAdmitted(authority, admitted);
23279
+ const entries = await readBoundSessionEntries(sessionFile).catch(() => void 0);
23280
+ if (entries === void 0) return void 0;
23281
+ const scopeId = scope?.invocationScopeId?.trim() ?? "";
23282
+ if (scopeId.length > 0) {
23283
+ const pointer = receiptAttemptPointer(admitted.runDirectory, scopeId);
23284
+ let selected;
23285
+ for (const entry of entries) {
23286
+ const raw2 = lifecycleFactsFromEntry(entry);
23287
+ if (raw2 === void 0) continue;
23288
+ try {
23289
+ const facts2 = parseNoReceiptLifecycleFacts(raw2);
23290
+ if (facts2.runPointer !== admitted.runDirectory) continue;
23291
+ if (facts2.attemptPointer !== pointer) continue;
23292
+ if (selected === void 0 || facts2.deliveryTurns >= selected.deliveryTurns) {
23293
+ selected = facts2;
23294
+ }
23295
+ } catch {
23296
+ }
23297
+ }
23298
+ return selected;
23299
+ }
23300
+ let attemptStart = 0;
23301
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
23302
+ if (entries[index]?.type === "message" && entries[index]?.message?.role === "user") {
23303
+ attemptStart = index;
23304
+ break;
23305
+ }
23306
+ }
23307
+ const lifecycleEntry = entries.slice(attemptStart).reverse().find((entry) => lifecycleFactsFromEntry(entry) !== void 0);
23308
+ const raw = lifecycleEntry === void 0 ? void 0 : lifecycleFactsFromEntry(lifecycleEntry);
23309
+ if (raw === void 0) return void 0;
23310
+ let facts;
23311
+ try {
23312
+ facts = parseNoReceiptLifecycleFacts(raw);
23313
+ } catch {
23314
+ return void 0;
23315
+ }
23316
+ if (facts.runPointer !== admitted.runDirectory) return void 0;
23317
+ if (facts.attemptPointer !== receiptAttemptPointer(admitted.runDirectory)) return void 0;
23318
+ return facts;
23319
+ }
23320
+ async function settleHostEndedNoReceipt(admitted, authority, scope, issuedDeliveryRequests = 0) {
23321
+ const scopeId = scope?.invocationScopeId?.trim() ?? "";
23322
+ const persisted = scopeId.length > 0 ? void 0 : await readCurrentAttemptNoReceiptFacts(admitted, authority, scope);
23323
+ let terminalToolCalled = persisted?.terminalToolCalled ?? false;
23324
+ let rejectedReceipts = persisted?.rejectedReceipts ?? [];
23325
+ let recordedTurns = persisted?.deliveryTurns ?? 0;
23326
+ if (scopeId.length > 0) {
23327
+ const { sessionFile } = coordinatesFromAdmitted(authority, admitted);
23328
+ const entries = await readBoundSessionEntries(sessionFile).catch(() => void 0);
23329
+ if (entries !== void 0) {
23330
+ const prior = priorReceiptContinuation(entries, scopeId);
23331
+ terminalToolCalled = prior.terminalToolCalled;
23332
+ rejectedReceipts = prior.rejectedReceipts;
23333
+ recordedTurns = prior.deliveryTurns;
23334
+ }
23335
+ }
23093
23336
  const facts = noReceiptLifecycleFacts({
23094
- terminalToolCalled: false,
23095
- rejectedReceipts: [],
23096
- deliveryTurns: RECEIPT_DELIVERY_TURN_LIMIT,
23337
+ terminalToolCalled,
23338
+ rejectedReceipts,
23339
+ deliveryTurns: Math.max(issuedDeliveryRequests, recordedTurns),
23097
23340
  runPointer: admitted.runDirectory,
23098
- attemptPointer: `current:${admitted.runDirectory}`
23341
+ attemptPointer: receiptAttemptPointer(admitted.runDirectory, scope?.invocationScopeId)
23099
23342
  });
23100
23343
  const coordinates = coordinatesFromAdmitted(authority, admitted);
23101
23344
  await clearOppositeTerminalArtifactFace(admitted.runDirectory);
@@ -24668,44 +24911,26 @@ async function settleFailureTerminalResult(admitted, failure, authority, options
24668
24911
  const coordinates = coordinatesFromAdmitted(authority, admitted);
24669
24912
  const { sessionDirectory, sessionFile } = coordinates;
24670
24913
  if (failure.cause === "output") {
24671
- const entries = await readBoundSessionEntries(sessionFile).catch(() => void 0);
24672
- if (entries !== void 0) {
24673
- let attemptStart = 0;
24674
- for (let index = entries.length - 1; index >= 0; index -= 1) {
24675
- if (entries[index]?.type === "message" && entries[index]?.message?.role === "user") {
24676
- attemptStart = index;
24677
- break;
24678
- }
24679
- }
24680
- const lifecycleEntry = entries.slice(attemptStart).reverse().find((entry) => entry.customType === NO_RECEIPT_LIFECYCLE_ENTRY_TYPE || entry.message?.customType === NO_RECEIPT_LIFECYCLE_ENTRY_TYPE);
24681
- const raw = lifecycleEntry?.data ?? lifecycleEntry?.message?.details;
24682
- if (raw !== void 0) {
24683
- let facts;
24684
- try {
24685
- facts = parseNoReceiptLifecycleFacts(raw);
24686
- } catch {
24687
- }
24688
- if (facts !== void 0 && facts.runPointer === admitted.runDirectory && facts.attemptPointer === `current:${admitted.runDirectory}`) {
24689
- let decisiveFacts2 = facts;
24690
- await clearOppositeTerminalArtifactFace(admitted.runDirectory);
24691
- return withOptionalGateProjection(
24692
- {
24693
- roleOutcome: {
24694
- kind: "no_receipt",
24695
- role: admitted.role,
24696
- status: "no-accepted-receipt",
24697
- ...facts,
24698
- decisiveFacts: decisiveFacts2
24699
- },
24700
- navigator: await extractNavigatorFactFromAdmittedSession(sessionFile),
24701
- artifacts: [],
24702
- runId: admitted.runId
24703
- },
24704
- sessionDirectory,
24705
- detourGateContext(admitted, options)
24706
- );
24707
- }
24708
- }
24914
+ const facts = await readCurrentAttemptNoReceiptFacts(admitted, authority, options);
24915
+ if (facts !== void 0) {
24916
+ const decisiveFacts2 = facts;
24917
+ await clearOppositeTerminalArtifactFace(admitted.runDirectory);
24918
+ return withOptionalGateProjection(
24919
+ {
24920
+ roleOutcome: {
24921
+ kind: "no_receipt",
24922
+ role: admitted.role,
24923
+ status: "no-accepted-receipt",
24924
+ ...facts,
24925
+ decisiveFacts: decisiveFacts2
24926
+ },
24927
+ navigator: await extractNavigatorFactFromAdmittedSession(sessionFile),
24928
+ artifacts: [],
24929
+ runId: admitted.runId
24930
+ },
24931
+ sessionDirectory,
24932
+ detourGateContext(admitted, options)
24933
+ );
24709
24934
  }
24710
24935
  }
24711
24936
  const navigator = await extractNavigatorFactFromAdmittedSession(sessionFile);
@@ -24875,16 +25100,19 @@ var init_settlement = __esm({
24875
25100
 
24876
25101
  // src/archivist-record-pointer.ts
24877
25102
  import { mkdirSync as mkdirSync3, writeFileSync } from "node:fs";
25103
+ import { readFile as readFile16 } from "node:fs/promises";
24878
25104
  import { dirname as dirname16, join as join28 } from "node:path";
24879
25105
  function bookDirectOfficerRunPointer(options) {
24880
25106
  const nest = join28(dirname16(options.parentSessionFile), "auditor-roles");
24881
25107
  mkdirSync3(nest, { recursive: true });
25108
+ const submissionToolCallId = options.submissionToolCallId?.trim() ?? "";
24882
25109
  const pointer = {
24883
25110
  version: 1,
24884
25111
  kind: DIRECT_OFFICER_RUN_POINTER_KIND,
24885
25112
  officer: options.officer,
24886
25113
  sessionFile: options.sessionFile,
24887
- ...options.runDirectory !== void 0 && options.runDirectory.trim() !== "" ? { runDirectory: options.runDirectory } : {}
25114
+ ...options.runDirectory !== void 0 && options.runDirectory.trim() !== "" ? { runDirectory: options.runDirectory } : {},
25115
+ ...submissionToolCallId === "" ? {} : { submissionToolCallId }
24888
25116
  };
24889
25117
  writeFileSync(
24890
25118
  join28(nest, `${options.officer}.pointer.json`),
@@ -24894,10 +25122,36 @@ function bookDirectOfficerRunPointer(options) {
24894
25122
  );
24895
25123
  return pointer;
24896
25124
  }
25125
+ async function readDirectOfficerRunPointer(parentSessionFile, officer) {
25126
+ try {
25127
+ const raw = JSON.parse(await readFile16(
25128
+ join28(dirname16(parentSessionFile), "auditor-roles", `${officer}.pointer.json`),
25129
+ "utf8"
25130
+ ));
25131
+ if (!isRecord(raw) || raw.kind !== DIRECT_OFFICER_RUN_POINTER_KIND || raw.version !== 1) {
25132
+ return void 0;
25133
+ }
25134
+ if (raw.officer !== officer) return void 0;
25135
+ if (typeof raw.sessionFile !== "string" || raw.sessionFile.trim() === "") return void 0;
25136
+ const runDirectory = typeof raw.runDirectory === "string" && raw.runDirectory.trim() !== "" ? raw.runDirectory : void 0;
25137
+ const submissionToolCallId = typeof raw.submissionToolCallId === "string" && raw.submissionToolCallId.trim() !== "" ? raw.submissionToolCallId : void 0;
25138
+ return {
25139
+ version: 1,
25140
+ kind: DIRECT_OFFICER_RUN_POINTER_KIND,
25141
+ officer,
25142
+ sessionFile: raw.sessionFile,
25143
+ ...runDirectory === void 0 ? {} : { runDirectory },
25144
+ ...submissionToolCallId === void 0 ? {} : { submissionToolCallId }
25145
+ };
25146
+ } catch {
25147
+ return void 0;
25148
+ }
25149
+ }
24897
25150
  var DIRECT_OFFICER_RUN_POINTER_KIND;
24898
25151
  var init_archivist_record_pointer = __esm({
24899
25152
  "src/archivist-record-pointer.ts"() {
24900
25153
  "use strict";
25154
+ init_unknown_value();
24901
25155
  DIRECT_OFFICER_RUN_POINTER_KIND = "direct-officer-run-pointer";
24902
25156
  }
24903
25157
  });
@@ -24915,6 +25169,7 @@ function createPiDoctorAuditor() {
24915
25169
  submission: options.submission,
24916
25170
  ...auditorRunDirectory(options.context) === void 0 ? {} : { runDirectory: auditorRunDirectory(options.context) },
24917
25171
  ...options.signal === void 0 ? {} : { signal: options.signal },
25172
+ ...options.autoResumeLimit === void 0 ? {} : { autoResumeLimit: options.autoResumeLimit },
24918
25173
  ...options.summonAuditor === void 0 ? {} : { summonAuditor: options.summonAuditor }
24919
25174
  });
24920
25175
  };
@@ -24943,10 +25198,23 @@ async function runJudgeGates(input) {
24943
25198
  if (await input.gateAlreadyConverged(subject)) continue;
24944
25199
  const pass = await input.runGate(subject);
24945
25200
  const received = pass?.status;
24946
- if (pass === void 0 || typeof received !== "string" || !REVIEW_QUEUE_STATUSES.has(received)) {
25201
+ if (pass === void 0 || (typeof received !== "string" || !REVIEW_QUEUE_STATUSES.has(received) && received !== "needs_reask")) {
24947
25202
  throw new Error("judge gate returned no conclusion");
24948
25203
  }
24949
25204
  const status = received;
25205
+ if (status === "needs_reask") {
25206
+ return {
25207
+ status,
25208
+ passes: [{
25209
+ subject,
25210
+ status,
25211
+ receipt: pass.receipt,
25212
+ ...pass.runId === void 0 ? {} : { runId: pass.runId },
25213
+ ...pass.runDirectory === void 0 ? {} : { runDirectory: pass.runDirectory },
25214
+ ...pass.terminal === void 0 ? {} : { terminal: pass.terminal }
25215
+ }]
25216
+ };
25217
+ }
24950
25218
  passes.push({
24951
25219
  subject,
24952
25220
  status,
@@ -25025,7 +25293,7 @@ function createDefaultGateOfficerSummon(options) {
25025
25293
  });
25026
25294
  };
25027
25295
  }
25028
- function bookDirectOfficerPointer(context, officer, result, summoned) {
25296
+ function bookDirectOfficerPointer(context, officer, result, summoned, toolCallId) {
25029
25297
  if (result.status !== "converged" && result.status !== "continue" && result.status !== "escalate" && result.status !== "needs_reask" && result.status !== "transport_failure") {
25030
25298
  return;
25031
25299
  }
@@ -25039,11 +25307,14 @@ function bookDirectOfficerPointer(context, officer, result, summoned) {
25039
25307
  parentSessionFile: parentFile,
25040
25308
  officer,
25041
25309
  sessionFile,
25042
- ...typeof summoned.runDirectory === "string" && summoned.runDirectory.trim() !== "" ? { runDirectory: summoned.runDirectory } : {}
25310
+ ...typeof summoned.runDirectory === "string" && summoned.runDirectory.trim() !== "" ? { runDirectory: summoned.runDirectory } : {},
25311
+ ...toolCallId.trim() === "" ? {} : { submissionToolCallId: toolCallId }
25043
25312
  });
25044
25313
  }
25045
25314
  async function requireSubmissionGate(options) {
25046
25315
  let reask;
25316
+ let reasksSpent = 0;
25317
+ const reaskLimit = deliveryLimitFromConfig(options.autoResumeLimit);
25047
25318
  const summonOfficer = options.summonOfficer ?? createDefaultGateOfficerSummon({
25048
25319
  cwd: options.context.cwd ?? process.cwd()
25049
25320
  });
@@ -25063,7 +25334,8 @@ async function requireSubmissionGate(options) {
25063
25334
  options.context,
25064
25335
  projected.officer,
25065
25336
  gatekeeper,
25066
- projected.summoned
25337
+ projected.summoned,
25338
+ options.toolCallId
25067
25339
  );
25068
25340
  } catch (error) {
25069
25341
  options.hostActions.failInfrastructure(error, options.context, options.toolCallId);
@@ -25086,6 +25358,17 @@ async function requireSubmissionGate(options) {
25086
25358
  };
25087
25359
  }
25088
25360
  if (gatekeeper.status === "needs_reask") {
25361
+ if (reasksSpent >= reaskLimit) {
25362
+ return {
25363
+ status: "needs_reask",
25364
+ officer: projected.officer,
25365
+ receipt: gatekeeper.receipt,
25366
+ ...typeof gatekeeper.runId === "string" && gatekeeper.runId.trim() !== "" ? { runId: gatekeeper.runId } : {},
25367
+ ...typeof projected.summoned?.runDirectory === "string" && projected.summoned.runDirectory.trim() !== "" ? { runDirectory: projected.summoned.runDirectory } : {},
25368
+ ...projected.summoned?.terminal === void 0 ? {} : { terminal: projected.summoned.terminal }
25369
+ };
25370
+ }
25371
+ reasksSpent += 1;
25089
25372
  reask = officerConclusionReask(gatekeeper.receivedStatus);
25090
25373
  continue;
25091
25374
  }
@@ -25115,6 +25398,7 @@ var init_submission_gate = __esm({
25115
25398
  init_archivist_record_pointer();
25116
25399
  init_gatekeeper_role();
25117
25400
  init_submission_errors();
25401
+ init_receipt_delivery_policy();
25118
25402
  init_session_assistant_usage();
25119
25403
  init_unknown_value();
25120
25404
  }
@@ -25172,7 +25456,8 @@ function projectRoleTurnRequest(admitted, roleDetails, options) {
25172
25456
  ...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs },
25173
25457
  ...options.courtAttemptId === void 0 || options.courtAttemptId.length === 0 ? {} : { courtAttemptId: options.courtAttemptId },
25174
25458
  ...options.invocationScopeId === void 0 || options.invocationScopeId.length === 0 ? {} : { invocationScopeId: options.invocationScopeId },
25175
- ...options.stationChild === void 0 ? {} : { stationChild: options.stationChild }
25459
+ ...options.stationChild === void 0 ? {} : { stationChild: options.stationChild },
25460
+ ...options.deliveryRequestLimit === void 0 ? {} : { deliveryRequestLimit: options.deliveryRequestLimit }
25176
25461
  };
25177
25462
  }
25178
25463
  function packagedSettleSkill(admitted) {
@@ -25366,12 +25651,67 @@ function unreadablePostSubmissionStatus(admitted, terminal) {
25366
25651
  const status = receivedDiscriminator(payload, "status");
25367
25652
  return typeof status === "string" && route.statuses.has(status) ? void 0 : route.reask ?? officerConclusionReask(status);
25368
25653
  }
25369
- async function reaskUnreadablePostSubmissionStatus(admitted, terminal, env, io) {
25370
- const message = unreadablePostSubmissionStatus(admitted, terminal);
25654
+ function withUnreadableReask(env) {
25655
+ const spent = env.unreadableReasksSpent ?? 0;
25656
+ if (spent >= deliveryLimitFromConfig(env.autoResumeLimit)) return void 0;
25657
+ return { ...env, unreadableReasksSpent: spent + 1 };
25658
+ }
25659
+ function isUnreadableReaskExhausted(value) {
25660
+ return value === UNREADABLE_REASK_EXHAUSTED;
25661
+ }
25662
+ function presentOriginalVolume(held, terminal, io) {
25663
+ if (terminal?.roleOutcome.decisiveFacts?.directionUnsettled === true) {
25664
+ io.stdout(formatTerminalResult(terminal));
25665
+ return;
25666
+ }
25667
+ if (held.length > 0) {
25668
+ for (const value of held) io.stdout(value);
25669
+ return;
25670
+ }
25671
+ if (terminal !== void 0) io.stdout(formatTerminalResult(terminal));
25672
+ }
25673
+ function withUnsettledDirection(parent, officer) {
25674
+ const outcome = parent.roleOutcome;
25675
+ if (outcome.kind !== "accepted" && outcome.kind !== "audit_escalation") return parent;
25676
+ const officerOutcome = officer?.roleOutcome;
25677
+ const officerPayloads = coalesceSubmissionRows(
25678
+ officer?.submissions,
25679
+ officerOutcome !== void 0 && officerOutcome.kind !== "no_receipt" ? officerOutcome.payloads : void 0
25680
+ );
25681
+ return {
25682
+ ...parent,
25683
+ roleOutcome: {
25684
+ ...outcome,
25685
+ decisiveFacts: {
25686
+ ...outcome.decisiveFacts ?? {},
25687
+ directionUnsettled: true,
25688
+ subsequentAudit: "incomplete",
25689
+ ...officerOutcome === void 0 ? {} : { officerRole: officerOutcome.role },
25690
+ ...officer?.runId === void 0 ? {} : { officerRunId: officer.runId },
25691
+ ...officerPayloads.length === 0 ? {} : { officerPayloads }
25692
+ }
25693
+ }
25694
+ };
25695
+ }
25696
+ function heldUnreadableTerminal(terminal) {
25697
+ if (terminal?.roleOutcome.kind !== "accepted") return false;
25698
+ if (latestPayloadEscalated(terminal.roleOutcome)) return false;
25699
+ const status = latestQueueStatus(terminal);
25700
+ return typeof status !== "string" || !REVIEW_QUEUE_STATUSES.has(status);
25701
+ }
25702
+ function presentUnsettledAudit(parent, officer, io) {
25703
+ const terminal = withUnsettledDirection(parent, officer);
25704
+ io.stdout(formatTerminalResult(terminal));
25705
+ if (officer !== void 0) io.stdout(formatTerminalResult(officer));
25706
+ return terminal;
25707
+ }
25708
+ async function reaskUnreadablePostSubmissionStatus(admitted, terminal, env, io, message = unreadablePostSubmissionStatus(admitted, terminal)) {
25371
25709
  if (message === void 0) return void 0;
25710
+ const next = withUnreadableReask(env);
25711
+ if (next === void 0) return UNREADABLE_REASK_EXHAUSTED;
25372
25712
  return runPublicInstructionSeatResume(
25373
25713
  { runId: admitted.runId, message },
25374
- { ...env, autoResumeLimit: 0 },
25714
+ next,
25375
25715
  io
25376
25716
  );
25377
25717
  }
@@ -25525,6 +25865,11 @@ async function dispatchAdmitted(admitted, env, io) {
25525
25865
  env,
25526
25866
  io
25527
25867
  );
25868
+ if (isUnreadableReaskExhausted(unreadableReask)) {
25869
+ const terminal = result.terminal === void 0 ? void 0 : withUnsettledDirection(result.terminal);
25870
+ presentOriginalVolume(held, terminal, io);
25871
+ return terminal === void 0 ? result : { ...result, terminal };
25872
+ }
25528
25873
  if (unreadableReask !== void 0) return unreadableReask;
25529
25874
  if (AUDITED_ROLES.has(admitted.role) && result.terminal?.roleOutcome.kind === "accepted") {
25530
25875
  return auditSubmittedRole(result, env, io);
@@ -25656,20 +26001,16 @@ async function runCountersignBody(parsed, env, io) {
25656
26001
  await persistAdmittedSourceRunPath(admitted, gateParentRunPath);
25657
26002
  admitted = { ...admitted, sourceRunPath: gateParentRunPath };
25658
26003
  }
25659
- const turnProjection = {
25660
- ...projectPublicTurnAxes(env),
25661
- ...env.correlationId === void 0 || env.correlationId.trim() === "" ? {} : { correlationId: env.correlationId },
25662
- continuation: {
25663
- kind: "initial",
25664
- prompt: env.reviewReask ?? env.gateReviewInstruction ?? buildInstructionTransportPrompt(
25665
- admitted,
25666
- engineSessionMaterialFromOptions({
25667
- ...pickEngineAxis(env),
25668
- packageRoot: env.packageRoot
25669
- })
25670
- )
25671
- }
25672
- };
26004
+ const turnProjection = roleTurnOptions(env, admitted, {
26005
+ kind: "initial",
26006
+ prompt: env.reviewReask ?? env.gateReviewInstruction ?? buildInstructionTransportPrompt(
26007
+ admitted,
26008
+ engineSessionMaterialFromOptions({
26009
+ ...pickEngineAxis(env),
26010
+ packageRoot: env.packageRoot
26011
+ })
26012
+ )
26013
+ });
25673
26014
  const turnRequest = buildInstructionSeatTurnRequest(admitted, turnProjection);
25674
26015
  const result = await runPostAdmissionOneShot({
25675
26016
  admitted,
@@ -25938,7 +26279,23 @@ async function runPublicInstructionSeatResume(request, env, io) {
25938
26279
  },
25939
26280
  afterAdmittedLoad: async (admitted) => {
25940
26281
  await warnMissingMethodSkills(env.home, env.host, admitted.role, requiredMethodSkills(admitted), io.stdout);
25941
- return { kind: "continue", adapters: seatAdapters(admitted, env) };
26282
+ const adapters = seatAdapters(admitted, env);
26283
+ if ((env.unreadableReasksSpent ?? 0) === 0 && env.reviewReask === void 0) {
26284
+ return { kind: "continue", adapters };
26285
+ }
26286
+ const original = await adapters.trySettle(
26287
+ admitted,
26288
+ env.principalAuthority,
26289
+ await readCurrentCourt(admitted.runDirectory)
26290
+ );
26291
+ const unsettled = POST_SUBMISSION_ROUTING[admitted.role] === void 0 ? heldUnreadableTerminal(original) : unreadablePostSubmissionStatus(admitted, original) !== void 0;
26292
+ return {
26293
+ kind: "continue",
26294
+ adapters: original === void 0 || !unsettled ? adapters : {
26295
+ ...adapters,
26296
+ trySettle: async (seat, authority, scope) => await adapters.trySettle(seat, authority, scope) ?? original
26297
+ }
26298
+ };
25942
26299
  },
25943
26300
  ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
25944
26301
  });
@@ -25948,6 +26305,11 @@ async function runPublicInstructionSeatResume(request, env, io) {
25948
26305
  env,
25949
26306
  io
25950
26307
  );
26308
+ if (isUnreadableReaskExhausted(unreadableReask)) {
26309
+ const terminal = result.terminal === void 0 ? void 0 : withUnsettledDirection(result.terminal);
26310
+ presentOriginalVolume(held, terminal, io);
26311
+ return terminal === void 0 ? result : { ...result, terminal };
26312
+ }
25951
26313
  if (unreadableReask !== void 0) return unreadableReask;
25952
26314
  if (result.admitted !== void 0 && AUDITED_ROLES.has(result.admitted.role) && result.terminal?.roleOutcome.kind === "accepted") {
25953
26315
  return auditSubmittedRole(result, env, io);
@@ -25973,22 +26335,42 @@ async function runPublicInstructionSeatResume(request, env, io) {
25973
26335
  }
25974
26336
  async function queueConclusionFromChild(child, env, io) {
25975
26337
  if (!GATE_CHILD_ROLES.has(child.role)) return void 0;
26338
+ if (child.role === "countersign") {
26339
+ const terminal = await trySettlePublicSeat(
26340
+ child,
26341
+ env.principalAuthority,
26342
+ await readCurrentCourt(child.runDirectory)
26343
+ );
26344
+ const status = latestQueueStatus(terminal);
26345
+ if (terminal !== void 0 && typeof status === "string" && REVIEW_QUEUE_STATUSES.has(status)) {
26346
+ return { admitted: child, terminal, status };
26347
+ }
26348
+ return { stop: { exitCode: 0, ...terminal === void 0 ? {} : { terminal } } };
26349
+ }
25976
26350
  let current = child;
26351
+ let budgetEnv = { ...env, unreadableReasksSpent: 0 };
25977
26352
  for (; ; ) {
25978
26353
  const terminal = await trySettlePublicSeat(
25979
26354
  current,
25980
26355
  env.principalAuthority,
25981
- void 0
26356
+ await readCurrentCourt(current.runDirectory)
25982
26357
  );
25983
26358
  const status = latestQueueStatus(terminal);
25984
26359
  if (terminal !== void 0 && typeof status === "string" && REVIEW_QUEUE_STATUSES.has(status)) {
25985
26360
  return { admitted: current, terminal, status };
25986
26361
  }
25987
- const reasked = await runPublicInstructionSeatResume({
25988
- runId: current.runId,
25989
- message: officerConclusionReask(status)
25990
- }, env, io);
25991
- if (reasked.exitCode !== 0 || reasked.admitted === void 0 || reasked.terminal === void 0) {
26362
+ const reasked = await reaskUnreadablePostSubmissionStatus(
26363
+ current,
26364
+ terminal,
26365
+ budgetEnv,
26366
+ io,
26367
+ officerConclusionReask(status)
26368
+ );
26369
+ if (reasked === void 0 || isUnreadableReaskExhausted(reasked)) {
26370
+ return { stop: { exitCode: 0, ...terminal === void 0 ? {} : { terminal } } };
26371
+ }
26372
+ budgetEnv = withUnreadableReask(budgetEnv);
26373
+ if (reasked.exitCode !== 0 || reasked.admitted === void 0 || reasked.terminal === void 0 || reasked.terminal.roleOutcome.kind === "no_receipt" || reasked.terminal.roleOutcome.decisiveFacts?.directionUnsettled === true) {
25992
26374
  return { stop: reasked };
25993
26375
  }
25994
26376
  const reaskedStatus = latestQueueStatus(reasked.terminal);
@@ -26006,7 +26388,17 @@ async function continueParentAfterChild(parentRunId, child, env, io) {
26006
26388
  }
26007
26389
  const admitted = loaded.admitted;
26008
26390
  const resolved = await queueConclusionFromChild(child, env, io);
26009
- if (resolved !== void 0 && "stop" in resolved) return resolved.stop;
26391
+ if (resolved !== void 0 && "stop" in resolved) {
26392
+ const stopped = resolved.stop;
26393
+ if (stopped.exitCode === 0 && heldUnreadableTerminal(stopped.terminal) && stopped.terminal !== void 0) {
26394
+ const parentTerminal = await trySettlePublicSeat(admitted, env.principalAuthority, void 0);
26395
+ if (parentTerminal?.roleOutcome.kind === "accepted" || parentTerminal?.roleOutcome.kind === "audit_escalation") {
26396
+ const terminal = presentUnsettledAudit(parentTerminal, stopped.terminal, io);
26397
+ return { exitCode: 0, admitted, terminal };
26398
+ }
26399
+ }
26400
+ return stopped;
26401
+ }
26010
26402
  if (resolved !== void 0 && resolved.status === "escalate") {
26011
26403
  return { exitCode: 0, admitted: resolved.admitted, terminal: resolved.terminal };
26012
26404
  }
@@ -26014,37 +26406,67 @@ async function continueParentAfterChild(parentRunId, child, env, io) {
26014
26406
  if (AUDITED_ROLES.has(admitted.role) && resolved.status === "converged") {
26015
26407
  const terminal = await trySettlePublicSeat(admitted, env.principalAuthority, void 0);
26016
26408
  if (terminal?.roleOutcome.kind !== "accepted") throw new Error("pending submission is not recorded");
26017
- return auditSubmittedRole({ exitCode: 0, admitted, terminal }, env, io, resolved.admitted.role, latestQueuePayload(resolved.terminal), resolved.admitted.runId);
26409
+ return auditSubmittedRole({ exitCode: 0, admitted, terminal }, env, io, resolved.admitted, latestQueuePayload(resolved.terminal));
26018
26410
  }
26019
26411
  return runPublicInstructionSeatResume({
26020
26412
  runId: parentRunId,
26021
26413
  message: readableGateItem(latestQueuePayload(resolved.terminal))
26022
- }, { ...env, autoResumeLimit: 0 }, io);
26414
+ }, { ...env, unreadableReasksSpent: 0 }, io);
26023
26415
  }
26024
26416
  const result = await dispatchAdmitted(admitted, env, { ...io, omitFailureStderrDiagnostic: true });
26025
26417
  showResumeErrorPointer(io, result.exitCode, result.terminal);
26026
26418
  return result;
26027
26419
  }
26028
- async function auditSubmittedRole(turn, env, io, passedOfficer, passedReceipt, passedRunId) {
26420
+ async function officerPassedCurrentSubmission(input) {
26421
+ const { env, officer } = input;
26422
+ const pointer = await readDirectOfficerRunPointer(input.parentSessionFile, officer);
26423
+ if (pointer?.runDirectory === void 0) return false;
26424
+ if (pointer.submissionToolCallId !== input.toolCallId) return false;
26425
+ const officerRunId = runIdFromRunDirectory(pointer.runDirectory);
26426
+ if (officerRunId === void 0) return false;
26427
+ let admitted;
26428
+ try {
26429
+ const loaded = await loadResumablePublicRole(
26430
+ env.home,
26431
+ officerRunId,
26432
+ env.principalAuthority
26433
+ );
26434
+ admitted = loaded.admitted;
26435
+ } catch {
26436
+ return false;
26437
+ }
26438
+ if (admitted.role !== officer) return false;
26439
+ const court = await readCurrentCourt(admitted.runDirectory);
26440
+ const terminal = await trySettlePublicSeat(admitted, env.principalAuthority, court);
26441
+ return latestQueueStatus(terminal) === "converged";
26442
+ }
26443
+ async function auditSubmittedRole(turn, env, io, resumedOfficer, passedReceipt) {
26029
26444
  const admitted = turn.admitted;
26030
26445
  if (admitted === void 0 || !AUDITED_ROLES.has(admitted.role) || turn.terminal?.roleOutcome.kind !== "accepted") return turn;
26031
26446
  const accepted = turn.terminal.roleOutcome.payloads?.at(-1);
26032
26447
  if (accepted === void 0) throw new Error("accepted submission has no payload");
26033
26448
  const record = isRecord(accepted) ? accepted : void 0;
26034
26449
  const status = admitted.role === "secretariat" ? record?.secretariatStatus : record?.status;
26450
+ const gateOwnsStatusReask = typeof env.parentRunPath === "string" && env.parentRunPath.trim() !== "";
26035
26451
  if (admitted.role === "secretariat" && status !== "converged" && status !== "escalate") {
26036
- return runPublicInstructionSeatResume(
26037
- { runId: admitted.runId, message: SECRETARIAT_STATUS_REASK },
26038
- { ...env, autoResumeLimit: 0 },
26039
- io
26040
- );
26452
+ if (gateOwnsStatusReask) return turn;
26453
+ const next = withUnreadableReask(env);
26454
+ if (next === void 0) {
26455
+ const terminal2 = withUnsettledDirection(turn.terminal);
26456
+ io.stdout(formatTerminalResult(terminal2));
26457
+ return { ...turn, terminal: terminal2 };
26458
+ }
26459
+ return runPublicInstructionSeatResume({ runId: admitted.runId, message: SECRETARIAT_STATUS_REASK }, next, io);
26041
26460
  }
26042
26461
  if (admitted.role === "countersign" && (typeof status !== "string" || !REVIEW_QUEUE_STATUSES.has(status))) {
26043
- return runPublicInstructionSeatResume(
26044
- { runId: admitted.runId, message: officerConclusionReask(status) },
26045
- { ...env, autoResumeLimit: 0 },
26046
- io
26047
- );
26462
+ if (gateOwnsStatusReask) return turn;
26463
+ const next = withUnreadableReask(env);
26464
+ if (next === void 0) {
26465
+ const terminal2 = withUnsettledDirection(turn.terminal);
26466
+ io.stdout(formatTerminalResult(terminal2));
26467
+ return { ...turn, terminal: terminal2 };
26468
+ }
26469
+ return runPublicInstructionSeatResume({ runId: admitted.runId, message: officerConclusionReask(status) }, next, io);
26048
26470
  }
26049
26471
  const selfEscalationSkipsAudit = status === "escalate" && (admitted.role === "judge" || admitted.role === "secretariat" || admitted.role === "countersign");
26050
26472
  const skipAudit = selfEscalationSkipsAudit || (admitted.role === "fixer" || admitted.role === "coder") && (typeof status !== "string" || !WORKER_DONE_STATUSES.has(status));
@@ -26074,12 +26496,19 @@ async function auditSubmittedRole(turn, env, io, passedOfficer, passedReceipt, p
26074
26496
  abort() {
26075
26497
  }
26076
26498
  };
26499
+ const passedThisSubmission = (officer) => officerPassedCurrentSubmission({
26500
+ env,
26501
+ parentSessionFile: sessionFile,
26502
+ officer,
26503
+ toolCallId
26504
+ });
26077
26505
  if (admitted.role === "doctor") {
26078
- if (passedOfficer !== "auditor") {
26506
+ if (!await passedThisSubmission("auditor")) {
26079
26507
  let lastSummon;
26080
26508
  const decision = await createPiDoctorAuditor()({
26081
26509
  context,
26082
26510
  submission: accepted,
26511
+ ...env.autoResumeLimit === void 0 ? {} : { autoResumeLimit: env.autoResumeLimit },
26083
26512
  ...env.signal === void 0 ? {} : { signal: env.signal },
26084
26513
  summonAuditor: async (subject, sourceRunDirectory, signal, reask, submission) => {
26085
26514
  const summoned = await summonPublicRole({
@@ -26108,6 +26537,7 @@ async function auditSubmittedRole(turn, env, io, passedOfficer, passedReceipt, p
26108
26537
  parentSessionFile: sessionFile,
26109
26538
  officer: "auditor",
26110
26539
  sessionFile: officerSession,
26540
+ submissionToolCallId: toolCallId,
26111
26541
  ...summoned.runDirectory === void 0 ? {} : { runDirectory: summoned.runDirectory }
26112
26542
  });
26113
26543
  }
@@ -26119,7 +26549,15 @@ async function auditSubmittedRole(turn, env, io, passedOfficer, passedReceipt, p
26119
26549
  return runPublicInstructionSeatResume({
26120
26550
  runId: admitted.runId,
26121
26551
  message: readableGateItem(decision.receipt ?? decision.violations)
26122
- }, { ...env, autoResumeLimit: 0 }, io);
26552
+ }, { ...env, unreadableReasksSpent: 0 }, io);
26553
+ }
26554
+ if (decision.status === "received") {
26555
+ if (lastSummon?.terminal === void 0) {
26556
+ throw new Error("doctor audit kept an unreadable reply with no terminal");
26557
+ }
26558
+ if (turn.terminal === void 0) throw new Error("doctor submission has no terminal");
26559
+ const terminal2 = presentUnsettledAudit(turn.terminal, lastSummon.terminal, io);
26560
+ return { exitCode: 0, admitted, terminal: terminal2 };
26123
26561
  }
26124
26562
  if (decision.status !== "converged") {
26125
26563
  if (lastSummon?.terminal !== void 0) {
@@ -26142,13 +26580,14 @@ async function auditSubmittedRole(turn, env, io, passedOfficer, passedReceipt, p
26142
26580
  ...env.hostAdapters === void 0 ? {} : { hostAdapters: env.hostAdapters }
26143
26581
  });
26144
26582
  let chain;
26145
- let officerRunId = passedRunId;
26583
+ let officerRunId = resumedOfficer?.runId;
26146
26584
  const runGate = (subject) => requireSubmissionGate({
26147
26585
  context,
26148
26586
  subject,
26149
26587
  toolCallId,
26150
26588
  submission: accepted,
26151
26589
  summonOfficer,
26590
+ ...env.autoResumeLimit === void 0 ? {} : { autoResumeLimit: env.autoResumeLimit },
26152
26591
  ...env.signal === void 0 ? {} : { signal: env.signal },
26153
26592
  hostActions: {
26154
26593
  failInfrastructure(error) {
@@ -26160,13 +26599,13 @@ async function auditSubmittedRole(turn, env, io, passedOfficer, passedReceipt, p
26160
26599
  });
26161
26600
  if (admitted.role === "judge") {
26162
26601
  chain = await runJudgeGates({
26163
- gateAlreadyConverged: async (subject) => passedOfficer === "auditor" || passedOfficer === "notary" && subject.kind === "judge_draft",
26602
+ gateAlreadyConverged: async (subject) => passedThisSubmission(gateOfficerForSubject(subject)),
26164
26603
  runGate
26165
26604
  });
26166
26605
  } else {
26167
26606
  const subject = admitted.role === "fixer" || admitted.role === "coder" ? { kind: "worker_completion" } : admitted.role === "secretariat" ? { kind: "secretariat_verdict" } : { kind: "countersign_verdict" };
26168
26607
  const officer = gateOfficerForSubject(subject);
26169
- if (passedOfficer === officer) {
26608
+ if (await passedThisSubmission(officer)) {
26170
26609
  chain = { status: "converged", passes: [] };
26171
26610
  } else {
26172
26611
  const pass = await runGate(subject);
@@ -26179,17 +26618,29 @@ async function auditSubmittedRole(turn, env, io, passedOfficer, passedReceipt, p
26179
26618
  status: pass.status,
26180
26619
  receipt: pass.receipt,
26181
26620
  ...pass.runId === void 0 ? {} : { runId: pass.runId },
26182
- ...pass.runDirectory === void 0 ? {} : { runDirectory: pass.runDirectory }
26621
+ ...pass.runDirectory === void 0 ? {} : { runDirectory: pass.runDirectory },
26622
+ ...pass.terminal === void 0 ? {} : { terminal: pass.terminal }
26183
26623
  }]
26184
26624
  };
26185
26625
  }
26186
26626
  }
26627
+ if (chain.status === "needs_reask") {
26628
+ const officerTerminal = chain.passes.at(-1)?.terminal;
26629
+ if (officerTerminal === void 0) throw new Error("unreadable audit has no terminal result");
26630
+ if (turn.terminal === void 0) throw new Error("audited submission has no terminal");
26631
+ const terminal2 = presentUnsettledAudit(turn.terminal, officerTerminal, io);
26632
+ return { exitCode: 0, admitted, terminal: terminal2 };
26633
+ }
26187
26634
  if (chain.status === "escalate") {
26188
26635
  const escalation = chain.passes.at(-1);
26189
26636
  const escalatedRunId = escalation?.runId ?? (escalation?.runDirectory === void 0 ? void 0 : runIdFromRunDirectory(escalation.runDirectory));
26190
26637
  if (escalatedRunId === void 0) throw new Error("escalated audit has no resumable run identity");
26191
26638
  const officer = await loadResumablePublicRole(env.home, escalatedRunId, env.principalAuthority);
26192
- const terminal2 = await trySettlePublicSeat(officer.admitted, env.principalAuthority, void 0);
26639
+ const terminal2 = await trySettlePublicSeat(
26640
+ officer.admitted,
26641
+ env.principalAuthority,
26642
+ await readCurrentCourt(officer.admitted.runDirectory)
26643
+ );
26193
26644
  if (terminal2 === void 0) throw new Error("escalated audit has no terminal result");
26194
26645
  io.stdout(formatTerminalResult(terminal2));
26195
26646
  return { exitCode: 0, admitted: officer.admitted, terminal: terminal2 };
@@ -26198,7 +26649,7 @@ async function auditSubmittedRole(turn, env, io, passedOfficer, passedReceipt, p
26198
26649
  return runPublicInstructionSeatResume({
26199
26650
  runId: admitted.runId,
26200
26651
  message: readableGateItem(chain.passes.at(-1)?.receipt)
26201
- }, { ...env, autoResumeLimit: 0 }, io);
26652
+ }, { ...env, unreadableReasksSpent: 0 }, io);
26202
26653
  }
26203
26654
  if (admitted.role === "secretariat") {
26204
26655
  const pass = chain.passes.at(-1);
@@ -26218,7 +26669,7 @@ async function auditSubmittedRole(turn, env, io, passedOfficer, passedReceipt, p
26218
26669
  io.stdout(formatTerminalResult(terminal));
26219
26670
  return turn;
26220
26671
  }
26221
- var AUDITED_ROLES, SECRETARIAT_STATUS_REASK, WORKER_ROUTING_STATUSES, WORKER_STATUS_REASK, DOCTOR_ROUTING_STATUSES, DOCTOR_STATUS_REASK, POST_SUBMISSION_ROUTING, GATE_CHILD_ROLES;
26672
+ var AUDITED_ROLES, SECRETARIAT_STATUS_REASK, WORKER_ROUTING_STATUSES, WORKER_STATUS_REASK, DOCTOR_ROUTING_STATUSES, DOCTOR_STATUS_REASK, POST_SUBMISSION_ROUTING, UNREADABLE_REASK_EXHAUSTED, GATE_CHILD_ROLES;
26222
26673
  var init_instruction_seat_run = __esm({
26223
26674
  "src/public-cli/instruction-seat-run.ts"() {
26224
26675
  "use strict";
@@ -26233,6 +26684,7 @@ var init_instruction_seat_run = __esm({
26233
26684
  init_worker_submission_contracts();
26234
26685
  init_secretariat_contracts();
26235
26686
  init_readable_gate_item();
26687
+ init_receipt_delivery_policy();
26236
26688
  init_run_terminal_artifacts();
26237
26689
  init_submission_gate();
26238
26690
  init_submission_ledger();
@@ -26290,6 +26742,7 @@ var init_instruction_seat_run = __esm({
26290
26742
  reask: DOCTOR_STATUS_REASK
26291
26743
  }
26292
26744
  };
26745
+ UNREADABLE_REASK_EXHAUSTED = { unreadableReaskExhausted: true };
26293
26746
  GATE_CHILD_ROLES = /* @__PURE__ */ new Set(["notary", "auditor", "inspector", "countersign"]);
26294
26747
  }
26295
26748
  });
@@ -26910,10 +27363,14 @@ async function runComplianceAudit(options) {
26910
27363
  });
26911
27364
  });
26912
27365
  let reask;
27366
+ let reasksSpent = 0;
27367
+ const reaskLimit = deliveryLimitFromConfig(options.autoResumeLimit);
26913
27368
  for (; ; ) {
26914
27369
  const summoned = await summon(subject, runDirectory, options.signal, reask, submission);
26915
27370
  const decision = await projectAuditorTerminal(summoned);
26916
27371
  if (decision.status === "received") {
27372
+ if (reasksSpent >= reaskLimit) return decision;
27373
+ reasksSpent += 1;
26917
27374
  reask = officerConclusionReask(receivedDiscriminator(decision.reply, "status"));
26918
27375
  continue;
26919
27376
  }
@@ -26929,6 +27386,7 @@ var init_compliance_transport = __esm({
26929
27386
  init_submission_errors();
26930
27387
  init_terminal();
26931
27388
  init_readable_gate_item();
27389
+ init_receipt_delivery_policy();
26932
27390
  init_unknown_value();
26933
27391
  AUDITOR_DOSSIER_PROMPT = "\u5377\u5B97\u6307\u9488\uFF1A";
26934
27392
  AUDITOR_PARENT_ATTEMPT_BINDING_ENTRY_TYPE = "ak_auditor_parent_attempt_binding";
@@ -27062,7 +27520,7 @@ __export(run_lifecycle_exports, {
27062
27520
  renderResumeCommand: () => renderResumeCommand,
27063
27521
  writeRoleRunState: () => writeRoleRunState
27064
27522
  });
27065
- import { chmod, lstat as lstat5, open, readdir as readdir6, readFile as readFile16, unlink as unlink4, writeFile as writeFile5 } from "node:fs/promises";
27523
+ import { chmod, lstat as lstat5, open, readdir as readdir6, readFile as readFile17, unlink as unlink4, writeFile as writeFile5 } from "node:fs/promises";
27066
27524
  import { basename as basename8, join as join31 } from "node:path";
27067
27525
  function buildAutoResumeContinuationPrompt(options) {
27068
27526
  return appendEngineSessionMaterial(
@@ -27139,7 +27597,7 @@ function parseCurrentCourtState(raw) {
27139
27597
  async function readRoleRunStateRaw(runDirectory) {
27140
27598
  let raw;
27141
27599
  try {
27142
- raw = JSON.parse(await readFile16(join31(runDirectory, RUN_STATE_FILE), "utf8"));
27600
+ raw = JSON.parse(await readFile17(join31(runDirectory, RUN_STATE_FILE), "utf8"));
27143
27601
  } catch (error) {
27144
27602
  if (errorCodeOf(error) === "ENOENT") return void 0;
27145
27603
  throw error;
@@ -27397,7 +27855,7 @@ function isProcessAlive(pid) {
27397
27855
  async function autopsyWriterLock(lockPath) {
27398
27856
  let content;
27399
27857
  try {
27400
- content = await readFile16(lockPath, "utf8");
27858
+ content = await readFile17(lockPath, "utf8");
27401
27859
  } catch (error) {
27402
27860
  if (errorCodeOf(error) === "ENOENT") return { verdict: "absent" };
27403
27861
  return { verdict: "unknown", reason: "unreadable", readFailure: error };
@@ -27594,7 +28052,7 @@ async function readRunParentPath(runDirectory) {
27594
28052
  let raw;
27595
28053
  try {
27596
28054
  raw = JSON.parse(
27597
- await readFile16(join31(runDirectory, "admitted-request.json"), "utf8")
28055
+ await readFile17(join31(runDirectory, "admitted-request.json"), "utf8")
27598
28056
  );
27599
28057
  } catch (error) {
27600
28058
  if (errorCodeOf(error) === "ENOENT") return void 0;
@@ -27709,7 +28167,7 @@ async function loadResumableRunRecord(home, runId, authority) {
27709
28167
  let sourceRun;
27710
28168
  try {
27711
28169
  const raw = JSON.parse(
27712
- await readFile16(run.admittedRequestPath, "utf8")
28170
+ await readFile17(run.admittedRequestPath, "utf8")
27713
28171
  );
27714
28172
  if (isRecord(raw)) {
27715
28173
  const record = raw;
@@ -27831,7 +28289,7 @@ async function loadResumableRunRecord(home, runId, authority) {
27831
28289
  let model;
27832
28290
  try {
27833
28291
  const invocationRaw = JSON.parse(
27834
- await readFile16(join31(run.runDirectory, "invocation.json"), "utf8")
28292
+ await readFile17(join31(run.runDirectory, "invocation.json"), "utf8")
27835
28293
  );
27836
28294
  if (isRecord(invocationRaw)) {
27837
28295
  const rec = invocationRaw;
@@ -28196,7 +28654,7 @@ var init_run_lifecycle = __esm({
28196
28654
  });
28197
28655
 
28198
28656
  // src/session-identity.ts
28199
- import { mkdir as mkdir3, readFile as readFile17, rename as rename2, writeFile as writeFile6 } from "node:fs/promises";
28657
+ import { mkdir as mkdir3, readFile as readFile18, rename as rename2, writeFile as writeFile6 } from "node:fs/promises";
28200
28658
  import { dirname as dirname18, join as join32 } from "node:path";
28201
28659
  function createSessionIdentityAuthority(authority, sessionBindingFile) {
28202
28660
  const bindingPath = (principal) => join32(authority.decode(principal).sessionDirectory, sessionBindingFile);
@@ -28206,7 +28664,7 @@ function createSessionIdentityAuthority(authority, sessionBindingFile) {
28206
28664
  },
28207
28665
  async load(principal) {
28208
28666
  try {
28209
- const value = JSON.parse(await readFile17(bindingPath(principal), "utf8"));
28667
+ const value = JSON.parse(await readFile18(bindingPath(principal), "utf8"));
28210
28668
  if (typeof value !== "object" || value === null || typeof value.sessionId !== "string") {
28211
28669
  throw new Error("durable session binding is invalid");
28212
28670
  }
@@ -28850,8 +29308,203 @@ async function settleDeferredPersist(admitted, authority, adapters, io, result)
28850
29308
  io,
28851
29309
  true
28852
29310
  );
28853
- return { ...failed, turnDispatched: true, skipAutoResume: true };
29311
+ return {
29312
+ ...failed,
29313
+ turnDispatched: true,
29314
+ skipAutoResume: true
29315
+ };
29316
+ }
29317
+ }
29318
+ function settlementScopeForTurn(request) {
29319
+ const hasCourt = request.courtAttemptId !== void 0 && request.courtAttemptId.length > 0;
29320
+ const hasScope = request.invocationScopeId !== void 0 && request.invocationScopeId.length > 0;
29321
+ if (!hasCourt && !hasScope) return void 0;
29322
+ return {
29323
+ ...hasCourt ? { courtAttemptId: request.courtAttemptId } : {},
29324
+ ...hasScope ? { invocationScopeId: request.invocationScopeId } : {}
29325
+ };
29326
+ }
29327
+ async function buildReceiptDeliveryRequest(input) {
29328
+ const { admitted, env, request, receiptDelivery } = input;
29329
+ const hostSessionId = await readStoredHostSessionId(
29330
+ env.host,
29331
+ env.principalAuthority,
29332
+ admitted.principal
29333
+ );
29334
+ return {
29335
+ ...request,
29336
+ continuation: {
29337
+ kind: "resume",
29338
+ prompt: JSON.stringify({
29339
+ ...receiptDelivery.deliveryState(),
29340
+ deliveryTurns: receiptDelivery.issuedDeliveryRequests() + 1
29341
+ }),
29342
+ ...hostSessionId === void 0 ? {} : { hostSessionId }
29343
+ },
29344
+ deliveryRequestLimit: receiptDelivery.limit
29345
+ };
29346
+ }
29347
+ async function settleCompletedHostTurn(input) {
29348
+ const { admitted, env, io, adapters, shouldPresent, request, result, persistRunState, deferredPersist } = input;
29349
+ const finishAfterTurn = input.finishAfterTurn;
29350
+ let stderrLogWriteFailure;
29351
+ try {
29352
+ await writeFile7(
29353
+ join35(admitted.runDirectory, "stderr.log"),
29354
+ result.stderr,
29355
+ "utf8"
29356
+ );
29357
+ } catch (error) {
29358
+ stderrLogWriteFailure = error;
29359
+ await recordBestEffortPostDispatchDiagnostic(
29360
+ admitted,
29361
+ env,
29362
+ `stderr.log write failed (best-effort continue): ${describeErrorIdentity(error)}`,
29363
+ io
29364
+ );
29365
+ }
29366
+ const courtScope = settlementScopeForTurn(request);
29367
+ let settled;
29368
+ let settledOutcome;
29369
+ let hostSignalFailed = false;
29370
+ let resolution;
29371
+ try {
29372
+ const sessionFile = admitted.principal !== void 0 ? env.principalAuthority.decode(admitted.principal).sessionFile : "";
29373
+ const runnerKnownFailure = adapters.resolveRunnerKnownFailure !== void 0 && sessionFile !== "" ? await adapters.resolveRunnerKnownFailure({ result, sessionFile }) : result.knownFailure;
29374
+ resolution = await resolveAuditedRunnerFailureResolution({
29375
+ runner: runnerKnownFailure,
29376
+ sessionFile,
29377
+ credential: void 0,
29378
+ runDirectory: admitted.runDirectory
29379
+ });
29380
+ const processCancelName = processCancelSignalName(env.signal);
29381
+ const directHostFailureSignal = result.timedOut || result.knownFailure !== void 0 || runnerKnownFailure !== void 0 || processCancelName !== void 0;
29382
+ hostSignalFailed = directHostFailureSignal || result.code !== null && result.code !== 0 || resolution.knownFailure !== void 0;
29383
+ settled = await adapters.trySettle(admitted, env.principalAuthority, courtScope);
29384
+ if (settled !== void 0) {
29385
+ settled = await attachRecordedSubmissions(admitted, settled, courtScope);
29386
+ }
29387
+ const settledIsFreshThisAttempt = settled === void 0 || settled.roleOutcome.kind !== "accepted" && settled.roleOutcome.kind !== "audit_escalation" ? true : await attemptProducedFreshSubmission(admitted, courtScope);
29388
+ const staleAcceptanceOutranksRealFailure = !settledIsFreshThisAttempt && hostSignalFailed;
29389
+ const cancelAfterSettle = processCancelSignalName(env.signal);
29390
+ if (settled !== void 0 && shouldPresent(settled) && !directHostFailureSignal && !staleAcceptanceOutranksRealFailure && stderrLogWriteFailure === void 0 && cancelAfterSettle === void 0) {
29391
+ if (settled.roleOutcome.kind === "accepted" && request.courtAttemptId !== void 0 && request.courtAttemptId.length > 0) {
29392
+ try {
29393
+ await clearCurrentCourt(admitted.runDirectory, request.courtAttemptId);
29394
+ } catch (error) {
29395
+ await recordBestEffortPostDispatchDiagnostic(
29396
+ admitted,
29397
+ env,
29398
+ `current-court cleanup failed after accepted settlement (best-effort continue): ${describeErrorIdentity(error)}`,
29399
+ io
29400
+ );
29401
+ }
29402
+ }
29403
+ settledOutcome = {
29404
+ exitCode: exitCodeForTerminalOutcome(settled.roleOutcome),
29405
+ admitted,
29406
+ terminal: settled,
29407
+ turnDispatched: true
29408
+ };
29409
+ }
29410
+ } catch (error) {
29411
+ const settledFailure = await settleAfterTurnStarted(
29412
+ admitted,
29413
+ withEngineDetourInvocationScope({
29414
+ timedOut: false,
29415
+ code: result.code,
29416
+ stderr: result.stderr,
29417
+ thrown: error
29418
+ }, request.invocationScopeId),
29419
+ adapters,
29420
+ env.principalAuthority,
29421
+ io,
29422
+ persistRunState
29423
+ );
29424
+ return { kind: "settled", outcome: await finishAfterTurn({ ...settledFailure, turnDispatched: true, ...deferredPersist }) };
29425
+ }
29426
+ if (settledOutcome !== void 0) {
29427
+ const lateCancel = processCancelSignalName(env.signal);
29428
+ if (lateCancel !== void 0) {
29429
+ return { kind: "settled", outcome: await finishAfterTurn(
29430
+ await settleProcessCancelAfterTurn({
29431
+ admitted,
29432
+ cancelName: lateCancel,
29433
+ result,
29434
+ adapters,
29435
+ env,
29436
+ io,
29437
+ persistRunState,
29438
+ deferredPersist,
29439
+ invocationScopeId: request.invocationScopeId
29440
+ })
29441
+ ) };
29442
+ }
29443
+ if (persistRunState) {
29444
+ try {
29445
+ await persistReturnedRunState(admitted, { lawful: true });
29446
+ } catch (error) {
29447
+ await recordBestEffortPostDispatchDiagnostic(
29448
+ admitted,
29449
+ env,
29450
+ `run-state persistence failed beside host terminal (best-effort continue): ${describeErrorIdentity(error)}`,
29451
+ io
29452
+ );
29453
+ }
29454
+ }
29455
+ return { kind: "settled", outcome: await finishAfterTurn({ ...settledOutcome, ...deferredPersist }) };
29456
+ }
29457
+ if (hostSignalFailed) {
29458
+ const resolutionInput = controlledFailureInputFromResolution(resolution);
29459
+ const processCancelName = processCancelSignalName(env.signal);
29460
+ const stderrLogWriteDetails = stderrLogWriteFailure === void 0 ? void 0 : { stderrLogWriteFailure: describeCaughtError(stderrLogWriteFailure) };
29461
+ const failed = await settleAfterTurnStarted(
29462
+ admitted,
29463
+ withEngineDetourInvocationScope({
29464
+ timedOut: result.timedOut,
29465
+ code: result.code,
29466
+ stderr: result.stderr,
29467
+ ...resolutionInput,
29468
+ ...processCancelName === void 0 ? {} : { knownDiagnostic: processCancelDiagnostic(processCancelName) },
29469
+ // Secondary fact only — never the cause. Rides on whichever channel
29470
+ // classification actually reads (knownFailure.details owns it when
29471
+ // a knownFailure exists; the top-level knownDetails otherwise).
29472
+ ...stderrLogWriteDetails === void 0 ? {} : resolutionInput.knownFailure !== void 0 ? {
29473
+ knownFailure: {
29474
+ ...resolutionInput.knownFailure,
29475
+ details: { ...resolutionInput.knownFailure.details ?? {}, ...stderrLogWriteDetails }
29476
+ }
29477
+ } : { knownDetails: stderrLogWriteDetails }
29478
+ }, request.invocationScopeId),
29479
+ adapters,
29480
+ env.principalAuthority,
29481
+ io,
29482
+ persistRunState
29483
+ );
29484
+ return { kind: "settled", outcome: await finishAfterTurn(
29485
+ withProcessCancelSkipAutoResume(
29486
+ { ...failed, turnDispatched: true, ...deferredPersist },
29487
+ env.signal
29488
+ )
29489
+ ) };
29490
+ }
29491
+ if (stderrLogWriteFailure !== void 0) {
29492
+ const failed = await settleAfterTurnStarted(
29493
+ admitted,
29494
+ withEngineDetourInvocationScope({
29495
+ timedOut: false,
29496
+ code: result.code,
29497
+ stderr: result.stderr,
29498
+ thrown: stderrLogWriteFailure
29499
+ }, request.invocationScopeId),
29500
+ adapters,
29501
+ env.principalAuthority,
29502
+ io,
29503
+ persistRunState
29504
+ );
29505
+ return { kind: "settled", outcome: await finishAfterTurn({ ...failed, turnDispatched: true, ...deferredPersist }) };
28854
29506
  }
29507
+ return { kind: "still-missing" };
28855
29508
  }
28856
29509
  async function dispatchPostAdmissionTurn(input) {
28857
29510
  const { admitted, env, io, request, lease, adapters, effectiveEngine } = input;
@@ -28859,6 +29512,9 @@ async function dispatchPostAdmissionTurn(input) {
28859
29512
  const deferredPersist = persistRunState ? {} : { needsPersist: true };
28860
29513
  const shouldPresent = adapters.shouldPresentSettled ?? ((terminal) => isLawfulTypedTerminalOutcome(terminal.roleOutcome));
28861
29514
  let afterDispatchApplied = false;
29515
+ const receiptDelivery = input.receiptDelivery ?? createReceiptDeliveryPolicy(env.autoResumeLimit);
29516
+ let turnDispatched = false;
29517
+ const akSeamDeliversReceipt = env.host !== void 0 && env.host !== "" && env.host !== DEFAULT_ROLE_TURN_HOST;
28862
29518
  const finishAfterTurn = async (result) => {
28863
29519
  if (afterDispatchApplied) return result;
28864
29520
  afterDispatchApplied = true;
@@ -28956,7 +29612,7 @@ async function dispatchPostAdmissionTurn(input) {
28956
29612
  return { exitCode: 0, admitted, terminal: paused, skipAutoResume: true };
28957
29613
  }
28958
29614
  } catch (error) {
28959
- const settled2 = await presentControlledFailure2(
29615
+ const settled = await presentControlledFailure2(
28960
29616
  admitted,
28961
29617
  withEngineDetourInvocationScope({
28962
29618
  timedOut: false,
@@ -28969,7 +29625,7 @@ async function dispatchPostAdmissionTurn(input) {
28969
29625
  io,
28970
29626
  persistRunState
28971
29627
  );
28972
- return { ...settled2, ...deferredPersist };
29628
+ return { ...settled, ...deferredPersist };
28973
29629
  }
28974
29630
  }
28975
29631
  let turnRequest = {
@@ -28993,10 +29649,11 @@ async function dispatchPostAdmissionTurn(input) {
28993
29649
  let result;
28994
29650
  try {
28995
29651
  recordRunStart(admitted.runDirectory);
29652
+ turnDispatched = true;
28996
29653
  result = await env.roleTurnHost.executeTurn(turnRequest);
28997
29654
  } catch (error) {
28998
29655
  const processCancelName = processCancelSignalName(env.signal);
28999
- const settled2 = await settleAfterTurnStarted(
29656
+ const settled = await settleAfterTurnStarted(
29000
29657
  admitted,
29001
29658
  withEngineDetourInvocationScope({
29002
29659
  timedOut: false,
@@ -29011,175 +29668,111 @@ async function dispatchPostAdmissionTurn(input) {
29011
29668
  );
29012
29669
  return await finishAfterTurn(
29013
29670
  withProcessCancelSkipAutoResume(
29014
- { ...settled2, turnDispatched: true, ...deferredPersist },
29671
+ { ...settled, turnDispatched: true, ...deferredPersist },
29015
29672
  env.signal
29016
29673
  )
29017
29674
  );
29018
29675
  }
29019
- let stderrLogWriteFailure;
29020
- try {
29021
- await writeFile7(
29022
- join35(admitted.runDirectory, "stderr.log"),
29023
- result.stderr,
29024
- "utf8"
29025
- );
29026
- } catch (error) {
29027
- stderrLogWriteFailure = error;
29028
- await recordBestEffortPostDispatchDiagnostic(
29676
+ const settledTurn = await settleCompletedHostTurn({
29677
+ admitted,
29678
+ env,
29679
+ io,
29680
+ adapters,
29681
+ shouldPresent,
29682
+ request,
29683
+ result,
29684
+ persistRunState,
29685
+ deferredPersist,
29686
+ finishAfterTurn
29687
+ });
29688
+ if (settledTurn.kind === "settled") return settledTurn.outcome;
29689
+ while (akSeamDeliversReceipt && receiptDelivery.nextAction() === "request-delivery") {
29690
+ let deliveryResult;
29691
+ let deliveryTurnRequest;
29692
+ try {
29693
+ const deliveryRequest = await buildReceiptDeliveryRequest({
29694
+ admitted,
29695
+ env,
29696
+ // Host and the other axes already selected on this turn ride the
29697
+ // shared projection. The pre-projection request does not have them.
29698
+ request: turnRequest,
29699
+ receiptDelivery
29700
+ });
29701
+ deliveryTurnRequest = {
29702
+ ...deliveryRequest,
29703
+ principal: admitted.principal,
29704
+ runDirectory: admitted.runDirectory,
29705
+ ...env.signal === void 0 ? {} : { signal: env.signal }
29706
+ };
29707
+ receiptDelivery.recordDeliveryRequest();
29708
+ deliveryResult = await env.roleTurnHost.executeTurn(deliveryTurnRequest);
29709
+ } catch (error) {
29710
+ const settled = await settleAfterTurnStarted(
29711
+ admitted,
29712
+ withEngineDetourInvocationScope(
29713
+ { timedOut: false, code: null, stderr: "", thrown: error },
29714
+ request.invocationScopeId
29715
+ ),
29716
+ adapters,
29717
+ env.principalAuthority,
29718
+ io,
29719
+ persistRunState
29720
+ );
29721
+ return await finishAfterTurn(
29722
+ withProcessCancelSkipAutoResume(
29723
+ {
29724
+ ...settled,
29725
+ turnDispatched: true,
29726
+ ...deferredPersist
29727
+ },
29728
+ env.signal
29729
+ )
29730
+ );
29731
+ }
29732
+ const deliveryTurn = await settleCompletedHostTurn({
29029
29733
  admitted,
29030
29734
  env,
29031
- `stderr.log write failed (best-effort continue): ${describeErrorIdentity(error)}`,
29032
- io
29033
- );
29034
- }
29035
- const courtScope = (request.courtAttemptId === void 0 || request.courtAttemptId.length === 0) && (request.invocationScopeId === void 0 || request.invocationScopeId.length === 0) ? void 0 : {
29036
- ...request.courtAttemptId === void 0 || request.courtAttemptId.length === 0 ? {} : { courtAttemptId: request.courtAttemptId },
29037
- ...request.invocationScopeId === void 0 || request.invocationScopeId.length === 0 ? {} : { invocationScopeId: request.invocationScopeId }
29038
- };
29039
- let settled;
29040
- let settledOutcome;
29041
- let hostSignalFailed = false;
29042
- let resolution;
29043
- try {
29044
- const sessionFile = admitted.principal !== void 0 ? env.principalAuthority.decode(admitted.principal).sessionFile : "";
29045
- const runnerKnownFailure = adapters.resolveRunnerKnownFailure !== void 0 && sessionFile !== "" ? await adapters.resolveRunnerKnownFailure({ result, sessionFile }) : result.knownFailure;
29046
- resolution = await resolveAuditedRunnerFailureResolution({
29047
- runner: runnerKnownFailure,
29048
- sessionFile,
29049
- credential: void 0,
29050
- runDirectory: admitted.runDirectory
29735
+ // Only the final Terminal presents; intermediate delivery attempts stay quiet.
29736
+ io: { ...io, stdout: () => {
29737
+ } },
29738
+ adapters,
29739
+ shouldPresent,
29740
+ request: deliveryTurnRequest,
29741
+ result: deliveryResult,
29742
+ // Run-state terminal write belongs to the OUTERMOST turn only, so a
29743
+ // still-silent delivery attempt never makes the run look lawfully terminal.
29744
+ persistRunState: false,
29745
+ deferredPersist,
29746
+ finishAfterTurn
29051
29747
  });
29052
- const processCancelName = processCancelSignalName(env.signal);
29053
- const directHostFailureSignal = result.timedOut || result.knownFailure !== void 0 || runnerKnownFailure !== void 0 || processCancelName !== void 0;
29054
- hostSignalFailed = directHostFailureSignal || result.code !== null && result.code !== 0 || resolution.knownFailure !== void 0;
29055
- settled = await adapters.trySettle(admitted, env.principalAuthority, courtScope);
29056
- if (settled !== void 0) {
29057
- settled = await attachRecordedSubmissions(admitted, settled, courtScope);
29058
- }
29059
- const settledIsFreshThisAttempt = settled === void 0 || settled.roleOutcome.kind !== "accepted" && settled.roleOutcome.kind !== "audit_escalation" ? true : await attemptProducedFreshSubmission(admitted, courtScope);
29060
- const staleAcceptanceOutranksRealFailure = !settledIsFreshThisAttempt && hostSignalFailed;
29061
- const cancelAfterSettle = processCancelSignalName(env.signal);
29062
- if (settled !== void 0 && shouldPresent(settled) && !directHostFailureSignal && !staleAcceptanceOutranksRealFailure && stderrLogWriteFailure === void 0 && cancelAfterSettle === void 0) {
29063
- if (settled.roleOutcome.kind === "accepted" && request.courtAttemptId !== void 0 && request.courtAttemptId.length > 0) {
29748
+ if (deliveryTurn.kind === "settled") {
29749
+ if (persistRunState && deliveryTurn.outcome.terminal !== void 0) {
29064
29750
  try {
29065
- await clearCurrentCourt(admitted.runDirectory, request.courtAttemptId);
29751
+ await persistReturnedRunState(admitted, {
29752
+ lawful: isLawfulTypedTerminalOutcome(deliveryTurn.outcome.terminal.roleOutcome)
29753
+ });
29066
29754
  } catch (error) {
29067
29755
  await recordBestEffortPostDispatchDiagnostic(
29068
29756
  admitted,
29069
29757
  env,
29070
- `current-court cleanup failed after accepted settlement (best-effort continue): ${describeErrorIdentity(error)}`,
29758
+ `run-state persistence failed beside\u50AC\u4EA4 terminal (best-effort continue): ${describeErrorIdentity(error)}`,
29071
29759
  io
29072
29760
  );
29073
29761
  }
29074
29762
  }
29075
- settledOutcome = {
29076
- exitCode: exitCodeForTerminalOutcome(settled.roleOutcome),
29077
- admitted,
29078
- terminal: settled,
29079
- turnDispatched: true
29080
- };
29081
- }
29082
- } catch (error) {
29083
- const settledFailure = await settleAfterTurnStarted(
29084
- admitted,
29085
- withEngineDetourInvocationScope({
29086
- timedOut: false,
29087
- code: result.code,
29088
- stderr: result.stderr,
29089
- thrown: error
29090
- }, request.invocationScopeId),
29091
- adapters,
29092
- env.principalAuthority,
29093
- io,
29094
- persistRunState
29095
- );
29096
- return await finishAfterTurn({ ...settledFailure, turnDispatched: true, ...deferredPersist });
29097
- }
29098
- if (settledOutcome !== void 0) {
29099
- const lateCancel = processCancelSignalName(env.signal);
29100
- if (lateCancel !== void 0) {
29101
- return await finishAfterTurn(
29102
- await settleProcessCancelAfterTurn({
29103
- admitted,
29104
- cancelName: lateCancel,
29105
- result,
29106
- adapters,
29107
- env,
29108
- io,
29109
- persistRunState,
29110
- deferredPersist,
29111
- invocationScopeId: request.invocationScopeId
29112
- })
29113
- );
29114
- }
29115
- if (persistRunState) {
29116
- try {
29117
- await persistReturnedRunState(admitted, { lawful: true });
29118
- } catch (error) {
29119
- await recordBestEffortPostDispatchDiagnostic(
29120
- admitted,
29121
- env,
29122
- `run-state persistence failed beside host terminal (best-effort continue): ${describeErrorIdentity(error)}`,
29123
- io
29124
- );
29125
- }
29763
+ return await finishAfterTurn(deliveryTurn.outcome);
29126
29764
  }
29127
- return await finishAfterTurn({ ...settledOutcome, ...deferredPersist });
29128
- }
29129
- if (hostSignalFailed) {
29130
- const resolutionInput = controlledFailureInputFromResolution(resolution);
29131
- const processCancelName = processCancelSignalName(env.signal);
29132
- const stderrLogWriteDetails = stderrLogWriteFailure === void 0 ? void 0 : { stderrLogWriteFailure: describeCaughtError(stderrLogWriteFailure) };
29133
- const failed = await settleAfterTurnStarted(
29134
- admitted,
29135
- withEngineDetourInvocationScope({
29136
- timedOut: result.timedOut,
29137
- code: result.code,
29138
- stderr: result.stderr,
29139
- ...resolutionInput,
29140
- ...processCancelName === void 0 ? {} : { knownDiagnostic: processCancelDiagnostic(processCancelName) },
29141
- // Secondary fact only — never the cause. Rides on whichever channel
29142
- // classification actually reads (knownFailure.details owns it when
29143
- // a knownFailure exists; the top-level knownDetails otherwise).
29144
- ...stderrLogWriteDetails === void 0 ? {} : resolutionInput.knownFailure !== void 0 ? {
29145
- knownFailure: {
29146
- ...resolutionInput.knownFailure,
29147
- details: { ...resolutionInput.knownFailure.details ?? {}, ...stderrLogWriteDetails }
29148
- }
29149
- } : { knownDetails: stderrLogWriteDetails }
29150
- }, request.invocationScopeId),
29151
- adapters,
29152
- env.principalAuthority,
29153
- io,
29154
- persistRunState
29155
- );
29156
- return await finishAfterTurn(
29157
- withProcessCancelSkipAutoResume(
29158
- { ...failed, turnDispatched: true, ...deferredPersist },
29159
- env.signal
29160
- )
29161
- );
29162
- }
29163
- if (stderrLogWriteFailure !== void 0) {
29164
- const failed = await settleAfterTurnStarted(
29165
- admitted,
29166
- withEngineDetourInvocationScope({
29167
- timedOut: false,
29168
- code: result.code,
29169
- stderr: result.stderr,
29170
- thrown: stderrLogWriteFailure
29171
- }, request.invocationScopeId),
29172
- adapters,
29173
- env.principalAuthority,
29174
- io,
29175
- persistRunState
29176
- );
29177
- return await finishAfterTurn({ ...failed, turnDispatched: true, ...deferredPersist });
29178
29765
  }
29766
+ const noReceiptScope = settlementScopeForTurn(request);
29179
29767
  const noReceipt = await attachRecordedSubmissions(
29180
29768
  admitted,
29181
- await settleHostEndedNoReceipt(admitted, env.principalAuthority, courtScope),
29182
- courtScope
29769
+ await settleHostEndedNoReceipt(
29770
+ admitted,
29771
+ env.principalAuthority,
29772
+ noReceiptScope,
29773
+ receiptDelivery.issuedDeliveryRequests()
29774
+ ),
29775
+ noReceiptScope
29183
29776
  );
29184
29777
  const noReceiptCancel = processCancelSignalName(env.signal);
29185
29778
  if (noReceiptCancel !== void 0) {
@@ -29216,6 +29809,11 @@ async function dispatchPostAdmissionTurn(input) {
29216
29809
  turnDispatched: true,
29217
29810
  ...deferredPersist
29218
29811
  });
29812
+ } catch (error) {
29813
+ if (turnDispatched && !(error instanceof TurnDispatchedFailure)) {
29814
+ throw new TurnDispatchedFailure(error);
29815
+ }
29816
+ throw error;
29219
29817
  } finally {
29220
29818
  if (lease !== void 0) {
29221
29819
  try {
@@ -29261,7 +29859,9 @@ function resumeTurnRequestProjectionOptions(admitted, request, env, summonsPrepa
29261
29859
  prompt
29262
29860
  },
29263
29861
  ...request.message === void 0 ? {} : { courtAttemptId: randomUUID6() },
29264
- ...env.stationChild === void 0 ? {} : { stationChild: env.stationChild }
29862
+ ...env.stationChild === void 0 ? {} : { stationChild: env.stationChild },
29863
+ // #1132: one configured ceiling, already resolved by the caller (#422).
29864
+ deliveryRequestLimit: deliveryLimitFromConfig(env.autoResumeLimit)
29265
29865
  };
29266
29866
  }
29267
29867
  function roleTurnOptions(env, admitted, continuation) {
@@ -29271,7 +29871,9 @@ function roleTurnOptions(env, admitted, continuation) {
29271
29871
  ...env.host === void 0 ? {} : { host: env.host },
29272
29872
  ...correlationId === void 0 || correlationId.trim() === "" ? {} : { correlationId },
29273
29873
  continuation,
29274
- ...env.stationChild === void 0 ? {} : { stationChild: env.stationChild }
29874
+ ...env.stationChild === void 0 ? {} : { stationChild: env.stationChild },
29875
+ // #1132: one configured ceiling, already resolved by the caller (#422).
29876
+ deliveryRequestLimit: deliveryLimitFromConfig(env.autoResumeLimit)
29275
29877
  };
29276
29878
  }
29277
29879
  async function dispatchAfterWriterLease(input) {
@@ -29289,6 +29891,7 @@ async function dispatchAfterWriterLease(input) {
29289
29891
  async function runSettledAutoResumeLoop(input) {
29290
29892
  const adapters = withOnceSuccessfulBeforeDispatch(input.adapters);
29291
29893
  const dispatchEnv = input.dispatchEnv ?? input.env;
29894
+ const receiptDelivery = createReceiptDeliveryPolicy(input.env.autoResumeLimit);
29292
29895
  return runWithAutoResumeLoop({
29293
29896
  admitted: input.admitted,
29294
29897
  principalAuthority: input.env.principalAuthority,
@@ -29310,6 +29913,7 @@ async function runSettledAutoResumeLoop(input) {
29310
29913
  ...lease === void 0 ? {} : { lease },
29311
29914
  adapters,
29312
29915
  persistRunState: false,
29916
+ receiptDelivery,
29313
29917
  ...input.effectiveEngine === void 0 ? {} : { effectiveEngine: input.effectiveEngine }
29314
29918
  });
29315
29919
  return settleDeferredPersist(
@@ -29672,12 +30276,14 @@ var init_post_admission = __esm({
29672
30276
  init_activation_ledger_topology();
29673
30277
  init_engine_material();
29674
30278
  init_session_identity();
30279
+ init_receipt_delivery_policy();
29675
30280
  init_role_run_relocation();
29676
30281
  init_packaged_role_registry();
29677
30282
  init_engine_detour_usage();
29678
30283
  init_run_lifecycle();
29679
30284
  init_process_cancel();
29680
30285
  init_activation_ledger_topology();
30286
+ init_host_descriptions();
29681
30287
  init_host_session_record();
29682
30288
  init_settlement();
29683
30289
  init_terminal();
@@ -29743,7 +30349,7 @@ var init_atomic_write = __esm({
29743
30349
  });
29744
30350
 
29745
30351
  // src/analyst-index.ts
29746
- import { open as open3, readFile as readFile18, unlink as unlink5 } from "node:fs/promises";
30352
+ import { open as open3, readFile as readFile19, unlink as unlink5 } from "node:fs/promises";
29747
30353
  import { dirname as dirname21, join as join37 } from "node:path";
29748
30354
  import { setTimeout as sleep } from "node:timers/promises";
29749
30355
  async function withAnalystLibraryIndexLock(ledgerHome, fn) {
@@ -29867,7 +30473,7 @@ async function readAnalystLibraryIndexPage(ledgerHome) {
29867
30473
  const path = analystLibraryIndexPath(ledgerHome);
29868
30474
  let raw;
29869
30475
  try {
29870
- raw = await readFile18(path, "utf8");
30476
+ raw = await readFile19(path, "utf8");
29871
30477
  } catch (error) {
29872
30478
  if (isMissingPathError(error)) return void 0;
29873
30479
  throw error;
@@ -30070,7 +30676,7 @@ var init_analyst_cohort = __esm({
30070
30676
  });
30071
30677
 
30072
30678
  // src/analyst-ledger.ts
30073
- import { readdir as readdir7, readFile as readFile19 } from "node:fs/promises";
30679
+ import { readdir as readdir7, readFile as readFile20 } from "node:fs/promises";
30074
30680
  import { basename as basename9, join as join38 } from "node:path";
30075
30681
  async function readExistingRunLifecycleState(runDirectory) {
30076
30682
  return (await readRoleRunIdentity(runDirectory))?.state;
@@ -30120,7 +30726,7 @@ async function listLedgerBookNames(booksRoot) {
30120
30726
  async function readInvocationScopeFields(runDirectory) {
30121
30727
  let raw;
30122
30728
  try {
30123
- raw = await readFile19(join38(runDirectory, "invocation.json"), "utf8");
30729
+ raw = await readFile20(join38(runDirectory, "invocation.json"), "utf8");
30124
30730
  } catch (error) {
30125
30731
  if (isMissingPathError(error)) return void 0;
30126
30732
  throw error;
@@ -30153,7 +30759,7 @@ function decideIssueScope(input) {
30153
30759
  }
30154
30760
  async function resolveSessionFile(runDirectory) {
30155
30761
  try {
30156
- const raw = await readFile19(join38(runDirectory, "invocation.json"), "utf8");
30762
+ const raw = await readFile20(join38(runDirectory, "invocation.json"), "utf8");
30157
30763
  const parsed = JSON.parse(raw);
30158
30764
  if (isRecord(parsed) && typeof parsed.sessionFile === "string" && parsed.sessionFile.trim() !== "") {
30159
30765
  return parsed.sessionFile;
@@ -31413,7 +32019,7 @@ var init_analyst_model_groups = __esm({
31413
32019
  });
31414
32020
 
31415
32021
  // src/analyst-entry.ts
31416
- import { readFile as readFile20 } from "node:fs/promises";
32022
+ import { readFile as readFile21 } from "node:fs/promises";
31417
32023
  function cachedPageMatchesRequestedScope(page, input) {
31418
32024
  if (page.bookKey !== input.bookKey) return false;
31419
32025
  const requestedTicket = input.ticketNumber ?? input.issueNumber;
@@ -31440,7 +32046,7 @@ async function readOrComputeAnalystIssuePage(input, options) {
31440
32046
  ...issueNumber === void 0 && input.bookKey === void 0 ? { scopeRootIdentity: projectRoot } : {}
31441
32047
  });
31442
32048
  try {
31443
- const raw = await readFile20(pagePath, "utf8");
32049
+ const raw = await readFile21(pagePath, "utf8");
31444
32050
  const page = JSON.parse(raw);
31445
32051
  if (cachedPageMatchesRequestedScope(page, { bookKey, ...input })) {
31446
32052
  const ghostScan = await scanAnalystIssueRuns({
@@ -31541,7 +32147,7 @@ async function runAnalystModelGroupsMode(input, home) {
31541
32147
  scopeRootIdentity: projectRoot
31542
32148
  });
31543
32149
  try {
31544
- const raw = await readFile20(pagePath, "utf8");
32150
+ const raw = await readFile21(pagePath, "utf8");
31545
32151
  JSON.parse(raw);
31546
32152
  } catch (error) {
31547
32153
  if (!isMissingPathError(error)) {
@@ -31639,7 +32245,7 @@ var init_analyst_entry = __esm({
31639
32245
  });
31640
32246
 
31641
32247
  // src/public-cli/analyst-run.ts
31642
- import { readFile as readFile21 } from "node:fs/promises";
32248
+ import { readFile as readFile22 } from "node:fs/promises";
31643
32249
  import { isAbsolute as isAbsolute10, resolve as resolve13 } from "node:path";
31644
32250
  function resolveAnalystIssueBookKeyFromCwd(cwd = process.cwd()) {
31645
32251
  try {
@@ -31692,7 +32298,7 @@ async function buildAnalystSweepModeInputFromAttachmentPaths(attachmentPaths) {
31692
32298
  const absolute = isAbsolute10(sourcePath) ? sourcePath : resolve13(sourcePath);
31693
32299
  let bytes;
31694
32300
  try {
31695
- bytes = await readFile21(absolute);
32301
+ bytes = await readFile22(absolute);
31696
32302
  } catch (error) {
31697
32303
  throw new CliUsageError(
31698
32304
  `analyst sweep attachment is not a readable regular file: ${sourcePath}`,
@@ -32581,7 +33187,7 @@ async function runAkRole(argv2, env) {
32581
33187
  io
32582
33188
  );
32583
33189
  let current = result;
32584
- while (current.exitCode === 0 && current.admitted?.correlationId !== void 0 && current.terminal?.roleOutcome.kind === "accepted" && !latestPayloadEscalated(current.terminal.roleOutcome)) {
33190
+ while (current.exitCode === 0 && current.admitted?.correlationId !== void 0 && current.terminal?.roleOutcome.kind === "accepted" && current.terminal.roleOutcome.decisiveFacts?.directionUnsettled !== true && !latestPayloadEscalated(current.terminal.roleOutcome)) {
32585
33191
  const parentRunId = current.admitted.correlationId;
32586
33192
  resumeFailureContext = {
32587
33193
  home,