@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
@@ -1,11 +1,7 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import type { HostContext } from "./host-contracts.ts";
3
3
 
4
- import {
5
- auditorRunDirectory,
6
- persistGateSubmissionCandidate,
7
- readLatestSubmissionArguments,
8
- } from "./auditor-dossier-tool.ts";
4
+ import { auditorRunDirectory } from "./auditor-dossier-tool.ts";
9
5
  import type { NoReceiptLifecycleFacts } from "./receipt-delivery-policy.ts";
10
6
  import { GatekeeperDecisionError } from "./submission-errors.ts";
11
7
  import { INSPECTOR_OUTPUT_TOOL_NAME } from "./inspector-contracts.ts";
@@ -59,10 +55,10 @@ export type GatekeeperResult =
59
55
  readonly submission?: unknown;
60
56
  };
61
57
 
62
- /** Non-pass faces that bounce the parent session (correctable). */
58
+ /** Non-pass faces returned to the parent session (correctable; #836 never kill leg). */
63
59
  export type GatekeeperNonPassResult = Extract<
64
60
  GatekeeperResult,
65
- { status: "bounce" | "escalate" | "no_receipt" }
61
+ { status: "bounce" | "escalate" | "no_receipt" | "transport_failure" }
66
62
  >;
67
63
 
