@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
@@ -6,25 +6,27 @@ import type { HostContext, HostToolResult, RoleHost } from "./host-contracts.ts"
6
6
  import { isAuditEscalationProjection } from "./audit-escalation.ts";
7
7
 
8
8
 
9
- import {
10
- acceptedFacts,
11
- isTerminatingToolName,
12
- type AcceptedDetails,
13
- type TerminatingToolName,
14
- } from "./package-contracts/terminating-tools.ts";
15
9
  import { runIdFromRunDirectory } from "./run-terminal-artifacts.ts";
16
10
  import { readSitianRecords, resolveSitianRecordPathInLedger, sitianReport, type RecordPointer } from "./sitian-facade.ts";
17
- import type { TerminalRoleName, TerminalRoleOutcome } from "./public-cli/terminal.ts";
11
+ import type { TerminalRoleName } from "./public-cli/terminal.ts";
18
12
  import { isCorrectableExecuteError } from "./submission-correctable-error.ts";
19
13
  import { failOnInfrastructureFailureDeclaration } from "./package-contracts/terminating-infrastructure.ts";
20
14
 
21
15
  export type SubmissionCall = { readonly id: string; readonly name: string };
22
16
  export type SubmissionOutcomeKind = "correctable-rejection" | "audit-escalation" | "infrastructure";
23
- /** Typed correctable-rejection codes — settlement residual precedence without re-judging 0041. */
24
- export type CorrectableRejectionCode = "non-sole-round" | "non-terminate" | "typed-bounce";
17
+ /** Typed correctable-rejection codes — bounce/reminder paths only (#836: no sole/non-terminate reject). */
18
+ export type CorrectableRejectionCode = "typed-bounce";
25
19
  export type SubmissionLedgerEvent =
26
20
  | { readonly type: "roundContext"; readonly attemptId: string; readonly calls: readonly SubmissionCall[] }
27
- | { readonly type: "candidate"; readonly attemptId: string; readonly toolCallId: string; readonly toolName: string; readonly sequence: number }
21
+ | {
22
+ readonly type: "candidate";
23
+ readonly attemptId: string;
24
+ readonly toolCallId: string;
25
+ readonly toolName: string;
26
+ readonly sequence: number;
27
+ /** LLM tool-call params at call time (#836 原话). */
28
+ readonly params?: unknown;
29
+ }
28
30
  | {
29
31
  readonly type: "outcome";
30
32
  readonly attemptId: string;
@@ -32,18 +34,25 @@ export type SubmissionLedgerEvent =
32
34
  readonly outcome: SubmissionOutcomeKind;
33
35
  readonly diagnostic?: string;
34
36
  readonly code?: CorrectableRejectionCode;
35
- /** Present for audit-escalation so settlement can project without JSONL rebuild. */
36
- readonly projection?: Extract<TerminalRoleOutcome, { kind: "audit_escalation" }>;
37
+ /** Seat identity — machine fact beside the payload (ADR 0042). */
38
+ readonly role?: TerminalRoleName;
39
+ /** Raw LLM params — bounce/infra/audit still keep the original words (#836). */
40
+ readonly accepted?: unknown;
37
41
  }
38
- | { readonly type: "sealed"; readonly attemptId: string; readonly toolCallId: string; readonly accepted: unknown; readonly projection: Extract<TerminalRoleOutcome, { kind: "accepted" }> }
39
- | { readonly type: "post-seal-anomaly"; readonly attemptId: string; readonly toolCallId: string; readonly toolName: string };
42
+ | {
43
+ readonly type: "sealed";
44
+ readonly attemptId: string;
45
+ readonly toolCallId: string;
46
+ /** Seat identity — machine fact beside the payload (ADR 0042). */
47
+ readonly role: TerminalRoleName;
48
+ /** Role payload as submitted — never rewritten (#836). */
49
+ readonly accepted: unknown;
50
+ };
40
51
 
41
52
  /**
42
53
  * Admitted run identity for the ledger subject.
43
54
  * Prefer AK_ROLE_RUN_DIR via sole runDirectory→runId parser (public-CLI correlation);
44
55
  * otherwise session header id. Never a shared "unbound" bucket.
45
- * Session-path layout fallback omitted: bare Pi and public CLI both expose header id
46
- * when a session exists; missing both is infrastructure, not a third guess.
47
56
  */
