@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,341 +1,39 @@
1
- import { extractReferencedAdrPaths } from "./adr-path-refs.ts";
2
- export { extractReferencedAdrPaths } from "./adr-path-refs.ts";
3
- import { sameReviewerPinnedTarget } from "./reviewer-git-snapshot.ts";
4
- import { branchNamesAtPinnedHead, immutableReviewerPin, type ReviewerPinnedGitReader, type ReviewerPinnedTarget, type ReviewerRange } from "./reviewer-pinned-git.ts";
5
- export { branchNamesAtPinnedHead, createReviewerPinnedGitReader, immutableReviewerPin, type ReviewerPinnedGitReader, type ReviewerPinnedTarget, type ReviewerRange } from "./reviewer-pinned-git.ts";
6
- import { isReviewerPromptText, sameReviewerPromptText, type ReviewerPromptText } from "./reviewer-prompt-identity.ts";
7
- import { sha256Hex } from "./sha256.ts";
8
- import {
9
- constructReviewerDispatch,
10
- type ConstructedReviewerDispatch,
11
- type ReviewerSpecAuthorityDiscovery,
12
- type ReviewerSpecFetchedMaterial,
13
- type ReviewerTicketNumberCandidate,
14
- type ReviewerTicketNumberSource,
15
- } from "./reviewer-construction.ts";
16
- export {
17
- type ReviewerSpecAuthorityDiscovery,
18
- type ReviewerSpecDisposition,
19
- type ReviewerSpecFetchedMaterial,
20
- type ReviewerTicketNumberCandidate,
21
- type ReviewerTicketNumberSource,
22
- } from "./reviewer-construction.ts";
23
- import { ReviewerCorrectablePreflightError } from "./reviewer-preflight-error.ts";
24
- export { sha256Hex } from "./sha256.ts";
25
- export { isReviewerPromptText as isReviewerPromptIdentity, sameReviewerPromptText as sameReviewerPromptIdentity, type ReviewerPromptText as ReviewerPromptIdentity } from "./reviewer-prompt-identity.ts";
26
-
27
- const GENERIC_FEATURE_TOKENS = new Set(["", "head", "main", "master", "trunk", "develop", "development"]);
28
- /** Conventional branch shells that must not hide the feature token (feat/login → login). */
29
- const BRANCH_SHELL_PREFIX = /^(?:feat|feature|fix|bugfix|hotfix|chore|docs|refactor)-/;
30
- /** Branch token ticket capture: (fix|feat|docs|audit|test)/issue-(\d+)- (#343). */
31
- const BRANCH_ISSUE_TOKEN = /(?:^|\/)((?:fix|feat|docs|audit|test)\/issue-(\d+)-)/;
32
-
33
- /** First #N in a commit subject (positive integer). */
34
- const COMMIT_TICKET_TOKEN = /#([1-9]\d*)/;
35
-
36
- function normalizeFeatureToken(value: string): string {
37
- return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
38
- }
39
-
40
- /** Expand one branch/ref name into matchable tokens, stripping conventional shells. */
41
- function expandFeatureTokens(raw: string): readonly string[] {
42
- const normalized = normalizeFeatureToken(raw);
43
- if (normalized.length === 0) return Object.freeze([]);
44
- const tokens = new Set<string>([normalized]);
45
- const stripped = normalized.replace(BRANCH_SHELL_PREFIX, "");
46
- if (stripped.length > 0 && stripped !== normalized) tokens.add(stripped);
47
- return Object.freeze([...tokens]);
48
- }
49
-
50
1
  /**
51
- * Shared capture/number → positive-integer → frozen candidate conversion.
52
- * Single true source for branch/commit (and typed) ticket candidate materialization.
2
+ * #836 删 8: no code-compiled axis dispatch.
3
+ * Parent seat invokes packaged code-review skill; this module does not construct or run children.
53
4
  */