68
64
  function gateSeatLabel(stage: GateOfficer): string {
@@ -90,11 +86,6 @@ export type GateOfficerSummon = (
90
86
  * conclusion (#753 / #756). Hosted as same-ticket resume instruction.
91
87
  */
92
88
  reask?: string,
93
- /**
94
- * In-flight parent 交卷 body (tool-call arguments). Production default relays
95
- * it verbatim on same-parent officer resume (#786).
96
- */
97
- submission?: unknown,
98
89
  ) => Promise<PublicSummonResult>;
99
90
 
100
91
  export type RunGatekeeperOptions = {
@@ -166,21 +157,13 @@ function failureReason(error: unknown): string {
166
157
  return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
167
158
  }
168
159
 
169
- /** Serializable stand-in when the child tool call had no arguments object. */
170
- export const MISSING_ARGUMENTS_SUBMISSION = Object.freeze({ missing: "arguments" as const });
171
-
172
160
  function isRecord(value: unknown): value is Record<string, unknown> {
173
161
  return typeof value === "object" && value !== null && !Array.isArray(value);
174
162
  }
175
163
 
176
- /** Keep original decision bytes for the next reader; undefined becomes a serializable missing-args fact. */
164
+ /** Original decision bytes — no sentinel replacement (#836). */
177
165
  function retainedReceipt(decision: unknown): unknown {
178
- // undefined must not be stored: JSON drops it and the missing-args fact vanishes.
179
- // Through the real provider adapter an undefined root argument arrives as an
180
- // empty object after serialization; that must also project a missing-args fact.
181
- return decision === undefined || (isRecord(decision) && Object.keys(decision).length === 0)
182
- ? MISSING_ARGUMENTS_SUBMISSION
183
- : decision;
166
+ return decision;
184
167
  }
185
168
 
186
169
  function readRecord(value: unknown): Record<string, unknown> | undefined {
@@ -216,66 +199,94 @@ function projectOfficerDecision(
216
199
 
217
200
  /**
218
201
  * Project a public-role terminal onto the gate queue surface.
219
- * Lifecycle facts (no_receipt / transport) stay loud; conclusion reads only
220
- * the status field. No unusable/unreadable judgment (#753).
202
+ * Host failure stays failure; recorded officer payloads ride beside it (#836 A.3).
203
+ * Multiple recorded payloads are all kept — code does not pick last-wins.
221
204
  */
205
+ function officerPayloads(terminal: TerminalResult | undefined): readonly unknown[] {
206
+ const outcome = terminal?.roleOutcome;
207
+ if (outcome !== undefined && (outcome.kind === "accepted" || outcome.kind === "audit_escalation")) {
208
+ return outcome.payloads ?? terminal?.submissions ?? [];
209
+ }
210
+ if (outcome?.kind === "failure") return outcome.payloads ?? terminal?.submissions ?? [];
211
+ return terminal?.submissions ?? [];
212
+ }
213
+
214
+ function projectOfficerPayloads(
215
+ officer: GateOfficer,
216
+ payloads: readonly unknown[],
217
+ fallbackStatus?: string,
218
+ ): GatekeeperResult {
219
+ if (payloads.length === 0) {
220
+ return projectOfficerDecision(officer, undefined, fallbackStatus);
221
+ }
222
+ // Present every recorded payload; queue only the latest conclusion so a reask
223
+ // can converge (#836 呈现 ≠ 排队).
224
+ const queued = projectOfficerDecision(officer, payloads[payloads.length - 1], fallbackStatus);
225
+ if (payloads.length === 1) return queued;
226
+ if (
227
+ queued.status === "pass"
228
+ || queued.status === "bounce"
229
+ || queued.status === "escalate"
230
+ || queued.status === "needs_reask"
231
+ ) {
232
+ return { ...queued, receipt: payloads };
233
+ }
234
+ return queued;
235
+ }
236
+
222
237
  function projectOfficerTerminal(
223
238
  officer: GateOfficer,
224
239
  summoned: PublicSummonResult,
225
240
  ): GatekeeperResult {
226
241
  const terminal: TerminalResult | undefined = summoned.terminal;
227
242
  const outcome = terminal?.roleOutcome;
243
+ const recorded = officerPayloads(terminal);
228
244
  if (outcome === undefined) {
229
- const detail = summoned.stderr?.trim();
245
+ const detail = summoned.stderr ?? "";
230
246
  return {
231
247
  status: "transport_failure",
232
248
  stage: officer,
233
- reason: detail && detail.length > 0
249
+ reason: detail.length > 0
234
250
  ? `${gateSeatLabel(officer)} public summon exit ${summoned.exitCode}: ${detail}`
235
251
  : `${gateSeatLabel(officer)} public summon produced no terminal (exit ${summoned.exitCode})`,
236
- submission: summoned,
252
+ submission: recorded.length > 0 ? recorded : summoned,
237
253
  };
238
254
  }
239
255
  if (outcome.kind === "no_receipt") {
240
256
  return {
241
257
  status: "no_receipt",
242
258
  stage: officer,
243
- reason: `${gateSeatLabel(officer)}未产生已接受回执即散局`,
259
+ reason: typeof outcome.status === "string" && outcome.status.length > 0
260
+ ? outcome.status
261
+ : "no_receipt",
244
262
  facts: outcome,
245
263
  };
246
264
  }
247
265
  if (outcome.kind === "failure") {
248
- // Real provider/engine/disk failure — keep loud. Not a shape judgment.
249
266
  return {
250
267
  status: "transport_failure",
251
268
  stage: officer,
252
269
  reason: outcome.diagnostic,
253
- submission: outcome.decisiveFacts,
270
+ submission: recorded.length > 0 ? recorded : outcome.decisiveFacts,
254
271
  };
255
272
  }
256
273
  if (outcome.kind === "audit_escalation") {
257
- // Residual/compliance escalate face: queue as escalate, receipt as written.
258
- // Nested officer escalate itself seals accepted+status escalate (no rewrite).
259
274
  return {
260
275
  status: "escalate",
261
276
  officer,
262
- receipt: retainedReceipt(outcome.decisiveFacts),
277
+ receipt: recorded.length === 1 ? recorded[0] : recorded,
263
278
  };
264
279
  }
265
280
  if (outcome.kind === "accepted") {
266
- // Prefer the officer's own decisiveFacts as the receipt body. outcome.status is
267
- // only a fallback when facts have no status key (missing-args sentinel stays intact).
268
- const facts = outcome.decisiveFacts;
269
- if (isRecord(facts) && Object.keys(facts).length > 0) {
270
- return projectOfficerDecision(officer, facts, outcome.status);
271
- }
272
- return projectOfficerDecision(officer, { status: outcome.status });
281
+ // outcome.status is the fixture/compat leaf: production settlement leaves
282
+ // it undefined once payloads are recorded, so this only matters when a
283
+ // caller still supplies status without any recorded payload (#836 hang).
284
+ return projectOfficerPayloads(officer, recorded, outcome.status);
273
285
  }
274
- // Unknown terminal kind: still not a shape judgment — ask the speaker again.
275
286
  return {
276
287
  status: "needs_reask",
277
288
  officer,
278
- receipt: retainedReceipt(outcome),
289
+ receipt: recorded.length > 0 ? recorded : retainedReceipt(outcome),
279
290
  };
280
291
  }
281
292
 
@@ -313,16 +324,13 @@ export async function projectGatekeeperRun(
313
324
  },
314
325
  };
315
326
  }
316
- // #632: Grok session.jsonl is header-only — freeze the in-memory tool-call leaf
317
- // as a run artifact so dossier exploration still resolves. LLM→LLM resume does
318
- // not ride this path: submission body goes verbatim on gateReviewInstruction (#786).
319
- persistGateSubmissionCandidate(runDirectory, options.context);
320
- const submission = readLatestSubmissionArguments(options.context);
327
+ // #836: officers receive the whole parent run directory pointer and find the
328
+ // submission themselves — code no longer picks latest toolCall leaf (A7.1–A7.3).
321
329
  let summoned: PublicSummonResult;
322
330
  try {
323
331
  const summon =
324
332
  options.summonOfficer
325
- ?? (async (nextOfficer, sourceRunDirectory, officerSignal, reask, nextSubmission) => {
333
+ ?? (async (nextOfficer, sourceRunDirectory, officerSignal, reask) => {
326
334
  const { summonGateOfficer } = await import("./public-role-summons.ts");
327
335
  return summonGateOfficer({
328
336
  officer: nextOfficer,
@@ -330,7 +338,6 @@ export async function projectGatekeeperRun(
330
338
  cwd: options.context.cwd ?? process.cwd(),
331
339
  ...(officerSignal === undefined ? {} : { signal: officerSignal }),
332
340
  ...(reask === undefined ? {} : { reask }),
333
- ...(nextSubmission === undefined ? {} : { submission: nextSubmission }),
334
341
  ...(options.home === undefined ? {} : { home: options.home }),
335
342
  ...(options.packageRoot === undefined ? {} : { packageRoot: options.packageRoot }),
336
343
  ...(options.roleTurnHost === undefined ? {} : { roleTurnHost: options.roleTurnHost }),
@@ -342,7 +349,6 @@ export async function projectGatekeeperRun(
342
349
  runDirectory,
343
350
  options.signal,
344
351
  options.reask,
345
- submission,
346
352
  );
347
353
  } catch (error) {
348
354
  return {
@@ -16,6 +16,8 @@ export {
16
16
  export type { GleanerLeftOutput };
17
17
  export { validateRecordedGleanerLeftOutput };
18
18
 
19
+ // #836 r16 class 1: pointer/statement are LLM/human-read narrative content — no
20
+ // code branches on their presence.
19
21
  /** 左拾遗弹章交卷形状;形状指引,非 schema 闸。 */
20
22
  export const gleanerLeftOutputSchema = withInfrastructureFailureDeclaration(
21
23
  openToolObject(
@@ -26,8 +28,8 @@ export const gleanerLeftOutputSchema = withInfrastructureFailureDeclaration(
26
28
  findings: Type.Array(
27
29
  Type.Object(
28
30
  {
29
- pointer: Type.String({ description: "文件/行指针" }),
30
- statement: Type.String({ description: "疑点陈述" }),
31
+ pointer: Type.Optional(Type.String({ description: "文件/行指针" })),
32
+ statement: Type.Optional(Type.String({ description: "疑点陈述" })),
31
33
  },
32
34
  { additionalProperties: true, description: "一条弹章" },
33
35
  ),
@@ -16,7 +16,7 @@ import {
16
16
  type PreparedRoleTurn,
17
17
  type SessionIdentityAuthority,
18
18
  } from "../prepared-role-turn.ts";
19
- import { retainDiagnosticTail } from "../diagnostic-tail.ts";
19
+
20
20
  import { reportHostSessionEvent } from "../host-session-record.ts";
21
21
  import {
22
22
  headlessMcpConfigDocument,
@@ -209,8 +209,7 @@ function spawnHeadlessTurn(options: {
209
209
  };
210
210
  child.stdout.setEncoding("utf8").on("data", (chunk: string) => { flushStdoutLines(chunk, false); });
211
211
  child.stderr.setEncoding("utf8").on("data", (chunk: string) => {
212
- // Rolling diagnostic tail only — not an unbounded transcript face.
213
- stderr = retainDiagnosticTail(stderr + chunk);
212
+ stderr += chunk;
214
213
  });
215
214
  child.on("error", (error) => {
216
215
  if (settled) return;
@@ -379,7 +378,7 @@ export function createHeadlessRoleTurnHost(config: HeadlessRoleTurnHostConfig):
379
378
  return terminalFromSpawned(spawned, {
380
379
  cause: "output",
381
380
  identity: { name: "HeadlessEmptyOutput", code: "empty-stdout" },
382
- diagnostic: retainDiagnosticTail(spawned.stderr.trim() || "headless CLI produced no parseable result"),
381
+ diagnostic: spawned.stderr.length > 0 ? spawned.stderr : "headless CLI produced no parseable result",
383
382
  details: { sessionId, exitCode: spawned.code },
384
383
  });
385
384
  }
@@ -400,7 +399,7 @@ export function createHeadlessRoleTurnHost(config: HeadlessRoleTurnHostConfig):
400
399
  ? envelope.result
401
400
  : Array.isArray(envelope.errors)
402
401
  ? envelope.errors.map(String).join("\n")
403
- : retainDiagnosticTail(spawned.stderr.trim() || "headless CLI reported is_error");
402
+ : spawned.stderr.length > 0 ? spawned.stderr : "headless CLI reported is_error";
404
403
  return terminalFromSpawned(spawned, {
405
404
  cause: "output",
406
405
  identity: { name: "HeadlessCliError", code: errorCode },
@@ -1,4 +1,4 @@
1
- import { Type, type Static, type TLiteral, type TSchema } from "typebox";
1
+ import type { Static, TSchema } from "typebox";
2
2
  import type { CorrectableSubmissionError } from "./submission-correctable-error.ts";
3
3
 
4
4
  type HostContentPart = { type: "text"; text: string } | { type: "toolCall"; id: string; name: string; arguments?: unknown } | { type: string };
@@ -301,8 +301,8 @@ export type HostEventRegistration = { [K in keyof HostEventMap]: [event: K, hand
301
301
  type HostGatekeeperSubject = {
302
302
  readonly kind: "worker_completion" | "judge_draft" | "judge_compliance" | "countersign_verdict";
303
303
  };
304
- /** Gatekeeper bounce/escalate/no_receipt plus other correct submission rejects share one projection map. */
305
- type HostGatekeeperNonPass = { readonly status: "bounce" | "escalate" | "no_receipt" } & Record<string, unknown>;
304
+ /** Gatekeeper non-pass faces returned to parent (#836 includes transport_failure; never kill leg). */
305
+ type HostGatekeeperNonPass = { readonly status: "bounce" | "escalate" | "no_receipt" | "transport_failure" } & Record<string, unknown>;
306
306
  export type HostSubmissionNonPass =
307
307
  | HostGatekeeperNonPass
308
308
  | { readonly code: "coder_skill_expansion_evidence_missing" };
@@ -470,8 +470,3 @@ export interface InstitutionalSessionHost {
470
470
  ): Promise<HostInstitutionalSessionHandle>;
471
471
  }
472
472
 
473
- /** Local replacement for Pi AI's convenience constructor. */
474
- export function stringEnum<const V extends readonly string[]>(values: V, options: Record<string, unknown> = {}) {
475
- return Type.Union(values.map((value) => Type.Literal(value)) as [TLiteral<V[number]>, ...TLiteral<V[number]>[]], options);
476
- }
477
-
package/src/judge-role.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import type { RoleHost, HostContext, HostToolResult, HostGatekeeperActions } from "./host-contracts.ts";
2
- import { stringEnum } from "./host-contracts.ts";
3
2
  import { Type, type Static } from "typebox";
4
3
 
5
4
  import { withInfrastructureFailureDeclaration } from "./package-contracts/terminating-infrastructure.ts";
@@ -19,31 +18,38 @@ const JUDGE_STATUS_REASK =
19
18
  export { JUDGE_OUTPUT_TOOL_NAME };
20
19
  export type { JudgeVerdict };
21
20
 
21
+ // #836 r16 class 1: fix/classes/note/decisionGate are LLM/human-read narrative
22
+ // content — 符宝郎/审刑院 read the raw receipt, no code branches on their length
23
+ // or nested presence. `judgeStatus` alone is the machine discriminator the
24
+ // queue reads to pick pass/bounce/escalate (src/judge-role.ts:90-125).
25
+ // #836 (ADR 0003 Amendment): judgeStatus kept open like countersignStatus
26
+ // (src/countersign-role.ts) — a closed domain here would reject an unknown
27
+ // value before the rawStatus/ParentQueueReaskError check below ever runs.
22
28
  export const judgeVerdictSchema = withInfrastructureFailureDeclaration(
23
29
  Type.Object(
24
30
  {
25
- judgeStatus: stringEnum(["converged", "continue", "escalate"] as const, { description: "converged | continue | escalate — 形状指引,非 schema 闸" }),
31
+ judgeStatus: Type.Unknown({ description: "converged | continue | escalate — 形状指引,非 schema 闸" }),
26
32
  fix: Type.Optional(
27
33
  Type.Object(
28
- { summary: Type.String({ minLength: 1, description: "continue 时的补救摘要" }) },
29
- { additionalProperties: false, description: "continue 时的补救说明" },
34
+ { summary: Type.Optional(Type.String({ description: "continue 时的补救摘要" })) },
35
+ { additionalProperties: true, description: "continue 时的补救说明" },
30
36
  ),
31
37
  ),
32
38
  classes: Type.Optional(Type.Array(Type.Object({
33
- name: Type.String({ minLength: 1 }),
34
- owner: Type.String({ minLength: 1 }),
35
- boundary: Type.String({ minLength: 1 }),
36
- disposition: Type.String({ minLength: 1 }),
37
- }, { additionalProperties: false }), { minItems: 1, description: "已裁决 finding 类及其 owner 与修理边界" })),
38
- note: Type.Optional(Type.String({ minLength: 1, description: "可选裁决附注" })),
39
+ name: Type.Optional(Type.String()),
40
+ owner: Type.Optional(Type.String()),
41
+ boundary: Type.Optional(Type.String()),
42
+ disposition: Type.Optional(Type.String()),
43
+ }, { additionalProperties: true }), { description: "已裁决 finding 类及其 owner 与修理边界" })),
44
+ note: Type.Optional(Type.String({ description: "可选裁决附注" })),
39
45
  evidence: Type.Optional(Type.Unknown({ description: "留存的裁决证据" })),
40
46
  decisionGate: Type.Optional(
41
47
  Type.Object(
42
48
  {
43
- question: Type.String({ minLength: 1 }),
44
- options: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
49
+ question: Type.Optional(Type.String()),
50
+ options: Type.Optional(Type.Array(Type.String())),
45
51
  },
46
- { additionalProperties: false, description: "需人权威处置的问题与选项" },
52
+ { additionalProperties: true, description: "需人权威处置的问题与选项" },
47
53
  ),
48
54
  ),
49
55
  },
@@ -14,9 +14,16 @@ export const mergerInputSchema = Type.Object({
14
14
  resolutionScope: Type.Array(Type.String(), { description: "材料:解析范围提示;可空" }),
15
15
  authorizedChecks: Type.Array(checkSchema),
16
16
  }, { additionalProperties: false });
17
+ // #836 r16 class 1: attemptId/report/diagnosis are LLM/human-read narrative
18
+ // content (candidate stored as submitted) — no code branches on their length.
19
+ // mergerInputSchema (host-authored material, not role output) is out of scope.
20
+ // #836 (ADR 0003 Amendment): status kept open like countersignStatus
21
+ // (src/countersign-role.ts) — one shared description across both variants
22
+ // so openToolObjectFromUnion's identical-declaration collapse drops none of it.
23
+ const MERGER_STATUS_DESCRIPTION = "completed | escalate — 形状指引,非 schema 闸" as const;
17
24
  const mergerOutputVariants = Type.Union([
18
- Type.Object({ status: Type.Literal("completed", { description: "completed — 形状指引,非 schema 闸" }), attemptId: Type.String({ minLength: 1, description: "已受理合并 attempt 身份" }), report: Type.String({ minLength: 1, description: "如实结果报告" }), mergeCommitId: Type.String({ description: "完成合并 commit object ID" }) }, { additionalProperties: false }),
19
- Type.Object({ status: Type.Literal("escalate", { description: "escalate — 形状指引,非 schema 闸" }), attemptId: Type.String({ minLength: 1, description: "已受理合并 attempt 身份" }), diagnosis: Type.String({ minLength: 1, description: "合并无法或不应由本席完成的原因(含无进行中合并、无活可干、需新的产品/权力决定)" }), report: Type.String({ minLength: 1, description: "如实结果报告" }) }, { additionalProperties: false }),
25
+ Type.Object({ status: Type.Unknown({ description: MERGER_STATUS_DESCRIPTION }), attemptId: Type.String({ description: "已受理合并 attempt 身份" }), report: Type.String({ description: "如实结果报告" }), mergeCommitId: Type.String({ description: "完成合并 commit object ID" }) }, { additionalProperties: false }),
26
+ Type.Object({ status: Type.Unknown({ description: MERGER_STATUS_DESCRIPTION }), attemptId: Type.String({ description: "已受理合并 attempt 身份" }), diagnosis: Type.String({ description: "合并无法或不应由本席完成的原因(含无进行中合并、无活可干、需新的产品/权力决定)" }), report: Type.String({ description: "如实结果报告" }) }, { additionalProperties: false }),
20
27
  ]);
21
28
  export const mergerOutputSchema = withInfrastructureFailureDeclaration(openToolObjectFromUnion(mergerOutputVariants));
22
29
 
@@ -54,8 +61,5 @@ export function validateMergerInput(value: unknown): MergerInput {
54
61
  }
55
62
 
56
63
  export function validateMergerOutput(value: unknown): MergerOutput {
57
- if (!record(value)) throw new Error("合并回执无已识别的执行判别");
58
- const status = typeof value.status === "string" ? value.status : undefined;
59
- if (status === "completed" || status === "escalate") return structuredClone(value) as MergerOutput;
60
- throw new Error("合并回执无已识别的执行判别");
64
+ return value as MergerOutput;
61
65
  }
@@ -19,13 +19,12 @@ function materialText(input: MergerInput, key: keyof MergerInput["materials"]):
19
19
 
20
20
  /**
21
21
  * Merger (校书郎) role runtime.
22
- * Code admits one submission and terminates the round (第 0 条).
22
+ * Submission tool records every call (#836); host end is the final.
23
23
  * Git state / completion verification are not attendance or rejection gates (#827).
24
24
  */
25
25
  export function createMergerRoleRuntime(pi: RoleHost, dependencies: MergerRoleDependencies) {
26
26
  let activation: { soul: string; input: Readonly<MergerInput> } | undefined;
27
27
  let registered = false;
28
- let accepted = false;
29
28
  pi.registerFlag(MERGER_INPUT_FLAG.name, MERGER_INPUT_FLAG.definition);
30
29
  return {
31
30
  async activate() {
@@ -35,15 +34,12 @@ export function createMergerRoleRuntime(pi: RoleHost, dependencies: MergerRoleDe
35
34
  if (!soul) throw new Error("Merger soul is empty");
36
35
  const input = validateMergerInput(await dependencies.loadInput(path));
37
36
  activation = { soul, input };
38
- accepted = false;
39
37
  if (!registered) {
40
38
  registered = true;
41
39
  pi.registerTool({
42
40
  name: MERGER_OUTPUT_TOOL_NAME, label: "合并输出", description: "提交合并结果;输出分支为 completed 与 escalate。", promptSnippet: "提交合并结果", parameters: mergerOutputSchema,
43
41
  async execute(_id: string, params: unknown, _signal: AbortSignal | undefined, _update: unknown, _ctx: HostContext) {
44
42
  if (!activation) throw new Error("校书郎未激活");
45
- if (accepted) throw new Error("合并回执已受理");
46
- accepted = true;
47
43
  return { content: [{ type: "text" as const, text: MERGER_ACCEPTED_TEXT }], details: params, terminate: true as const };
48
44
  },
49
45
  });
@@ -100,7 +100,7 @@ export type NavigatorWorkContext = {
100
100
  contextError?: unknown;
101
101
  };
102
102
 
103
- export type NavigatorRouteTarget = { role: NavigatorTargetRole; phase: NavigatorPhase };
103
+ export type NavigatorRouteTarget = { role: string; phase: NavigatorPhase };
104
104
  /** Normalized preparation advice. v1 success needs machine-usable next only. */
105
105
  export type NavigatorCandidate = {
106
106
  id?: string;
@@ -108,6 +108,7 @@ export type NavigatorCandidate = {
108
108
  route?: NavigatorRouteTarget[];
109
109
  next?: NavigatorRouteTarget;
110
110
  reason?: string;
111
+ command?: string;
111
112
  };
112
113
 
113
114
  export type NavigatorReport = {
@@ -237,24 +238,18 @@ function targetIsValid(value: unknown): value is NavigatorRouteTarget {
237
238
  return metadata !== undefined && metadata.phases.includes(value.phase as never);
238
239
  }
239
240
 
240
- /** Normalize one advice target. Phase is kept only when present and meaningful; bare role stays usable. */
241
+ /** Keep the role/phase the model wrote. Unknown seats stay on the advice. */
241
242
  function normalizeTarget(value: unknown): NavigatorRouteTarget | undefined {
242
243
  if (!exactRecord(value)) return undefined;
243
244
  const role = typeof value.role === "string" ? value.role.trim() : "";
244
- if (!targetRoles.has(role)) return undefined;
245
- const metadata = packagedRoleMetadata(role);
246
- if (metadata === undefined) return undefined;
245
+ if (role === "") return undefined;
247
246
  if (value.phase === undefined || value.phase === null) {
248
- return { role: role as NavigatorTargetRole, phase: null };
247
+ return { role, phase: null };
249
248
  }
250
249
  if (value.phase === "plan" || value.phase === "apply") {
251
- if (metadata.phases.includes(value.phase as never)) {
252
- return { role: role as NavigatorTargetRole, phase: value.phase };
253
- }
254
- // Present but not meaningful for this role → drop to bare role direction.
255
- return { role: role as NavigatorTargetRole, phase: null };
250
+ return { role, phase: value.phase };
256
251
  }
257
- return undefined;
252
+ return { role, phase: null };
258
253
  }
259
254
 
260
255
  function normalizeMatches(value: unknown): NavigatorCandidate["matches"] | undefined {
@@ -289,13 +284,14 @@ function normalizeCandidate(value: unknown): NavigatorCandidate | undefined {
289
284
  const matches = normalizeMatches(value.matches);
290
285
  const id = typeof value.id === "string" && value.id.trim() !== "" ? value.id : undefined;
291
286
  const reason = typeof value.reason === "string" && value.reason.trim() !== "" ? value.reason : undefined;
292
- // Model command prose is never execution authority; omit from normalized advice.
287
+ const command = typeof value.command === "string" ? value.command : undefined;
293
288
  return {
294
289
  ...(id === undefined ? {} : { id }),
295
290
  ...(matches === undefined ? {} : { matches }),
296
291
  ...(route === undefined || route.length === 0 ? {} : { route }),
297
292
  ...(next === undefined ? {} : { next }),
298
293
  ...(reason === undefined ? {} : { reason }),
294
+ ...(command === undefined ? {} : { command }),
299
295
  };
300
296
  }
301
297
 
@@ -316,9 +312,7 @@ function routeText(route: readonly NavigatorRouteTarget[]): string {
316
312
  function targetText(target: NavigatorRouteTarget): string {
317
313
  return target.phase === null ? target.role : `${target.role} ${target.phase}`;
318
314
  }
319
- function oneLine(value: string): string {
320
- return value.split(/\r?\n/, 1)[0]!.trim();
321
- }
315
+
322
316
  export function navigatorSubjectKey(
323
317
  subjectRoot: string,
324
318
  subject: string,
@@ -416,16 +410,20 @@ export function selectNavigatorCandidate(
416
410
  export function formatNavigatorReport(report: NavigatorReport): string {
417
411
  const playbookFailure = report.routePlaybookReadFailure === undefined
418
412
  ? []
419
- : [`路书读取失败:${oneLine(report.routePlaybookReadFailure)}`];
413
+ : [`路书读取失败:${report.routePlaybookReadFailure}`];
420
414
  if (report.disposition === "no-advice") return playbookFailure.join("\n");
421
- if (report.disposition === "unavailable") return [...playbookFailure, `导航不可用:${oneLine(report.unavailableReason ?? "未能完成导航准备")}`].join("\n");
422
- if (report.disposition === "arrival") return [...playbookFailure, oneLine(report.arrivalMessage ?? "已到达目的地")].join("\n");
415
+ if (report.disposition === "unavailable") {
416
+ return [...playbookFailure, ...(report.unavailableReason ? [report.unavailableReason] : [])].join("\n");
417
+ }
418
+ if (report.disposition === "arrival") {
419
+ return [...playbookFailure, ...(report.arrivalMessage ? [report.arrivalMessage] : [])].join("\n");
420
+ }
423
421
  return [
424
422
  ...playbookFailure,
425
423
  ...(report.route === undefined ? [] : [`路线:${routeText(report.route)}`]),
426
- `下一步:${targetText(report.next!)}`,
427
- ...(report.reason === undefined || report.reason.trim() === "" ? [] : [`理由:${oneLine(report.reason)}`]),
428
- ...(report.command === undefined || report.command.trim() === "" ? [] : [`命令:${oneLine(report.command)}`]),
424
+ ...(report.next === undefined ? [] : [`下一步:${targetText(report.next)}`]),
425
+ ...(report.reason === undefined || report.reason.trim() === "" ? [] : [`理由:${report.reason}`]),
426
+ ...(report.command === undefined || report.command.trim() === "" ? [] : [`命令:${report.command}`]),
429
427
  ].join("\n");
430
428
  }
431
429
 
@@ -450,45 +448,6 @@ export function settlementNavigationFromEvent(event: NavigatorEvent): Settlement
450
448
  };
451
449
  }
452
450
 
453
- type SettlementTextPart = { type: "text"; text: string };
454
-
455
- function appendNavigatorReportToContent<T extends { type: string }>(
456
- content: readonly T[],
457
- reportText: string,
458
- ): Array<T | SettlementTextPart> {
459
- if (reportText === "") return content.slice();
460
- const parts: Array<T | SettlementTextPart> = content.slice();
461
- for (let index = parts.length - 1; index >= 0; index -= 1) {
462
- const part = parts[index];
463
- if (part !== undefined && part.type === "text" && typeof (part as SettlementTextPart).text === "string") {
464
- parts[index] = { ...(part as object), type: "text", text: `${(part as SettlementTextPart).text}\n${reportText}` } as SettlementTextPart;
465
- return parts;
466
- }
467
- }
468
- return [...parts, { type: "text", text: reportText }];
469
- }
470
-
471
- /**
472
- * Decorate an accepted role-output tool result so the one mandatory settlement
473
- * extraction (last ak_*_output toolResult) carries recommendation essentials in
474
- * content text. Receipt details stay byte-identical to the terminating-tool
475
- * contract — unavailable and affirmative no-advice leave the settlement untouched.
476
- */
477
- export function decorateSettlementWithNavigation<T extends { type: string }>(
478
- event: { content: readonly T[]; details: unknown },
479
- presentation: { event: NavigatorEvent; report: NavigatorReport } | undefined,
480
- ): { content: Array<T | SettlementTextPart>; details: unknown } | undefined {
481
- if (presentation === undefined) return undefined;
482
- if (settlementNavigationFromEvent(presentation.event) === undefined) return undefined;
483
- const { routePlaybookReadFailure: _advisoryFailure, ...receiptReport } = presentation.report;
484
- const reportText = formatNavigatorReport(receiptReport);
485
- if (reportText === "") return undefined;
486
- return {
487
- content: appendNavigatorReportToContent(event.content, reportText),
488
- details: event.details,
489
- };
490
- }
491
-
492
451
  export function createNavigatorAttendance(options: NavigatorAttendanceOptions) {
493
452
  let preparation: Promise<NavigatorCandidate[]> | undefined;
494
453
  let sessionReady: Promise<NavigatorPreparationSession> | undefined;
@@ -620,15 +579,18 @@ export function createNavigatorAttendance(options: NavigatorAttendanceOptions) {
620
579
  let output: PrepareOutput | undefined;
621
580
  let prepareBatchRejected = false;
622
581
  outputSink = (value) => {
623
- if (prepareBatchRejected || output !== undefined) {
624
- // Tool executions in one assistant response are provisional until the
625
- // whole response is known to contain exactly one submission. A
626
- // duplicate invalidates the batch, including its first call.
627
- output = undefined;
628
- prepareBatchRejected = true;
629
- throw new Error("Navigator preparation must submit exactly one typed candidate batch");
582
+ // #836: extra prepare calls append; they do not void the first batch.
583
+ if (output === undefined) {
584
+ output = value;
585
+ return;
630
586
  }
631
- output = value;
587
+ const prior = output.candidates;
588
+ const next = value.candidates;
589
+ const merged = [
590
+ ...(Array.isArray(prior) ? prior : prior === undefined ? [] : [prior]),
591
+ ...(Array.isArray(next) ? next : next === undefined ? [] : [next]),
592
+ ];
593
+ output = { ...value, candidates: merged };
632
594
  };
633
595
  const tool = createNavigatorPrepareTool((value) => { outputSink?.(value); });
634
596
  if (session === undefined) {
@@ -675,7 +637,6 @@ export function createNavigatorAttendance(options: NavigatorAttendanceOptions) {
675
637
  }
676
638
  const publicSettlementHistory = activeSession.entries()
677
639
  .filter((entry): entry is { type: "custom"; customType: string; data?: unknown } => exactRecord(entry) && entry.type === "custom" && entry.customType === SETTLEMENT_ENTRY && exactRecord(entry.data))
678
- .slice(-8)
679
640
  .map((entry) => entry.data as NavigatorSettlementFact);
680
641
  const projection: NavigatorContextProjection = {
681
642
  subjectKey,
@@ -867,7 +828,7 @@ export function createNavigatorAttendance(options: NavigatorAttendanceOptions) {
867
828
  try { await preparation; } catch (error) { preparationFailure ??= error; }
868
829
  }
869
830
  report = preparationFailure === undefined
870
- ? { disposition: "arrival", arrivalMessage: settlement.message ?? "已到达目的地" }
831
+ ? { disposition: "arrival", ...(settlement.message === undefined ? {} : { arrivalMessage: settlement.message }) }
871
832
  : unavailable(invocationId, preparationFailure);
872
833
  } else if (preparation === undefined) {
873
834
  report = unavailable(invocationId, "Navigator preparation did not start");
@@ -900,13 +861,15 @@ export function createNavigatorAttendance(options: NavigatorAttendanceOptions) {
900
861
  } else {
901
862
  const selectedRoute = selectedCandidate.route;
902
863
  const routeChanged = selectedRoute !== undefined && !routeEqual(previousRoute, selectedRoute);
903
- // Single owner: public registry renderer (ADR 0052). Model command prose is never authority.
904
- const command = renderPublicAkRoleCommand(selectedCandidate.next);
864
+ const command =
865
+ typeof selectedCandidate.command === "string" && selectedCandidate.command.trim() !== ""
866
+ ? selectedCandidate.command
867
+ : renderPublicAkRoleCommand(selectedCandidate.next);
905
868
  report = {
906
869
  disposition: "recommendation",
907
870
  ...(routeChanged ? { route: selectedRoute } : {}),
908
871
  next: selectedCandidate.next,
909
- ...(selectedCandidate.reason === undefined ? {} : { reason: oneLine(selectedCandidate.reason) }),
872
+ ...(selectedCandidate.reason === undefined ? {} : { reason: selectedCandidate.reason }),
910
873
  ...(command === undefined ? {} : { command }),
911
874
  };
912
875
  if (selectedRoute !== undefined) {
@@ -228,12 +228,6 @@ export function classifyPackagedRoleTerminalResult(
228
228
  if (typeof message.toolName !== "string") return { kind: "nonterminal" };
229
229
  if (!PACKAGED_ROLE_OUTPUT_TOOLS.has(message.toolName)) return { kind: "nonterminal" };
230
230
 
231
- if (
232
- typeof message.details === "object" &&
233
- message.details !== null &&
234
- (message.details as { submissionDisposition?: unknown }).submissionDisposition === "pending-round-closure"
235
- ) return { kind: "nonterminal" };
236
-
237
231
  // Base identity is enough; durable details may carry typed failure evidence (#475).
238
232
  const hasInfraBase = hasNavigatorInfrastructureFailureBase(message.details);
239
233
  const infraFact = hasInfraBase ? buildNavigatorInfrastructureFailureFact() : undefined;