@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,7 +1,6 @@
1
1
  import type { Static } from "typebox";
2
2
  import { Type } from "typebox";
3
3
 
4
- import { stringEnum } from "./host-contracts.ts";
5
4
  import { withInfrastructureFailureDeclaration } from "./package-contracts/terminating-infrastructure.ts";
6
5
  import {
7
6
  COUNTERSIGN_OUTPUT_TOOL_NAME,
@@ -12,26 +11,36 @@ import {
12
11
  export { COUNTERSIGN_ACCEPTED_TEXT, COUNTERSIGN_OUTPUT_TOOL_NAME } from "./countersign-contracts.ts";
13
12
  export type { CountersignVerdict };
14
13
 
14
+ // #836 r16 class 1: fix/note/decisionGate are LLM/human-read narrative content —
15
+ // no code branches on their length or nested presence. `countersignStatus`
16
+ // alone is the machine discriminator the queue reads (src/role-runtime.ts:979-1025).
17
+ // #836 (2026-09-11 御批 / ADR 0003 Amendment): registered-to-provider closed
18
+ // value domains reject an unknown countersignStatus before the submission
19
+ // ledger ever records it, defeating 读不出三态→resume 说话者本人. Kept open
20
+ // (Type.Unknown) like every other gate-queue status field in this package
21
+ // (notary/auditor/gatekeeper/navigator); src/role-runtime.ts:997-1025 still
22
+ // classifies the recorded value and reasks the countersign itself when it
23
+ // isn't one of the three states — code, not the transport, does that work.
15
24
  /** 给事中票庭审读五问的交卷形状(ADR 0074);形状指引,非 schema 闸。 */
16
25
  export const countersignVerdictSchema = withInfrastructureFailureDeclaration(
17
26
  Type.Object(
18
27
  {
19
- countersignStatus: stringEnum(["converged", "continue", "escalate"] as const, { description: "converged | continue | escalate" }),
28
+ countersignStatus: Type.Unknown({ description: "converged | continue | escalate。非三态时请重读后重交,勿改标。" }),
20
29
  fix: Type.Optional(
21
30
  Type.Object(
22
- { summary: Type.String({ minLength: 1, description: "退回摘要" }) },
23
- { additionalProperties: false, description: "退回说明" },
31
+ { summary: Type.Optional(Type.String({ description: "退回摘要" })) },
32
+ { additionalProperties: true, description: "退回说明" },
24
33
  ),
25
34
  ),
26
- note: Type.Optional(Type.String({ minLength: 1, description: "附注" })),
35
+ note: Type.Optional(Type.String({ description: "附注" })),
27
36
  evidence: Type.Optional(Type.Unknown({ description: "留存证据" })),
28
37
  decisionGate: Type.Optional(
29
38
  Type.Object(
30
39
  {
31
- question: Type.String({ minLength: 1 }),
32
- options: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
40
+ question: Type.Optional(Type.String()),
41
+ options: Type.Optional(Type.Array(Type.String())),
33
42
  },
34
- { additionalProperties: false, description: "需陛下处置的问题与选项" },
43
+ { additionalProperties: true, description: "需陛下处置的问题与选项" },
35
44
  ),
36
45
  ),
37
46
  },
@@ -64,41 +64,8 @@ export function validateRecordedDiaristOutput(value: unknown): DiaristOutput {
64
64
  throw new Error("Diarist output has no execution discriminator");
65
65
  }
66
66
 
67
- /**
68
- * Lenient projection of submitted entries (第 0 条: shape is not an admission
69
- * gate). Rows that cannot form a lawful volume entry are dropped from the
70
- * commit, never bounced back at the role. This is write-seam self-check only —
71
- * not quote/ticket/relevance judgment of LLM content (#779).
72
- */
73
- export function projectDiaristEntries(value: unknown): DiaristEntrySubmission[] {
67
+ /** Entries array as the diarist wrote it — no field rewrite (#836 B6.8/B6.9). */
68
+ export function projectDiaristEntries(value: unknown): unknown[] {
74
69
  const rows = (value as { entries?: unknown } | null)?.entries;
75
- if (!Array.isArray(rows)) return [];
76
- const out: DiaristEntrySubmission[] = [];
77
- for (const row of rows) {
78
- if (row === null || typeof row !== "object" || Array.isArray(row)) continue;
79
- const record = row as Record<string, unknown>;
80
- if (typeof record.sourceKind !== "string") continue;
81
- if (typeof record.transcript !== "string" || record.transcript.length === 0) continue;
82
- if (typeof record.timestamp !== "string" || record.timestamp.length === 0) continue;
83
- if (record.sourceRef === null || typeof record.sourceRef !== "object" || Array.isArray(record.sourceRef)) {
84
- continue;
85
- }
86
- const ref = record.sourceRef as Record<string, unknown>;
87
- const sourceRef: TicketProvenanceSourceRef = {
88
- ...(typeof ref.sessionFile === "string" ? { sessionFile: ref.sessionFile } : {}),
89
- ...(typeof ref.entryId === "string" || typeof ref.entryId === "number"
90
- ? { entryId: ref.entryId }
91
- : {}),
92
- ...(typeof ref.path === "string" ? { path: ref.path } : {}),
93
- ...(typeof ref.url === "string" ? { url: ref.url } : {}),
94
- };
95
- out.push({
96
- sourceKind: record.sourceKind as TicketProvenanceSourceKind,
97
- sourceRef,
98
- transcript: record.transcript,
99
- timestamp: record.timestamp,
100
- ...(typeof record.note === "string" ? { note: record.note } : {}),
101
- });
102
- }
103
- return out;
70
+ return Array.isArray(rows) ? [...rows] : [];
104
71
  }
@@ -16,6 +16,12 @@ export {
16
16
  export type { DiaristOutput };
17
17
  export { validateRecordedDiaristOutput };
18
18
 
19
+ // #836 r16 class 1: entries[].sourceKind/sourceRef/transcript/timestamp are
20
+ // LLM/human-read content — src/ticket-provenance-contracts.ts:130-140 reads
21
+ // sourceKind/transcript, but the lawful path on a miss is to keep the entry as
22
+ // unprojected raw payload (src/diarist.ts:52-75 never rejects or drops it), so
23
+ // provider `required` would cut off that very branch; sourceRef/timestamp are
24
+ // not branched on at all.
19
25
  /** 起居郎交卷形状;形状指引,非 schema 闸。 */
20
26
  export const diaristOutputSchema = withInfrastructureFailureDeclaration(
21
27
  openToolObject(
@@ -38,11 +44,11 @@ export const diaristOutputSchema = withInfrastructureFailureDeclaration(
38
44
  Type.Array(
39
45
  Type.Object(
40
46
  {
41
- sourceKind: Type.String({
47
+ sourceKind: Type.Optional(Type.String({
42
48
  description:
43
49
  "来源族:cc-session | issue-body-comment | adr-decision-key | ticket-decree-block",
44
- }),
45
- sourceRef: Type.Object(
50
+ })),
51
+ sourceRef: Type.Optional(Type.Object(
46
52
  {
47
53
  sessionFile: Type.Optional(Type.String()),
48
54
  entryId: Type.Optional(Type.Unknown()),
@@ -50,11 +56,11 @@ export const diaristOutputSchema = withInfrastructureFailureDeclaration(
50
56
  url: Type.Optional(Type.String()),
51
57
  },
52
58
  { additionalProperties: true, description: "不可变源指针" },
53
- ),
54
- transcript: Type.String({
59
+ )),
60
+ transcript: Type.Optional(Type.String({
55
61
  description: "整块原文(誊录整块,不指针化)",
56
- }),
57
- timestamp: Type.String({ description: "源时间戳 ISO" }),
62
+ })),
63
+ timestamp: Type.Optional(Type.String({ description: "源时间戳 ISO" })),
58
64
  note: Type.Optional(
59
65
  Type.String({ description: "该材料与本案的关系(人读)" }),
60
66
  ),
package/src/diarist.ts CHANGED
@@ -13,7 +13,6 @@ import {
13
13
  writeTicketProvenanceHumanView,
14
14
  } from "./ticket-provenance.ts";
15
15
  import { projectTicketProvenanceEntry } from "./ticket-provenance-contracts.ts";
16
- import type { DiaristEntrySubmission } from "./diarist-contracts.ts";
17
16
 
18
17
  /**
19
18
  * Honest machine facts about what this turn actually committed to the volume.
@@ -44,7 +43,7 @@ export async function commitDiaristEntries(input: {
44
43
  readonly ticketNumber: number;
45
44
  readonly cwd: string;
46
45
  readonly home?: string;
47
- readonly entries: readonly DiaristEntrySubmission[];
46
+ readonly entries: readonly unknown[];
48
47
  }): Promise<DiaristCommitFacts> {
49
48
  const { ticketNumber, cwd } = input;
50
49
  const homeOpt = input.home === undefined ? {} : { home: input.home };
@@ -54,26 +53,14 @@ export async function commitDiaristEntries(input: {
54
53
  let dropped = 0;
55
54
 
56
55
  for (const submitted of input.entries) {
57
- const entry = projectTicketProvenanceEntry({
58
- basis: {
59
- method: "llm-semantic",
60
- anchors: [`#${ticketNumber}`],
61
- ...(submitted.note === undefined ? {} : { note: submitted.note }),
62
- },
63
- sourceKind: submitted.sourceKind,
64
- sourceRef: submitted.sourceRef,
65
- transcript: submitted.transcript,
66
- timestamp: submitted.timestamp,
67
- });
68
- if (entry === undefined) {
56
+ if (projectTicketProvenanceEntry(submitted) === undefined) {
69
57
  dropped += 1;
70
- continue;
71
58
  }
72
59
  appendTicketProvenanceEntry({
73
60
  ticketNumber,
74
61
  cwd,
75
62
  ...homeOpt,
76
- entry,
63
+ payload: submitted,
77
64
  source: "diarist",
78
65
  });
79
66
  }
@@ -84,6 +71,7 @@ export async function commitDiaristEntries(input: {
84
71
  cwd,
85
72
  ...homeOpt,
86
73
  entries: volume.entries,
74
+ unprojected: volume.unprojected,
87
75
  });
88
76
 
89
77
  const appended = volume.entries.length - before.entries.length;
@@ -7,7 +7,7 @@ export const DOCTOR_EVIDENCE_TOOL_NAME = "ak_doctor_evidence";
7
7
  export const DOCTOR_OUTPUT_TOOL_NAME = "ak_doctor_output";
8
8
  export const DOCTOR_ACCEPTED_TEXT = "太医署回执已接受";
9
9
  export const DOCTOR_ACCEPTED_AUDIT_NO_RECEIPT_TEXT = "太医署回执已接受;审计无回执";
10
- export const DOCTOR_OUTPUT_TOOL_DESCRIPTION = "提交唯一终局单案证词;completed 允许空 findings;runtime 补记派生成本入回执。";
10
+ export const DOCTOR_OUTPUT_TOOL_DESCRIPTION = "提交唯一终局单案证词;completed 允许空 findings。";
11
11
  export const DOCTOR_TARGET_KINDS = ["law", "gate", "template", "station", "seat"] as const;
12
12
  export type DoctorTargetKind = typeof DOCTOR_TARGET_KINDS[number];
13
13
  export type DoctorCaseIdentity = { issueNumber: number; runsPath: string };
@@ -40,133 +40,112 @@ export type DoctorFinding =
40
40
  export type DoctorSubmission =
41
41
  | { status: "completed"; case: DoctorCaseIdentity; findings: DoctorFinding[] }
42
42
  | { status: "refused"; reason: string; missingEvidence: Array<{ need: string; targetKeys: string[] }> };
43
- export type DoctorOutput =
44
- | { status: "completed"; case: DoctorCaseIdentity; findings: DoctorFinding[]; cost: DoctorCaseCost }
45
- | Extract<DoctorSubmission, { status: "refused" }>;
43
+ // #836: runtime cost is a fact beside the role payload, never merged into it —
44
+ // DoctorOutput is the accepted payload itself, identical to DoctorSubmission.
45
+ export type DoctorOutput = DoctorSubmission;
46
46
  export type DoctorEvidenceEntry = { id: string; kind: "session" | "stderr"; byteLength: number; contentLength: number; sha256: string; content: string };
47
47
  export type DoctorCase = { version: 1; identity: DoctorCaseIdentity; evidence: DoctorEvidenceEntry[]; cost: DoctorCaseCost };
48
48
 
49
- const nonblank = Type.String({ minLength: 1, pattern: "\\S" });
50
- const count = Type.Object({ count: Type.Integer({ minimum: 0 }), sources: Type.Array(nonblank) }, { additionalProperties: false });
51
- const evidenceIds = Type.Array(nonblank, { minItems: 1 });
52
- const guardrail = Type.Object({ answer: Type.Boolean(), evidenceIds, explanation: nonblank }, { additionalProperties: false });
49
+ // #836 r16 class 1: case/finding/assetEvidence/guardrails/prescription/
50
+ // lastRealBite/missingEvidence are LLM/human-read narrative content — Judge/
51
+ // 察院 read the original volume, no code branches on their length or nested
52
+ // presence (src/doctor-contracts.ts:136-138 passes the submission through
53
+ // unprojected). Field/type/description/Literal value stay; provider
54
+ // required/minLength/minItems/minimum/nested additionalProperties:false is deleted.
55
+ const nonblank = Type.Optional(Type.String());
56
+ const evidenceIds = Type.Optional(Type.Array(Type.String()));
57
+ const guardrail = Type.Object({ answer: Type.Optional(Type.Boolean()), evidenceIds, explanation: nonblank }, { additionalProperties: true });
53
58
  const lastRealBite = Type.Union([
54
- Type.Object({ kind: Type.Literal("actual"), targetKey: nonblank, evidenceId: nonblank }, { additionalProperties: false }),
55
- Type.Object({ kind: Type.Literal("noRealBite"), targetKey: nonblank, eligibleEvidenceIds: evidenceIds }, { additionalProperties: false }),
59
+ Type.Object({ kind: Type.Optional(Type.Literal("actual")), targetKey: nonblank, evidenceId: nonblank }, { additionalProperties: true }),
60
+ Type.Object({ kind: Type.Optional(Type.Literal("noRealBite")), targetKey: nonblank, eligibleEvidenceIds: evidenceIds }, { additionalProperties: true }),
56
61
  ]);
57
62
  const assetKinds = DOCTOR_TARGET_KINDS;
58
63
  const findingBody = {
59
- evidenceIds, disposition: Type.Union([Type.Literal("keep"), Type.Literal("thin"), Type.Literal("delete")]),
60
- guardrails: Type.Object({ reproducibleFailure: guardrail, owningSeamOrInvariant: guardrail, deletionOrSimplificationSuffices: guardrail }, { additionalProperties: true }),
61
- prescription: Type.Object({ kind: Type.Union([Type.Literal("retain"), Type.Literal("delete"), Type.Literal("simplify"), Type.Literal("patch"), Type.Literal("addMechanism")]), recommendation: nonblank, necessityExplanation: Type.Optional(nonblank) }, { additionalProperties: false }), lastRealBite,
64
+ evidenceIds, disposition: Type.Optional(Type.Union([Type.Literal("keep"), Type.Literal("thin"), Type.Literal("delete")])),
65
+ guardrails: Type.Optional(Type.Object({ reproducibleFailure: guardrail, owningSeamOrInvariant: guardrail, deletionOrSimplificationSuffices: guardrail }, { additionalProperties: true })),
66
+ prescription: Type.Optional(Type.Object({ kind: Type.Optional(Type.Union([Type.Literal("retain"), Type.Literal("delete"), Type.Literal("simplify"), Type.Literal("patch"), Type.Literal("addMechanism")])), recommendation: nonblank, necessityExplanation: nonblank }, { additionalProperties: true })), lastRealBite: Type.Optional(lastRealBite),
62
67
  };
63
68
  const finding = Type.Union([
64
- Type.Object({ targetKey: nonblank, observation: nonblank, evidenceIds }, { additionalProperties: false }),
65
- Type.Object({ targetKey: nonblank, targetKind: Type.Union(assetKinds.map((kind) => Type.Literal(kind))), assetEvidence: Type.Object({ targetKey: nonblank, targetKind: Type.Union(assetKinds.map((kind) => Type.Literal(kind))), evidenceId: nonblank }, { additionalProperties: false }), ...findingBody }, { additionalProperties: false }),
69
+ Type.Object({ targetKey: nonblank, observation: nonblank, evidenceIds }, { additionalProperties: true }),
70
+ Type.Object({ targetKey: nonblank, targetKind: Type.Optional(Type.Union(assetKinds.map((kind) => Type.Literal(kind)))), assetEvidence: Type.Optional(Type.Object({ targetKey: nonblank, targetKind: Type.Optional(Type.Union(assetKinds.map((kind) => Type.Literal(kind)))), evidenceId: nonblank }, { additionalProperties: true })), ...findingBody }, { additionalProperties: true }),
66
71
  ]);
67
- const caseIdentity = Type.Object({ issueNumber: Type.Integer({ minimum: 1 }), runsPath: nonblank }, { additionalProperties: false });
68
- const cost = Type.Object({
69
- invocations: count, legs: count, modelApiTurns: count, outputTokens: count, toolCalls: count,
70
- retries: Type.Object({ count: Type.Integer({ minimum: 0 }), sources: Type.Array(nonblank), evidence: Type.Literal("literal run-dir naming") }, { additionalProperties: false }),
71
- statuses: Type.Array(Type.Object({ source: nonblank, status: nonblank }, { additionalProperties: false })),
72
- commits: Type.Array(Type.Object({ source: nonblank, commit: nonblank }, { additionalProperties: false })),
73
- sessions: Type.Array(Type.Union([
74
- Type.Object({ source: nonblank, startedAt: nonblank, endedAt: nonblank, wallMilliseconds: Type.Number({ minimum: 0 }), completion: Type.Literal("accepted") }, { additionalProperties: false }),
75
- Type.Object({ source: nonblank, startedAt: Type.Optional(nonblank), endedAt: Type.Optional(nonblank), wallMilliseconds: Type.Optional(Type.Number({ minimum: 0 })), completion: Type.Literal("incomplete"), degradationReason: Type.Optional(nonblank) }, { additionalProperties: false }),
76
- ])),
77
- outputBytes: Type.Object({ count: Type.Integer({ minimum: 0 }), sources: Type.Array(nonblank), payload: Type.Literal("raw JSONL bytes"), providerWireBytes: Type.Literal("unavailable") }, { additionalProperties: false }),
78
- }, { additionalProperties: false });
72
+ const caseIdentity = Type.Object({ issueNumber: Type.Optional(Type.Integer()), runsPath: nonblank }, { additionalProperties: true });
73
+ // #836 (ADR 0003 Amendment): status kept open like countersignStatus
74
+ // (src/countersign-role.ts) — one shared description across both variants
75
+ // so openToolObjectFromUnion's identical-declaration collapse drops none of it.
76
+ const DOCTOR_STATUS_DESCRIPTION =
77
+ "completed | refused — 形状指引,非 schema 闸;completed 允许空 findings;refused 仅当证据不足以支撑如实案证词" as const;
79
78
  const doctorSubmissionVariants = Type.Union([
80
79
  Type.Object({
81
- status: Type.Literal("completed", { description: "completed — 形状指引,非 schema 闸;允许空 findings;runtime 补记派生成本入回执" }),
80
+ status: Type.Unknown({ description: DOCTOR_STATUS_DESCRIPTION }),
82
81
  case: Type.Unsafe({ ...caseIdentity, description: "留存太医署案身份" }),
83
82
  findings: Type.Array(finding, { description: "可空或仅含非处方案观察;缺可复用资产或 bounded-bite 证据只排除对应资产处方" }),
84
83
  }, { additionalProperties: false, description: "单案证词,不要求任何处方或可复用 finding" }),
85
84
  Type.Object({
86
- status: Type.Literal("refused", { description: "refused — 形状指引,非 schema 闸;仅当证据不足以支撑如实案证词" }),
87
- reason: Type.String({ minLength: 1, description: "证据不足以支撑如实证词的原因" }),
88
- missingEvidence: Type.Array(Type.Object({ need: nonblank, targetKeys: Type.Array(nonblank, { minItems: 1 }) }, { additionalProperties: false }), { minItems: 1, description: "如实证词所需而尚缺的证据" }),
85
+ status: Type.Unknown({ description: DOCTOR_STATUS_DESCRIPTION }),
86
+ reason: Type.String({ description: "证据不足以支撑如实证词的原因" }),
87
+ missingEvidence: Type.Array(Type.Object({ need: nonblank, targetKeys: evidenceIds }, { additionalProperties: true }), { description: "如实证词所需而尚缺的证据" }),
89
88
  }, { additionalProperties: false, description: "证据不足以支撑如实案证词" }),
90
89
  ]);
91
90
  export const doctorSubmissionSchema = withInfrastructureFailureDeclaration(
92
91
  openToolObjectFromUnion(doctorSubmissionVariants),
93
92
  );
94
- export const doctorOutputSchema = Type.Union([
95
- Type.Object({ status: Type.Literal("completed"), case: caseIdentity, findings: Type.Array(finding), cost }, { additionalProperties: false }),
96
- doctorSubmissionVariants.anyOf[1]!,
97
- ]);
98
- export const doctorEvidenceReadSchema = Type.Object({ evidenceId: Type.String({ minLength: 1, description: "待读留存证据标识" }), offset: Type.Optional(Type.Integer({ minimum: 0, description: "起始字节偏移(从 0 计)" })), limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 4096, description: "返回字节上限" })) }, { additionalProperties: false });
93
+ // #836 r16 class 3: action tool — code reads evidenceId to look up the Map entry
94
+ // and offset/limit to slice + accumulate coverage (src/doctor-contracts.ts:97-128,
95
+ // src/doctor-role.ts:38); those constraints stay. Root additionalProperties:false
96
+ // is deleted — no reader consumes extra fields, so a closed object only rejects
97
+ // the role for saying more (src/doctor-role.ts execute reads named params only).
98
+ export const doctorEvidenceReadSchema = Type.Object({ evidenceId: Type.String({ minLength: 1, description: "待读留存证据标识" }), offset: Type.Optional(Type.Integer({ minimum: 0, description: "起始字节偏移(从 0 计)" })), limit: Type.Optional(Type.Integer({ minimum: 1, description: "返回字节数(无上限)" })) }, { additionalProperties: true });
99
99
  export class DoctorSubmissionContractError extends Error { override readonly name = "DoctorSubmissionContractError"; }
100
100
  function isRecord(value: unknown): value is Record<string, unknown> { return typeof value === "object" && value !== null && !Array.isArray(value); }
101
101
  function read(value: unknown, key: string): unknown { if (!isRecord(value)) return undefined; try { return value[key]; } catch { return undefined; } }
102
102
  export function validateDoctorSubmissionShape(value: unknown): DoctorSubmission {
103
- const status = read(value, "status");
104
- if (status !== "completed" && status !== "refused") throw new DoctorSubmissionContractError("太医署交卷无已识别的执行状态");
105
103
  return value as DoctorSubmission;
106
104
  }
107
105
  export function validateRecordedDoctorOutput(value: unknown): DoctorOutput {
108
- const output = validateDoctorSubmissionShape(value);
109
- const status = read(output, "status");
110
- if (status === "completed" && read(output, "cost") === undefined) throw new DoctorSubmissionContractError("completed 太医署回执缺少 runtime 持有的 cost 证词");
111
- return output as DoctorOutput;
106
+ return value as DoctorOutput;
112
107
  }
113
108
 
114
109
  export class DoctorEvidenceStore {
115
110
  readonly entries: Map<string, DoctorEvidenceEntry>; private readonly coverage = new Map<string, Array<[number, number]>>();
116
111
  constructor(readonly patient: DoctorCase) { this.entries = new Map(patient.evidence.map((entry) => [entry.id, entry])); }
117
- read(evidenceId: string, offset = 0, limit = 4096) { const entry = this.entries.get(evidenceId); if (!entry) throw new Error(`证据 ID 未准入:${evidenceId}`); if (!Number.isInteger(offset) || offset < 0 || !Number.isInteger(limit) || limit < 1 || limit > 4096) throw new Error("证据分页参数无效"); if (offset > entry.contentLength) throw new Error("证据 offset 超出内容"); const end = Math.min(entry.contentLength, offset + limit); const ranges = [...(this.coverage.get(evidenceId) ?? []), [offset, end] as [number, number]].sort((a, b) => a[0] - b[0]); const merged: Array<[number, number]> = []; for (const range of ranges) { const prior = merged.at(-1); if (prior && range[0] <= prior[1]) prior[1] = Math.max(prior[1], range[1]); else merged.push([...range]); } this.coverage.set(evidenceId, merged); return { evidenceId, kind: entry.kind, offset, content: entry.content.slice(offset, end), nextOffset: end < entry.contentLength ? end : null, contentLength: entry.contentLength, byteLength: entry.byteLength, sha256: entry.sha256 }; }
112
+ // #836 A6.5: no 4096 hard cap — limit only bounds the requested window when provided.
113
+ read(evidenceId: string, offset = 0, limit?: number) {
114
+ const entry = this.entries.get(evidenceId);
115
+ if (!entry) throw new Error(`证据 ID 未准入:${evidenceId}`);
116
+ if (!Number.isInteger(offset) || offset < 0) throw new Error("证据分页参数无效");
117
+ if (offset > entry.contentLength) throw new Error("证据 offset 超出内容");
118
+ const window = limit === undefined
119
+ ? entry.contentLength - offset
120
+ : (!Number.isInteger(limit) || limit < 1 ? (() => { throw new Error("证据分页参数无效"); })() : limit);
121
+ const end = Math.min(entry.contentLength, offset + window);
122
+ const ranges = [...(this.coverage.get(evidenceId) ?? []), [offset, end] as [number, number]].sort((a, b) => a[0] - b[0]);
123
+ const merged: Array<[number, number]> = [];
124
+ for (const range of ranges) {
125
+ const prior = merged.at(-1);
126
+ if (prior && range[0] <= prior[1]) prior[1] = Math.max(prior[1], range[1]);
127
+ else merged.push([...range]);
128
+ }
129
+ this.coverage.set(evidenceId, merged);
130
+ return {
131
+ evidenceId,
132
+ kind: entry.kind,
133
+ offset,
134
+ content: entry.content.slice(offset, end),
135
+ nextOffset: end < entry.contentLength ? end : null,
136
+ contentLength: entry.contentLength,
137
+ byteLength: entry.byteLength,
138
+ sha256: entry.sha256,
139
+ };
140
+ }
118
141
  hasRead(id: string) { const entry = this.entries.get(id); const ranges = this.coverage.get(id); return !!entry && ranges?.length === 1 && ranges[0]![0] === 0 && ranges[0]![1] === entry.contentLength; }
119
142
  readRecord() { return [...this.coverage.keys()].sort().map((evidenceId) => ({ evidenceId, fullyRead: this.hasRead(evidenceId) })); }
120
143
  }
121
- export function validateDoctorOutput(value: unknown, patient: DoctorCase, store: DoctorEvidenceStore): DoctorSubmission {
122
- const output = validateDoctorSubmissionShape(value);
123
- const lawfulTargets = new Set(["case", ...patient.cost.invocations.sources]);
124
- const assertTarget = (targetKey: unknown) => { if (typeof targetKey === "string" && !lawfulTargets.has(targetKey)) throw new DoctorSubmissionContractError(`targetKey 不是合法案目标:${targetKey}`); };
125
- const readCitations = (ids: unknown, label: string) => { if (!Array.isArray(ids)) return; for (const id of ids) if (typeof id === "string" && (!store.entries.has(id) || !store.hasRead(id))) throw new DoctorSubmissionContractError(`${label} 须引用已准入/已读证据:${id}`); };
126
- if (read(output, "status") === "refused") {
127
- const missingEvidence = read(output, "missingEvidence");
128
- if (Array.isArray(missingEvidence)) for (const missing of missingEvidence) {
129
- const targets = read(missing, "targetKeys");
130
- if (Array.isArray(targets)) for (const target of targets) assertTarget(target);
131
- }
132
- return output;
133
- }
134
- const identity = read(output, "case");
135
- const issueNumber = read(identity, "issueNumber");
136
- const runsPath = read(identity, "runsPath");
137
- if ((issueNumber !== undefined && issueNumber !== patient.identity.issueNumber) || (runsPath !== undefined && runsPath !== patient.identity.runsPath)) throw new DoctorSubmissionContractError("太医署交卷 case 须等于已激活案身份");
138
- const findings = read(output, "findings");
139
- if (!Array.isArray(findings)) return output;
140
- for (const finding of findings) {
141
- const targetKey = read(finding, "targetKey");
142
- readCitations(read(finding, "evidenceIds"), "finding");
143
- const assetEvidence = read(finding, "assetEvidence");
144
- if (!isRecord(assetEvidence)) { assertTarget(targetKey); continue; }
145
- const assetTargetKey = read(assetEvidence, "targetKey");
146
- const assetTargetKind = read(assetEvidence, "targetKind");
147
- const assetEvidenceId = read(assetEvidence, "evidenceId");
148
- if (typeof assetTargetKey === "string" && assetTargetKey !== targetKey) throw new DoctorSubmissionContractError("类型化资产证据须确立 finding 的 targetKey");
149
- if (typeof assetTargetKind === "string" && assetTargetKind !== read(finding, "targetKind")) throw new DoctorSubmissionContractError("类型化资产证据须确立 finding 的 targetKind");
150
- if (typeof assetEvidenceId === "string") readCitations([assetEvidenceId], "asset evidence");
151
- const guardrails = read(finding, "guardrails");
152
- for (const key of ["reproducibleFailure", "owningSeamOrInvariant", "deletionOrSimplificationSuffices"]) readCitations(read(read(guardrails, key), "evidenceIds"), "guardrail");
153
- const bite = read(finding, "lastRealBite");
154
- const biteKind = read(bite, "kind");
155
- if (biteKind !== "actual" && biteKind !== "noRealBite") continue;
156
- if (read(bite, "targetKey") !== targetKey) throw new DoctorSubmissionContractError("lastRealBite 目标不匹配");
157
- if (biteKind === "actual") {
158
- const evidenceId = read(bite, "evidenceId");
159
- const entry = typeof evidenceId === "string" ? store.entries.get(evidenceId) : undefined;
160
- if (!entry || entry.kind !== "session" || !store.hasRead(entry.id)) throw new DoctorSubmissionContractError("actual bite 须引用已准入/已读的留存 session");
161
- } else {
162
- const eligible = patient.evidence.map((entry) => entry.id).sort();
163
- const ids = read(bite, "eligibleEvidenceIds");
164
- if (Array.isArray(ids)) {
165
- const claimed = ids.filter((id): id is string => typeof id === "string").sort();
166
- if (canonicalJson(claimed) !== canonicalJson(eligible)) throw new DoctorSubmissionContractError("noRealBite 须证明完整的单案合格证据全集");
167
- readCitations(eligible, "noRealBite");
168
- }
169
- }
170
- }
171
- return output;
144
+ /**
145
+ * #836: cross-check rejection deleted (2.6). Shape guidance only — code does not
146
+ * re-verify evidence citations, case identity, or bite completeness against the store.
147
+ * Judge/察院 read the original volume.
148
+ */
149
+ export function validateDoctorOutput(value: unknown, _patient: DoctorCase, _store: DoctorEvidenceStore): DoctorSubmission {
150
+ return validateDoctorSubmissionShape(value);
172
151
  }
@@ -23,7 +23,7 @@ function deriveSession(content: string, id: string): SessionDerivation {
23
23
  const message = record(row.message) ? row.message : undefined;
24
24
  if (message?.role === "assistant") { for (const part of Array.isArray(message.content) ? message.content : []) if (record(part) && part.type === "toolCall") calls++; if (typeof message.responseId === "string") { turns++; const usage = record(message.usage) ? message.usage : undefined; if (usage && typeof usage.output === "number") tokens += usage.output; } }
25
25
  if (message?.role === "toolResult" && message.isError !== true && typeof message.toolName === "string" && isTerminatingToolName(message.toolName) && record(message.details)) { let details; try { details = validateAcceptedDetails(message.toolName, message.details); } catch (error) { // Contract: README.md#Doctor — non-accepted terminating receipts are expected-negative evidence and are skipped; all other validation failures propagate with their cause.
26
- if (error instanceof AcceptedDetailsContractError) continue; throw error; } accepted = row; const facts = acceptedFacts(message.toolName, details); if (facts.commit && facts.commit !== observedCommit) { commits.push({ source: id, commit: facts.commit }); observedCommit = facts.commit; } statuses.length = 0; if (facts.status !== undefined) { statuses.push({ source: id, status: facts.status }); } else { statuses.push({ source: id, status: "terminating receipt has no receipt-level status" }); } }
26
+ if (error instanceof AcceptedDetailsContractError) continue; throw error; } accepted = row; const facts = acceptedFacts(message.toolName, details); if (facts.commit && facts.commit !== observedCommit) { commits.push({ source: id, commit: facts.commit }); observedCommit = facts.commit; } /* #836 B10.3: do not wipe earlier statuses or invent a code status sentence */ if (facts.status !== undefined) { statuses.push({ source: id, status: facts.status }); } }
27
27
  }
28
28
  const acceptedAt = accepted && timestamp(accepted); const final = acceptedAt ? accepted! : rows.at(-1); const endedAt = final && timestamp(final); const wall = startedAt && endedAt ? Date.parse(endedAt) - Date.parse(startedAt) : undefined;
29
29
  if (wall !== undefined && wall < 0) degradationReasons.push(`non-monotonic session timestamps in ${id}`);
@@ -1,7 +1,7 @@
1
1
  import type { RoleHost, HostContext, HostToolResult } from "./host-contracts.ts";
2
2
  import { disposeComplianceDecision } from "./audit-escalation.ts";
3
3
  import { ComplianceResponseRetentionError, type ComplianceDecision } from "./compliance-transport.ts";
4
- import { joinReadableGateItems } from "./readable-gate-item.ts";
4
+ import { GatekeeperDecisionError } from "./submission-errors.ts";
5
5
  import { DOCTOR_CANDIDATE_ENTRY_TYPE } from "./dossier-resolution.ts";
6
6
  import { DOCTOR_ACCEPTED_AUDIT_NO_RECEIPT_TEXT, DOCTOR_ACCEPTED_TEXT, DOCTOR_EVIDENCE_TOOL_NAME, DOCTOR_OUTPUT_TOOL_DESCRIPTION, DOCTOR_OUTPUT_TOOL_NAME, DoctorEvidenceStore, doctorEvidenceReadSchema, doctorSubmissionSchema, validateDoctorOutput, type DoctorCase } from "./doctor-contracts.ts";
7
7
 
@@ -36,7 +36,7 @@ export function createDoctorRoleRuntime(pi: RoleHost, dependencies: DoctorRoleDe
36
36
  let activation: { soul: string; patient: DoctorCase; store: DoctorEvidenceStore } | undefined; let registered = false; pi.registerFlag(DOCTOR_CASE_FLAG.name, DOCTOR_CASE_FLAG.definition);
37
37
  return { async activate() { const path = pi.getFlag(DOCTOR_CASE_FLAG.name); if (typeof path !== "string" || !path.trim()) throw new Error("Doctor requires --ak-doctor-case"); const soul = (await dependencies.loadSoul()).trim(); if (!soul) throw new Error("Doctor soul is empty"); const patient = await dependencies.loadCase(path); activation = { soul, patient, store: new DoctorEvidenceStore(patient) };
38
38
  if (!registered) { registered = true; pi.registerTool({ name: DOCTOR_EVIDENCE_TOOL_NAME, label: "太医署证据", description: "分页读取留存的 Pi session 字节。", parameters: doctorEvidenceReadSchema, async execute(_id: string, params: { evidenceId: string; offset?: number; limit?: number }) { if (!activation) throw new Error("太医署未激活"); const details = activation.store.read(params.evidenceId, params.offset, params.limit); return { content: [{ type: "text" as const, text: JSON.stringify(details) }], details }; } });
39
- pi.registerTool({ name: DOCTOR_OUTPUT_TOOL_NAME, label: "太医署输出", description: DOCTOR_OUTPUT_TOOL_DESCRIPTION, parameters: doctorSubmissionSchema, async execute(id: string, params: unknown, signal: AbortSignal | undefined, _update: unknown, ctx: HostContext): Promise<HostToolResult<unknown>> { if (!activation) throw new Error("太医署未激活"); const testimony = validateDoctorOutput(params, activation.patient, activation.store); try { appendCandidate(ctx, { version: 1, testimony, readRecord: activation.store.readRecord(), patientIdentity: activation.patient.identity }); } catch (error) { host.failInfrastructure(error, ctx, id); } let audit: ComplianceDecision; try { audit = await dependencies.auditCompliance(signal === undefined ? { context: ctx } : { context: ctx, signal }); } catch (error) { host.failInfrastructure(error, ctx, id); } const details = testimony.status === "completed" ? { ...testimony, cost: activation.patient.cost } : testimony; const acceptedDetails = details; return disposeComplianceDecision<HostToolResult<unknown>>(audit, { pass: (usage) => ({ content: [{ type: "text" as const, text: DOCTOR_ACCEPTED_TEXT }], details: acceptedDetails, terminate: true as const, ...(usage === undefined ? {} : { usage }) }), noReceipt: (auditNoReceipt, usageProjection) => ({ content: [{ type: "text" as const, text: DOCTOR_ACCEPTED_AUDIT_NO_RECEIPT_TEXT }], details: { ...acceptedDetails, auditNoReceipt }, terminate: true as const, ...usageProjection }), received: (auditReceived, usageProjection) => ({ content: [{ type: "text" as const, text: DOCTOR_ACCEPTED_TEXT }], details: { ...acceptedDetails, audit: auditReceived.reply }, terminate: true as const, ...usageProjection }), bounce: (violations) => { throw new Error(`太医署回执违 soul:${joinReadableGateItems(violations)}`); }, escalate: (result) => result }, acceptedDetails); } });
40
- pi.on("before_agent_start", (event) => { if (!activation) throw new Error("太医署未激活"); const catalog = { version: activation.patient.version, identity: activation.patient.identity, admittedMetrics: { provenance: "由留存 session 字节推导,封入受理回执。", cost: activation.patient.cost }, lawfulTargetKeys: ["case", ...activation.patient.cost.invocations.sources], evidence: activation.patient.evidence.map(({ id, kind, sha256, byteLength, contentLength }) => ({ id, kind, sha256, byteLength, contentLength })) }; return { systemPrompt: `${event.systemPrompt}\n\n<doctor_soul>\n${activation.soul}\n</doctor_soul>\n\n<doctor_case>\n${JSON.stringify(catalog)}\n</doctor_case>` }; }); }
39
+ pi.registerTool({ name: DOCTOR_OUTPUT_TOOL_NAME, label: "太医署输出", description: DOCTOR_OUTPUT_TOOL_DESCRIPTION, parameters: doctorSubmissionSchema, async execute(id: string, params: unknown, signal: AbortSignal | undefined, _update: unknown, ctx: HostContext): Promise<HostToolResult<unknown>> { if (!activation) throw new Error("太医署未激活"); const active = activation; const testimony = validateDoctorOutput(params, active.patient, active.store); try { appendCandidate(ctx, { version: 1, testimony, cost: active.patient.cost, readRecord: active.store.readRecord(), patientIdentity: active.patient.identity }); } catch (error) { host.failInfrastructure(error, ctx, id); } let audit: ComplianceDecision; try { audit = await dependencies.auditCompliance(signal === undefined ? { context: ctx } : { context: ctx, signal }); } catch (error) { host.failInfrastructure(error, ctx, id); } const acceptedDetails = testimony; return disposeComplianceDecision<HostToolResult<unknown>>(audit, { pass: (usage) => ({ content: [{ type: "text" as const, text: DOCTOR_ACCEPTED_TEXT }], details: acceptedDetails, terminate: true as const, ...(usage === undefined ? {} : { usage }) }), noReceipt: (auditNoReceipt, usageProjection) => { try { appendCandidate(ctx, { version: 1, testimony, cost: active.patient.cost, auditNoReceipt, readRecord: active.store.readRecord(), patientIdentity: active.patient.identity }); } catch (error) { host.failInfrastructure(error, ctx, id); } return { content: [{ type: "text" as const, text: DOCTOR_ACCEPTED_AUDIT_NO_RECEIPT_TEXT }], details: acceptedDetails, terminate: true as const, ...usageProjection }; }, received: () => { throw new Error("审刑院非三态应交 runComplianceAudit 重问说话者"); }, bounce: (violations) => { throw new GatekeeperDecisionError({ status: "bounce", officer: "auditor", receipt: violations }); }, escalate: (result) => result, transportFailure: (facts) => { host.failInfrastructure(Object.assign(new Error(facts.diagnostic), { name: "ComplianceTransportFailure", ...(facts.submissions === undefined && facts.terminal === undefined ? {} : { submission: facts.submissions ?? facts.terminal }) }), ctx, id); } }, acceptedDetails); } });
40
+ pi.on("before_agent_start", (event) => { if (!activation) throw new Error("太医署未激活"); const catalog = { version: activation.patient.version, identity: activation.patient.identity, admittedMetrics: { cost: activation.patient.cost }, lawfulTargetKeys: ["case", ...activation.patient.cost.invocations.sources], evidence: activation.patient.evidence.map(({ id, kind, sha256, byteLength, contentLength }) => ({ id, kind, sha256, byteLength, contentLength })) }; return { systemPrompt: `${event.systemPrompt}\n\n<doctor_soul>\n${activation.soul}\n</doctor_soul>\n\n<doctor_case>\n${JSON.stringify(catalog)}\n</doctor_case>` }; }); }
41
41
  const required = [DOCTOR_EVIDENCE_TOOL_NAME, DOCTOR_OUTPUT_TOOL_NAME]; const names = pi.getAllTools().map((tool) => tool.name); for (const name of required) if (names.filter((item) => item === name).length !== 1) throw new Error(`Doctor required tool collision or missing: ${name}`); pi.setActiveTools(required); const active = pi.getActiveTools?.() ?? required; if (active.length !== 2 || !required.every((name) => active.includes(name))) throw new Error("Doctor active tool narrowing failed"); } };
42
42
  }
@@ -16,6 +16,9 @@ import {
16
16
  runEngineDetourOnce,
17
17
  } from "./engine-detour.ts";
18
18
 
19
+ // #836 r16 class 3: argv required/minItems/element-minLength stay — execute()
20
+ // must obtain the first item as the executable and spawn it (below; #82-98).
21
+ // Root additionalProperties:false is deleted — execute() reads only `argv`.
19
22
  const engineDetourArgsSchema = Type.Object(
20
23
  {
21
24
  argv: Type.Array(Type.String({ minLength: 1 }), {
@@ -23,7 +26,7 @@ const engineDetourArgsSchema = Type.Object(
23
26
  description: "首项为 PATH 中的可执行文件,其余项为参数。",
24
27
  }),
25
28
  },
26
- { additionalProperties: false },
29
+ { additionalProperties: true },
27
30
  );
28
31
 
29
32
  type EngineDetourArgs = Static<typeof engineDetourArgsSchema>;
@@ -128,6 +128,7 @@ export async function driveExternalRoleTurnRounds(
128
128
  ): Promise<RoleTurnResult> {
129
129
  let prompt = promptWithPriorNativePaths(prepared.prompt, request);
130
130
  const abortSignal = mergeRoleTurnAbortSignals(prepared.abortSignal, request.signal);
131
+ let stderr = "";
131
132
 
132
133
  for (let attempt = 0; attempt < EXTERNAL_ROLE_TURN_ROUND_LIMIT; attempt += 1) {
133
134
  if (abortSignal?.aborted) return settleHostAborted(prepared, driver.currentSessionId());
@@ -139,14 +140,19 @@ export async function driveExternalRoleTurnRounds(
139
140
  if (isHostAbortedError(error)) return settleHostAborted(prepared, driver.currentSessionId());
140
141
  throw error;
141
142
  }
142
- if (round.status === "terminal") return round.result;
143
+ if (round.status === "terminal") {
144
+ const result = round.result;
145
+ const combined = `${stderr}${result.stderr}`;
146
+ return combined === result.stderr ? result : { ...result, stderr: combined };
147
+ }
148
+ if (round.stderr !== undefined && round.stderr.length > 0) stderr += round.stderr;
143
149
 
144
150
  const closure = await prepared.closeRound();
145
151
  if (closure.accepted) {
146
152
  await driver.afterAccepted?.();
147
- return { code: 0, stderr: "", timedOut: false };
153
+ return { code: 0, stderr, timedOut: false };
148
154
  }
149
- if ("failure" in closure) return asFailure(closure.failure, round.stderr ?? "");
155
+ if ("failure" in closure) return asFailure(closure.failure, stderr);
150
156
  prompt = closure.retry.message;
151
157
  driver.afterRetry?.();
152
158
  }
@@ -43,6 +43,7 @@ function bookDirectOfficerPointer(
43
43
  && result.status !== "bounce"
44
44
  && result.status !== "escalate"
45
45
  && result.status !== "needs_reask"
46
+ && result.status !== "transport_failure"
46
47
  ) {
47
48
  return;
48
49
  }
@@ -102,23 +103,17 @@ export async function requireGatekeeperPass(options: {
102
103
  }
103
104
  if (gatekeeper.status === "pass") return;
104
105
  if (gatekeeper.status === "needs_reask") {
105
- // Resume the speaker with plain-language re-ask — never bounce the parent (#753).
106
106
  reask = OFFICER_CONCLUSION_REASK;
107
107
  continue;
108
108
  }
109
109
  if (gatekeeper.status === "transport_failure") {
110
- const error = new Error(`交卷闸 transport_failure(${gatekeeper.stage}):${gatekeeper.reason}`) as Error & {
111
- stage: typeof gatekeeper.stage;
112
- reason: string;
113
- submission?: unknown;
114
- };
115
- error.stage = gatekeeper.stage;
116
- error.reason = gatekeeper.reason;
117
- if (gatekeeper.submission !== undefined) error.submission = gatekeeper.submission;
118
- options.hostActions.failInfrastructure(error, options.context, options.toolCallId);
110
+ const failure = Object.assign(new Error(gatekeeper.reason), {
111
+ name: "GatekeeperTransportFailure",
112
+ ...(gatekeeper.submission === undefined ? {} : { submission: gatekeeper.submission }),
113
+ });
114
+ options.hostActions.failInfrastructure(failure, options.context, options.toolCallId);
119
115
  }
120
- // bounce | escalate | no_receipt: raw receipt (or lifecycle fact) back to parent.
121
- // escalate is NOT thrown as parent next-step — parent reads the officer words (#753).
116
+ // bounce | escalate | no_receipt: parent stands and may resubmit. Not a run abort.
122
117
  options.hostActions.bindSubmissionNonPass(options.toolCallId, gatekeeper);
123
118
  throw new GatekeeperDecisionError(gatekeeper);
124
119
  }