54
- function ticketCandidateFromRaw(
55
- source: ReviewerTicketNumberSource,
56
- raw: unknown,
57
- ): ReviewerTicketNumberCandidate | undefined {
58
- const n = typeof raw === "number" ? raw : typeof raw === "string" ? Number(raw) : Number.NaN;
59
- if (!Number.isInteger(n) || n < 1) return undefined;
60
- return Object.freeze({ source, ticketNumber: n });
61
- }
62
-
63
- /**
64
- * Resolve ticket number with unique priority (#343):
65
- * typed ticketNumber → branch token → newest commit message first #N.
66
- * High-priority hit is adopted; lower sources that also yield a number are abandoned candidates.
67
- */
68
- export function resolveReviewerTicketNumber(input: {
69
- ticketNumber?: number;
70
- branchNames: readonly string[];
71
- commitMessagesNewestFirst: readonly string[];
72
- }): Readonly<{ adopted: ReviewerTicketNumberCandidate; abandoned: readonly ReviewerTicketNumberCandidate[] }> | undefined {
73
- const typed = ticketCandidateFromRaw("typed-ticket-number", input.ticketNumber);
74
-
75
- let branch: ReviewerTicketNumberCandidate | undefined;
76
- for (const name of input.branchNames) {
77
- const match = BRANCH_ISSUE_TOKEN.exec(name);
78
- if (match) {
79
- branch = ticketCandidateFromRaw("branch-token", match[2]);
80
- if (branch !== undefined) break;
81
- }
82
- }
83
-
84
- let commit: ReviewerTicketNumberCandidate | undefined;
85
- const newest = input.commitMessagesNewestFirst[0];
86
- if (newest !== undefined) {
87
- const match = COMMIT_TICKET_TOKEN.exec(newest);
88
- if (match) {
89
- commit = ticketCandidateFromRaw("commit-message", match[1]);
90
- }
91
- }
92
-
93
- if (typed !== undefined) {
94
- const abandoned = [branch, commit].filter((c): c is ReviewerTicketNumberCandidate => c !== undefined);
95
- return Object.freeze({ adopted: typed, abandoned: Object.freeze(abandoned) });
96
- }
97
- if (branch !== undefined) {
98
- const abandoned = commit === undefined ? Object.freeze([]) : Object.freeze([commit]);
99
- return Object.freeze({ adopted: branch, abandoned });
100
- }
101
- if (commit !== undefined) {
102
- return Object.freeze({ adopted: commit, abandoned: Object.freeze([]) });
103
- }
104
- return undefined;
105
- }
5
+ export {
6
+ branchNamesAtPinnedHead,
7
+ createReviewerPinnedGitReader,
8
+ immutableReviewerPin,
9
+ type ReviewerPinnedGitReader,
10
+ type ReviewerPinnedTarget,
11
+ type ReviewerRange,
12
+ } from "./reviewer-pinned-git.ts";
13
+ export { extractReferencedAdrPaths } from "./adr-path-refs.ts";
14
+ export { sha256Hex } from "./sha256.ts";
15
+ export {
16
+ isReviewerPromptText as isReviewerPromptIdentity,
17
+ sameReviewerPromptText as sameReviewerPromptIdentity,
18
+ type ReviewerPromptText as ReviewerPromptIdentity,
19
+ } from "./reviewer-prompt-identity.ts";
20
+
21
+ export type ReviewerIssueFetchResult = Readonly<{
22
+ number: number;
23
+ title?: string;
24
+ body?: string;
25
+ }>;
106
26
 
107
- export type ReviewerIssueFetchResult = Readonly<{ body: string }>;
108
- /**
109
- * Soft issue fetch capability: undefined means confirmed tracker unreachable / issue not found.
110
- * Unrecognized runner failures and parse/implementation errors propagate with true cause (not washed into degrade).
111
- * Optional signal rides the shared GhApiRunner cancellation chain; role modules never own gh lifecycle.
112
- */
113
27
  export type ReviewerIssueFetcher = (input: {
114
- owner: string;
115
28
  repo: string;
116
29
  ticketNumber: number;
117
30
  signal?: AbortSignal;
118
31
  }) => Promise<ReviewerIssueFetchResult | undefined>;
119
32
 
