@akagilnc/pi-workflow-roles 0.1.6108 → 0.1.6115

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 (65) hide show
  1. package/dist/acp-host/production-host.js +209 -177
  2. package/dist/compliance-transport.js +3 -3
  3. package/dist/diarist-contracts.js +0 -16
  4. package/dist/diarist-role.js +1 -2
  5. package/dist/doctor-contracts.js +1 -5
  6. package/dist/gatekeeper-role.js +6 -9
  7. package/dist/headless-host/production-host.js +162 -130
  8. package/dist/inspector-contracts.js +2 -22
  9. package/dist/inspector-role.js +1 -2
  10. package/dist/merger-contracts.js +1 -5
  11. package/dist/migrate-book-topology.js +32 -45
  12. package/dist/navigator-invocation-identity.js +8 -10
  13. package/dist/notary-contracts.js +1 -9
  14. package/dist/package-contracts/auditor-output.js +0 -10
  15. package/dist/package-contracts/fixer-output.js +3 -0
  16. package/dist/package-contracts/gatekeeper-output.js +1 -7
  17. package/dist/package-contracts/navigator-output.js +1 -25
  18. package/dist/package-contracts/reviewer-output.js +1 -5
  19. package/dist/package-contracts/terminating-tools.js +10 -24
  20. package/dist/packaged-role-registry.js +20 -4
  21. package/dist/public-cli/countersign-run.js +2 -4
  22. package/dist/public-cli/instruction-seat-run.js +55 -16
  23. package/dist/public-cli/invocation.js +22 -12
  24. package/dist/public-cli/main.js +192 -143
  25. package/dist/public-cli/post-admission.js +2 -2
  26. package/dist/review-submission.js +1 -1
  27. package/dist/role-runtime.js +15 -32
  28. package/dist/secretariat-contracts.js +1 -1
  29. package/dist/submission-errors.js +0 -9
  30. package/dist/submission-gate.js +3 -7
  31. package/dist/submission-ledger.js +4 -12
  32. package/dist/ticket-progress.js +64 -28
  33. package/dist/ticket-trajectory.js +6 -17
  34. package/dist/worker-role.js +3 -4
  35. package/package.json +1 -1
  36. package/src/compliance-transport.ts +3 -3
  37. package/src/diarist-contracts.ts +0 -16
  38. package/src/diarist-role.ts +0 -2
  39. package/src/doctor-contracts.ts +0 -4
  40. package/src/gatekeeper-role.ts +6 -9
  41. package/src/inspector-contracts.ts +1 -21
  42. package/src/inspector-role.ts +0 -2
  43. package/src/merger-contracts.ts +0 -4
  44. package/src/navigator-invocation-identity.ts +9 -16
  45. package/src/notary-contracts.ts +0 -13
  46. package/src/package-contracts/auditor-output.ts +0 -12
  47. package/src/package-contracts/fixer-output.ts +4 -0
  48. package/src/package-contracts/gatekeeper-output.ts +0 -9
  49. package/src/package-contracts/navigator-output.ts +0 -34
  50. package/src/package-contracts/reviewer-output.ts +0 -4
  51. package/src/package-contracts/terminating-tools.ts +21 -37
  52. package/src/packaged-role-registry.ts +33 -3
  53. package/src/public-cli/countersign-run.ts +2 -5
  54. package/src/public-cli/instruction-seat-run.ts +58 -13
  55. package/src/public-cli/invocation.ts +31 -16
  56. package/src/public-cli/post-admission.ts +2 -2
  57. package/src/review-submission.ts +1 -1
  58. package/src/role-runtime.ts +16 -29
  59. package/src/secretariat-contracts.ts +2 -3
  60. package/src/submission-errors.ts +0 -8
  61. package/src/submission-gate.ts +3 -7
  62. package/src/submission-ledger.ts +3 -11
  63. package/src/ticket-progress.ts +76 -33
  64. package/src/ticket-trajectory.ts +5 -18
  65. package/src/worker-role.ts +3 -4
@@ -18,7 +18,7 @@ import { readStoredHostSessionId } from "../session-identity.js";
18
18
  import { reportRunRecord } from "../sitian-facade.js";
19
19
  import { createReceiptDeliveryPolicy, deliveryLimitFromConfig, } from "../receipt-delivery-policy.js";
20
20
  import { rewritePrincipalSessionPaths, rewriteRunDirectoryPathValue, rewriteAdmittedRoleRunPage } from "../role-run-relocation.js";
21
- import { isOfficerReviewSeat } from "../packaged-role-registry.js";
21
+ import { isOfficerReviewSeat, receiptStatus } from "../packaged-role-registry.js";
22
22
  /** Original error bytes, never relabeled — a secondary fact riding beside a classified cause. */