48
57
  function runIdentity(context: HostContext): string {
49
58
  const directory = process.env.AK_ROLE_RUN_DIR;
@@ -57,10 +66,8 @@ function runIdentity(context: HostContext): string {
57
66
  }
58
67
 
59
68
  /**
60
- * Court-turn attempt identity (#637 same-ticket re-summons / #833 message re-review).
61
- * AK_ROLE_COURT_ATTEMPT is injected for a new court turn on an already-retained run
62
- * (summons / message / open-court continue). Bare resume and first mint omit it so
63
- * the session-stable id keeps sole-final per attempt.
69
+ * Court-turn attempt identity (#637 same-ticket re-summons).
70
+ * Recording tag only — does not gate acceptance or block further submissions (#836).
64
71
  */
65
72
  export const COURT_ATTEMPT_ENV = "AK_ROLE_COURT_ATTEMPT" as const;
66
73
 
@@ -70,29 +77,21 @@ function attemptIdentity(context: HostContext, runId: string): string {
70
77
  return context.sessionManager.getHeader?.()?.id ?? context.sessionManager.getLeafId?.() ?? `${runId}:initial`;
71
78
  }
72
79
 
73
- function isAcceptedProjection(value: unknown): value is Extract<TerminalRoleOutcome, { kind: "accepted" }> {
74
- if (typeof value !== "object" || value === null) return false;
75
- const candidate = value as Partial<Extract<TerminalRoleOutcome, { kind: "accepted" }>>;
76
- return candidate.kind === "accepted" && typeof candidate.role === "string" && typeof candidate.status === "string" && typeof candidate.decisiveFacts === "object" && candidate.decisiveFacts !== null;
77
- }
80
+ /** One recorded role submission as stored — original payload plus host identity. */
81
+ export type RecordedSubmissionRow = {
82
+ readonly role: TerminalRoleName;
83
+ readonly kind: "accepted" | "audit-escalation";
84
+ readonly accepted: unknown;
85
+ };
78
86
 
79
- function isAuditEscalationTerminalProjection(
80
- value: unknown,
81
- ): value is Extract<TerminalRoleOutcome, { kind: "audit_escalation" }> {
82
- if (typeof value !== "object" || value === null) return false;
83
- const candidate = value as Partial<Extract<TerminalRoleOutcome, { kind: "audit_escalation" }>>;
84
- return (
85
- candidate.kind === "audit_escalation" &&
86
- typeof candidate.role === "string" &&
87
- candidate.status === "audit_escalation" &&
88
- typeof candidate.decisiveFacts === "object" &&
89
- candidate.decisiveFacts !== null
90
- );
91
- }
87
+ /** Closed-submission callback: original payload, no status/facts projection (#836). */
88
+ export type ClosedSubmission = {
89
+ readonly role: TerminalRoleName;
90
+ readonly kind: "accepted" | "audit_escalation";
91
+ readonly accepted: unknown;
92
+ };
92
93
 
93
- export type SealedSubmissionProjection = Extract<SubmissionLedgerEvent, { type: "sealed" }>["projection"];
94
- export type AuditEscalationSubmissionProjection = Extract<TerminalRoleOutcome, { kind: "audit_escalation" }>;
95
- export type ClosedSubmissionProjection = SealedSubmissionProjection | AuditEscalationSubmissionProjection;
94
+ export type ClosedSubmissionProjection = ClosedSubmission;
96
95
 
97
96
  function submissionRecordFile(cwd: string, runId: string, home?: string): string {
98
97
  const ledgerHome = resolveActivationLedgerHome(home);
@@ -116,7 +115,10 @@ async function readOwnedSubmissionRecords(cwd: string, runId: string, home?: str
116
115
  /** Optional court-turn scope for settlement reads (#637). */
117
116
  export type SubmissionLedgerReadScope = {
118
117
  readonly home?: string;
119
- /** When set, only this court attempt's ledger rows participate. */
118
+ /**
119
+ * Recording tag for this court. Presentation of original payloads is run-scoped
120
+ * (#836: attempt/latest must not hide already-recorded rows).
121
+ */
120
122
  readonly attemptId?: string;
121
123
  };
122
124
 
@@ -128,6 +130,16 @@ function resolveReadScope(
128
130
  return homeOrScope;
129
131
  }
130
132
 
133
+ function recordsForAttempt<T extends { subject?: unknown; payload?: unknown }>(
134
+ owned: readonly T[],
135
+ attemptId: string | undefined,
136
+ ): readonly T[] {
137
+ // #836: courtAttempt is a recording tag for new courts, not a visibility gate.
138
+ void attemptId;
139
+ return owned;
140
+ }
141
+
142
+ /** Recording tag a row was written under — subject first, historical payload fallback. */
131
143
  function recordAttemptId(record: { subject?: unknown; payload?: unknown }): string | undefined {
132
144
  if (typeof record.subject === "object" && record.subject !== null) {
133
145
  const fromSubject = (record.subject as { attemptId?: unknown }).attemptId;
@@ -140,52 +152,102 @@ function recordAttemptId(record: { subject?: unknown; payload?: unknown }): stri
140
152
  return undefined;
141
153
  }
142
154
 
143
- function recordsForAttempt<T extends { subject?: unknown; payload?: unknown }>(
144
- owned: readonly T[],
145
- attemptId: string | undefined,
146
- ): readonly T[] {
147
- if (attemptId === undefined) return owned;
148
- return owned.filter((record) => recordAttemptId(record) === attemptId);
155
+ /**
156
+ * True when the given attemptId itself already produced a sealed or
157
+ * audit-escalation submission (#836 r12 class 2). This is a separate
158
+ * freshness signal, not a presentation filter — `recordsForAttempt` above
159
+ * stays a pass-through so every original payload keeps presenting honestly
160
+ * (#836: attemptId is a recording tag, not a visibility gate). Settlement
161
+ * consumes this only to stop a prior attempt's stale acceptance from
162
+ * outranking the current attempt's own real host-turn failure signal
163
+ * (#637 original intent, restored narrowly).
164
+ */
165
+ export async function hasFreshAttemptSubmission(
166
+ cwd: string,
167
+ runId: string,
168
+ attemptId: string,
169
+ home?: string,
170
+ ): Promise<boolean> {
171
+ const { owned } = await readOwnedSubmissionRecords(cwd, runId, home);
172
+ return owned.some((record) => {
173
+ if (recordAttemptId(record) !== attemptId) return false;
174
+ if (record.kind === "sealed") return true;
175
+ if (record.kind === "outcome") {
176
+ const payload = record.payload as { type?: string; outcome?: string } | undefined;
177
+ return payload?.type === "outcome" && payload.outcome === "audit-escalation";
178
+ }
179
+ return false;
180
+ });
181
+ }
182
+
183
+ function isTerminalRoleName(value: unknown): value is TerminalRoleName {
184
+ return typeof value === "string" && value.length > 0;
149
185
  }
150
186
 
151
- /** Settlement read seam: typed sealed projection only, never host session JSONL.
152
- * Omit attemptId for run-scoped latest sealed.
153
- * Pass attemptId for the current court turn so a prior seal cannot wash this turn.
154
- * post-seal-anomaly is forensic only — later turns must not erase an earlier seal (#833). */
155
- export async function readSealedSubmission(
187
+ function recordedRole(payload: { role?: unknown; projection?: { role?: unknown } }): TerminalRoleName | undefined {
188
+ if (isTerminalRoleName(payload.role)) return payload.role;
189
+ // Historical rows stored role only inside the deleted projection envelope.
190
+ if (isTerminalRoleName(payload.projection?.role)) return payload.projection.role;
191
+ return undefined;
192
+ }
193
+
194
+ /**
195
+ * All recorded role submissions in ledger order (#836 multi-submit).
196
+ * `accepted` is the original payload; never rebuilt from a status/facts envelope.
197
+ */
198
+ export async function readRecordedSubmissionRows(
156
199
  cwd: string,
157
200
  runId: string,
158
201
  homeOrScope?: string | SubmissionLedgerReadScope,
159
- ): Promise<SealedSubmissionProjection | undefined> {
202
+ ): Promise<readonly RecordedSubmissionRow[]> {
160
203
  const scope = resolveReadScope(homeOrScope);
161
204
  const { owned } = await readOwnedSubmissionRecords(cwd, runId, scope.home);
162
205
  const scoped = recordsForAttempt(owned, scope.attemptId);
163
- for (let index = scoped.length - 1; index >= 0; index -= 1) {
164
- const record = scoped[index];
165
- if (record?.kind !== "sealed") continue;
166
- const payload = record.payload as Partial<Extract<SubmissionLedgerEvent, { type: "sealed" }>> | undefined;
167
- if (payload?.type === "sealed" && isAcceptedProjection(payload.projection)) return payload.projection;
206
+ const out: RecordedSubmissionRow[] = [];
207
+ for (const record of scoped) {
208
+ if (record.kind === "sealed") {
209
+ const payload = record.payload as Partial<Extract<SubmissionLedgerEvent, { type: "sealed" }>> & {
210
+ projection?: { role?: unknown };
211
+ } | undefined;
212
+ if (payload?.type !== "sealed" || payload.accepted === undefined) continue;
213
+ const role = recordedRole(payload);
214
+ if (role === undefined) continue;
215
+ out.push({ role, kind: "accepted", accepted: payload.accepted });
216
+ continue;
217
+ }
218
+ if (record.kind !== "outcome") continue;
219
+ const payload = record.payload as Partial<Extract<SubmissionLedgerEvent, { type: "outcome" }>> & {
220
+ projection?: { role?: unknown };
221
+ } | undefined;
222
+ if (payload?.type !== "outcome" || payload.outcome !== "audit-escalation" || payload.accepted === undefined) {
223
+ continue;
224
+ }
225
+ const role = recordedRole(payload);
226
+ if (role === undefined) continue;
227
+ out.push({ role, kind: "audit-escalation", accepted: payload.accepted });
168
228
  }
169
- return undefined;
229
+ return out;
170
230
  }
171
231
 
172
- /** Non-final audit-escalation projection written by the submission ledger. */
173
- export async function readAuditEscalationSubmission(
232
+ /**
233
+ * All raw role payloads in ledger order (#836 multi-submit).
234
+ * Returns `accepted` bytes as stored — unknown, never re-wrapped.
235
+ */
236
+ export async function readRecordedSubmissions(
174
237
  cwd: string,
175
238
  runId: string,
176
239
  homeOrScope?: string | SubmissionLedgerReadScope,
177
- ): Promise<AuditEscalationSubmissionProjection | undefined> {
178
- const scope = resolveReadScope(homeOrScope);
179
- const { owned } = await readOwnedSubmissionRecords(cwd, runId, scope.home);
180
- const scoped = recordsForAttempt(owned, scope.attemptId);
181
- for (let index = scoped.length - 1; index >= 0; index -= 1) {
182
- const record = scoped[index];
183
- if (record?.kind !== "outcome") continue;
184
- const payload = record.payload as Partial<Extract<SubmissionLedgerEvent, { type: "outcome" }>> | undefined;
185
- if (payload?.type !== "outcome" || payload.outcome !== "audit-escalation") continue;
186
- if (isAuditEscalationTerminalProjection(payload.projection)) return payload.projection;
187
- }
188
- return undefined;
240
+ ): Promise<readonly unknown[]> {
241
+ return (await readRecordedSubmissionRows(cwd, runId, homeOrScope)).map((row) => row.accepted);
242
+ }
243
+
244
+ /** True when the run has at least one recorded accepted or audit-escalation payload. */
245
+ export async function hasRecordedSubmission(
246
+ cwd: string,
247
+ runId: string,
248
+ homeOrScope?: string | SubmissionLedgerReadScope,
249
+ ): Promise<boolean> {
250
+ return (await readRecordedSubmissionRows(cwd, runId, homeOrScope)).length > 0;
189
251
  }
190
252
 
191
253
  export type LatestSubmissionOutcome = Extract<SubmissionLedgerEvent, { type: "outcome" }>;
@@ -210,27 +272,13 @@ export async function readLatestSubmissionOutcome(
210
272
  return undefined;
211
273
  }
212
274
 
213
- type LedgerState = { prior?: RecordPointer; sealedAttemptIds: Set<string>; sequence: number };
214
-
215
- function sealedAttemptIdFromRecord(record: { kind: string; payload?: unknown }): string | undefined {
216
- if (record.kind !== "sealed") return undefined;
217
- const payload = record.payload as Partial<Extract<SubmissionLedgerEvent, { type: "sealed" }>> | undefined;
218
- return payload?.type === "sealed" && typeof payload.attemptId === "string" && payload.attemptId.length > 0
219
- ? payload.attemptId
220
- : undefined;
221
- }
275
+ type LedgerState = { prior?: RecordPointer; sequence: number };
222
276
 
223
277
  async function restoreState(cwd: string, runId: string, home?: string): Promise<LedgerState> {
224
278
  const { file, owned } = await readOwnedSubmissionRecords(cwd, runId, home);
225
279
  const last = owned.at(-1);
226
- const sealedAttemptIds = new Set<string>();
227
- for (const record of owned) {
228
- const attemptId = sealedAttemptIdFromRecord(record);
229
- if (attemptId !== undefined) sealedAttemptIds.add(attemptId);
230
- }
231
280
  return {
232
281
  ...(last === undefined ? {} : { prior: { identity: last.identity, recordFile: file, kind: last.kind, level: last.level } }),
233
- sealedAttemptIds,
234
282
  sequence: owned.reduce((maximum, record) => {
235
283
  const payload = record.payload as Partial<SubmissionLedgerEvent> | undefined;
236
284
  return payload?.type === "candidate" && typeof payload.sequence === "number" ? Math.max(maximum, payload.sequence) : maximum;
@@ -238,17 +286,20 @@ async function restoreState(cwd: string, runId: string, home?: string): Promise<
238
286
  };
239
287
  }
240
288
 
241
- /** Pipeline-owned sole-final state and durable projection. */
289
+ /**
290
+ * Submission ledger host — record only (#836).
291
+ * Each terminating submission is appended with the role's original payload.
292
+ * No sole-final, no seal barrier, no context.abort(), no details rewrite.
293
+ * Host end (turn close / exit code) is the final; ledger contents are presented as-is.
294
+ */
242
295
  export function createSubmissionLedgerHost(
243
296
  host: RoleHost,
244
297
  outputTools: ReadonlyMap<string, TerminalRoleName>,
245
298
  failInfrastructure: (error: unknown, context: HostContext) => never = (error) => { throw error; },
246
- projectClosure: (projection: ClosedSubmissionProjection, context: HostContext) => void | Promise<void> = () => undefined,
299
+ projectClosure: (closed: ClosedSubmission, context: HostContext) => void | Promise<void> = () => undefined,
247
300
  options?: { home?: string },
248
301
  ): RoleHost {
249
302
  const states = new Map<string, Promise<LedgerState>>();
250
- type PendingCandidate = { toolCallId: string; toolName: TerminatingToolName; role: TerminalRoleName; result: HostToolResult<unknown>; context: HostContext; auditProjection?: Extract<TerminalRoleOutcome, { kind: "audit_escalation" }> };
251
- const rounds = new Map<string, PendingCandidate[]>();
252
303
  const resolveHomeFromContext = (context: HostContext): string | undefined => {
253
304
  if (options?.home !== undefined) return options.home;
254
305
  const sessionFile = context.sessionManager.getSessionFile?.() || context.sessionManager.getSessionDir?.();
@@ -263,9 +314,6 @@ export function createSubmissionLedgerHost(
263
314
  return pending;
264
315
  })();
265
316
  const appendFor = (state: LedgerState, context: HostContext, runId: string, attemptId: string, event: SubmissionLedgerEvent): RecordPointer => {
266
- // Home only — must match submissionRecordFile topology (cwd + runId hash under
267
- // ledger home). Do not pass sessionParent: that nests under the session dir and
268
- // breaks restoreState reads which resolve the hash path without sessionParent.
269
317
  const home = resolveHomeFromContext(context);
270
318
  const pointer = sitianReport({
271
319
  level: "event",
@@ -281,57 +329,15 @@ export function createSubmissionLedgerHost(
281
329
  return pointer;
282
330
  };
283
331
 
284
- host.on("tool_execution_start", async ({ toolCallId, toolName }, context) => {
285
- try {
286
- const runId = runIdentity(context);
287
- const attemptId = attemptIdentity(context, runId);
288
- const state = await stateFor(context, runId);
289
- if (state.sealedAttemptIds.has(attemptId)) {
290
- appendFor(state, context, runId, attemptId, { type: "post-seal-anomaly", attemptId, toolCallId, toolName });
291
- }
292
- } catch (error) {
293
- failInfrastructure(error, context);
294
- }
295
- });
296
332
  host.on("turn_end", async (event, context) => {
297
333
  try {
298
334
  const runId = runIdentity(context);
299
335
  const attemptId = attemptIdentity(context, runId);
300
- const candidates = rounds.get(attemptId);
301
- if (candidates === undefined) return;
302
- rounds.delete(attemptId);
303
336
  const state = await stateFor(context, runId);
304
337
  const calls = event.calls.map(({ toolCallId: id, toolName: name }) => ({ id, name }));
305
- appendFor(state, context, runId, attemptId, { type: "roundContext", attemptId, calls });
306
- const sole = calls.length === 1 && candidates.length === 1 && calls[0]?.id === candidates[0]?.toolCallId;
307
- if (!sole) {
308
- for (const candidate of candidates) appendFor(state, context, runId, attemptId, { type: "outcome", attemptId, toolCallId: candidate.toolCallId, outcome: "correctable-rejection", code: "non-sole-round" });
309
- if (host.deliverSubmissionRejection === undefined) {
310
- throw new Error("宿主未提供模型可见的交卷封驳接缝");
311
- }
312
- context.abort();
313
- await host.deliverSubmissionRejection({
314
- kind: "correctable-rejection",
315
- code: "non-sole-round",
316
- toolCallIds: candidates.map(({ toolCallId }) => toolCallId),
317
- });
318
- return;
319
- }
320
- const candidate = candidates[0]!;
321
- if (candidate.auditProjection !== undefined) {
322
- appendFor(state, context, runId, attemptId, { type: "outcome", attemptId, toolCallId: candidate.toolCallId, outcome: "audit-escalation", projection: candidate.auditProjection });
323
- await projectClosure(candidate.auditProjection, context);
324
- context.abort();
325
- return;
338
+ if (calls.length > 0) {
339
+ appendFor(state, context, runId, attemptId, { type: "roundContext", attemptId, calls });
326
340
  }
327
- const details = typeof candidate.result.details === "object" && candidate.result.details !== null ? candidate.result.details as Record<string, unknown> : {};
328
- const status = acceptedFacts(candidate.toolName, details as AcceptedDetails).status;
329
- if (typeof status !== "string" || status.length === 0) throw new Error("提交账封账缺少 acceptedFacts.status");
330
- const projection: Extract<TerminalRoleOutcome, { kind: "accepted" }> = { kind: "accepted", role: candidate.role, status, decisiveFacts: details };
331
- appendFor(state, candidate.context, runId, attemptId, { type: "sealed", attemptId, toolCallId: candidate.toolCallId, accepted: candidate.result.details, projection });
332
- state.sealedAttemptIds.add(attemptId);
333
- await projectClosure(projection, context);
334
- context.abort();
335
341
  } catch (error) {
336
342
  failInfrastructure(error, context);
337
343
  }
@@ -349,15 +355,17 @@ export function createSubmissionLedgerHost(
349
355
  const attemptId = attemptIdentity(context, runId);
350
356
  const state = await stateFor(context, runId);
351
357
  const append = (event: SubmissionLedgerEvent) => appendFor(state, context, runId, attemptId, event);
352
- if (state.sealedAttemptIds.has(attemptId)) throw new Error("提交账已封账");
353
- // #541 / #575: shared infra-declaration fail lives on the ledger seam,
354
- // before any role execute or sole-final work (one owner for every seat).
355
- // #641 chain②: seats may opt into bouncing a machine-verified normal
356
- // completion misdeclared as infrastructure failure — the bounce throws a
357
- // correctable error from the declaration call, so it lands in the same
358
- // correctable-rejection path as execute-thrown rejections below. The
359
- // candidate is booked first so the bounced attempt stays observable.
360
- append({ type: "candidate", attemptId, toolCallId, toolName: tool.name, sequence: ++state.sequence });
358
+ // #541 / #575: shared infra-declaration fail lives on the ledger seam.
359
+ // #641 chain②: seats may bounce a misdeclared infrastructure failure
360
+ // as correctable (2.1/2.2/2.3 keep paths).
361
+ append({
362
+ type: "candidate",
363
+ attemptId,
364
+ toolCallId,
365
+ toolName: tool.name,
366
+ sequence: ++state.sequence,
367
+ params,
368
+ });
361
369
  let result: HostToolResult<unknown>;
362
370
  try {
363
371
  failOnInfrastructureFailureDeclaration(
@@ -373,8 +381,6 @@ export function createSubmissionLedgerHost(
373
381
  );
374
382
  result = await tool.execute(toolCallId, params, signal, update, context);
375
383
  } catch (error) {
376
- // #753: gate no longer throws GatekeeperEscalationError to select parent
377
- // next-step. Officer bounce|escalate returns as correctable with raw receipt.
378
384
  if (isCorrectableExecuteError(error)) {
379
385
  append({
380
386
  type: "outcome",
@@ -383,6 +389,7 @@ export function createSubmissionLedgerHost(
383
389
  outcome: "correctable-rejection",
384
390
  code: "typed-bounce",
385
391
  diagnostic: error instanceof Error ? error.message : String(error),
392
+ accepted: params,
386
393
  });
387
394
  throw error;
388
395
  } else {
@@ -392,52 +399,45 @@ export function createSubmissionLedgerHost(
392
399
  toolCallId,
393
400
  outcome: "infrastructure",
394
401
  diagnostic: error instanceof Error ? error.message : String(error),
402
+ accepted: params,
395
403
  });
396
404
  throw error;
397
405
  }
398
406
  }
399
- // #753 escalate-thrown-verbatim: officer escalate seals as accepted with the
400
- // raw receipt — no projectOfficerEscalation rewrite, no fabricated reason.
401
- // Compliance seats still return live audit_escalation projections below.
402
- if (isAuditEscalationProjection(result.details)) {
403
- const candidates = rounds.get(attemptId) ?? [];
404
- candidates.push({
407
+ // #836: ledger authority is the LLM tool-call params as-is (角色原话), never result.details.
408
+ // Machine facts on result.details stay on the tool-result face returned to the model.
409
+ if (isAuditEscalationProjection(result.details) || isAuditEscalationProjection(params)) {
410
+ const closed: ClosedSubmission = {
411
+ role,
412
+ kind: "audit_escalation",
413
+ accepted: params,
414
+ };
415
+ append({
416
+ type: "outcome",
417
+ attemptId,
405
418
  toolCallId,
406
- toolName: tool.name as TerminatingToolName,
419
+ outcome: "audit-escalation",
407
420
  role,
408
- result,
409
- context,
410
- auditProjection: {
411
- kind: "audit_escalation",
412
- role,
413
- status: "audit_escalation",
414
- decisiveFacts: result.details as Record<string, unknown>,
415
- },
421
+ accepted: params,
416
422
  });
417
- rounds.set(attemptId, candidates);
418
- // The role's own acceptance text must reach the model: an empty
419
- // result reads as "nothing happened" on hosts without terminate
420
- // semantics (grok build kept resubmitting, #750 evidence).
421
- return {
422
- content: result.content,
423
- details: { submissionDisposition: "pending-round-closure" },
424
- };
425
- }
426
- if (result.terminate !== true) {
427
- append({ type: "outcome", attemptId, toolCallId, outcome: "correctable-rejection", code: "non-terminate" });
423
+ await projectClosure(closed, context);
428
424
  return result;
429
425
  }
430
- if (!isTerminatingToolName(tool.name)) {
431
- append({ type: "outcome", attemptId, toolCallId, outcome: "infrastructure", diagnostic: `non-terminating tool ${tool.name}` });
432
- throw new Error("提交账只受理终止工具");
433
- }
434
- const candidates = rounds.get(attemptId) ?? [];
435
- candidates.push({ toolCallId, toolName: tool.name, role, result, context });
436
- rounds.set(attemptId, candidates);
437
- return {
438
- content: result.content,
439
- details: { submissionDisposition: "pending-round-closure" },
426
+ // Terminating-tool wrap records every call; terminate flag does not withhold params.
427
+ const closed: ClosedSubmission = {
428
+ role,
429
+ kind: "accepted",
430
+ accepted: params,
440
431
  };
432
+ append({
433
+ type: "sealed",
434
+ attemptId,
435
+ toolCallId,
436
+ role,
437
+ accepted: params,
438
+ });
439
+ await projectClosure(closed, context);
440
+ return result;
441
441
  },
442
442
  });
443
443
  },
@@ -12,12 +12,8 @@ export const TICKET_PROVENANCE_HUMAN_VIEW = "起居录.md" as const;
12
12
  /** Payload discriminator: diagnostic residue (not a diary body entry). */
13
13
  export const TICKET_PROVENANCE_RECORD_CLASS_DIAGNOSTIC = "diagnostic" as const;
14
14
 
15
- /** Source families the diarist may enumerate (v1). */
16
- export type TicketProvenanceSourceKind =
17
- | "cc-session"
18
- | "issue-body-comment"
19
- | "adr-decision-key"
20
- | "ticket-decree-block";
15
+ /** Source family as the diarist wrote it (#836: no allowlist drop). */
16
+ export type TicketProvenanceSourceKind = string;
21
17
 
22
18
  /**
23
19
  * How a block entered the volume.
@@ -87,15 +83,6 @@ function isRecord(value: unknown): value is Record<string, unknown> {
87
83
  return typeof value === "object" && value !== null && !Array.isArray(value);
88
84
  }
89
85
 
90
- const SOURCE_KINDS = new Set<string>([
91
- "cc-session",
92
- "issue-body-comment",
93
- "adr-decision-key",
94
- "ticket-decree-block",
95
- ]);
96
-
97
- const BASIS_METHODS = new Set<string>(["llm-semantic"]);
98
-
99
86
  const DIAGNOSTIC_KINDS = new Set<string>([
100
87
  "collector-failed",
101
88
  "issue-source-failed",
@@ -144,54 +131,11 @@ export function projectTicketProvenanceEntry(
144
131
  value: unknown,
145
132
  ): TicketProvenanceEntry | undefined {
146
133
  if (!isRecord(value)) return undefined;
147
- // Diagnostics are a separate projection — never body entries.
148
134
  if (value.recordClass === TICKET_PROVENANCE_RECORD_CLASS_DIAGNOSTIC) {
149
135
  return undefined;
150
136
  }
151
- if (!isRecord(value.basis)) return undefined;
152
- if (typeof value.basis.method !== "string" || !BASIS_METHODS.has(value.basis.method)) {
153
- return undefined;
154
- }
155
- if (typeof value.sourceKind !== "string" || !SOURCE_KINDS.has(value.sourceKind)) {
156
- return undefined;
157
- }
158
- if (!isRecord(value.sourceRef)) return undefined;
159
- if (typeof value.transcript !== "string" || value.transcript.length === 0) {
160
- return undefined;
161
- }
162
- if (typeof value.timestamp !== "string" || value.timestamp.length === 0) {
137
+ if (typeof value.sourceKind !== "string" || typeof value.transcript !== "string") {
163
138
  return undefined;
164
139
  }
165
-
166
- const basis: TicketProvenanceBasis = {
167
- method: value.basis.method as TicketProvenanceBasisMethod,
168
- ...(Array.isArray(value.basis.anchors)
169
- ? {
170
- anchors: value.basis.anchors.filter(
171
- (item): item is string => typeof item === "string",
172
- ),
173
- }
174
- : {}),
175
- ...(typeof value.basis.note === "string" ? { note: value.basis.note } : {}),
176
- };
177
-
178
- const sourceRef: TicketProvenanceSourceRef = {
179
- ...(typeof value.sourceRef.sessionFile === "string"
180
- ? { sessionFile: value.sourceRef.sessionFile }
181
- : {}),
182
- ...(typeof value.sourceRef.entryId === "string" ||
183
- typeof value.sourceRef.entryId === "number"
184
- ? { entryId: value.sourceRef.entryId }
185
- : {}),
186
- ...(typeof value.sourceRef.path === "string" ? { path: value.sourceRef.path } : {}),
187
- ...(typeof value.sourceRef.url === "string" ? { url: value.sourceRef.url } : {}),
188
- };
189
-
190
- return {
191
- basis,
192
- sourceKind: value.sourceKind as TicketProvenanceSourceKind,
193
- sourceRef,
194
- transcript: value.transcript,
195
- timestamp: value.timestamp,
196
- };
140
+ return value as TicketProvenanceEntry;
197
141
  }