120
- /** Optional AbortSignal carried on the dispatch invocation bag (same shape runDispatch already reads). */
121
- function optionalInvocationSignal(invocation: unknown): AbortSignal | undefined {
122
- if (typeof invocation !== "object" || invocation === null) return undefined;
123
- const signal = (invocation as { signal?: unknown }).signal;
124
- return signal instanceof AbortSignal ? signal : undefined;
125
- }
126
-
127
- /**
128
- * Unique production owner of code-review Skill step 2 Spec discovery (#343).
129
- * Primary: self-fetch latest issue by ticket number (typed → branch token → commit #N).
130
- * Degradation (unique order): self-fetch fail → supplied authorityRefs → local path match → missing.
131
- * Prompt/admitted-request prose is never Spec material.
132
- * Only confirmed absence yields missing; non-absence Git/I-O failures keep true cause for preflight.
133
- * Construction builds Standards/Spec solely from this product.
134
- */
135
- export async function discoverReviewerSpecAuthority(input: {
136
- authorityRefs: readonly string[];
137
- reader: ReviewerPinnedGitReader;
138
- /** Typed #176 ticketNumber from admitted invocation, when present. */
139
- ticketNumber?: number;
140
- /** base..HEAD commit scan base (resolved oid). Required for commit-message ticket source. */
141
- baseCommit?: string;
142
- /**
143
- * Injected issue-fetch capability from the shared execution seam.
144
- * Absent capability = self-fetch unavailable (degrade); role module never owns gh lifecycle.
145
- */
146
- fetchIssue?: ReviewerIssueFetcher;
147
- /** Optional cancellation signal for the soft-fetch gh subprocess (invocation AbortSignal). */
148
- signal?: AbortSignal;
149
- }): Promise<ReviewerSpecAuthorityDiscovery> {
150
- // Path-matching tokens (heads/tags/remotes) stay separate from branch-ticket provenance.
151
- const featureTokens = await input.reader.featureTokens();
152
- const commitMessages =
153
- input.baseCommit === undefined
154
- ? Object.freeze([])
155
- : await input.reader.commitMessagesNewestFirst(input.baseCommit);
156
- const ticketResolution = resolveReviewerTicketNumber({
157
- ...(input.ticketNumber === undefined ? {} : { ticketNumber: input.ticketNumber }),
158
- // Branch ticket source: real heads/remotes at targetHead only — never tags via featureTokens.
159
- branchNames: branchNamesAtPinnedHead(input.reader.pin),
160
- commitMessagesNewestFirst: commitMessages,
161
- });
162
-
163
- // ① Primary: self-fetch latest issue + referenced docs/adr via injected capability only.
164
- if (ticketResolution !== undefined) {
165
- const origin = await input.reader.originRepository();
166
- if (origin !== undefined && input.fetchIssue !== undefined) {
167
- const issue = await input.fetchIssue({
168
- owner: origin.owner,
169
- repo: origin.repo,
170
- ticketNumber: ticketResolution.adopted.ticketNumber,
171
- ...(input.signal === undefined ? {} : { signal: input.signal }),
172
- });
173
- if (issue !== undefined) {
174
- const adrPaths = extractReferencedAdrPaths(issue.body);
175
- const adrs = [];
176
- for (const path of adrPaths) {
177
- const body = await input.reader.readPinnedText(path);
178
- if (body === undefined) {
179
- adrs.push(Object.freeze({ path, status: "missing" as const }));
180
- } else {
181
- adrs.push(Object.freeze({ path, status: "present" as const, body }));
182
- }
183
- }
184
- const issueRef = `https://github.com/${origin.owner}/${origin.repo}/issues/${ticketResolution.adopted.ticketNumber}`;
185
- const presentAdrRefs = adrs
186
- .filter((a) => a.status === "present")
187
- .map((a) => a.path);
188
- const fetched: ReviewerSpecFetchedMaterial = Object.freeze({
189
- issueRef,
190
- owner: origin.owner,
191
- repo: origin.repo,
192
- ticketNumber: ticketResolution.adopted.ticketNumber,
193
- adopted: ticketResolution.adopted,
194
- abandoned: ticketResolution.abandoned,
195
- issueBody: issue.body,
196
- adrs: Object.freeze(adrs),
197
- });
198
- return Object.freeze({
199
- status: "available" as const,
200
- refs: Object.freeze([issueRef, ...presentAdrRefs]),
201
- fetched,
202
- });
203
- }
204
- }
205
- }
206
-
207
- // ② Degrade: explicit --authority-ref (human intent before local heuristics).
208
- if (input.authorityRefs.length > 0) {
209
- return Object.freeze({
210
- status: "available" as const,
211
- refs: Object.freeze([...input.authorityRefs]),
212
- });
213
- }
214
-
215
- // ③ Degrade: matching pinned-target docs/specs/.scratch paths via branch feature tokens.
216
- const tokens = [
217
- ...new Set(
218
- featureTokens
219
- .flatMap((raw) => expandFeatureTokens(raw))
220
- .filter((token) => token.length >= 3 && !GENERIC_FEATURE_TOKENS.has(token)),
221
- ),
222
- ];
223
- if (tokens.length === 0) {
224
- return Object.freeze({ status: "missing" as const });
225
- }
226
- // Pinned target tree only — Spec child cannot read live-worktree or gitignored paths.
227
- const candidates = await input.reader.listSpecCandidatePaths();
228
- const matched = candidates.filter((relativePath) => {
229
- const normalizedPath = normalizeFeatureToken(relativePath);
230
- return tokens.some((token) => normalizedPath.includes(token));
231
- });
232
- if (matched.length === 0) {
233
- return Object.freeze({ status: "missing" as const });
234
- }
235
- return Object.freeze({
236
- status: "available" as const,
237
- refs: Object.freeze(matched),
238
- });
239
- }
240
-
241
- export type AcceptedReviewerLeg = ConstructedReviewerDispatch["legs"][number];
242
- export type AcceptedReviewerDispatch = ConstructedReviewerDispatch;
243
- export type AcceptedReviewerExecution = Readonly<{
244
- identity: string;
245
- recipe: "reviewer-common-bundle-v1";
246
- targetSnapshot: ReviewerPinnedTarget;
247
- legs: readonly AcceptedReviewerLeg[];
248
- }>;
249
- export const REVIEWER_PREFLIGHT_VIOLATIONS = ["base-invalid", "range-invalid", "prompt-identity-invalid", "target-drift"] as const;
33
+ export const REVIEWER_PREFLIGHT_VIOLATIONS = [
34
+ "base-invalid",
35
+ "range-invalid",
36
+ "prompt-identity-invalid",
37
+ "target-drift",
38
+ ] as const;
250
39
  export type ReviewerPreflightViolation = (typeof REVIEWER_PREFLIGHT_VIOLATIONS)[number];