23
23
  function describeCaughtError(error) {
24
24
  if (error instanceof Error) {
@@ -607,7 +607,7 @@ export async function bindDiaristAssertedTicketNumber(admitted) {
607
607
  for (const row of rows) {
608
608
  if (row.role !== admitted.role || !isRecord(row.accepted))
609
609
  continue;
610
- if (row.accepted.status !== "completed" || !("ticketNumber" in row.accepted))
610
+ if (receiptStatus(row.accepted) !== "completed" || !("ticketNumber" in row.accepted))
611
611
  continue;
612
612
  const ticketNumber = parseTicketNumber(row.accepted.ticketNumber);
613
613
  if (ticketNumber !== undefined) {
@@ -212,7 +212,7 @@ export const architectureRowSchema = Type.Union([
212
212
  ], { description: "五种行形:遵循·合/遵循·不合(带 rule)/核架构·合理或查不到/核架构·已拍(带 decidedBy)/核架构·可改进(带 suggestion)" });
213
213
  const ARCH_TABLE_COMMON = "架构归位表:先盘既有架构——docs/adr 与票面点名法源里的层表与规矩,再打开分层配置与代码看每层现在装着什么、有没有法源里没有的层。遵循行:稿里每样进代码的东西各一行,归到法源的层里;核架构行:既有架构每条条款各一行,联网找所选框架官方文档与公认资料里承担同一关切的做法,附链接与原句。法源里既没有层表也没有架构规矩时才为空数组,并在 note 写明;只有规矩没有层表的,遵循行的 layer 写被核的那条规矩原句,核架构行按规矩逐条列。";
214
214
  export const secretariatArchitectureField = Type.Array(architectureRowSchema, {
215
- description: `${ARCH_TABLE_COMMON}有「不合」或「可改进」行,secretariatStatus 只能是 escalate:不合行的原文与两边(改稿归位/改架构)、可改进的建议,都列进 decisionGate 由陛下拍,不出给宰相答。`,
215
+ description: `${ARCH_TABLE_COMMON}有「不合」或「可改进」行,status 只能是 escalate:不合行的原文与两边(改稿归位/改架构)、可改进的建议,都列进 decisionGate 由陛下拍,不出给宰相答。`,
216
216
  });
217
217
  export const countersignArchitectureField = Type.Array(architectureRowSchema, {
218
218
  description: `${ARCH_TABLE_COMMON}有「不合」行不得署:票面意在改架构的上呈,否则封驳退签发方归位;有「可改进」行上呈,建议附原文。`,
@@ -40,7 +40,7 @@ import { formatNavigatorReport, NAVIGATOR_EVENT_TYPE, subjectPath } from "./navi
40
40
  import { AK_ROLE_AUDITOR_SOURCE_RUN_ENV } from "./auditor-soul.js";
41
41
  import { buildNavigatorInfrastructureFailureFact, classifyPackagedRoleTerminalResult, packagedRoleOutputRejectionReason, extractInfrastructureFailureEvidence, NAVIGATOR_INVOCATION_ENTRY, resolveLifecycleInvocationPrincipal, } from "./navigator-invocation-identity.js";
42
42
  import { NAVIGATOR_POST_ROLE_GRACE_MS, raceNavigatorGrace } from "./public-cli/settlement.js";
43
- import { PACKAGED_ROLE_REGISTRY, isNavigatorSeat, packagedRoleActivationFlags, packagedRoleMetadata, packagedRoleOutputTool, packagedRolePhaseFlag, } from "./packaged-role-registry.js";
43
+ import { PACKAGED_ROLE_REGISTRY, isNavigatorSeat, packagedRoleActivationFlags, packagedRoleMetadata, packagedRoleOutputTool, packagedRolePhaseFlag, receiptSeat, receiptStatus, } from "./packaged-role-registry.js";
44
44
  import { createJudgeRoleRuntime, } from "./judge-role.js";
45
45
  import { createReviewerRoleRuntime, } from "./reviewer-role.js";
46
46
  /**
@@ -180,7 +180,7 @@ export { DOCTOR_AUDIT_TOOL_NAME, createPiDoctorAuditor } from "./doctor-auditor.
180
180
  export { COLLECTOR_OUTPUT_TOOL } from "./collector-role.js";
181
181
  export * from "./navigator-attendance.js";
182
182
  export { MERGER_INPUT_FLAG, createMergerRoleRuntime } from "./merger-role.js";
183
- export { MERGER_OUTPUT_TOOL_NAME, mergerInputSchema, mergerOutputSchema, validateMergerInput, validateMergerOutput } from "./merger-contracts.js";
183
+ export { MERGER_OUTPUT_TOOL_NAME, mergerInputSchema, mergerOutputSchema, validateMergerInput } from "./merger-contracts.js";
184
184
  export { createProductionMergerGitState } from "./merger-git-state.js";
185
185
  function activationStage(role, activate) {
186
186
  const record = packagedRoleMetadata(role);
@@ -267,17 +267,6 @@ function navigatorPhase(roleHost, role) {
267
267
  function navigatorOutputTool(role) {
268
268
  return packagedRoleOutputTool(role);
269
269
  }
270
- /** Status leaves that are not the shared `status` key, in registry order. */
271
- function receiptStatusFromRegistry(details) {
272
- for (const entry of PACKAGED_ROLE_REGISTRY) {
273
- if (!("receiptStatusKey" in entry))
274
- continue;
275
- const value = details[entry.receiptStatusKey];
276
- if (typeof value === "string")
277
- return value;
278
- }
279
- return undefined;
280
- }
281
270
  export function publicNavigatorSettlement(role, phase, event) {
282
271
  // One shared classifier owns terminal discriminant (lifecycle + settlement + extractors).
283
272
  if (event.toolName !== navigatorOutputTool(role))
@@ -289,13 +278,9 @@ export function publicNavigatorSettlement(role, phase, event) {
289
278
  return { kind: "role_infrastructure_failure", role, phase };
290
279
  }
291
280
  // accepted/human — project role/phase status; classifier already rejected infra/contradiction.
292
- const details = isRecord(event.details)
293
- ? event.details
294
- : {};
295
- const status = typeof details.status === "string"
296
- ? details.status
297
- : receiptStatusFromRegistry(details);
298
- if (status !== undefined && status === "escalate") {
281
+ const received = receiptStatus(event.details);
282
+ const status = typeof received === "string" ? received : undefined;
283
+ if (status === "escalate") {
299
284
  return { kind: "human_decision", role, phase, status };
300
285
  }
301
286
  return { kind: "accepted", role, phase, ...(status === undefined ? {} : { status }) };
@@ -499,8 +484,7 @@ export function createDiaristRoleRuntime(roleHost, dependencies, hostActions) {
499
484
  // Routing belongs to the public seam after this tool call has returned.
500
485
  // Only completed receipts need local diary projection; other statuses
501
486
  // pass through verbatim for that seam to route.
502
- const status = submitted?.status;
503
- if (status !== "completed")
487
+ if (receiptStatus(parameters) !== "completed")
504
488
  return parameters;
505
489
  const assertion = readDiaristTicketAssertion(submitted);
506
490
  // #836 7.3: pre-bound ticket is material for the LLM, not an override.
@@ -605,16 +589,15 @@ deliveryRequestLimit) {
605
589
  let projectClosedSubmission = async () => {
606
590
  throw new Error("角色终局投射接缝尚未初始化");
607
591
  };
608
- const roleHost = createSubmissionLedgerHost(envelopeHost.host, new Map(PACKAGED_ROLE_REGISTRY.reduce((entries, { role, outputTool }) => {
609
- const existingIndex = entries.findIndex(([name]) => name === outputTool);
610
- if (existingIndex < 0)
611
- entries.push([outputTool, role]);
612
- else {
613
- const previous = entries[existingIndex][1];
614
- entries[existingIndex] = [outputTool, [...(Array.isArray(previous) ? previous : [previous]), role]];
615
- }
616
- return entries;
617
- }, [])), (error, ctx, toolCallId) => hostActions.failInfrastructure(error, ctx, toolCallId), async (closed, context, toolCallId) => projectClosedSubmission(closed, context, toolCallId));
592
+ const roleHost = createSubmissionLedgerHost(envelopeHost.host, {
593
+ get(toolName) {
594
+ const seat = receiptSeat(toolName, () => {
595
+ const active = envelopeHost.host.getFlag(ROLE_FLAG.name);
596
+ return typeof active === "string" ? active : undefined;
597
+ })?.seat;
598
+ return seat === undefined ? undefined : packagedRoleMetadata(seat)?.role;
599
+ },
600
+ }, (error, ctx, toolCallId) => hostActions.failInfrastructure(error, ctx, toolCallId), async (closed, context, toolCallId) => projectClosedSubmission(closed, context, toolCallId));
618
601
  roleHost.registerFlag(ROLE_FLAG.name, ROLE_FLAG.definition);
619
602
  // Reviewer transport flags: shared envelope owns registration (ADR 0018).
620
603
  for (const flag of REVIEWER_TRANSPORT_FLAGS) {
@@ -5,7 +5,7 @@ const SECRETARIAT_OUTPUT_TOOL_NAME = "ak_secretariat_output";
5
5
  const secretariatVerdictSchema = withTerminatingOutputDeclarations(
6
6
  Type.Object(
7
7
  {
8
- secretariatStatus: Type.Unknown({
8
+ status: Type.Unknown({
9
9
  description: "converged | escalate"
10
10
  }),
11
11
  ticketNumber: Type.Optional(
@@ -1,5 +1,4 @@
1
1
  import { readableGateItem } from "./readable-gate-item.js";
2
- import { isRecord } from "./unknown-value.js";
3
2
  export class WorkerCommitReminderError extends Error {
4
3
  code = "worker_commit_reminder";
5
4
  constructor() {
@@ -40,14 +39,6 @@ export function unreadableDiscriminatorNotice(field, received) {
40
39
  return `读不出 ${field}`;
41
40
  return `读不出 ${field}:${readableGateItem(received)}`;
42
41
  }
43
- /** The received discriminator only — never the rest of the receipt. */
44
- export function receivedDiscriminator(receipt, field) {
45
- if (!isRecord(receipt))
46
- return undefined;
47
- if (!Object.hasOwn(receipt, field))
48
- return undefined;
49
- return receipt[field];
50
- }
51
42
  /**
52
43
  * Parent seat status unreadable for queueing (#753).
53
44
  * Correctable back to the parent itself — not a gate officer bounce, no officer field.
@@ -1,7 +1,7 @@
1
1
  import { persistAdmittedAuditedSubmissionToolCallId } from "./public-cli/invocation.js";
2
2
  import { readRunParentPath, readRoleRunIdentity } from "./public-cli/run-lifecycle.js";
3
3
  import { officerConclusionReask, projectGatekeeperRun, } from "./gatekeeper-role.js";
4
- import { receivedDiscriminator } from "./submission-errors.js";
4
+ import { receiptStatus } from "./packaged-role-registry.js";
5
5
  import { deliveryLimitFromConfig } from "./receipt-delivery-policy.js";
6
6
  /**
7
7
  * Directory of the seat this gate actually summoned — not a nested escalate
@@ -35,11 +35,8 @@ export function latestQueueStatus(terminal) {
35
35
  return "escalate";
36
36
  if (outcome.kind !== "accepted")
37
37
  return undefined;
38
- const latest = outcome.payloads?.[outcome.payloads.length - 1];
39
- if (isRecord(latest) && Object.hasOwn(latest, "status")) {
40
- return receivedDiscriminator(latest, "status");
41
- }
42
- return outcome.status;
38
+ const received = receiptStatus(outcome.payloads?.[outcome.payloads.length - 1]);
39
+ return received === undefined ? outcome.status : received;
43
40
  }
44
41
  export function latestQueuePayload(terminal) {
45
42
  const outcome = terminal?.roleOutcome;
@@ -50,7 +47,6 @@ export function latestQueuePayload(terminal) {
50
47
  const payloads = outcome.payloads ?? [];
51
48
  return payloads.length === 0 ? undefined : payloads[payloads.length - 1];
52
49
  }
53
- import { isRecord } from "./unknown-value.js";
54
50
  /**
55
51
  * Shared-envelope default officer summon (ADR 0018).
56
52
  * Role modules must not own this drive seam — only project results.
@@ -338,7 +338,9 @@ export function sealAcceptedSubmission(options) {
338
338
  * No sole-final, no seal barrier, no context.abort(), no details rewrite.
339
339
  * Host end (turn close / exit code) is the final; ledger contents are presented as-is.
340
340
  */
341
- export function createSubmissionLedgerHost(host, outputTools, failInfrastructure = (error) => { throw error; }, projectClosure = () => undefined, options) {
341
+ export function createSubmissionLedgerHost(host,
342
+ /** The seat an output tool's submissions belong to. Absent for any other tool. */
343
+ outputTools, failInfrastructure = (error) => { throw error; }, projectClosure = () => undefined, options) {
342
344
  const states = new Map();
343
345
  const resolveHomeFromContext = (context) => homeFromHostContext(context, options?.home);
344
346
  const stateFor = (context, runId) => states.get(runId) ?? (() => {
@@ -382,17 +384,7 @@ export function createSubmissionLedgerHost(host, outputTools, failInfrastructure
382
384
  return {
383
385
  ...host,
384
386
  registerTool(tool) {
385
- const registeredRole = outputTools.get(tool.name);
386
- let role;
387
- if (typeof registeredRole === "string") {
388
- role = registeredRole;
389
- }
390
- else if (registeredRole !== undefined) {
391
- const activeRole = host.getFlag("ak-role");
392
- role = typeof activeRole === "string" && registeredRole.includes(activeRole)
393
- ? activeRole
394
- : undefined;
395
- }
387
+ const role = outputTools.get(tool.name);
396
388
  if (role === undefined)
397
389
  return host.registerTool(tool);
398
390
  host.registerTool({
@@ -16,27 +16,25 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSyn
16
16
  import { basename, dirname, join, relative, sep } from "node:path";
17
17
  import { resolveHostDossierLandingPath } from "./host-session-record.js";
18
18
  import { runDirectoryFromHostContext } from "./host-contracts.js";
19
- import { acceptedFacts, isTerminatingToolName, } from "./package-contracts/terminating-tools.js";
20
- import { packagedRoleOutputTool } from "./packaged-role-registry.js";
19
+ import { packagedGateStageLabel, receiptStatus } from "./packaged-role-registry.js";
21
20
  import { isUnboundRunDirectory, sessionDirectoryOf, sessionFileOf, subjectDirectoryOfRun, } from "./role-run-placement.js";
22
21
  import { readPageSync } from "./run-dossier.js";
23
22
  import { parseSitianRecordText } from "./sitian-reader.js";
24
- import { isRecord } from "./unknown-value.js";
23
+ import { errorText, isRecord } from "./unknown-value.js";
25
24
  const CURRENT_FILENAME = "current.jsonl";
26
25
  const RECEIPTS_DIRNAME = "receipts";
27
26
  const LEG_PROGRESS_FILENAME = "progress.jsonl";
28
27
  /**
29
- * Append-only progress JSONL — same posture as run-dossier row files:
30
- * sole Sitian decoder keeps reachable rows; malformed lines leave diagnostics
31
- * on stderr and do not abort seal/relocate.
28
+ * Append-only progress JSONL through the sole Sitian decoder: reachable rows
29
+ * plus one diagnostic per malformed line.
32
30
  */
33
- function parseProgressText(text, pathForDiagnostic) {
31
+ function decodeProgressFile(path) {
32
+ if (!existsSync(path))
33
+ return { lines: [], malformed: [] };
34
+ const text = readFileSync(path, "utf8");
34
35
  if (text.trim() === "")
35
- return [];
36
+ return { lines: [], malformed: [] };
36
37
  const { records, diagnostics } = parseSitianRecordText(text);
37
- for (const diagnostic of diagnostics) {
38
- process.stderr.write(`[ticket-progress] ${pathForDiagnostic} has malformed row(s); keeps reachable rows and retains the diagnostic: line ${diagnostic.line}: ${diagnostic.error}\n`);
39
- }
40
38
  const lines = [];
41
39
  for (const record of records) {
42
40
  const parsed = record;
@@ -46,12 +44,21 @@ function parseProgressText(text, pathForDiagnostic) {
46
44
  continue;
47
45
  lines.push(parsed);
48
46
  }
49
- return lines;
47
+ return {
48
+ lines,
49
+ malformed: diagnostics.map((diagnostic) => `line ${diagnostic.line}: ${diagnostic.error}`),
50
+ };
50
51
  }
52
+ /**
53
+ * Same posture as run-dossier row files: malformed lines leave diagnostics on
54
+ * stderr and do not abort seal/relocate.
55
+ */
51
56
  function readProgressFile(path) {
52
- if (!existsSync(path))
53
- return [];
54
- return parseProgressText(readFileSync(path, "utf8"), path);
57
+ const { lines, malformed } = decodeProgressFile(path);
58
+ for (const diagnostic of malformed) {
59
+ process.stderr.write(`[ticket-progress] ${path} has malformed row(s); keeps reachable rows and retains the diagnostic: ${diagnostic}\n`);
60
+ }
61
+ return lines;
55
62
  }
56
63
  /**
57
64
  * Read progress rows under a subject.
@@ -112,28 +119,55 @@ function nextLegReceiptIndex(runDirectory) {
112
119
  }
113
120
  /**
114
121
  * Copy structured status/summary from the seat receipt.
115
- * Status leaves reuse acceptedFacts (terminating-tools authority) via the seat's
116
- * current output tool — legacy judgeStatus/countersignStatus keys are unreachable
117
- * at this seal seam (tool is the live registry name, not ak_judge_output).
118
- * summary is seat-authored prose on the receipt and is not part of AcceptedFacts.
122
+ * summary is seat-authored prose on the receipt.
119
123
  * Missing fields stay absent — never invent "" or "accepted".
120
- *
121
- * Not receiptStatusFromRegistry: that scans every registry key for navigator
122
- * projection when the seat is unknown; here the seal already knows the seat.
123
124
  */
124
- function statusAndSummaryFromPayload(seat, payload) {
125
+ function statusAndSummaryFromPayload(payload) {
125
126
  if (!isRecord(payload))
126
127
  return {};
127
- const toolName = packagedRoleOutputTool(seat);
128
- const status = toolName !== undefined && isTerminatingToolName(toolName)
129
- ? acceptedFacts(toolName, payload).status
130
- : undefined;
128
+ const received = receiptStatus(payload);
129
+ const status = typeof received === "string" ? received : undefined;
131
130
  const summary = typeof payload.summary === "string" ? payload.summary : undefined;
132
131
  return {
133
132
  ...(status === undefined ? {} : { status }),
134
133
  ...(summary === undefined ? {} : { summary }),
135
134
  };
136
135
  }
136
+ /**
137
+ * #1200「审 谁#轮」as the ticket has it now: the audited leg's latest row. Read
138
+ * at the officer's admission, before the officer runs. An audited leg with no
139
+ * round yet (unbound, or no accepted receipt) has none. A progress file that
140
+ * cannot be read or has malformed rows has none either and returns the cause
141
+ * for the caller to retain — the officer still runs.
142
+ */
143
+ export function readAuditedRound(auditedRunDirectory) {
144
+ try {
145
+ const subjectDirectory = subjectDirectoryOfRun(auditedRunDirectory);
146
+ if (subjectDirectory === undefined)
147
+ return {};
148
+ const path = join(subjectDirectory, CURRENT_FILENAME);
149
+ const { lines, malformed } = decodeProgressFile(path);
150
+ if (malformed.length > 0) {
151
+ throw new Error(`${path} has malformed row(s): ${malformed.join("; ")}`);
152
+ }
153
+ const receipts = `runs/${basename(auditedRunDirectory)}/`;
154
+ const latest = lines.filter((line) => line.receipt.startsWith(receipts)).at(-1);
155
+ return latest === undefined ? {} : { for: `${latest.seat}#${latest.round}` };
156
+ }
157
+ catch (error) {
158
+ return { fault: `audited round unavailable for ${auditedRunDirectory}: ${errorText(error)}` };
159
+ }
160
+ }
161
+ /**
162
+ * The row's `for`: gate officers copy the admission pin; the fixer's receipt
163
+ * reports its own (copied when it is a string, never checked). No other seat has one.
164
+ */
165
+ function forOfSealedRow(runDirectory, seat, payload) {
166
+ const reported = packagedGateStageLabel(seat) !== undefined
167
+ ? readPageSync(runDirectory, "admitted")?.for
168
+ : seat === "fixer" && isRecord(payload) ? payload.for : undefined;
169
+ return typeof reported === "string" ? reported : undefined;
170
+ }
137
171
  /** Worktree HEAD at seal. On failure head is empty and fault carries the true cause. */
138
172
  export function captureWorktreeHead(projectRoot) {
139
173
  try {
@@ -247,12 +281,14 @@ export function landTicketProgress(input) {
247
281
  const sessionRelative = input.sessionFile === undefined
248
282
  ? ""
249
283
  : relative(subjectDirectory, input.sessionFile).split(sep).join("/");
250
- const { status, summary } = statusAndSummaryFromPayload(input.role, input.accepted);
284
+ const { status, summary } = statusAndSummaryFromPayload(input.accepted);
285
+ const reviewed = forOfSealedRow(runDirectory, input.role, input.accepted);
251
286
  const instruction = input.instruction;
252
287
  const line = {
253
288
  at: new Date().toISOString(),
254
289
  seat: input.role,
255
290
  round,
291
+ ...(reviewed === undefined ? {} : { for: reviewed }),
256
292
  instruction,
257
293
  head: input.sealHead.head,
258
294
  ...(status === undefined ? {} : { status }),
@@ -31,7 +31,7 @@ import { isPositiveTicketNumber, readRunTicketNumber } from "./run-ticket-number
31
31
  import { extractSessionTimestampSpan, readLedgerSessionJsonl, } from "./ledger-session-read.js";
32
32
  export { readLedgerSessionJsonl } from "./ledger-session-read.js";
33
33
  import { AcceptedDetailsContractError, acceptedFacts, isTerminatingToolName, validateAcceptedDetails, } from "./package-contracts/terminating-tools.js";
34
- import { LEGACY_REVIEW_OUTPUT_ROLES, PACKAGED_ROLE_REGISTRY } from "./packaged-role-registry.js";
34
+ import { PACKAGED_ROLE_REGISTRY, receiptSeat } from "./packaged-role-registry.js";
35
35
  import { isRecord, isMissingPathError } from "./unknown-value.js";
36
36
  /** Declared refresh bound for the same viewing surface (seconds). */
37
37
  export const DEFAULT_REFRESH_BOUNDARY_SECONDS = 30;
@@ -46,15 +46,7 @@ async function realpathOrLexicalIfMissing(path) {
46
46
  throw error;
47
47
  }
48
48
  }
49
- const TOOL_TO_ROLE = new Map([
50
- ...PACKAGED_ROLE_REGISTRY.filter((entry) => entry.outputTool !== "ak_submission_output")
51
- .map((entry) => [entry.outputTool, entry.role]),
52
- ...LEGACY_REVIEW_OUTPUT_ROLES,
53
- ]);
54
49
  const NAME_PREFIX_ROLES = PACKAGED_ROLE_REGISTRY.map((entry) => entry.role);
55
- function roleFromToolName(toolName) {
56
- return TOOL_TO_ROLE.get(toolName);
57
- }
58
50
  function roleFromRunName(runId) {
59
51
  const base = runId.split("@")[0] ?? runId;
60
52
  const lower = base.toLowerCase();
@@ -222,14 +214,11 @@ async function readInvocation(runDir) {
222
214
  }
223
215
  }
224
216
  function resolveStation(input) {
225
- if (input.invocationRole && input.toolNames.includes("ak_submission_output")) {
226
- return { station: input.invocationRole, stationSource: "invocation" };
227
- }
228
- for (const toolName of input.toolNames) {
229
- const role = roleFromToolName(toolName);
230
- if (role)
231
- return { station: role, stationSource: "tool" };
232
- }
217
+ const seats = input.toolNames.flatMap((toolName) => receiptSeat(toolName, () => input.invocationRole) ?? []);
218
+ // A receipt on the shared tool name places the run before any seat-owned name does.
219
+ const placed = seats.find((seat) => seat.source === "invocation") ?? seats[0];
220
+ if (placed !== undefined)
221
+ return { station: placed.seat, stationSource: placed.source };
233
222
  // Also accept tool names observed only via accepted results order
234
223
  if (input.invocationRole) {
235
224
  return { station: input.invocationRole, stationSource: "invocation" };
@@ -5,7 +5,7 @@ import { roleSubmissionDeclaration } from "./role-submission-declarations.js";
5
5
  import { createWorkerSubmissionGate, WorkerCommitReminderError, WorkerPrefixReminderError, WorkerUnfinishedReasonReminderError, } from "./worker-submission-gates.js";
6
6
  import { deliveryLimitFromEnv } from "./receipt-delivery-policy.js";
7
7
  import { fixerBashSeatbeltDenyReason, matchFixerBashForbiddenLiteral, } from "./fixer-bash-seatbelt.js";
8
- import { isRecord } from "./unknown-value.js";
8
+ import { receiptStatus } from "./packaged-role-registry.js";
9
9
  export { CODER_OUTPUT_TOOL_NAME, FIXER_OUTPUT_TOOL_NAME, coderOutputSchema, validateAcceptedWorkerDetails, } from "./package-contracts/worker-output.js";
10
10
  /** #1168: phase only — dispatch text is the first message, not a packet flag. */
11
11
  export const FIXER_FLAG_DEFINITIONS = {
@@ -23,9 +23,8 @@ function isWorkerPhase(value) {
23
23
  }
24
24
  /** Read only the field that selects the worker's next package-owned path. */
25
25
  function workerStatusOf(output) {
26
- return isRecord(output) && typeof output.status === "string"
27
- ? output.status
28
- : undefined;
26
+ const status = receiptStatus(output);
27
+ return typeof status === "string" ? status : undefined;
29
28
  }
30
29
  function deepFreeze(value) {
31
30
  if (typeof value !== "object" || value === null || Object.isFrozen(value))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akagilnc/pi-workflow-roles",
3
- "version": "0.1.6108",
3
+ "version": "0.1.6115",
4
4
  "description": "Soul-bound workflow roles for Pi",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -5,7 +5,7 @@ import type { HostContext } from "./host-contracts.ts";
5
5
  import type { NoReceiptLifecycleFacts } from "./receipt-delivery-policy.ts";
6
6
  import type { PublicSummonResult } from "./public-role-summons.ts";
7
7
  import { officerConclusionReask } from "./gatekeeper-role.ts";
8
- import { receivedDiscriminator } from "./submission-errors.ts";
8
+ import { receiptStatus } from "./packaged-role-registry.ts";
9
9
  import { currentReplyRows } from "./public-cli/terminal.ts";
10
10
  import { readableGateItem } from "./readable-gate-item.ts";
11
11
  import { deliveryLimitFromConfig } from "./receipt-delivery-policy.ts";
@@ -68,7 +68,7 @@ export function tryReadComplianceCandidate(arguments_: unknown, usage?: Usage):
68
68
  return undefined;
69
69
  }
70
70
  const args = arguments_ as Record<string, unknown>;
71
- const status = args.status;
71
+ const status = receiptStatus(arguments_);
72
72
  if (status === "converged") return { status, receipt: arguments_, ...(usage === undefined ? {} : { usage }) };
73
73
  if (status === "continue") return { status, violations: readListField(args.violations), receipt: arguments_, ...(usage === undefined ? {} : { usage }) };
74
74
  if (status === "escalate") {
@@ -234,7 +234,7 @@ export async function runComplianceAudit(options: RunComplianceAuditOptions): Pr
234
234
  if (decision.status === "received") {
235
235
  if (reasksSpent >= reaskLimit) return decision;
236
236
  reasksSpent += 1;
237
- reask = officerConclusionReask(receivedDiscriminator(decision.reply, "status"));
237
+ reask = officerConclusionReask(receiptStatus(decision.reply));
238
238
  continue;
239
239
  }
240
240
  return decision;
@@ -58,22 +58,6 @@ export type DiaristSinceLast =
58
58
  | { readonly lastRecorded: null; readonly swept: null; readonly found: "本卷尚无成录(本票没有起居录,或起居录里没有本卷),本轮从本卷开头收" }
59
59
  | { readonly lastRecorded: null; readonly swept: null; readonly found: "无法扫:起居录或源卷读不出,本轮 status 只能是 escalate,reason 写明读不出什么" };
60
60
 
61
- export function validateRecordedDiaristOutput(value: unknown): DiaristOutput {
62
- if (!isRecord(value)) {
63
- throw new Error("Diarist output has no execution discriminator");
64
- }
65
- let status: unknown;
66
- try {
67
- status = (value as Record<string, unknown>).status;
68
- } catch {
69
- throw new Error("Diarist output has no execution discriminator");
70
- }
71
- if (status === "completed" || status === "escalate") {
72
- return value as DiaristOutput;
73
- }
74
- throw new Error("Diarist output has no execution discriminator");
75
- }
76
-
77
61
  /**
78
62
  * Project sessions from a completed diarist payload.
79
63
  * Null / absent key → empty (lawful). Non-null but unusable → undefined (caller reasks).
@@ -3,7 +3,6 @@ import type { Static } from "typebox";
3
3
  import {
4
4
  DIARIST_OUTPUT_TOOL_NAME,
5
5
  diaristOutputSchema,
6
- validateRecordedDiaristOutput,
7
6
  type DiaristOutput,
8
7
  } from "./diarist-contracts.ts";
9
8
  import { roleSubmissionDeclaration } from "./role-submission-declarations.ts";
@@ -13,7 +12,6 @@ export {
13
12
  diaristOutputSchema,
14
13
  } from "./diarist-contracts.ts";
15
14
  export type { DiaristOutput };
16
- export { validateRecordedDiaristOutput };
17
15
 
18
16
  export type DiaristOutputParameters = Static<typeof diaristOutputSchema>;
19
17
 
@@ -91,10 +91,6 @@ function read(value: unknown, key: string): unknown { if (!isRecord(value)) retu
91
91
  export function validateDoctorSubmissionShape(value: unknown): DoctorSubmission {
92
92
  return value as DoctorSubmission;
93
93
  }
94
- export function validateRecordedDoctorOutput(value: unknown): DoctorOutput {
95
- return value as DoctorOutput;
96
- }
97
-
98
94
  export class DoctorEvidenceStore {
99
95
  readonly entries: Map<string, DoctorEvidenceEntry>; private readonly coverage = new Map<string, Array<[number, number]>>();
100
96
  constructor(readonly patient: DoctorCase) { this.entries = new Map(patient.evidence.map((entry) => [entry.id, entry])); }
@@ -2,9 +2,9 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import type { HostContext } from "./host-contracts.ts";
3
3
 
4
4
  import { auditorRunDirectory } from "./role-run-placement.ts";
5
- import { packagedGateStageLabel } from "./packaged-role-registry.ts";
5
+ import { packagedGateStageLabel, receiptStatus } from "./packaged-role-registry.ts";
6
6
  import type { NoReceiptLifecycleFacts } from "./receipt-delivery-policy.ts";
7
- import { receivedDiscriminator, unreadableDiscriminatorNotice } from "./submission-errors.ts";
7
+ import { unreadableDiscriminatorNotice } from "./submission-errors.ts";
8
8
  import { INSPECTOR_OUTPUT_TOOL_NAME } from "./inspector-contracts.ts";
9
9
  import { REVIEW_QUEUE_STATUSES, REVIEW_SUBMISSION_OUTPUT_TOOL_NAME } from "./review-submission.ts";
10
10
  import { GATEKEEPER_OUTPUT_TOOL_NAME } from "./package-contracts/gatekeeper-output.ts";
@@ -12,7 +12,6 @@ import { roleSubmissionDeclaration } from "./role-submission-declarations.ts";
12
12
  import type { PublicSummonResult } from "./public-role-summons.ts";
13
13
  import { currentReplyRows, type TerminalResult } from "./public-cli/terminal.ts";
14
14
  import { runIdFromRunDirectory } from "./run-terminal-artifacts.ts";
15
- import { isRecord } from "./unknown-value.ts";
16
15
  import { serializeThrownValue } from "./serialize-thrown-value.ts";
17
16
  export const INSPECTOR_OUTPUT_TOOL = INSPECTOR_OUTPUT_TOOL_NAME;
18
17
  export const NOTARY_OUTPUT_TOOL = REVIEW_SUBMISSION_OUTPUT_TOOL_NAME;
@@ -177,10 +176,8 @@ function projectOfficerDecision(
177
176
  fallbackStatus?: string,
178
177
  ): GatekeeperResult {
179
178
  const receipt = retainedReceipt(decision);
180
- const record = isRecord(decision) ? decision : undefined;
181
- const status = record !== undefined && Object.hasOwn(record, "status")
182
- ? receivedDiscriminator(record, "status")
183
- : fallbackStatus;
179
+ const received = receiptStatus(decision);
180
+ const status = received === undefined ? fallbackStatus : received;
184
181
  const queueStatus = typeof status === "string" ? reviewQueueStatus(status) : undefined;
185
182
  if (queueStatus === "converged") {
186
183
  return { status: "converged", officer, receipt };
@@ -316,7 +313,7 @@ function projectOfficerTerminal(
316
313
  status: "needs_reask",
317
314
  officer,
318
315
  receipt,
319
- receivedStatus: receivedDiscriminator(receipt, "status"),
316
+ receivedStatus: receiptStatus(receipt),
320
317
  },
321
318
  summoned,
322
319
  );
@@ -336,7 +333,7 @@ function projectOfficerTerminal(
336
333
  officer,
337
334
  // This-court receipt only (#879).
338
335
  receipt,
339
- receivedStatus: receivedDiscriminator(receipt, "status"),
336
+ receivedStatus: receiptStatus(receipt),
340
337
  },
341
338
  summoned,
342
339
  );
@@ -4,8 +4,7 @@
4
4
  * Dual path: gate-dispatched and independently callable (#568 / ADR 0074).
5
5
  */
6
6
 
7
- import { REVIEW_QUEUE_STATUSES, REVIEW_SUBMISSION_OUTPUT_TOOL_NAME } from "./review-submission.ts";
8
- import { isRecord } from "./unknown-value.ts";
7
+ import { REVIEW_SUBMISSION_OUTPUT_TOOL_NAME } from "./review-submission.ts";
9
8
 
10
9
  export const INSPECTOR_OUTPUT_TOOL_NAME: string = REVIEW_SUBMISSION_OUTPUT_TOOL_NAME;
11
10
  export const INSPECTOR_SOURCE_RUN_FLAG = {
@@ -20,22 +19,3 @@ export type InspectorOutput =
20
19
  | { readonly status: "converged"; readonly findings?: unknown }
21
20
  | { readonly status: "continue"; readonly findings?: unknown }
22
21
  | { readonly status: "escalate"; readonly reason?: unknown; readonly findings?: unknown };
23
-
24
- export function validateRecordedInspectorOutput(value: unknown): InspectorOutput {
25
- if (!isRecord(value)) {
26
- throw new Error("Inspector output has no execution discriminator");
27
- }
28
- let status: unknown;
29
- try {
30
- status = (value as Record<string, unknown>).status;
31
- } catch {
32
- throw new Error("Inspector output has no execution discriminator");
33
- }
34
- if (typeof status !== "string") {
35
- throw new Error("Inspector output has no execution discriminator");
36
- }
37
- if (REVIEW_QUEUE_STATUSES.has(status)) {
38
- return value as InspectorOutput;
39
- }
40
- throw new Error("Inspector output has no execution discriminator");
41
- }
@@ -3,7 +3,6 @@ import { inspectorSubmissionSchema } from "./review-submission.ts";
3
3
  import { roleSubmissionDeclaration } from "./role-submission-declarations.ts";
4
4
  import {
5
5
  INSPECTOR_OUTPUT_TOOL_NAME,
6
- validateRecordedInspectorOutput,
7
6
  type InspectorOutput,
8
7
  } from "./inspector-contracts.ts";
9
8
 
@@ -12,7 +11,6 @@ export {
12
11
  };
13
12
  export { INSPECTOR_OUTPUT_TOOL_NAME as INSPECTOR_OUTPUT_TOOL };
14
13
  export type { InspectorOutput };
15
- export { validateRecordedInspectorOutput };
16
14
 
17
15
  /** 台院事后察举交卷形状。 */
18
16
  export type InspectorOutputParameters = Static<typeof inspectorSubmissionSchema>;
@@ -70,7 +70,3 @@ export function validateMergerInput(value: unknown): MergerInput {
70
70
  const authorizedChecks = Array.isArray(value.authorizedChecks) ? value.authorizedChecks.filter((check): check is Record<string, unknown> => isRecord(check)).map(c => ({ name: asString(c.name), argv: asStringArray(c.argv).filter(a => a.trim().length > 0) })).filter(c => c.name.trim().length > 0 && c.argv.length > 0) : [];
71
71
  return deepFreeze(structuredClone({ attemptId: (value.attemptId as string).trim(), targetObjectId: asString(value.targetObjectId), sourceObjectId: asString(value.sourceObjectId), materials, expectedConflictPaths: asStringArray(value.expectedConflictPaths), resolutionScope: asStringArray(value.resolutionScope), authorizedChecks }) as MergerInput);
72
72
  }
73
-
74
- export function validateMergerOutput(value: unknown): MergerOutput {
75
- return value as MergerOutput;
76
- }