@akagilnc/pi-workflow-roles 0.1.3932 → 0.1.3975

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 (162) hide show
  1. package/CLAUDE.md +1 -1
  2. package/dist/acp-host/production-host.js +2389 -6018
  3. package/dist/analyst-gate-cycles-read.js +15 -19
  4. package/dist/audit-escalation.js +16 -46
  5. package/dist/auditor-dossier-tool.js +7 -62
  6. package/dist/collector-identity.js +0 -157
  7. package/dist/collector-ledger.js +2 -42
  8. package/dist/compliance-transport.js +40 -14
  9. package/dist/diarist-contracts.js +2 -40
  10. package/dist/doctor-contracts.js +39 -108
  11. package/dist/doctor-evidence.js +1 -5
  12. package/dist/engine-detour-tool.js +1 -1
  13. package/dist/gatekeeper-role.js +49 -38
  14. package/dist/headless-host/production-host.js +4814 -8450
  15. package/dist/host-contracts.js +0 -5
  16. package/dist/merger-contracts.js +4 -6
  17. package/dist/navigator-attendance.js +30 -52
  18. package/dist/navigator-invocation-identity.js +0 -1
  19. package/dist/navigator-public-session.js +2 -1
  20. package/dist/notary-contracts.js +4 -10
  21. package/dist/package-contracts/auditor-output.js +5 -23
  22. package/dist/package-contracts/fixer-output.js +25 -49
  23. package/dist/package-contracts/gatekeeper-output.js +3 -13
  24. package/dist/package-contracts/navigator-output.js +4 -7
  25. package/dist/package-contracts/reviewer-output.js +1 -95
  26. package/dist/package-contracts/terminating-tools.js +33 -144
  27. package/dist/package-contracts/worker-output.js +1 -3
  28. package/dist/public-cli/auto-resume.js +30 -68
  29. package/dist/public-cli/case-dossier-delivery.js +5 -17
  30. package/dist/public-cli/diarist-run.js +9 -4
  31. package/dist/public-cli/inspector-run.js +2 -8
  32. package/dist/public-cli/instruction-seat-run.js +3 -7
  33. package/dist/public-cli/invocation.js +5 -2
  34. package/dist/public-cli/main.js +6068 -6964
  35. package/dist/public-cli/notary-run.js +1 -8
  36. package/dist/public-cli/post-admission.js +314 -113
  37. package/dist/public-cli/run-lifecycle.js +14 -38
  38. package/dist/public-cli/settlement.js +209 -390
  39. package/dist/public-cli/terminal.js +51 -45
  40. package/dist/public-role-summons.js +1 -12
  41. package/dist/reviewer-dispatch.js +12 -258
  42. package/dist/submission-correctable-error.js +0 -12
  43. package/dist/submission-errors.js +6 -1
  44. package/dist/submission-ledger.js +125 -168
  45. package/dist/ticket-provenance-contracts.js +2 -49
  46. package/dist/ticket-provenance.js +82 -31
  47. package/extensions/role-runtime.ts +1 -6
  48. package/package.json +1 -1
  49. package/resources/836-deleted-machine-instruction-inventory.md +18 -0
  50. package/src/acp-host/role-turn-host.ts +8 -3
  51. package/src/analyst-gate-cycles-read.ts +17 -29
  52. package/src/audit-escalation.ts +20 -50
  53. package/src/auditor-dossier-tool.ts +5 -103
  54. package/src/canonical-skill-binding.ts +3 -2
  55. package/src/collector-identity.ts +0 -179
  56. package/src/collector-ledger.ts +3 -46
  57. package/src/collector-role.ts +32 -61
  58. package/src/collector-tool-schemas.ts +20 -14
  59. package/src/compliance-transport.ts +55 -17
  60. package/src/countersign-role.ts +17 -8
  61. package/src/diarist-contracts.ts +3 -36
  62. package/src/diarist-role.ts +13 -7
  63. package/src/diarist.ts +4 -16
  64. package/src/doctor-contracts.ts +73 -94
  65. package/src/doctor-evidence.ts +1 -1
  66. package/src/doctor-role.ts +3 -3
  67. package/src/engine-detour-tool.ts +4 -1
  68. package/src/external-host-turn-loop.ts +9 -3
  69. package/src/gatekeeper-pass-envelope.ts +7 -12
  70. package/src/gatekeeper-role.ts +56 -50
  71. package/src/gleaner-left-role.ts +4 -2
  72. package/src/headless-host/role-turn-host.ts +4 -5
  73. package/src/host-contracts.ts +3 -8
  74. package/src/judge-role.ts +19 -13
  75. package/src/merger-contracts.ts +10 -6
  76. package/src/merger-role.ts +1 -5
  77. package/src/navigator-attendance.ts +37 -74
  78. package/src/navigator-invocation-identity.ts +0 -6
  79. package/src/navigator-public-session.ts +2 -1
  80. package/src/notary-contracts.ts +7 -10
  81. package/src/package-contracts/auditor-output.ts +4 -21
  82. package/src/package-contracts/fixer-output.ts +34 -52
  83. package/src/package-contracts/gatekeeper-output.ts +5 -22
  84. package/src/package-contracts/navigator-output.ts +7 -7
  85. package/src/package-contracts/reviewer-output.ts +2 -150
  86. package/src/package-contracts/terminating-tools.ts +32 -147
  87. package/src/package-contracts/worker-output.ts +0 -1
  88. package/src/pi/adapter.ts +3 -8
  89. package/src/public-cli/auto-resume.ts +41 -94
  90. package/src/public-cli/case-dossier-delivery.ts +5 -15
  91. package/src/public-cli/countersign-run.ts +14 -6
  92. package/src/public-cli/diarist-run.ts +11 -9
  93. package/src/public-cli/inspector-run.ts +2 -18
  94. package/src/public-cli/instruction-seat-run.ts +3 -17
  95. package/src/public-cli/invocation.ts +5 -2
  96. package/src/public-cli/merger-run.ts +1 -1
  97. package/src/public-cli/notary-run.ts +1 -18
  98. package/src/public-cli/post-admission.ts +385 -115
  99. package/src/public-cli/run-lifecycle.ts +13 -44
  100. package/src/public-cli/settlement.ts +314 -562
  101. package/src/public-cli/terminal.ts +66 -72
  102. package/src/public-role-summons.ts +5 -30
  103. package/src/reviewer-dispatch.ts +29 -331
  104. package/src/reviewer-role.ts +16 -83
  105. package/src/role-envelope.ts +16 -24
  106. package/src/role-runtime-dependencies.ts +1 -6
  107. package/src/role-runtime.ts +65 -201
  108. package/src/submission-correctable-error.ts +0 -14
  109. package/src/submission-errors.ts +6 -1
  110. package/src/submission-ledger.ts +187 -187
  111. package/src/ticket-provenance-contracts.ts +4 -60
  112. package/src/ticket-provenance.ts +98 -32
  113. package/src/worker-role.ts +35 -36
  114. package/dist/activation-ledger-session.js +0 -105
  115. package/dist/activation-ledger.js +0 -139
  116. package/dist/activation-trace.js +0 -33
  117. package/dist/atomic-write.js +0 -23
  118. package/dist/auditor-role.js +0 -12
  119. package/dist/canonical-skill-binding.js +0 -61
  120. package/dist/collector-handbook.js +0 -142
  121. package/dist/collector-receipt.js +0 -107
  122. package/dist/collector-role.js +0 -566
  123. package/dist/collector-tool-schemas.js +0 -107
  124. package/dist/countersign-role.js +0 -28
  125. package/dist/diarist-role.js +0 -44
  126. package/dist/diarist.js +0 -66
  127. package/dist/doctor-role.js +0 -75
  128. package/dist/fixer-bash-seatbelt.js +0 -13
  129. package/dist/gatekeeper-pass-envelope.js +0 -77
  130. package/dist/gleaner-left-role.js +0 -26
  131. package/dist/inspector-role.js +0 -29
  132. package/dist/judge-role.js +0 -104
  133. package/dist/merger-role.js +0 -55
  134. package/dist/navigator-role.js +0 -12
  135. package/dist/notary-role.js +0 -134
  136. package/dist/oauth-keepalive.js +0 -158
  137. package/dist/pi/adapter.js +0 -223
  138. package/dist/reviewer-agent.js +0 -122
  139. package/dist/reviewer-child-executor.js +0 -194
  140. package/dist/reviewer-construction.js +0 -103
  141. package/dist/reviewer-execution-ledger.js +0 -166
  142. package/dist/reviewer-failure-diagnostic.js +0 -17
  143. package/dist/reviewer-role.js +0 -159
  144. package/dist/reviewer-scope-prompt.js +0 -21
  145. package/dist/reviewer-settlement.js +0 -66
  146. package/dist/reviewer-workspace.js +0 -132
  147. package/dist/role-runtime.js +0 -1604
  148. package/dist/stderr-jsonl.js +0 -26
  149. package/dist/tool-execution-observation.js +0 -141
  150. package/dist/worker-role.js +0 -345
  151. package/dist/worker-submission-gates.js +0 -305
  152. package/src/collector-receipt.ts +0 -140
  153. package/src/diagnostic-tail.ts +0 -18
  154. package/src/reviewer-agent.ts +0 -135
  155. package/src/reviewer-child-executor.ts +0 -252
  156. package/src/reviewer-construction.ts +0 -195
  157. package/src/reviewer-execution-ledger.ts +0 -212
  158. package/src/reviewer-failure-diagnostic.ts +0 -18
  159. package/src/reviewer-scope-prompt.ts +0 -24
  160. package/src/reviewer-settlement.ts +0 -74
  161. package/src/reviewer-workspace.ts +0 -105
  162. package/src/shape-unreadable-failure.ts +0 -49