251
- export type ReviewerDispatchResult =
252
- | Readonly<{ status: "rejected"; identity: string; violations: readonly ReviewerPreflightViolation[]; diagnostic: string }>
253
- | Readonly<{ status: "accepted"; dispatch: AcceptedReviewerDispatch; results: unknown }>;
254
- export type ReviewerDecisionEvidence =
255
- | Readonly<{ disposition: "rejected"; identity: string; violations: readonly ReviewerPreflightViolation[]; started: false }>
256
- | Readonly<{ disposition: "accepted"; identity: string; dispatch: AcceptedReviewerDispatch }>;
257
- type DispatcherDependencies = Readonly<{
258
- canonicalSkill: string;
259
- reader: ReviewerPinnedGitReader;
260
- reviewScopeKeys?: readonly string[];
261
- /** Durable authority references preserved unchanged into Spec-leg construction only. */
262
- authorityRefs?: readonly string[];
263
- /** Typed #176 ticketNumber from admitted invocation (Spec self-fetch primary). */
264
- ticketNumber?: number;
265
- /** Injected issue-fetch capability from shared execution seam (production/tests). */
266
- fetchIssue?: ReviewerIssueFetcher;
267
- run(execution: AcceptedReviewerExecution, invocation: unknown): Promise<unknown>;
268
- decisionEvidence?(decision: ReviewerDecisionEvidence): void;
269
- }>;
270
- export class ReviewerPreflightError extends Error {
271
- constructor(readonly code: ReviewerPreflightViolation, readonly diagnostic = `${code} constraint failed`) {
272
- super(`${code}: ${diagnostic}`);
273
- }
274
- }
275
- export function toReviewerExecution(dispatch: AcceptedReviewerDispatch): AcceptedReviewerExecution {
276
- return Object.freeze({
277
- identity: dispatch.identity,
278
- recipe: dispatch.recipe,
279
- targetSnapshot: immutableReviewerPin(dispatch.targetSnapshot),
280
- legs: Object.freeze(dispatch.legs.map((l) => Object.freeze({ axis: l.axis, prompt: l.prompt }))),
281
- });
282
- }
283
- const preflight = (error: unknown): ReviewerPreflightError | undefined => {
284
- if (error instanceof ReviewerPreflightError) return error;
285
- if (error instanceof ReviewerCorrectablePreflightError) {
286
- return new ReviewerPreflightError(error.code as ReviewerPreflightViolation, error.diagnostic);
287
- }
288
- return undefined;
289
- };
290
- export function createReviewerDispatcher(d: DispatcherDependencies) {
291
- const target = immutableReviewerPin(d.reader.pin);
292
- let started = false;
293
- return Object.freeze({
294
- async dispatch(baseRevision: string, invocation?: unknown): Promise<ReviewerDispatchResult> {
295
- if (started) throw new Error("Reviewer fixed dispatch can start exactly once");
296
- const identity = sha256Hex(JSON.stringify({
297
- baseRevision,
298
- target: target.targetHead,
299
- canonicalSkill: sha256Hex(d.canonicalSkill),
300
- }));
301
- let dispatch: AcceptedReviewerDispatch;
302
- try {
303
- const base = await d.reader.resolve(baseRevision);
304
- const range = await d.reader.range(base);
305
- const authorityRefs = Object.freeze([...(d.authorityRefs ?? [])]);
306
- const signal = optionalInvocationSignal(invocation);
307
- const specAuthority = await discoverReviewerSpecAuthority({
308
- authorityRefs,
309
- reader: d.reader,
310
- baseCommit: base,
311
- ...(d.ticketNumber === undefined ? {} : { ticketNumber: d.ticketNumber }),
312
- ...(d.fetchIssue === undefined ? {} : { fetchIssue: d.fetchIssue }),
313
- ...(signal === undefined ? {} : { signal }),
314
- });
315
- dispatch = constructReviewerDispatch({
316
- identity,
317
- canonicalSkill: d.canonicalSkill,
318
- target,
319
- range,
320
- ...(d.reviewScopeKeys === undefined ? {} : { reviewScopeKeys: d.reviewScopeKeys }),
321
- specAuthority,
322
- });
323
- if (!sameReviewerPinnedTarget(await d.reader.snapshot(), target)) {
324
- throw new ReviewerPreflightError("target-drift", "pinned target snapshot changed before child execution");
325
- }
326
- } catch (error) {
327
- const p = preflight(error);
328
- if (!p) throw error;
329
- d.decisionEvidence?.(Object.freeze({ disposition: "rejected", identity, violations: Object.freeze([p.code]), started: false }));
330
- return Object.freeze({ status: "rejected", identity, violations: Object.freeze([p.code]), diagnostic: p.diagnostic });
331
- }
332
- started = true;
333
- d.decisionEvidence?.(Object.freeze({ disposition: "accepted", identity, dispatch }));
334
- const results = await d.run(toReviewerExecution(dispatch), invocation);
335
- return Object.freeze({ status: "accepted", dispatch, results });
336
- },
337
- });
338
- }
339
-
340
- export type { ReviewerPromptText };
341
- export { isReviewerPromptText, sameReviewerPromptText };
@@ -5,12 +5,8 @@ import { withInfrastructureFailureDeclaration } from "./package-contracts/termin
5
5
 
6
6
  import type { AnyCanonicalSkillBinding, CanonicalSkillBinding } from "./canonical-skill-binding.ts";
7
7
  export type { CanonicalSkillBinding };
8
- import { type ReviewerSpecDisposition } from "./reviewer-construction.ts";
9
- import { createReviewerDispatcher, type AcceptedReviewerDispatch, type AcceptedReviewerExecution, type ReviewerIssueFetcher, type ReviewerPinnedGitReader } from "./reviewer-dispatch.ts";
10
- import { ReviewerDispatchExecutionError, type ReviewerDispatchRunResult } from "./reviewer-agent.ts";
11
- import { createReviewerExecutionLedger, projectAcceptedDispatch, projectReviewerDispatchOutcome, type ReviewerExecutionRecord } from "./reviewer-execution-ledger.ts";
12
- import { assembleRuntimeReviewerReceipt } from "./reviewer-settlement.ts";
13
- import { REVIEWER_ACCEPTED_TEXT, REVIEWER_OUTPUT_TOOL_NAME, validateReviewerIntent, type ReviewerIntent } from "./package-contracts/reviewer-output.ts";
8
+ import { type ReviewerPinnedGitReader } from "./reviewer-pinned-git.ts";
9
+ import { REVIEWER_ACCEPTED_TEXT, REVIEWER_OUTPUT_TOOL_NAME, type ReviewerIntent } from "./package-contracts/reviewer-output.ts";
14
10
 
15
11
  export { REVIEWER_OUTPUT_TOOL_NAME };
16
12
  export type { ReviewerIntent };
@@ -29,14 +25,21 @@ const reviewerAmendmentsSchema = Type.Object({
29
25
  standards: Type.Optional(Type.String({ description: "相对 Standards 子报告的增量:增 finding、撤回或事实更正" })),
30
26
  spec: Type.Optional(Type.String({ description: "相对 Spec 子报告的增量:增 finding、撤回或事实更正" })),
31
27
  }, { additionalProperties: true, description: "相对子报告的可选轴增量;非替代报告。无增量的轴可省略。" });
28
+ // #836 r16 class 1: diagnostic is LLM/human-read narrative content — no code
29
+ // branches on its length (src/reviewer-role.ts consumer: reviewer content is
30
+ // returned as submitted, ADR 0057).
31
+ // #836 (ADR 0003 Amendment): status kept open like countersignStatus
32
+ // (src/countersign-role.ts) — one shared description across both variants
33
+ // so openToolObjectFromUnion's identical-declaration collapse drops none of it.
34
+ const REVIEWER_STATUS_DESCRIPTION = "completed | refused — 形状指引,非 schema 闸" as const;
32
35
  const reviewerOutputVariants = Type.Union([
33
36
  Type.Object({
34
- status: Type.Literal("completed", { description: "completed — 形状指引,非 schema 闸" }),
37
+ status: Type.Unknown({ description: REVIEWER_STATUS_DESCRIPTION }),
35
38
  amendments: Type.Optional(reviewerAmendmentsSchema),
36
39
  }, { additionalProperties: false }),
37
40
  Type.Object({
38
- status: Type.Literal("refused", { description: "refused — 形状指引,非 schema 闸" }),
39
- diagnostic: Type.String({ minLength: 1, description: "拒绝诊断说明" }),
41
+ status: Type.Unknown({ description: REVIEWER_STATUS_DESCRIPTION }),
42
+ diagnostic: Type.String({ description: "拒绝诊断说明" }),
40
43
  amendments: Type.Optional(reviewerAmendmentsSchema),
41
44
  }, { additionalProperties: false }),
42
45
  ]);