@@ -14,9 +14,9 @@ import {
14
14
  import { readSitianRecords, resolveSitianRecordPath, sitianReport } from "../sitian-facade.ts";
15
15
 
16
16
  import {
17
- readAuditEscalationSubmission,
18
- readLatestSubmissionOutcome,
19
- readSealedSubmission,
17
+ hasFreshAttemptSubmission,
18
+ readRecordedSubmissionRows,
19
+ readRecordedSubmissions,
20
20
  } from "../submission-ledger.ts";
21
21
 
22
22
  import { isAuditEscalationResult } from "../audit-escalation.ts";
@@ -27,7 +27,6 @@ import type { RoleTurnKnownFailure } from "../host-contracts.ts";
27
27
  import { knownFailureFromProviderStop } from "../pi/known-failure.ts";
28
28
  import { readReviewerDispatchRejection } from "./reviewer-dispatch-rejection.ts";
29
29
  import {
30
- RESUME_TRANSPORT_ENVELOPE,
31
30
  isV1ResumableProvider,
32
31
  readLatestTypedProviderHttpObservation,
33
32
  readTypedHttp429Observation,
@@ -65,14 +64,16 @@ import {
65
64
  type CoderOutput,
66
65
  type FixerOutput,
67
66
  } from "../package-contracts/worker-output.ts";
68
- import { validateAcceptedDetails } from "../package-contracts/terminating-tools.ts";
67
+
69
68
  import {
70
69
  DOCTOR_OUTPUT_TOOL_NAME,
70
+ type DoctorCaseCost,
71
71
  type DoctorOutput,
72
72
  } from "../doctor-contracts.ts";
73
+ import { DOCTOR_CANDIDATE_ENTRY_TYPE } from "../dossier-resolution.ts";
73
74
  import {
74
75
  REVIEWER_OUTPUT_TOOL_NAME,
75
- type RuntimeReviewerReceiptV2,
76
+ type ReviewerIntent,
76
77
  } from "../package-contracts/reviewer-output.ts";
77
78
  import {
78
79
  MERGER_OUTPUT_TOOL_NAME,
@@ -118,7 +119,13 @@ import {
118
119
  type InvocationMarkerIdentity,
119
120
  } from "../navigator-invocation-identity.ts";
120
121
  import type { NavigatorPhase } from "../navigator-attendance.ts";
121
- import { NO_RECEIPT_LIFECYCLE_ENTRY_TYPE, parseNoReceiptLifecycleFacts, type NoReceiptLifecycleFacts } from "../receipt-delivery-policy.ts";
122
+ import {
123
+ NO_RECEIPT_LIFECYCLE_ENTRY_TYPE,
124
+ RECEIPT_DELIVERY_TURN_LIMIT,
125
+ noReceiptLifecycleFacts,
126
+ parseNoReceiptLifecycleFacts,
127
+ type NoReceiptLifecycleFacts,
128
+ } from "../receipt-delivery-policy.ts";
122
129
  import type {
123
130
  DurablePrincipal,
124
131
  DurablePrincipalAuthority,
@@ -151,8 +158,7 @@ function sealedLedgerHome(admitted: AdmittedRoleInvocation): string {
151
158
 
152
159
  /**
153
160
  * Court-turn settlement scope (#637 same-ticket re-summons).
154
- * When courtAttemptId is set, ledger reads only that attempt so a prior seal
155
- * cannot present as this turn's result. Omit for run-scoped latest sealed read.
161
+ * courtAttemptId tags the new court; recorded payloads stay run-scoped (#836).
156
162
  */
157
163
  export type SettlementCourtScope = {
158
164
  readonly courtAttemptId?: string;
@@ -170,54 +176,122 @@ function ledgerReadScope(
170
176
  };
171
177
  }
172
178
 
179
+ function roleOutcomeFromRows(
180
+ role: TerminalRoleName,
181
+ rows: readonly { readonly role: TerminalRoleName; readonly kind: "accepted" | "audit-escalation"; readonly accepted: unknown }[],
182
+ ): Extract<TerminalRoleOutcome, { kind: "accepted" | "audit_escalation" }> | undefined {
183
+ const mine = rows.filter((row) => row.role === role);
184
+ if (mine.length === 0) return undefined;
185
+ const payloads = mine.map((row) => row.accepted);
186
+ if (mine.some((row) => row.kind === "audit-escalation")) {
187
+ return { kind: "audit_escalation", role, status: "audit_escalation", payloads };
188
+ }
189
+ return { kind: "accepted", role, payloads };
190
+ }
191
+
173
192
  async function sealedLedgerOutcome(
174
193
  admitted: AdmittedRoleInvocation,
194
+ role: TerminalRoleName,
175
195
  scope?: SettlementCourtScope,
176
- ): Promise<Extract<TerminalRoleOutcome, { kind: "accepted" }> | undefined> {
177
- return readSealedSubmission(admitted.projectRoot, admitted.runId, ledgerReadScope(admitted, scope));
196
+ ): Promise<Extract<TerminalRoleOutcome, { kind: "accepted" | "audit_escalation" }> | undefined> {
197
+ const rows = await readRecordedSubmissionRows(
198
+ admitted.projectRoot,
199
+ admitted.runId,
200
+ ledgerReadScope(admitted, scope),
201
+ );
202
+ return roleOutcomeFromRows(role, rows);
178
203
  }
179
204
 
180
205
  /**
181
- * Shared sealed-acceptance redispatch disposition for resume entrypoints
182
- * (#648 sealed authority; #672 / ADR 0080 single-settlement-disposition).
183
- * Owns the fail-closed gate auto and manual resume previously rebuilt beside
184
- * the shared sealed query: sealed → block; authority throw → block with
185
- * preserved cause; otherwise allow. Callers present entry-specific terminals;
186
- * they must not re-derive this judgment. Ledger projection remains the sole
187
- * seal truth — this is disposition over that read, not a second state.
188
- * Always run-scoped (no court attempt filter): any retained seal blocks auto-resume redispatch.
206
+ * True when this court/attempt itself already produced a sealed or
207
+ * audit-escalation submission (#836 r12 class 2). Presentation
208
+ * (submissions/payloads) always stays run-scoped and unfiltered — this is a
209
+ * control-flow signal only, consumed to keep a stale prior-attempt
210
+ * acceptance from outranking this attempt's own real host-turn failure.
211
+ * Absent a courtAttemptId scope there is no distinct prior attempt to stale
212
+ * against, so this defaults true (unchanged behavior for ordinary,
213
+ * non-court dispatches).
189
214
  */
190
- export type SealedAcceptanceRedispatchDisposition =
191
- | { readonly kind: "allow" }
192
- | { readonly kind: "block"; readonly reason: "sealed-accepted" }
193
- | { readonly kind: "block"; readonly reason: "authority-failed"; readonly cause: unknown };
194
-
195
- export async function sealedAcceptanceRedispatchDisposition(
215
+ export async function attemptProducedFreshSubmission(
196
216
  admitted: AdmittedRoleInvocation,
197
- ): Promise<SealedAcceptanceRedispatchDisposition> {
198
- try {
199
- if ((await sealedLedgerOutcome(admitted)) !== undefined) {
200
- return { kind: "block", reason: "sealed-accepted" };
201
- }
202
- return { kind: "allow" };
203
- } catch (cause) {
204
- // Ledger authority must not wash read failure into "unsealed" (#648).
205
- return { kind: "block", reason: "authority-failed", cause };
206
- }
217
+ scope?: SettlementCourtScope,
218
+ ): Promise<boolean> {
219
+ if (scope?.courtAttemptId === undefined || scope.courtAttemptId.length === 0) return true;
220
+ return hasFreshAttemptSubmission(
221
+ admitted.projectRoot,
222
+ admitted.runId,
223
+ scope.courtAttemptId,
224
+ sealedLedgerHome(admitted),
225
+ );
207
226
  }
208
227
 
209
- async function auditEscalationLedgerOutcome(
228
+ /** #836: every raw role payload in settle scope (调几次记几次). */
229
+ export async function recordedSubmissionPayloads(
210
230
  admitted: AdmittedRoleInvocation,
211
- role: TerminalRoleName,
212
231
  scope?: SettlementCourtScope,
213
- ): Promise<Extract<TerminalRoleOutcome, { kind: "audit_escalation" }> | undefined> {
214
- const projection = await readAuditEscalationSubmission(
232
+ ): Promise<readonly unknown[]> {
233
+ return readRecordedSubmissions(
215
234
  admitted.projectRoot,
216
235
  admitted.runId,
217
236
  ledgerReadScope(admitted, scope),
218
237
  );
219
- if (projection?.role !== role) return undefined;
220
- return projection;
238
+ }
239
+
240
+ export function withSubmissions<T extends TerminalResult>(
241
+ terminal: T,
242
+ submissions: readonly unknown[],
243
+ ): T {
244
+ if (submissions.length === 0) return terminal;
245
+ const roleOutcome = terminal.roleOutcome;
246
+ const withPayloads =
247
+ roleOutcome.kind === "accepted" || roleOutcome.kind === "audit_escalation"
248
+ ? { ...roleOutcome, payloads: (roleOutcome.payloads ?? []).length > 0 ? roleOutcome.payloads : submissions }
249
+ : roleOutcome.kind === "failure"
250
+ ? { ...roleOutcome, payloads: roleOutcome.payloads ?? submissions }
251
+ : roleOutcome;
252
+ return { ...terminal, roleOutcome: withPayloads, submissions };
253
+ }
254
+
255
+ /** Attach full ledger submissions onto any settled terminal (#836). */
256
+ export async function attachRecordedSubmissions<T extends TerminalResult>(
257
+ admitted: AdmittedRoleInvocation,
258
+ terminal: T,
259
+ scope?: SettlementCourtScope,
260
+ ): Promise<T> {
261
+ return withSubmissions(terminal, await recordedSubmissionPayloads(admitted, scope));
262
+ }
263
+
264
+ /**
265
+ * Host ended with no recorded submission — lawful no_receipt (exit 0).
266
+ * Does not invent an output failure for an empty ledger.
267
+ */
268
+ export async function settleHostEndedNoReceipt(
269
+ admitted: AdmittedRoleInvocation,
270
+ authority: DurablePrincipalAuthority,
271
+ ): Promise<TerminalResult> {
272
+ const facts = noReceiptLifecycleFacts({
273
+ terminalToolCalled: false,
274
+ rejectedReceipts: [],
275
+ deliveryTurns: RECEIPT_DELIVERY_TURN_LIMIT,
276
+ runPointer: admitted.runDirectory,
277
+ attemptPointer: `current:${admitted.runDirectory}`,
278
+ });
279
+ const coordinates = coordinatesFromAdmitted(authority, admitted);
280
+ return withOptionalGateProjection(
281
+ {
282
+ roleOutcome: {
283
+ kind: "no_receipt",
284
+ role: admitted.role,
285
+ status: "no-accepted-receipt",
286
+ ...facts,
287
+ decisiveFacts: facts,
288
+ },
289
+ navigator: await extractNavigatorFactFromAdmittedSession(coordinates.sessionFile),
290
+ artifacts: [],
291
+ runId: admitted.runId,
292
+ },
293
+ coordinates.sessionDirectory,
294
+ );
221
295
  }
222
296
 
223
297
  async function closedLedgerOutcome(
@@ -225,10 +299,7 @@ async function closedLedgerOutcome(
225
299
  role: TerminalRoleName,
226
300
  scope?: SettlementCourtScope,
227
301
  ): Promise<Extract<TerminalRoleOutcome, { kind: "accepted" | "audit_escalation" }> | undefined> {
228
- const sealed = await sealedLedgerOutcome(admitted, scope);
229
- return sealed?.role === role
230
- ? sealed
231
- : auditEscalationLedgerOutcome(admitted, role, scope);
302
+ return sealedLedgerOutcome(admitted, role, scope);
232
303
  }
233
304
 
234
305
  /** Transitional host-session reads remain only for non-sealed failure and audit evidence. */
@@ -242,9 +313,8 @@ import {
242
313
  exitCodeForTerminalOutcome,
243
314
  formatTerminalResult,
244
315
  isLawfulTypedTerminalOutcome,
316
+ lastRolePayloadRecord,
245
317
  recommendationNavigatorFact,
246
- buildResidualIncompleteTerminalOutcome,
247
- redactExactRunId,
248
318
  type ControlledFailureCause,
249
319
  type TerminalArtifactRef,
250
320
  type TerminalGateFact,
@@ -275,85 +345,15 @@ export type ControlledFailure = {
275
345
  readonly details?: Readonly<Record<string, unknown>>;
276
346
  };
277
347
 
278
- /** Presentation bound for one stderr diagnostic line (durable artifact keeps full text). */
279
- export const CONCISE_DIAGNOSTIC_MAX_CHARS = 480;
280
-
281
- /**
282
- * True when a stderr line is observation/event/token/stack flood rather than a diagnostic.
283
- * Recognizes both `event:` prefixes and real JSONL records with an `event` key
284
- * (tool_execution_* observation face).
285
- */
286
- export function isChildDiagnosticFloodLine(line: string): boolean {
287
- if (/^at\s+/.test(line)) return true;
288
- if (line.startsWith("event:")) return true;
289
- if (/\btokens?=/.test(line)) return true;
290
- if (/\btool_calls?=/.test(line)) return true;
291
- if (line.startsWith("{")) {
292
- try {
293
- const parsed: unknown = JSON.parse(line);
294
- if (
295
- typeof parsed === "object" &&
296
- parsed !== null &&
297
- !Array.isArray(parsed) &&
298
- typeof (parsed as { event?: unknown }).event === "string"
299
- ) {
300
- return true;
301
- }
302
- } catch {
303
- // Not JSON — may still be a real diagnostic.
304
- }
305
- }
306
- return false;
307
- }
308
-
309
- /**
310
- * True when a stderr line is Pi auth/model help scaffolding rather than the failure identity.
311
- * Real counterexample: multi-line "No API key…" guidance ends with docs/*.md path lines;
312
- * those footers must not displace the primary diagnostic.
313
- */
314
- export function isChildDiagnosticHelpFooterLine(line: string): boolean {
315
- const trimmed = line.trim();
316
- if (trimmed.length === 0) return false;
317
- // Path-only doc references (indented or bare).
318
- if (/^\S+\.(md|txt)$/i.test(trimmed)) return true;
319
- // Auth guidance continuations from Pi formatNoApiKeyFoundMessage / getProviderLoginHelp.
320
- if (/^Use \//i.test(trimmed)) return true;
321
- if (/^Then use \//i.test(trimmed)) return true;
322
- if (/^See:\s*$/i.test(trimmed)) return true;
323
- return false;
324
- }
325
-
326
- /** Bound one diagnostic for human stderr presentation; durable evidence stays full. */
327
- export function boundConciseDiagnostic(
328
- diagnostic: string,
329
- maxChars: number = CONCISE_DIAGNOSTIC_MAX_CHARS,
330
- ): string {
331
- if (diagnostic.length <= maxChars) return diagnostic;
332
- if (maxChars <= 1) return "…";
333
- return `${diagnostic.slice(0, maxChars - 1)}…`;
334
- }
335
-
336
348
  /**
337
- * Pick one concise diagnostic line from child stderr without stacks/events/tokens/help footers.
338
- * Prefers the last nonblank line that is not a frame, observation flood, or docs-path footer.
339
- * Returns the full selected diagnostic (bound only at presentation).
349
+ * Host stderr as recorded — full bytes, no flood filter, no char clip (#836).
340
350
  */
341
351
  export function conciseChildDiagnostic(
342
352
  stderr: string,
343
353
  fallback: string,
344
354
  ): string {
345
- const lines = stderr
346
- .split(/\r?\n/)
347
- .map((line) => line.trim())
348
- .filter((line) => line.length > 0);
349
- for (let i = lines.length - 1; i >= 0; i -= 1) {
350
- const line = lines[i]!;
351
- if (isChildDiagnosticFloodLine(line)) continue;
352
- if (isChildDiagnosticHelpFooterLine(line)) continue;
353
- // Strip a leading "Error:" label but keep the message identity.
354
- return line.replace(/^Error:\s*/i, "").trim() || fallback;
355
- }
356
- return fallback;
355
+ const trimmed = stderr.trim();
356
+ return trimmed.length > 0 ? stderr : fallback;
357
357
  }
358
358
 
359
359
  export function formatCliDiagnostic(message: string): string {
@@ -364,15 +364,10 @@ export function formatCliDiagnostic(message: string): string {
364
364
  * One concise stderr line for humans. Durable Error Artifact / Terminal keep the
365
365
  * full original diagnostic — presentation collapses newlines and flood frames.
366
366
  */
367
+ /** #836: full diagnostic on stderr — no first-line clip / flood filter. */
367
368
  export function formatFailureStderrDiagnostic(failure: ControlledFailure): string {
368
- const selected = conciseChildDiagnostic(failure.diagnostic, "failure");
369
- // conciseChildDiagnostic already returns one split line; defend fallback paths.
370
- const oneLine =
371
- selected
372
- .split(/\r?\n/)
373
- .map((line) => line.trim())
374
- .find((line) => line.length > 0) ?? "failure";
375
- return formatCliDiagnostic(boundConciseDiagnostic(oneLine));
369
+ const text = failure.diagnostic.trim().length > 0 ? failure.diagnostic : "failure";
370
+ return formatCliDiagnostic(text);
376
371
  }
377
372
 
378
373
  /**
@@ -1018,15 +1013,13 @@ async function loadBoundAuditorVolumes(
1018
1013
  }
1019
1014
  const parentId = parentEntries.find((entry) => entry.type === "session")?.id;
1020
1015
  if (parentId === undefined) return undefined;
1021
- const RESUME_ENVELOPE = RESUME_TRANSPORT_ENVELOPE;
1022
- // Keyed prefix on the transport token line only (#600 / 8e767152). Resume may
1023
- // append engine handbook presentation after the token; settlement must not
1024
- // treat those prose lines as a real user turn or key on their shape.
1025
1016
  const isResumeEnvelopeBytes = (value: unknown): boolean => {
1026
1017
  if (typeof value !== "string") return false;
1018
+ if (value.length === 0) return true;
1027
1019
  const nl = value.indexOf("\n");
1028
1020
  const firstLine = nl === -1 ? value : value.slice(0, nl);
1029
- return firstLine === RESUME_ENVELOPE;
1021
+ const body = firstLine === "" && nl !== -1 ? value.slice(nl + 1) : value;
1022
+ return body.startsWith("本次配置的劳务引擎及其手册:") || body.startsWith("- engine:");
1030
1023
  };
1031
1024
  const isResumeEnvelope = (msg: unknown): boolean => {
1032
1025
  if (!isRecord(msg) || msg.role !== "user") return false;
@@ -1488,42 +1481,6 @@ function safelyRead(object: object, key: string): { readable: true; value: unkno
1488
1481
  }
1489
1482
  }
1490
1483
 
1491
- function auditNoReceiptDecisiveFact(candidate: object): Record<string, unknown> {
1492
- const projected = safelyRead(candidate, "auditNoReceipt");
1493
- if (!projected.readable || projected.value === undefined) return {};
1494
- try {
1495
- return { auditNoReceipt: parseNoReceiptLifecycleFacts(projected.value) };
1496
- } catch {
1497
- return {};
1498
- }
1499
- }
1500
-
1501
- /** Keep optional auditNoReceipt parallel fact when present on sealed details. */
1502
- function withAuditNoReceiptFacts(
1503
- candidate: Readonly<Record<string, unknown>>,
1504
- ): Record<string, unknown> {
1505
- return {
1506
- ...candidate,
1507
- ...auditNoReceiptDecisiveFact(candidate),
1508
- };
1509
- }
1510
-
1511
- /**
1512
- * ADR 0037: a shape-valid Collector receipt may still name the wrong live target.
1513
- * Public success binds receipt identity to this admitted repository/PR/request manifest
1514
- * at the existing settlement seam — not a second receipt factory or validator.
1515
- */
1516
- function collectorReceiptBindingFailure(
1517
- diagnostic: string,
1518
- ): Error & { knownCause: ControlledFailureCause } {
1519
- const error = new Error(diagnostic) as Error & {
1520
- knownCause: ControlledFailureCause;
1521
- };
1522
- error.name = "CollectorReceiptBindingError";
1523
- error.knownCause = "output";
1524
- return error;
1525
- }
1526
-
1527
1484
  function toolResultText(message: SessionMessage): string {
1528
1485
  const content = message.content;
1529
1486
  if (typeof content === "string") return content.trim();
@@ -1736,33 +1693,6 @@ export async function readEngineDetourInfrastructureFailure(
1736
1693
  );
1737
1694
  }
1738
1695
 
1739
- /**
1740
- * Compare a validated receipt with the admitted Collector invocation identity.
1741
- * Throws a typed output failure when any identity field mismatches.
1742
- */
1743
- export function assertCollectorReceiptMatchesAdmitted(
1744
- receipt: CollectorReceipt,
1745
- admitted: AdmittedCollectorInvocation,
1746
- ): void {
1747
- if (receipt.repository !== admitted.repository.canonical) {
1748
- throw collectorReceiptBindingFailure(
1749
- `Collector receipt repository "${receipt.repository}" does not match admitted repository "${admitted.repository.canonical}"`,
1750
- );
1751
- }
1752
- // #676 A: when admission left the target unbound, receipt.prNumber is the role bind.
1753
- // When admission bound explicitly/head-commit, receipt must match.
1754
- if (admitted.prNumber !== undefined && receipt.prNumber !== admitted.prNumber) {
1755
- throw collectorReceiptBindingFailure(
1756
- `Collector receipt prNumber ${receipt.prNumber} does not match admitted prNumber ${admitted.prNumber}`,
1757
- );
1758
- }
1759
- if (receipt.manifestDigest !== admitted.manifestDigest) {
1760
- throw collectorReceiptBindingFailure(
1761
- `Collector receipt manifestDigest does not match admitted manifestDigest`,
1762
- );
1763
- }
1764
- }
1765
-
1766
1696
  function auditToolNameForRole(
1767
1697
  role: (typeof AUDITOR_SOUL_ROLES)[number],
1768
1698
  ): string {
@@ -2441,12 +2371,8 @@ export async function publishCoderArtifacts(
2441
2371
  }
2442
2372
 
2443
2373
  /** Lawful Coder accepted outcome extracted from session (shared success interface). */
2444
- export type LawfulCoderRoleOutcome = {
2445
- kind: "accepted";
2446
- role: "coder";
2447
- status: string;
2448
- decisiveFacts: Readonly<Record<string, unknown>>;
2449
- };
2374
+ export type LawfulCoderRoleOutcome = Extract<TerminalRoleOutcome, { kind: "accepted" }>;
2375
+
2450
2376
  /**
2451
2377
  * Read session entries for lawful settlement. Missing path → undefined (absence).
2452
2378
  * Malformed JSONL / other read failures throw with knownCause=session.
@@ -2477,20 +2403,7 @@ export async function readLawfulJudgeRoleOutcome(
2477
2403
  authority: DurablePrincipalAuthority,
2478
2404
  scope?: SettlementCourtScope,
2479
2405
  ): Promise<LawfulJudgeRoleOutcome | undefined> {
2480
- const sealed = await sealedLedgerOutcome(admitted, scope);
2481
- if (sealed?.role === "judge") {
2482
- const details = sealed.decisiveFacts as Record<string, unknown>;
2483
- // sealed.status is the sole authority (written by acceptedFacts at seal).
2484
- return {
2485
- kind: "accepted",
2486
- role: "judge",
2487
- status: sealed.status,
2488
- // #757: sealed details pass through (judgeStatus already on the receipt).
2489
- decisiveFacts: withAuditNoReceiptFacts(details),
2490
- };
2491
- }
2492
- // Non-final: consume ledger audit-escalation projection (no JSONL accepted rebuild).
2493
- return auditEscalationLedgerOutcome(admitted, "judge", scope);
2406
+ return sealedLedgerOutcome(admitted, "judge", scope);
2494
2407
  }
2495
2408
 
2496
2409
  /**
@@ -2573,11 +2486,10 @@ async function settleLawfulCoderTerminalResult(
2573
2486
  ): Promise<TerminalResult | undefined> {
2574
2487
  const ledgerOutcome = await closedLedgerOutcome(admitted, "coder", scope);
2575
2488
  if (ledgerOutcome === undefined) return undefined;
2576
- // #757: sealed facts pass through — no shape re-project / field drop.
2577
2489
  const roleOutcome: TerminalRoleOutcome = ledgerOutcome;
2578
2490
  const output: CoderOutput | undefined =
2579
2491
  ledgerOutcome.kind === "accepted"
2580
- ? (ledgerOutcome.decisiveFacts as unknown as CoderOutput)
2492
+ ? (lastRolePayloadRecord(ledgerOutcome.payloads ?? []) as CoderOutput | undefined)
2581
2493
  : undefined;
2582
2494
  const coordinates = coordinatesFromAdmitted(authority, admitted);
2583
2495
  const entries = await readLawfulSettlementEntries(coordinates.sessionFile) ?? [];
@@ -2740,12 +2652,7 @@ export async function publishFixerArtifacts(
2740
2652
  }
2741
2653
 
2742
2654
  /** Lawful Fixer accepted outcome extracted from session (no LLM auditor after #242). */
2743
- export type LawfulFixerRoleOutcome = {
2744
- kind: "accepted";
2745
- role: "fixer";
2746
- status: string;
2747
- decisiveFacts: Readonly<Record<string, unknown>>;
2748
- };
2655
+ export type LawfulFixerRoleOutcome = Extract<TerminalRoleOutcome, { kind: "accepted" }>;
2749
2656
  async function settleLawfulFixerTerminalResult(
2750
2657
  admitted: AdmittedFixerInvocation,
2751
2658
  authority: DurablePrincipalAuthority,
@@ -2758,11 +2665,10 @@ async function settleLawfulFixerTerminalResult(
2758
2665
  ): Promise<TerminalResult | undefined> {
2759
2666
  const ledgerOutcome = await closedLedgerOutcome(admitted, "fixer", scope);
2760
2667
  if (ledgerOutcome === undefined) return undefined;
2761
- // #757: sealed facts pass through — no shape re-project / field drop.
2762
2668
  const roleOutcome: TerminalRoleOutcome = ledgerOutcome;
2763
2669
  const output: FixerOutput | undefined =
2764
2670
  ledgerOutcome.kind === "accepted"
2765
- ? (ledgerOutcome.decisiveFacts as unknown as FixerOutput)
2671
+ ? (lastRolePayloadRecord(ledgerOutcome.payloads ?? []) as FixerOutput | undefined)
2766
2672
  : undefined;
2767
2673
  const coordinates = coordinatesFromAdmitted(authority, admitted);
2768
2674
  const { sessionDirectory, sessionFile } = coordinates;
@@ -2874,13 +2780,7 @@ export async function publishCollectorArtifacts(
2874
2780
  }
2875
2781
 
2876
2782
  /** Lawful Collector accepted outcome extracted from session. */
2877
- export type LawfulCollectorRoleOutcome = {
2878
- kind: "accepted";
2879
- role: "collector";
2880
- /** Collector has no status leaf — sealed projection carries acceptedFacts collected. */
2881
- status: string;
2882
- decisiveFacts: Readonly<Record<string, unknown>>;
2883
- };
2783
+ export type LawfulCollectorRoleOutcome = Extract<TerminalRoleOutcome, { kind: "accepted" }>;
2884
2784
  async function settleLawfulCollectorTerminalResult(
2885
2785
  admitted: AdmittedCollectorInvocation,
2886
2786
  authority: DurablePrincipalAuthority,
@@ -2889,8 +2789,8 @@ async function settleLawfulCollectorTerminalResult(
2889
2789
  const coordinates = coordinatesFromAdmitted(authority, admitted);
2890
2790
  const { sessionDirectory, sessionFile } = coordinates;
2891
2791
  const entries = await readLawfulSettlementEntries(sessionFile) ?? [];
2892
- const roleOutcome = await sealedLedgerOutcome(admitted, scope);
2893
- if (roleOutcome?.role !== "collector") {
2792
+ const roleOutcome = await sealedLedgerOutcome(admitted, "collector", scope);
2793
+ if (roleOutcome?.role !== "collector" || roleOutcome.kind !== "accepted") {
2894
2794
  // Bounded to the current attempt so multi-attempt resume timeout/no-output
2895
2795
  // is not masked by a prior wait-tool residual (#633).
2896
2796
  const scanStart = currentAttemptStartIndex(entries);
@@ -2900,33 +2800,18 @@ async function settleLawfulCollectorTerminalResult(
2900
2800
  const residual = boundErroredToolCandidate(entries, index, message, COLLECTOR_WAIT_TOOL);
2901
2801
  if (residual === undefined) continue;
2902
2802
  const candidate = residual.candidate;
2903
- const duration = isRecord(candidate) ? candidate.durationMs : undefined;
2904
- if (Number.isSafeInteger(duration) && (duration as number) >= 1 && (duration as number) <= 900_000) {
2905
- continue;
2906
- }
2907
- return {
2908
- roleOutcome: buildResidualIncompleteTerminalOutcome({
2909
- role: "collector",
2910
- candidate,
2911
- diagnostic: residual.diagnostic,
2912
- }),
2913
- navigator: { disposition: "no-advice" },
2914
- artifacts: [],
2915
- runId: admitted.runId,
2916
- };
2803
+ const details = isRecord(candidate) ? candidate : { candidate };
2804
+ const failed = await settleFailureTerminalResult(admitted, {
2805
+ cause: "output",
2806
+ diagnostic: residual.diagnostic,
2807
+ details,
2808
+ }, authority);
2809
+ return attachRecordedSubmissions(admitted, failed, scope);
2917
2810
  }
2918
2811
  return undefined;
2919
2812
  }
2920
- // #757: sealed facts pass through — no groups rebuild / field drop.
2921
- // ADR 0037 identity binding stays (external admitted facts, not shape).
2922
- const receipt = roleOutcome.decisiveFacts as unknown as CollectorReceipt;
2923
- assertCollectorReceiptMatchesAdmitted(receipt, admitted);
2924
- const accepted: LawfulCollectorRoleOutcome = {
2925
- kind: "accepted",
2926
- role: "collector",
2927
- status: roleOutcome.status,
2928
- decisiveFacts: { ...roleOutcome.decisiveFacts },
2929
- };
2813
+ const receipt = (lastRolePayloadRecord(roleOutcome.payloads ?? []) ?? {}) as CollectorReceipt;
2814
+ const accepted: LawfulCollectorRoleOutcome = roleOutcome;
2930
2815
  const navigator = extractNavigatorFact(entries);
2931
2816
  const artifacts = await publishCollectorArtifacts(
2932
2817
  admitted,
@@ -2934,14 +2819,18 @@ async function settleLawfulCollectorTerminalResult(
2934
2819
  coordinates,
2935
2820
  { collectorReceipt: receipt },
2936
2821
  );
2937
- return withOptionalGateProjection(
2938
- {
2939
- roleOutcome: accepted,
2940
- navigator,
2941
- artifacts,
2942
- runId: admitted.runId,
2943
- },
2944
- sessionDirectory,
2822
+ return attachRecordedSubmissions(
2823
+ admitted,
2824
+ await withOptionalGateProjection(
2825
+ {
2826
+ roleOutcome: accepted,
2827
+ navigator,
2828
+ artifacts,
2829
+ runId: admitted.runId,
2830
+ },
2831
+ sessionDirectory,
2832
+ ),
2833
+ scope,
2945
2834
  );
2946
2835
  }
2947
2836
 
@@ -2969,12 +2858,53 @@ export async function trySettleCollectorTerminalResult(
2969
2858
  return settleLawfulCollectorTerminalResult(admitted, authority, scope);
2970
2859
  }
2971
2860
 
2861
+ /**
2862
+ * #836: runtime cost is a machine fact recorded beside the role's original
2863
+ * testimony (`ak_doctor_audit_candidate` custom entry), never merged into the
2864
+ * accepted payload itself. Absence (no candidate entry, or entry without a
2865
+ * cost sibling) reads as undefined — never invented.
2866
+ */
2867
+ function extractDoctorCandidateCostFact(
2868
+ entries: readonly SessionEntry[],
2869
+ ): DoctorCaseCost | undefined {
2870
+ const scanStart = currentAttemptStartIndex(entries);
2871
+ for (let i = entries.length - 1; i >= scanStart; i -= 1) {
2872
+ const entry = entries[i];
2873
+ if (entry?.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
2874
+ const data = entry.data;
2875
+ return isRecord(data) ? (data.cost as DoctorCaseCost | undefined) : undefined;
2876
+ }
2877
+ }
2878
+ return undefined;
2879
+ }
2880
+
2881
+ /**
2882
+ * #836: the auditor's own no-receipt lifecycle facts are a machine fact about
2883
+ * the audit leg, recorded beside (never merged into) the role's accepted
2884
+ * testimony. Absence reads as undefined — never invented.
2885
+ */
2886
+ function extractDoctorCandidateAuditNoReceiptFact(
2887
+ entries: readonly SessionEntry[],
2888
+ ): unknown {
2889
+ const scanStart = currentAttemptStartIndex(entries);
2890
+ for (let i = entries.length - 1; i >= scanStart; i -= 1) {
2891
+ const entry = entries[i];
2892
+ if (entry?.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
2893
+ const data = entry.data;
2894
+ return isRecord(data) ? data.auditNoReceipt : undefined;
2895
+ }
2896
+ }
2897
+ return undefined;
2898
+ }
2899
+
2972
2900
  export async function publishDoctorArtifacts(
2973
2901
  admitted: AdmittedDoctorInvocation,
2974
2902
  roleOutcome: TerminalRoleOutcome,
2975
2903
  coordinates: DurablePrincipalCoordinates,
2976
2904
  options: {
2977
2905
  readonly doctorOutput?: DoctorOutput;
2906
+ readonly cost?: DoctorCaseCost;
2907
+ readonly auditNoReceipt?: unknown;
2978
2908
  } = {},
2979
2909
  ): Promise<TerminalArtifactRef[]> {
2980
2910
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
@@ -2991,6 +2921,9 @@ export async function publishDoctorArtifacts(
2991
2921
  ...(options.doctorOutput === undefined
2992
2922
  ? {}
2993
2923
  : { receipt: options.doctorOutput }),
2924
+ // Independent machine fields beside the receipt — not merged into it.
2925
+ ...(options.cost === undefined ? {} : { cost: options.cost }),
2926
+ ...(options.auditNoReceipt === undefined ? {} : { auditNoReceipt: options.auditNoReceipt }),
2994
2927
  },
2995
2928
  null,
2996
2929
  2,
@@ -3028,35 +2961,25 @@ export async function publishDoctorArtifacts(
3028
2961
  }
3029
2962
 
3030
2963
  /** Lawful Doctor accepted/refused/audit_escalation outcome extracted from session. */
3031
- export type LawfulDoctorRoleOutcome =
3032
- | {
3033
- kind: "accepted";
3034
- role: "doctor";
3035
- status: string;
3036
- decisiveFacts: Readonly<Record<string, unknown>>;
3037
- }
3038
- | {
3039
- kind: "audit_escalation";
3040
- role: "doctor";
3041
- status: "audit_escalation";
3042
- decisiveFacts: Readonly<Record<string, unknown>>;
3043
- };
2964
+ export type LawfulDoctorRoleOutcome = Extract<
2965
+ TerminalRoleOutcome,
2966
+ { kind: "accepted" } | { kind: "audit_escalation" }
2967
+ >;
3044
2968
  async function settleLawfulDoctorTerminalResult(
3045
2969
  admitted: AdmittedDoctorInvocation,
3046
2970
  authority: DurablePrincipalAuthority,
3047
2971
  scope?: SettlementCourtScope,
3048
2972
  ): Promise<TerminalResult | undefined> {
3049
- const sealed = await sealedLedgerOutcome(admitted, scope);
2973
+ const sealed = await sealedLedgerOutcome(admitted, "doctor", scope);
3050
2974
  const coordinates = coordinatesFromAdmitted(authority, admitted);
3051
2975
  const { sessionDirectory, sessionFile } = coordinates;
3052
2976
  const entries = await readLawfulSettlementEntries(sessionFile) ?? [];
3053
- if (sealed?.role !== "doctor") {
3054
- const escalation = await auditEscalationLedgerOutcome(admitted, "doctor", scope);
3055
- if (escalation === undefined) return undefined;
3056
- const artifacts = await publishDoctorArtifacts(admitted, escalation, coordinates);
2977
+ if (sealed === undefined) return undefined;
2978
+ if (sealed.kind === "audit_escalation") {
2979
+ const artifacts = await publishDoctorArtifacts(admitted, sealed, coordinates);
3057
2980
  return withOptionalGateProjection(
3058
2981
  {
3059
- roleOutcome: escalation,
2982
+ roleOutcome: sealed,
3060
2983
  navigator: extractNavigatorFact(entries),
3061
2984
  artifacts,
3062
2985
  runId: admitted.runId,
@@ -3064,39 +2987,20 @@ async function settleLawfulDoctorTerminalResult(
3064
2987
  sessionDirectory,
3065
2988
  );
3066
2989
  }
3067
- // #757: sealed facts pass through — no validateRecordedDoctorOutput shape gate.
3068
- const output = sealed.decisiveFacts as unknown as DoctorOutput;
3069
- const roleOutcome: Extract<LawfulDoctorRoleOutcome, { kind: "accepted" }> = {
3070
- kind: "accepted",
3071
- role: "doctor",
3072
- status: sealed.status,
3073
- decisiveFacts: { ...sealed.decisiveFacts },
3074
- };
3075
- // Bind completed receipt case identity to the admitted Issue evidence case (external fact).
3076
- if (String((output as { status?: unknown }).status) === "completed") {
3077
- const completedCase = (
3078
- output as {
3079
- case: { issueNumber: number; runsPath: string };
3080
- }
3081
- ).case;
3082
- if (
3083
- completedCase.issueNumber !== admitted.caseIdentity.issueNumber ||
3084
- completedCase.runsPath !== admitted.caseIdentity.runsPath
3085
- ) {
3086
- const error = new Error(
3087
- "Doctor receipt case identity does not match admitted case identity",
3088
- ) as Error & { knownCause: ControlledFailureCause };
3089
- error.name = "DoctorReceiptBindingError";
3090
- error.knownCause = "output";
3091
- throw error;
3092
- }
3093
- }
2990
+ const output = (lastRolePayloadRecord(sealed.payloads ?? []) ?? {}) as DoctorOutput;
2991
+ const roleOutcome = sealed;
3094
2992
  const navigator = extractNavigatorFact(entries);
2993
+ const cost = extractDoctorCandidateCostFact(entries);
2994
+ const auditNoReceipt = extractDoctorCandidateAuditNoReceiptFact(entries);
3095
2995
  const artifacts = await publishDoctorArtifacts(
3096
2996
  admitted,
3097
2997
  roleOutcome,
3098
2998
  coordinates,
3099
- { doctorOutput: output },
2999
+ {
3000
+ doctorOutput: output,
3001
+ ...(cost === undefined ? {} : { cost }),
3002
+ ...(auditNoReceipt === undefined ? {} : { auditNoReceipt }),
3003
+ },
3100
3004
  );
3101
3005
  return withOptionalGateProjection(
3102
3006
  {
@@ -3179,70 +3083,66 @@ async function settleLawfulSeatAcceptedTerminalResult(
3179
3083
  const coordinates = coordinatesFromAdmitted(authority, admitted);
3180
3084
  const { sessionDirectory, sessionFile } = coordinates;
3181
3085
  const entries = await readLawfulSettlementEntries(sessionFile) ?? [];
3086
+ const submissions = await recordedSubmissionPayloads(admitted, scope);
3087
+ // Host isError residual wins over any recorded projection (#836 A.3 coexistence).
3088
+ const scanStart = currentAttemptStartIndex(entries);
3089
+ for (let index = entries.length - 1; index >= scanStart; index -= 1) {
3090
+ const message = entries[index]?.message;
3091
+ if (message?.role !== "toolResult") continue;
3092
+ const residual = boundErroredToolCandidate(
3093
+ entries,
3094
+ index,
3095
+ message,
3096
+ spec.toolName,
3097
+ );
3098
+ if (residual !== undefined) {
3099
+ const details = isRecord(residual.candidate)
3100
+ ? residual.candidate
3101
+ : { candidate: residual.candidate };
3102
+ const failed = await settleFailureTerminalResult(admitted, {
3103
+ cause: "output",
3104
+ diagnostic: residual.diagnostic,
3105
+ details,
3106
+ }, authority);
3107
+ return withSubmissions(failed, submissions);
3108
+ }
3109
+ }
3182
3110
  const roleOutcome = await closedLedgerOutcome(admitted, spec.role as TerminalRoleName, scope);
3183
3111
  if (roleOutcome?.kind === "audit_escalation") {
3184
3112
  const navigator = extractNavigatorFact(entries);
3185
- return withOptionalGateProjection(
3186
- {
3187
- roleOutcome,
3188
- navigator,
3189
- artifacts: [],
3190
- runId: admitted.runId,
3191
- },
3192
- sessionDirectory,
3113
+ return withSubmissions(
3114
+ await withOptionalGateProjection(
3115
+ {
3116
+ roleOutcome,
3117
+ navigator,
3118
+ artifacts: [],
3119
+ runId: admitted.runId,
3120
+ },
3121
+ sessionDirectory,
3122
+ ),
3123
+ submissions,
3193
3124
  );
3194
3125
  }
3195
- if (roleOutcome?.role !== spec.role) {
3196
- // No sealed ledger outcome for this seat/court. Prefer a real isError residual
3197
- // (transport/lifecycle failure). Accepted-once without seal is absence — seal is
3198
- // the sole acceptance authority (#637); do not promote session bytes to success.
3199
- // Bounded to the current attempt so multi-attempt resume timeout/no-output
3200
- // is not masked by a prior residual (#599 / #633).
3201
- const scanStart = currentAttemptStartIndex(entries);
3202
- for (let index = entries.length - 1; index >= scanStart; index -= 1) {
3203
- const message = entries[index]?.message;
3204
- if (message?.role !== "toolResult") continue;
3205
- const residual = boundErroredToolCandidate(
3206
- entries,
3207
- index,
3208
- message,
3209
- spec.toolName,
3210
- );
3211
- if (residual !== undefined) {
3212
- // isError residual: retain candidate bytes as details (no shape stamp).
3213
- const details = isRecord(residual.candidate)
3214
- ? residual.candidate
3215
- : { candidate: residual.candidate };
3216
- return settleFailureTerminalResult(admitted, {
3217
- cause: "output",
3218
- diagnostic: residual.diagnostic,
3219
- details,
3220
- }, authority);
3221
- }
3222
- }
3223
- return undefined;
3126
+ if (roleOutcome?.role === spec.role) {
3127
+ const navigator = extractNavigatorFact(entries);
3128
+ return withSubmissions(
3129
+ await withOptionalGateProjection(
3130
+ {
3131
+ roleOutcome,
3132
+ navigator,
3133
+ artifacts: [],
3134
+ runId: admitted.runId,
3135
+ },
3136
+ sessionDirectory,
3137
+ ),
3138
+ submissions,
3139
+ );
3224
3140
  }
3225
- // Sealed ledger outcome: pass through full decisiveFacts (#757).
3226
- const acceptedOutcome = roleOutcome;
3227
- const navigator = extractNavigatorFact(entries);
3228
- return withOptionalGateProjection(
3229
- {
3230
- roleOutcome: acceptedOutcome,
3231
- navigator,
3232
- artifacts: [],
3233
- runId: admitted.runId,
3234
- },
3235
- sessionDirectory,
3236
- );
3141
+ return undefined;
3237
3142
  }
3238
3143
 
3239
3144
  /** Lawful Notary accepted outcome (pass/bounce/escalate). */
3240
- export type LawfulNotaryRoleOutcome = {
3241
- kind: "accepted";
3242
- role: "notary";
3243
- status: string;
3244
- decisiveFacts: Readonly<Record<string, unknown>>;
3245
- };
3145
+ export type LawfulNotaryRoleOutcome = Extract<TerminalRoleOutcome, { kind: "accepted" }>;
3246
3146
 
3247
3147
  async function settleLawfulNotaryTerminalResult(
3248
3148
  admitted: AdmittedNotaryInvocation,
@@ -3281,12 +3181,7 @@ export async function trySettleNotaryTerminalResult(
3281
3181
  }
3282
3182
 
3283
3183
  /** Lawful Countersign accepted outcome (署/封驳/上呈, #572 / ADR 0074). */
3284
- export type LawfulCountersignRoleOutcome = {
3285
- kind: "accepted";
3286
- role: "countersign";
3287
- status: string;
3288
- decisiveFacts: Readonly<Record<string, unknown>>;
3289
- };
3184
+ export type LawfulCountersignRoleOutcome = Extract<TerminalRoleOutcome, { kind: "accepted" }>;
3290
3185
 
3291
3186
  async function settleLawfulCountersignTerminalResult(
3292
3187
  admitted: AdmittedCountersignInvocation,
@@ -3324,12 +3219,7 @@ export async function trySettleCountersignTerminalResult(
3324
3219
  }
3325
3220
 
3326
3221
  /** Lawful Gleaner-Left accepted outcome (completed 弹章, #502). */
3327
- export type LawfulGleanerLeftRoleOutcome = {
3328
- kind: "accepted";
3329
- role: "gleaner-left";
3330
- status: string;
3331
- decisiveFacts: Readonly<Record<string, unknown>>;
3332
- };
3222
+ export type LawfulGleanerLeftRoleOutcome = Extract<TerminalRoleOutcome, { kind: "accepted" }>;
3333
3223
 
3334
3224
  async function settleLawfulGleanerLeftTerminalResult(
3335
3225
  admitted: AdmittedGleanerLeftInvocation,
@@ -3367,12 +3257,7 @@ export async function trySettleGleanerLeftTerminalResult(
3367
3257
  }
3368
3258
 
3369
3259
  /** Lawful Diarist accepted outcome (completed 入录选择, #708). */
3370
- export type LawfulDiaristRoleOutcome = {
3371
- kind: "accepted";
3372
- role: "diarist";
3373
- status: string;
3374
- decisiveFacts: Readonly<Record<string, unknown>>;
3375
- };
3260
+ export type LawfulDiaristRoleOutcome = Extract<TerminalRoleOutcome, { kind: "accepted" }>;
3376
3261
 
3377
3262
  async function settleLawfulDiaristTerminalResult(
3378
3263
  admitted: AdmittedDiaristInvocation,
@@ -3395,12 +3280,7 @@ export async function trySettleDiaristTerminalResult(
3395
3280
  }
3396
3281
 
3397
3282
  /** Lawful Inspector accepted outcome (pass/bounce/escalate). */
3398
- export type LawfulInspectorRoleOutcome = {
3399
- kind: "accepted";
3400
- role: "inspector";
3401
- status: string;
3402
- decisiveFacts: Readonly<Record<string, unknown>>;
3403
- };
3283
+ export type LawfulInspectorRoleOutcome = Extract<TerminalRoleOutcome, { kind: "accepted" }>;
3404
3284
 
3405
3285
  async function settleLawfulInspectorTerminalResult(
3406
3286
  admitted: AdmittedInspectorInvocation,
@@ -3422,12 +3302,7 @@ export async function trySettleInspectorTerminalResult(
3422
3302
  }
3423
3303
 
3424
3304
  /** Lawful Gatekeeper accepted outcome (dispatch | pass, #639). */
3425
- export type LawfulGatekeeperRoleOutcome = {
3426
- kind: "accepted";
3427
- role: "gatekeeper";
3428
- status: string;
3429
- decisiveFacts: Readonly<Record<string, unknown>>;
3430
- };
3305
+ export type LawfulGatekeeperRoleOutcome = Extract<TerminalRoleOutcome, { kind: "accepted" }>;
3431
3306
 
3432
3307
  async function settleLawfulGatekeeperTerminalResult(
3433
3308
  admitted: AdmittedGatekeeperInvocation,
@@ -3450,12 +3325,7 @@ export async function trySettleGatekeeperTerminalResult(
3450
3325
  }
3451
3326
 
3452
3327
  /** Lawful Navigator accepted outcome (route advice, #639). */
3453
- export type LawfulNavigatorRoleOutcome = {
3454
- kind: "accepted";
3455
- role: "navigator";
3456
- status: string;
3457
- decisiveFacts: Readonly<Record<string, unknown>>;
3458
- };
3328
+ export type LawfulNavigatorRoleOutcome = Extract<TerminalRoleOutcome, { kind: "accepted" }>;
3459
3329
 
3460
3330
  async function settleLawfulNavigatorTerminalResult(
3461
3331
  admitted: AdmittedNavigatorInvocation,
@@ -3478,12 +3348,7 @@ export async function trySettleNavigatorTerminalResult(
3478
3348
  }
3479
3349
 
3480
3350
  /** Lawful Auditor accepted outcome (pass/bounce/escalate, #675 / #754). */
3481
- export type LawfulAuditorRoleOutcome = {
3482
- kind: "accepted";
3483
- role: "auditor";
3484
- status: string;
3485
- decisiveFacts: Readonly<Record<string, unknown>>;
3486
- };
3351
+ export type LawfulAuditorRoleOutcome = Extract<TerminalRoleOutcome, { kind: "accepted" }>;
3487
3352
 
3488
3353
  async function settleLawfulAuditorTerminalResult(
3489
3354
  admitted: import("./invocation.ts").AdmittedAuditorInvocation,
@@ -3568,7 +3433,7 @@ export async function publishReviewerArtifacts(
3568
3433
  options: {
3569
3434
  readonly methodProvenance: PackagedMethodSkillProvenance;
3570
3435
  readonly methodInvocations?: readonly ObservedPackagedMethodSkillInvocation[];
3571
- readonly reviewerReceipt?: RuntimeReviewerReceiptV2;
3436
+ readonly reviewerReceipt?: ReviewerIntent;
3572
3437
  },
3573
3438
  ): Promise<TerminalArtifactRef[]> {
3574
3439
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
@@ -3605,10 +3470,6 @@ export async function publishReviewerArtifacts(
3605
3470
  ...(admitted.instructionEmpty
3606
3471
  ? {}
3607
3472
  : { callerProvenance: admitted.instruction }),
3608
- // Self-fetch Spec bytes + source annotation when primary path produced material (#343).
3609
- ...(options.reviewerReceipt?.specFetchedMaterial === undefined
3610
- ? {}
3611
- : { specFetchedMaterial: options.reviewerReceipt.specFetchedMaterial }),
3612
3473
  attachments: admitted.attachments.map((a) => ({
3613
3474
  provenancePath: a.provenancePath,
3614
3475
  frozenPath: a.frozenPath,
@@ -3632,12 +3493,7 @@ export async function publishReviewerArtifacts(
3632
3493
  }
3633
3494
 
3634
3495
  /** Lawful Reviewer accepted outcome extracted from session (no LLM auditor after #495 S6). */
3635
- export type LawfulReviewerRoleOutcome = {
3636
- kind: "accepted";
3637
- role: "reviewer";
3638
- status: string;
3639
- decisiveFacts: Readonly<Record<string, unknown>>;
3640
- };
3496
+ export type LawfulReviewerRoleOutcome = Extract<TerminalRoleOutcome, { kind: "accepted" }>;
3641
3497
  async function settleLawfulReviewerTerminalResult(
3642
3498
  admitted: AdmittedReviewerInvocation,
3643
3499
  authority: DurablePrincipalAuthority,
@@ -3648,19 +3504,13 @@ async function settleLawfulReviewerTerminalResult(
3648
3504
  },
3649
3505
  scope?: SettlementCourtScope,
3650
3506
  ): Promise<TerminalResult | undefined> {
3651
- const sealed = await sealedLedgerOutcome(admitted, scope);
3652
- if (sealed?.role !== "reviewer") return undefined;
3507
+ const sealed = await sealedLedgerOutcome(admitted, "reviewer", scope);
3508
+ if (sealed?.role !== "reviewer" || sealed.kind !== "accepted") return undefined;
3653
3509
  const coordinates = coordinatesFromAdmitted(authority, admitted);
3654
3510
  const { sessionDirectory, sessionFile } = coordinates;
3655
3511
  const entries = await readLawfulSettlementEntries(sessionFile) ?? [];
3656
- // #757: sealed facts pass through — no validateRuntimeReviewerReceipt shape gate.
3657
- const receipt = sealed.decisiveFacts as unknown as RuntimeReviewerReceiptV2;
3658
- const roleOutcome: LawfulReviewerRoleOutcome = {
3659
- kind: "accepted",
3660
- role: "reviewer",
3661
- status: sealed.status,
3662
- decisiveFacts: { ...sealed.decisiveFacts },
3663
- };
3512
+ const receipt = lastRolePayloadRecord(sealed.payloads ?? []) as ReviewerIntent | undefined;
3513
+ const roleOutcome: LawfulReviewerRoleOutcome = sealed;
3664
3514
  const navigator = extractNavigatorFact(entries);
3665
3515
  const methodInvocations = extractReviewerMethodInvocations(entries, {
3666
3516
  allowedLocations: [
@@ -3673,7 +3523,7 @@ async function settleLawfulReviewerTerminalResult(
3673
3523
  roleOutcome,
3674
3524
  coordinates,
3675
3525
  {
3676
- reviewerReceipt: receipt,
3526
+ ...(receipt === undefined ? {} : { reviewerReceipt: receipt }),
3677
3527
  methodProvenance: options.methodProvenance,
3678
3528
  methodInvocations,
3679
3529
  },
@@ -3818,12 +3668,7 @@ export async function publishMergerArtifacts(
3818
3668
  }
3819
3669
 
3820
3670
  /** Lawful Merger accepted outcome extracted from session (shared success interface). */
3821
- export type LawfulMergerRoleOutcome = {
3822
- kind: "accepted";
3823
- role: "merger";
3824
- status: string;
3825
- decisiveFacts: Readonly<Record<string, unknown>>;
3826
- };
3671
+ export type LawfulMergerRoleOutcome = Extract<TerminalRoleOutcome, { kind: "accepted" }>;
3827
3672
  async function settleLawfulMergerTerminalResult(
3828
3673
  admitted: AdmittedMergerInvocation,
3829
3674
  authority: DurablePrincipalAuthority,
@@ -3837,78 +3682,52 @@ async function settleLawfulMergerTerminalResult(
3837
3682
  const coordinates = coordinatesFromAdmitted(authority, admitted);
3838
3683
  const { sessionDirectory, sessionFile } = coordinates;
3839
3684
  const entries = await readLawfulSettlementEntries(sessionFile) ?? [];
3840
- const roleOutcome = await sealedLedgerOutcome(admitted, scope);
3841
- if (roleOutcome?.role !== "merger") {
3842
- // Ledger owns 0041: a non-sole closed round is not residual-incomplete material.
3843
- const latestOutcome = await readLatestSubmissionOutcome(
3844
- admitted.projectRoot,
3845
- admitted.runId,
3846
- ledgerReadScope(admitted, scope),
3847
- );
3848
- if (latestOutcome?.outcome === "correctable-rejection" && latestOutcome.code === "non-sole-round") {
3849
- return undefined;
3850
- }
3851
- // Residual incomplete: shape/identity fail after the sole-round barrier passed (ledger typed).
3852
- // Settlement does not re-judge calls.length.
3685
+ const roleOutcome = await sealedLedgerOutcome(admitted, "merger", scope);
3686
+ if (roleOutcome?.role !== "merger" || roleOutcome.kind !== "accepted") {
3687
+ // #836: non-sole-round barrier deleted; residual path is host/session only.
3853
3688
  for (let index = entries.length - 1; index >= 0; index -= 1) {
3854
3689
  const message = entries[index]?.message;
3855
3690
  if (message?.role !== "toolResult") continue;
3856
3691
  const residual = boundErroredToolCandidate(entries, index, message, MERGER_OUTPUT_TOOL_NAME);
3857
3692
  if (residual === undefined) continue;
3858
- const attemptId = isRecord(residual.candidate)
3859
- ? safelyRead(residual.candidate, "attemptId")
3860
- : { readable: true as const, value: undefined };
3861
- // Admitted-attempt identity binding only (ADR 0037) — not sole-final cardinality.
3862
- // isError residual with matching attemptId is incomplete; no shape re-judge (#757).
3863
- if (!attemptId.readable || attemptId.value !== admitted.runId) continue;
3864
- return {
3865
- roleOutcome: buildResidualIncompleteTerminalOutcome({
3866
- role: "merger",
3867
- candidate: residual.candidate,
3868
- diagnostic: residual.diagnostic,
3869
- }),
3870
- navigator: { disposition: "no-advice" },
3871
- artifacts: [],
3872
- runId: admitted.runId,
3873
- };
3693
+ const candidate = residual.candidate;
3694
+ const details = isRecord(candidate) ? candidate : { candidate };
3695
+ const failed = await settleFailureTerminalResult(admitted, {
3696
+ cause: "output",
3697
+ diagnostic: residual.diagnostic,
3698
+ details,
3699
+ }, authority);
3700
+ return attachRecordedSubmissions(admitted, failed, scope);
3874
3701
  }
3875
3702
  return undefined;
3876
3703
  }
3877
- // #757: sealed facts pass through — no validateMergerOutput shape gate.
3878
- const output = roleOutcome.decisiveFacts as unknown as MergerOutput;
3879
- const accepted: LawfulMergerRoleOutcome = {
3880
- kind: "accepted",
3881
- role: "merger",
3882
- status: roleOutcome.status,
3883
- decisiveFacts: { ...roleOutcome.decisiveFacts },
3884
- };
3704
+ const accepted: LawfulMergerRoleOutcome = roleOutcome;
3705
+ const navigator = extractNavigatorFact(entries);
3885
3706
  const methodInvocations = extractMergerMethodInvocations(entries, {
3886
- allowedLocations: [
3887
- options.methodSkillPath,
3888
- options.methodSkillConfiguredPath,
3889
- ],
3707
+ allowedLocations: [options.methodSkillPath, options.methodSkillConfiguredPath],
3890
3708
  });
3891
- // Every invocation must expand the merge-only method before conflict work.
3892
- if (methodInvocations.length === 0) return undefined;
3893
- const navigator = extractNavigatorFact(entries);
3894
3709
  const artifacts = await publishMergerArtifacts(
3895
3710
  admitted,
3896
3711
  accepted,
3897
3712
  coordinates,
3898
3713
  {
3899
- mergerOutput: output,
3714
+ mergerOutput: (lastRolePayloadRecord(accepted.payloads ?? []) ?? {}) as MergerOutput,
3900
3715
  methodProvenance: options.methodProvenance,
3901
3716
  methodInvocations,
3902
3717
  },
3903
3718
  );
3904
- return withOptionalGateProjection(
3905
- {
3906
- roleOutcome: accepted,
3907
- navigator,
3908
- artifacts,
3909
- runId: admitted.runId,
3910
- },
3911
- sessionDirectory,
3719
+ return attachRecordedSubmissions(
3720
+ admitted,
3721
+ await withOptionalGateProjection(
3722
+ {
3723
+ roleOutcome: accepted,
3724
+ navigator,
3725
+ artifacts,
3726
+ runId: admitted.runId,
3727
+ },
3728
+ sessionDirectory,
3729
+ ),
3730
+ scope,
3912
3731
  );
3913
3732
  }
3914
3733
 
@@ -4164,67 +3983,6 @@ export async function publishFailureArtifacts(
4164
3983
  ];
4165
3984
  }
4166
3985
 
4167
- /**
4168
- * Durably record a controlled failure (Error Artifact first), then return the
4169
- * Terminal aggregate. Presentation must happen only after this resolves.
4170
- */
4171
- /** Redact exact run ID from any string leaves inside decisive facts (arrays/objects included). */
4172
- function redactDecisiveFactValue(value: unknown, runId: string): unknown {
4173
- if (typeof value === "string") return redactExactRunId(value, runId);
4174
- if (Array.isArray(value)) {
4175
- return value.map((entry) => redactDecisiveFactValue(entry, runId));
4176
- }
4177
- if (typeof value === "object" && value !== null) {
4178
- const out: Record<string, unknown> = {};
4179
- for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
4180
- out[key] = redactDecisiveFactValue(child, runId);
4181
- }
4182
- return out;
4183
- }
4184
- return value;
4185
- }
4186
-
4187
- /** Redact exact run ID from decisive facts at the public Terminal boundary. */
4188
- function redactDecisiveFactsForPublicTerminal(
4189
- facts: Readonly<Record<string, unknown>>,
4190
- runId: string,
4191
- ): Record<string, unknown> {
4192
- const out: Record<string, unknown> = {};
4193
- for (const [key, value] of Object.entries(facts)) {
4194
- out[key] = redactDecisiveFactValue(value, runId);
4195
- }
4196
- return out;
4197
- }
4198
-
4199
- /** Redact exact run ID from navigator free-text fields (reason only; commands are registry-owned). */
4200
- function redactNavigatorFactForPublicTerminal(
4201
- navigator: TerminalNavigatorFact,
4202
- runId: string,
4203
- ): TerminalNavigatorFact {
4204
- const advisoryDiagnostic = navigator.advisoryDiagnostic === undefined
4205
- ? {}
4206
- : { advisoryDiagnostic: redactExactRunId(navigator.advisoryDiagnostic, runId) };
4207
- if (navigator.disposition === "recommendation") {
4208
- return {
4209
- ...navigator,
4210
- ...advisoryDiagnostic,
4211
- reason: redactExactRunId(navigator.reason, runId),
4212
- };
4213
- }
4214
- if (navigator.disposition === "unavailable") {
4215
- return {
4216
- ...navigator,
4217
- ...advisoryDiagnostic,
4218
- reason: redactExactRunId(navigator.reason, runId),
4219
- };
4220
- }
4221
- return { ...navigator, ...advisoryDiagnostic };
4222
- }
4223
-
4224
- /**
4225
- * Durably record a controlled failure (Error Artifact first), then return the
4226
- * Terminal aggregate. Presentation must happen only after this resolves.
4227
- */
4228
3986
  /**
4229
3987
  * Shared controlled-failure Terminal settlement (#107 ownership).
4230
3988
  * Role identity comes from the admitted run; no new failure classes are introduced here.
@@ -4304,23 +4062,17 @@ export async function settleFailureTerminalResult(
4304
4062
  // path components, or untrusted free text — only resume.command may carry it
4305
4063
  // (AC2 / #108).
4306
4064
  if (options.resume !== undefined) {
4307
- const publicDiagnostic = redactExactRunId(failure.diagnostic, admitted.runId);
4308
- const publicFacts = redactDecisiveFactsForPublicTerminal(
4309
- { ...decisiveFacts, diagnostic: publicDiagnostic },
4310
- admitted.runId,
4311
- );
4312
4065
  const roleOutcome: TerminalRoleOutcome = {
4313
4066
  kind: "failure",
4314
4067
  role: admitted.role,
4315
4068
  cause: failure.cause,
4316
- diagnostic: publicDiagnostic,
4317
- decisiveFacts: publicFacts,
4069
+ diagnostic: failure.diagnostic,
4070
+ decisiveFacts,
4318
4071
  };
4319
- // #478: resume desensitization stays; gate is additive typed fact only.
4320
4072
  return withOptionalGateProjection(
4321
4073
  {
4322
4074
  roleOutcome,
4323
- navigator: redactNavigatorFactForPublicTerminal(navigator, admitted.runId),
4075
+ navigator,
4324
4076
  artifacts: [],
4325
4077
  resume: options.resume,
4326
4078
  },