@@ -47,22 +50,15 @@ export type ReviewerRoleDependencies = {
47
50
  loadSoul(): Promise<string>;
48
51
  loadCanonicalSkillBinding(name: "code-review"): Promise<AnyCanonicalSkillBinding>;
49
52
  createPinnedGitReader(): Promise<ReviewerPinnedGitReader>;
50
- /** Injected issue-fetch capability; shared seam owns gh lifecycle. */
51
- fetchIssue?: ReviewerIssueFetcher;
52
- runDispatch(execution: AcceptedReviewerExecution, options: { context: HostContext; signal?: AbortSignal }): Promise<ReviewerDispatchRunResult>;
53
- shutdownAgent?(): Promise<void>;
54
53
  };
55
54
  export type ReviewerRoleHostActions = { failInfrastructure(error: unknown, ctx: HostContext, toolCallId?: string): never };
56
55
 
57
56
 
58
57
  export type ReviewerActivation = Readonly<{
59
- dispatcher: ReturnType<typeof createReviewerDispatcher>;
60
58
  fixedBaseRevision: string;
61
59
  soul: string;
62
60
  /** Frozen code-review binding — envelope owns expansion capture against this data. */
63
61
  skillBinding: CanonicalSkillBinding<"code-review">;
64
- /** Honest Spec disposition after accepted dispatch, for envelope parent prompt assembly. */
65
- getSpecDisposition(): ReviewerSpecDisposition | undefined;
66
62
  }>;
67
63
 
68
64
  /**
@@ -73,106 +69,43 @@ export type ReviewerActivation = Readonly<{
73
69
  export function createReviewerRoleRuntime(
74
70
  pi: RoleHost,
75
71
  dependencies: ReviewerRoleDependencies,
76
- hostActions: ReviewerRoleHostActions,
72
+ _hostActions: ReviewerRoleHostActions,
77
73
  ): {
78
74
  activate(ctx: HostContext | undefined, admitted: ReviewerAdmittedInputs): Promise<ReviewerActivation>;
79
75
  } {
80
76
  let soul: string | undefined;
81
77
  let binding: CanonicalSkillBinding<"code-review"> | undefined;
82
- let reader: ReviewerPinnedGitReader | undefined;
83
- let dispatcher: ReturnType<typeof createReviewerDispatcher> | undefined;
84
78
  let registered = false;
85
79
  let fixedBaseRevision: string | undefined;
86
- let acceptedDispatch: AcceptedReviewerDispatch | undefined;
87
- const ledger = createReviewerExecutionLedger();
88
80
 
89
81
  return {
90
82
  async activate(_ctx, admitted) {
91
83
  soul = (await dependencies.loadSoul()).trim();
92
84
  if (!soul) throw new Error("Reviewer soul is empty");
93
- // Behavior layer receives frozen admitted inputs only — no pi.getFlag.
94
85
  fixedBaseRevision = admitted.baseRevision;
95
- const reviewScopeKeys = admitted.reviewScopeKeys;
96
- const authorityRefs = admitted.authorityRefs;
97
- const ticketNumber = admitted.ticketNumber;
98
86
  const loaded = await dependencies.loadCanonicalSkillBinding("code-review");
99
87
  if (loaded.name !== "code-review") throw new Error("Canonical Skill binding loader returned tdd for code-review");
100
88
  binding = loaded;
101
- reader = await dependencies.createPinnedGitReader();
102
-
103
- acceptedDispatch = undefined;
104
- const executeAndProjectDispatch = async (execution: AcceptedReviewerExecution, invocation: unknown): Promise<ReviewerDispatchRunResult> => {
105
- const dispatch = acceptedDispatch;
106
- if (dispatch === undefined || dispatch.identity !== execution.identity) throw new Error("Reviewer execution lacks accepted construction evidence");
107
- const { context, signal } = invocation as { context: HostContext; signal?: AbortSignal };
108
- ledger.append({ source: "reviewer-agent", type: "dispatch-started", dispatchIdentity: execution.identity, cardinality: execution.legs.length as 1 | 2 });
109
- try {
110
- const result = await dependencies.runDispatch(execution, { context, ...(signal === undefined ? {} : { signal }) });
111
- projectReviewerDispatchOutcome(ledger, dispatch, result);
112
- return result;
113
- } catch (error) {
114
- if (error instanceof ReviewerDispatchExecutionError) {
115
- try { projectReviewerDispatchOutcome(ledger, dispatch, error.outcome); }
116
- catch (mismatch) { throw ledger.recordInfrastructureFailure(mismatch); }
117
- throw error;
118
- }
119
- throw ledger.recordInfrastructureFailure(error);
120
- }
121
- };
122
- dispatcher = createReviewerDispatcher({
123
- canonicalSkill: binding.snapshot.raw,
124
- reader,
125
- ...(reviewScopeKeys === undefined ? {} : { reviewScopeKeys }),
126
- ...(authorityRefs === undefined ? {} : { authorityRefs }),
127
- ...(ticketNumber === undefined ? {} : { ticketNumber }),
128
- ...(dependencies.fetchIssue === undefined ? {} : { fetchIssue: dependencies.fetchIssue }),
129
- decisionEvidence(decision) {
130
- try {
131
- if (decision.disposition === "accepted") {
132
- ledger.append(projectAcceptedDispatch(decision.dispatch));
133
- acceptedDispatch = decision.dispatch;
134
- } else ledger.append({ source: "reviewer-dispatch", type: "rejected", identity: decision.identity, violations: decision.violations, started: false });
135
- } catch (error) {
136
- throw ledger.recordInfrastructureFailure(error);
137
- }
138
- },
139
- run: executeAndProjectDispatch,
140
- });
141
89
 
142
90
  if (!registered) {
143
91
  registered = true;
144
- pi.registerTool({ name: REVIEWER_OUTPUT_TOOL_NAME, label: "御史台输出", description: "Standards/Spec 评审腿由 runtime 以取证子会话代跑,本席收腿报告后交薄回执。", promptSnippet: "提交御史台终局回执", parameters: reviewerOutputSchema,
145
- async execute(id: string, parameters: unknown, _signal: AbortSignal | undefined, _update: unknown, toolCtx: HostContext): Promise<HostToolResult<unknown>> {
92
+ pi.registerTool({ name: REVIEWER_OUTPUT_TOOL_NAME, label: "御史台输出", description: "提交御史台终局回执。本席自调 code-review skill。", promptSnippet: "提交御史台终局回执", parameters: reviewerOutputSchema,
93
+ async execute(_id: string, parameters: unknown): Promise<HostToolResult<unknown>> {
146
94
  if (!soul || !binding) throw new Error("御史台输入未装载");
147
- const output = validateReviewerIntent(parameters);
148
- let record: ReviewerExecutionRecord;
149
- try { record = ledger.recordForAudit(output.status); } catch (error) { if ((error as any)?.fatalReviewerInfrastructure) hostActions.failInfrastructure(error, toolCtx, id); throw error; }
150
- const candidate = assembleRuntimeReviewerReceipt({
151
- intent: output,
152
- record,
153
- canonicalSkillText: binding.snapshot.raw,
154
- });
155
- try { await dependencies.shutdownAgent?.(); } catch (error) { hostActions.failInfrastructure(ledger.recordInfrastructureFailure(error), toolCtx, id); }
156
95
  return {
157
96
  content: [{ type: "text" as const, text: REVIEWER_ACCEPTED_TEXT }],
158
- details: candidate,
97
+ details: parameters,
159
98
  terminate: true as const,
160
99
  };
161
100
  } });
162
- // Skill invocation transform + agent_start expansion/prompt lifecycle: shared envelope (ADR 0018).
163
- pi.on("session_shutdown", async () => { try { await dependencies.shutdownAgent?.(); } catch (error) { throw ledger.recordInfrastructureFailure(error); } });
164
101
  }
165
102
  const activatedSoul = soul;
166
103
  const activatedBase = fixedBaseRevision;
167
104
  const activatedBinding = binding;
168
105
  return Object.freeze({
169
- dispatcher,
170
106
  fixedBaseRevision: activatedBase,
171
107
  soul: activatedSoul,
172
108
  skillBinding: activatedBinding,
173
- getSpecDisposition() {
174
- return acceptedDispatch?.specDisposition;
175
- },
176
109
  });
177
110
  },
178
111
  };
@@ -26,7 +26,6 @@ import type { PreparedRoleTurn } from "./prepared-role-turn.ts";
26
26
  import { projectActivationFlags } from "./role-activation-flags.ts";
27
27
  import {
28
28
  isCorrectableExecuteError,
29
- mechanicalSubmissionRejectionResumeMessage,
30
29
  projectCorrectableExecuteRejection,
31
30
  } from "./submission-correctable-error.ts";
32
31
  import {
@@ -58,7 +57,7 @@ export function buildSkillExpansion(
58
57
  return Object.freeze({
59
58
  name,
60
59
  location: method.path,
61
- content: `References are relative to ${dirname(method.path)}.\n\n${method.body}`,
60
+ content: method.body,
62
61
  // Non-pi typed chain keeps original task bytes (ticket #822 r3); no consumer trim.
63
62
  userMessage: prompt,
64
63
  });
@@ -183,9 +182,8 @@ export async function prepareRoleEnvelope(options: {
183
182
  },
184
183
  },
185
184
  abort() {
186
- // Lawful abort (non-sole rejection / seal / audit-escalation in submission-ledger)
187
- // must not poison ACP retry prompts (#593 r1). hostAbort is armed only by typed
188
- // infra: rememberInfrastructureFailure and non-correctable MCP catch.
185
+ // #836: hostAbort is armed only by typed infra (rememberInfrastructureFailure
186
+ // and non-correctable MCP catch). Submission does not abort the turn.
189
187
  },
190
188
  };
191
189
  const bookCustomMessage = (customType: string, message: { content?: string; details?: unknown }): void => {
@@ -207,13 +205,8 @@ export async function prepareRoleEnvelope(options: {
207
205
  };
208
206
 
209
207
  const host: RoleHost = {
210
- deliverSubmissionRejection(value) {
211
- // Mechanical round rejection has no officer receipt; shared resume text is the fact (#813).
212
- rejection = {
213
- code: value.code,
214
- toolCallIds: value.toolCallIds,
215
- message: mechanicalSubmissionRejectionResumeMessage(value.code),
216
- };
208
+ deliverSubmissionRejection(_value) {
209
+ // #836 删 1/A4.5: do not arm closeRound retry with「终局交卷并非本轮唯一工具调用」.
217
210
  },
218
211
  capabilities: {
219
212
  skillExpansion(prompt): HostSkillExpansionEvidence | undefined {
@@ -591,10 +584,7 @@ export async function prepareRoleEnvelope(options: {
591
584
  calls.length = 0;
592
585
  await emit("turn_end", { turnIndex: 0, calls: roundCalls });
593
586
  }
594
- // Infrastructure failure outranks accepted closure / correctable retry: the
595
- // declaration already aborted hostAbort; "already declared" is not success (#593).
596
- // Lawful seal / non-sole rejection still call context.abort() (ledger), but that
597
- // path does not arm hostAbort — only infrastructureRoundFailure is terminal here.
587
+ // Infrastructure failure outranks accepted closure / correctable retry (#593).
598
588
  if (infrastructureRoundFailure !== undefined) {
599
589
  return { accepted: false as const, failure: infrastructureRoundFailure };
600
590
  }
@@ -617,11 +607,10 @@ export async function prepareRoleEnvelope(options: {
617
607
  rejection = undefined;
618
608
  return { accepted: false as const, retry };
619
609
  }
620
- const failure: RoleTurnKnownFailure = {
621
- cause: "output",
622
- identity: { name: "MissingSubmission", code: "round-ended-without-submission" },
623
- };
624
- return { accepted: false as const, failure };
610
+ // #836: host ended without a recorded submission is not a failure.
611
+ // Settlement presents ledger contents; empty ledger → no_receipt.
612
+ await emit("agent_settled", {});
613
+ return { accepted: true as const };
625
614
  };
626
615
 
627
616
  // Shared envelope activation. systemPrompt must be ready before session/new
@@ -652,9 +641,12 @@ export async function prepareRoleEnvelope(options: {
652
641
  systemPrompt: methodPrompt,
653
642
  systemPromptOptions: {},
654
643
  });
655
- const systemPromptBody = [...promptResults].reverse().find((value): value is { systemPrompt: string } =>
656
- typeof value === "object" && value !== null && "systemPrompt" in value && typeof value.systemPrompt === "string")?.systemPrompt
657
- ?? methodPrompt;
644
+ const systemPromptParts = promptResults.flatMap((value) => {
645
+ if (typeof value !== "object" || value === null) return [];
646
+ if (!("systemPrompt" in value) || typeof value.systemPrompt !== "string") return [];
647
+ return [value.systemPrompt];
648
+ });
649
+ const systemPromptBody = systemPromptParts.length > 0 ? systemPromptParts.join("\n\n") : methodPrompt;
658
650
  // Typed reading materials from agent-start handlers (machine face; independent of prompt bytes).
659
651
  // Folded into the provider-visible systemPrompt by the adapter at the send boundary.
660
652
  const readingMaterials: unknown[] = [];