@akagilnc/pi-workflow-roles 0.1.6111 → 0.1.6123

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 (47) hide show
  1. package/README.md +3 -3
  2. package/README.zh-CN.md +3 -3
  3. package/dist/acp-host/production-host.js +442 -279
  4. package/dist/engine-detour-usage.js +2 -1
  5. package/dist/gatekeeper-role.js +3 -15
  6. package/dist/headless-host/production-host.js +427 -264
  7. package/dist/migrate-book-topology.js +42 -22
  8. package/dist/notary-source-run.js +8 -8
  9. package/dist/package-contracts/fixer-output.js +3 -0
  10. package/dist/public-cli/auto-resume.js +3 -3
  11. package/dist/public-cli/cli.js +38 -32
  12. package/dist/public-cli/instruction-seat-run.js +52 -13
  13. package/dist/public-cli/invocation.js +22 -12
  14. package/dist/public-cli/main.js +398 -237
  15. package/dist/public-cli/option-definitions.js +22 -21
  16. package/dist/public-cli/run-lifecycle.js +27 -26
  17. package/dist/public-cli/seat-ticket-binding.js +2 -1
  18. package/dist/public-cli/settlement.js +33 -8
  19. package/dist/public-cli/terminal.js +13 -3
  20. package/dist/public-role-summons.js +1 -7
  21. package/dist/role-run-placement.js +1 -1
  22. package/dist/run-dossier-files.js +4 -2
  23. package/dist/submission-gate.js +3 -3
  24. package/dist/submission-ledger.js +29 -3
  25. package/dist/ticket-address.js +77 -0
  26. package/dist/ticket-progress.js +90 -14
  27. package/package.json +1 -1
  28. package/src/engine-detour-usage.ts +2 -1
  29. package/src/gatekeeper-role.ts +5 -18
  30. package/src/notary-source-run.ts +8 -8
  31. package/src/package-contracts/fixer-output.ts +4 -0
  32. package/src/public-cli/auto-resume.ts +4 -3
  33. package/src/public-cli/cli.ts +53 -32
  34. package/src/public-cli/instruction-seat-run.ts +55 -11
  35. package/src/public-cli/invocation.ts +31 -16
  36. package/src/public-cli/option-definitions.ts +22 -21
  37. package/src/public-cli/run-lifecycle.ts +31 -31
  38. package/src/public-cli/seat-ticket-binding.ts +2 -1
  39. package/src/public-cli/settlement.ts +43 -7
  40. package/src/public-cli/terminal.ts +33 -14
  41. package/src/public-role-summons.ts +3 -15
  42. package/src/role-run-placement.ts +1 -1
  43. package/src/run-dossier-files.ts +5 -2
  44. package/src/submission-gate.ts +3 -2
  45. package/src/submission-ledger.ts +32 -2
  46. package/src/ticket-address.ts +91 -0
  47. package/src/ticket-progress.ts +113 -15
@@ -142,17 +142,25 @@ export type TerminalResult = {
142
142
  submissionToolCallId?: string;
143
143
  /** Call-local auto-resume observation (0..2) for this single LLM call; read-only, not persisted. */
144
144
  autoResumeCount?: number;
145
- } & (
146
- | {
147
- runId: string;
148
- batch?: undefined;
149
- }
150
- | {
151
- /** Deterministic public batch projection; no parent Role run exists. */
152
- batch: "reviewer";
153
- runId?: undefined;
154
- }
155
- );
145
+ /**
146
+ * #1201 public identity: ticket + seat + round + receipt. The seat is
147
+ * roleOutcome.role. Absent while the leg has reported no ticket, and on a
148
+ * reviewer batch: a batch is no leg, each lens in reviewerChildren carries its own.
149
+ */
150
+ ticket?: number;
151
+ /** One per accepted submission in roleOutcome.payloads, in ledger order. */
152
+ receipts?: readonly TerminalReceiptRef[];
153
+ /** Deterministic public batch projection; no parent Role run exists. */
154
+ batch?: "reviewer";
155
+ };
156
+
157
+ /** One accepted receipt as the ticket's progress row names it (#1201). */
158
+ export type TerminalReceiptRef = {
159
+ /** Seat-local round on the ticket; absent while the leg has reported no ticket. */
160
+ readonly round?: string;
161
+ /** Path of the receipt original: the row's reference under its subject directory. */
162
+ readonly receipt: string;
163
+ };
156
164
 
157
165
  /**
158
166
  * Build an advice navigator fact (#959). Prose is presented as submitted;
@@ -162,6 +170,16 @@ export function adviceNavigatorFact(input: { prose: string }): TerminalNavigator
162
170
  return { disposition: "advice", prose: input.prose };
163
171
  }
164
172
 
173
+ /** One leg's public identity rows (#1201): its ticket, then its receipts newest first. */
174
+ function identityRows(leg: TerminalResult): string[] {
175
+ const seat = leg.roleOutcome.role;
176
+ return [
177
+ ...(leg.ticket === undefined ? [] : [`ticket\t${leg.ticket}`]),
178
+ ...[...(leg.receipts ?? [])].reverse().map((filed) =>
179
+ `receipt\t${encodeTerminalField(filed.round === undefined ? seat : `${seat}#${filed.round}`)}\t${encodeTerminalField(filed.receipt)}`),
180
+ ];
181
+ }
182
+
165
183
  /**
166
184
  * Present one Terminal result for humans. Labels, row order, wording, and layout
167
185
  * are unfrozen (ADR 0052). Machine consumers and tests must read typed
@@ -227,11 +245,12 @@ export function formatTerminalResult(result: TerminalResult): string {
227
245
  if (child.stderr !== undefined && child.stderr !== "") {
228
246
  lines.push(`reviewer-child-diagnostic\t${axis}\t${encodeTerminalField(child.stderr)}`);
229
247
  }
248
+ // Each lens reports under its own ticket: the two may have reported different ones.
249
+ const lens = result.reviewerChildren?.[axis];
250
+ if (lens !== undefined) lines.push(...identityRows(lens));
230
251
  }
231
252
  }
232
- if (result.runId !== undefined) {
233
- lines.push(`run\t${encodeTerminalField(result.runId)}`);
234
- }
253
+ lines.push(...identityRows(result));
235
254
  if (result.autoResumeCount !== undefined) {
236
255
  lines.push(`autoResumeCount\t${encodeTerminalField(String(result.autoResumeCount))}`);
237
256
  }
@@ -522,21 +522,9 @@ export async function summonPublicRole(
522
522
  }
523
523
 
524
524
  const stderr = captured?.stderrText();
525
- // Nested escalate may present a lower terminal; prefer that seat's admitted
526
- // runDirectory when already in hand — do not re-resolve bare runId across books (#1195).
527
- let runDirectory = result.admitted?.runDirectory;
528
- if (
529
- result.terminal !== undefined
530
- && result.terminal.roleOutcome.role !== options.role
531
- && typeof result.terminal.runId === "string"
532
- && result.admitted?.runId !== result.terminal.runId
533
- ) {
534
- // Compatibility surface with no admitted locator for that terminal.
535
- runDirectory = await (await import("./public-cli/run-lifecycle.ts")).findRunDirectoryById(
536
- home,
537
- result.terminal.runId,
538
- ) ?? runDirectory;
539
- }
525
+ // Nested escalate returns the officer's terminal with that officer's admitted
526
+ // leg beside it — the run directory in hand is the one that terminal belongs to (#1195).
527
+ const runDirectory = result.admitted?.runDirectory;
540
528
  return {
541
529
  exitCode: result.exitCode,
542
530
  ...(result.terminal === undefined ? {} : { terminal: result.terminal }),
@@ -143,7 +143,7 @@ export async function findRoleRunDirectory(
143
143
  }
144
144
  if (matches.length === 0) return undefined;
145
145
  if (matches.length === 1) return matches[0];
146
- throw new Error(`ambiguous role run id ${runId}: ${matches.join(", ")}`);
146
+ throw new Error(`ambiguous role run: ${matches.join(", ")}`);
147
147
  }
148
148
 
149
149
  /** The single authority for every path belonging to an admitted role run. */
@@ -10,13 +10,16 @@ export const RUN_STATE_FILE = "state.jsonl" as const;
10
10
  /**
11
11
  * Record kinds that make a leg's history: they land in `history.jsonl`. The
12
12
  * original submission ledger and attempt history, the prompt/schema each turn was
13
- * started with, and officer pointers.
13
+ * started with, officer pointers, and the ticket progress rows a leg wrote.
14
14
  */
15
15
  export const RUN_HISTORY_KINDS: ReadonlySet<string> = new Set([
16
16
  "candidate", "roundContext", "outcome", "sealed", "post-seal-anomaly",
17
- "attempt-history", "turn-delivery", "officer-pointer",
17
+ "attempt-history", "turn-delivery", "officer-pointer", "progress",
18
18
  ]);
19
19
 
20
+ /** History record kind of a ticket progress row carried to settlement (#1201). */
21
+ export const PROGRESS_RECORD_KIND = "progress" as const;
22
+
20
23
  /** History record kind of a booked officer pointer (appender routes it to history.jsonl). */
21
24
  export const OFFICER_POINTER_RECORD_KIND = "officer-pointer" as const;
22
25
 
@@ -21,6 +21,7 @@ import { persistAdmittedAuditedSubmissionToolCallId } from "./public-cli/invocat
21
21
  import { readRunParentPath, readRoleRunIdentity } from "./public-cli/run-lifecycle.ts";
22
22
  import {
23
23
  officerConclusionReask,
24
+ officerRunIdFromSummoned,
24
25
  projectGatekeeperRun,
25
26
  type GatekeeperSubject,
26
27
  type GateOfficer,
@@ -262,7 +263,7 @@ export async function requireSubmissionGate(options: {
262
263
  officer: projected.officer,
263
264
  receipt: gatekeeper.submission ?? { reason: gatekeeper.reason },
264
265
  reason: gatekeeper.reason,
265
- runId: projected.summoned?.terminal?.runId,
266
+ runId: projected.summoned === undefined ? undefined : officerRunIdFromSummoned(projected.summoned),
266
267
  runDirectory: projected.summoned?.runDirectory,
267
268
  terminal: projected.summoned?.terminal,
268
269
  });
@@ -285,7 +286,7 @@ export async function requireSubmissionGate(options: {
285
286
  officer: projected.officer,
286
287
  receipt: gatekeeper.facts ?? { reason: gatekeeper.reason },
287
288
  reason: gatekeeper.reason,
288
- runId: projected.summoned?.terminal?.runId,
289
+ runId: projected.summoned === undefined ? undefined : officerRunIdFromSummoned(projected.summoned),
289
290
  runDirectory: projected.summoned?.runDirectory,
290
291
  terminal: projected.summoned?.terminal,
291
292
  });
@@ -16,6 +16,7 @@ import {
16
16
  import { runIdFromRunDirectory } from "./run-terminal-artifacts.ts";
17
17
  import { readSitianRecords, resolveSitianRecordPathInLedger, sitianReport, type RecordPointer } from "./sitian-facade.ts";
18
18
  import type { SitianRecord } from "./sitian-contracts.ts";
19
+ import { PROGRESS_RECORD_KIND } from "./run-dossier-files.ts";
19
20
  import { findRunDirectoryById } from "./public-cli/run-lifecycle.ts";
20
21
  import type { TerminalRoleName } from "./public-cli/terminal.ts";
21
22
  import { isCorrectableExecuteError } from "./submission-correctable-error.ts";
@@ -116,6 +117,12 @@ export type RecordedSubmissionRow = {
116
117
  readonly auditOfficer?: unknown;
117
118
  /** Present when the ledger row names the tool call — used to dedupe candidate+outcome. */
118
119
  readonly toolCallId?: string;
120
+ /**
121
+ * #1201: the ticket progress row written for this accepted submission — its
122
+ * receipt reference, and its round once the leg is filed under a ticket.
123
+ */
124
+ readonly receipt?: string;
125
+ readonly round?: string;
119
126
  };
120
127
 
121
128
  /** Closed-submission callback: original payload, no status/facts projection (#836). */
@@ -285,8 +292,23 @@ function rowFromPayload(
285
292
  */
286
293
  function mapOwnedToSubmissionRows(
287
294
  owned: readonly { kind?: unknown; subject?: unknown; payload?: unknown }[],
295
+ /** Whole-leg records: a round filled at bind carries no court attempt (#1201). */
296
+ leg: readonly { kind?: unknown; subject?: unknown; payload?: unknown }[] = owned,
288
297
  ): readonly RecordedSubmissionRow[] {
289
298
  const scoped = owned;
299
+ const receiptByCall = new Map<string, string>();
300
+ const roundByReceipt = new Map<string, string>();
301
+ for (const record of leg) {
302
+ if (record.kind !== PROGRESS_RECORD_KIND) continue;
303
+ const payload = record.payload as { toolCallId?: unknown; receipt?: unknown; round?: unknown } | undefined;
304
+ if (typeof payload?.receipt !== "string") continue;
305
+ if (typeof payload.toolCallId === "string") {
306
+ receiptByCall.set(submissionCallKey(recordAttemptId(record), payload.toolCallId), payload.receipt);
307
+ }
308
+ if (typeof payload.round === "string" && payload.round !== "") {
309
+ roundByReceipt.set(payload.receipt, payload.round);
310
+ }
311
+ }
290
312
  const out: RecordedSubmissionRow[] = [];
291
313
  const indexByCall = new Map<string, number>();
292
314
  // Recover seat identity for historical non-sealed rows that omitted role (#881).
@@ -359,7 +381,13 @@ function mapOwnedToSubmissionRows(
359
381
  ? submissionCallKey(recordAttemptId(record), payload.toolCallId)
360
382
  : undefined;
361
383
  const fallback = callKey === undefined ? undefined : roleByCall.get(callKey);
362
- take(rowFromPayload(kind, payload, original, fallback), callKey);
384
+ const receipt = kind === "accepted" && callKey !== undefined ? receiptByCall.get(callKey) : undefined;
385
+ const round = receipt === undefined ? undefined : roundByReceipt.get(receipt);
386
+ take({
387
+ ...rowFromPayload(kind, payload, original, fallback),
388
+ ...(receipt === undefined ? {} : { receipt }),
389
+ ...(round === undefined ? {} : { round }),
390
+ }, callKey);
363
391
  }
364
392
  return out;
365
393
  }
@@ -394,7 +422,7 @@ export async function readAttemptScopedSubmissionRows(
394
422
  if (attemptId.length === 0) return [];
395
423
  const scope = resolveReadScope(homeOrScope);
396
424
  const { owned } = await readOwnedSubmissionRecords(cwd, runId, scope);
397
- return mapOwnedToSubmissionRows(owned.filter((record) => recordAttemptId(record) === attemptId));
425
+ return mapOwnedToSubmissionRows(owned.filter((record) => recordAttemptId(record) === attemptId), owned);
398
426
  }
399
427
 
400
428
  /** #1214 R2c: the court-turn attempt that recorded this tool call's submission, if any. */
@@ -511,6 +539,7 @@ export function sealAcceptedSubmission(options: {
511
539
  sealHead,
512
540
  sessionFile: undefined,
513
541
  instruction: options.instruction ?? "",
542
+ call: { attemptId, toolCallId: options.toolCallId },
514
543
  });
515
544
  }
516
545
 
@@ -668,6 +697,7 @@ export function createSubmissionLedgerHost(
668
697
  ...(rawLens === "completeness" || rawLens === "correctness"
669
698
  ? { lens: rawLens }
670
699
  : {}),
700
+ call: { attemptId, toolCallId },
671
701
  });
672
702
  // Native structured-output hosts have no tool-result reply to the model.
673
703
  // Keep the conversation open only after the receipt is durably sealed.
@@ -0,0 +1,91 @@
1
+ /**
2
+ * #1201 public address: ticket + seat (+ round). One locator shared by
3
+ * `ak-role resume <ticket> <seat>[#<round>]` and
4
+ * `--source-run <ticket>:<seat>#<round>` (ADR 0088).
5
+ *
6
+ * Only legs filed under the ticket are visible here. A leg that has reported no
7
+ * ticket stays in `unbound/` and is not in this address.
8
+ */
9
+ import { existsSync, readdirSync, statSync } from "node:fs";
10
+ import { join } from "node:path";
11
+
12
+ import { CliUsageError } from "./public-cli/cli-errors.ts";
13
+ import { parseRunLeaf } from "./role-run-placement.ts";
14
+ import { parseTicketNumber } from "./run-ticket-number.ts";
15
+ import { readTicketProgressLines } from "./ticket-progress.ts";
16
+
17
+ export type TicketLegAddress = {
18
+ readonly ticketNumber: number;
19
+ readonly seat: string;
20
+ /** Round as written on the progress row (`2`, `1.completeness`). */
21
+ readonly round?: string;
22
+ };
23
+
24
+ /** Bare digits; a quoted leading `#` is accepted. */
25
+ export function parseAddressTicket(token: string): number | undefined {
26
+ return parseTicketNumber(token.startsWith("#") ? token.slice(1) : token);
27
+ }
28
+
29
+ /** `<seat>` or `<seat>#<round>`. */
30
+ export function parseSeatRound(token: string): { readonly seat: string; readonly round?: string } {
31
+ const hash = token.indexOf("#");
32
+ return hash === -1
33
+ ? { seat: token }
34
+ : { seat: token.slice(0, hash), round: token.slice(hash + 1) };
35
+ }
36
+
37
+ /** `<ticket>:<seat>#<round>`; undefined when the token is not that spelling. */
38
+ export function parseTicketLegLocator(token: string): Required<TicketLegAddress> | undefined {
39
+ const colon = token.indexOf(":");
40
+ if (colon === -1) return undefined;
41
+ const ticketNumber = parseAddressTicket(token.slice(0, colon));
42
+ const { seat, round } = parseSeatRound(token.slice(colon + 1));
43
+ if (ticketNumber === undefined || seat === "" || round === undefined || round === "") {
44
+ return undefined;
45
+ }
46
+ return { ticketNumber, seat, round };
47
+ }
48
+
49
+ /**
50
+ * Run directory of the addressed leg under the caller's book directory.
51
+ * With a round: the leg that sealed that progress row (the row's receipt
52
+ * reference names it). Without: the seat's most recently active leg under the
53
+ * ticket, read off the leg directories themselves — rows exist only for accepted
54
+ * receipts, so a leg that has not submitted yet is still found. Activity is the
55
+ * leg directory's mtime: every turn takes and releases the leg's writer lease
56
+ * there. One `runs/` listing and one stat per leg of the seat.
57
+ */
58
+ export function locateTicketLeg(bookDirectory: string, input: TicketLegAddress): string {
59
+ const ticketDirectory = join(bookDirectory, String(input.ticketNumber));
60
+ if (!existsSync(ticketDirectory)) {
61
+ throw new CliUsageError(`ticket ${input.ticketNumber} has no records in this project's book: ${ticketDirectory}`);
62
+ }
63
+ if (input.round !== undefined) {
64
+ const row = readTicketProgressLines(ticketDirectory)
65
+ .find((line) => line.seat === input.seat && line.round === input.round);
66
+ if (row === undefined) {
67
+ throw new CliUsageError(
68
+ `ticket ${input.ticketNumber} has no progress row ${input.seat}#${input.round}`,
69
+ );
70
+ }
71
+ // `runs/<leg>/receipts/<n>.json`
72
+ return join(ticketDirectory, ...row.receipt.split("/").slice(0, 2));
73
+ }
74
+ const runsDirectory = join(ticketDirectory, "runs");
75
+ let latest: { readonly leaf: string; readonly mtimeMs: number } | undefined;
76
+ for (const entry of existsSync(runsDirectory) ? readdirSync(runsDirectory, { withFileTypes: true }) : []) {
77
+ if (!entry.isDirectory() || parseRunLeaf(entry.name)?.role !== input.seat) continue;
78
+ const { mtimeMs } = statSync(join(runsDirectory, entry.name));
79
+ if (
80
+ latest === undefined
81
+ || mtimeMs > latest.mtimeMs
82
+ || (mtimeMs === latest.mtimeMs && entry.name > latest.leaf)
83
+ ) {
84
+ latest = { leaf: entry.name, mtimeMs };
85
+ }
86
+ }
87
+ if (latest === undefined) {
88
+ throw new CliUsageError(`ticket ${input.ticketNumber} has no ${input.seat} leg`);
89
+ }
90
+ return join(runsDirectory, latest.leaf);
91
+ }
@@ -26,7 +26,7 @@ import { basename, dirname, join, relative, sep } from "node:path";
26
26
  import { resolveHostDossierLandingPath } from "./host-session-record.ts";
27
27
  import type { HostContext } from "./host-contracts.ts";
28
28
  import { runDirectoryFromHostContext } from "./host-contracts.ts";
29
- import { receiptStatus } from "./packaged-role-registry.ts";
29
+ import { packagedGateStageLabel, receiptStatus } from "./packaged-role-registry.ts";
30
30
  import {
31
31
  isUnboundRunDirectory,
32
32
  sessionDirectoryOf,
@@ -34,8 +34,11 @@ import {
34
34
  subjectDirectoryOfRun,
35
35
  } from "./role-run-placement.ts";
36
36
  import { readPageSync } from "./run-dossier.ts";
37
+ import { PROGRESS_RECORD_KIND } from "./run-dossier-files.ts";
38
+ import { runIdFromRunDirectory } from "./run-terminal-artifacts.ts";
39
+ import { sitianReport } from "./sitian-facade.ts";
37
40
  import { parseSitianRecordText } from "./sitian-reader.ts";
38
- import { isRecord } from "./unknown-value.ts";
41
+ import { errorText, isRecord } from "./unknown-value.ts";
39
42
 
40
43
  const CURRENT_FILENAME = "current.jsonl" as const;
41
44
  const RECEIPTS_DIRNAME = "receipts" as const;
@@ -47,6 +50,11 @@ export type TicketProgressLine = {
47
50
  readonly seat: string;
48
51
  /** Seat-local round; reviewer dual-lens uses `<n>.<lens>`. Empty while unbound. */
49
52
  readonly round: string;
53
+ /**
54
+ * #1200 `<seat>#<round>` this row reviews or fixes. Officer rows copy the value
55
+ * pinned at admission; fixer rows copy the receipt's own `for`. Absent otherwise.
56
+ */
57
+ readonly for?: string;
50
58
  /** This-round summons instruction bytes; empty string when none. */
51
59
  readonly instruction: string;
52
60
  /** `git rev-parse HEAD` at seal from the seat worktree; empty on failure. */
@@ -62,18 +70,17 @@ export type TicketProgressLine = {
62
70
  };
63
71
 
64
72
  /**
65
- * Append-only progress JSONL — same posture as run-dossier row files:
66
- * sole Sitian decoder keeps reachable rows; malformed lines leave diagnostics
67
- * on stderr and do not abort seal/relocate.
73
+ * Append-only progress JSONL through the sole Sitian decoder: reachable rows
74
+ * plus one diagnostic per malformed line.
68
75
  */
69
- function parseProgressText(text: string, pathForDiagnostic: string): TicketProgressLine[] {
70
- if (text.trim() === "") return [];
76
+ function decodeProgressFile(path: string): {
77
+ readonly lines: TicketProgressLine[];
78
+ readonly malformed: readonly string[];
79
+ } {
80
+ if (!existsSync(path)) return { lines: [], malformed: [] };
81
+ const text = readFileSync(path, "utf8");
82
+ if (text.trim() === "") return { lines: [], malformed: [] };
71
83
  const { records, diagnostics } = parseSitianRecordText(text);
72
- for (const diagnostic of diagnostics) {
73
- process.stderr.write(
74
- `[ticket-progress] ${pathForDiagnostic} has malformed row(s); keeps reachable rows and retains the diagnostic: line ${diagnostic.line}: ${diagnostic.error}\n`,
75
- );
76
- }
77
84
  const lines: TicketProgressLine[] = [];
78
85
  for (const record of records) {
79
86
  const parsed: unknown = record;
@@ -81,12 +88,24 @@ function parseProgressText(text: string, pathForDiagnostic: string): TicketProgr
81
88
  if (typeof parsed.seat !== "string" || typeof parsed.round !== "string") continue;
82
89
  lines.push(parsed as unknown as TicketProgressLine);
83
90
  }
84
- return lines;
91
+ return {
92
+ lines,
93
+ malformed: diagnostics.map((diagnostic) => `line ${diagnostic.line}: ${diagnostic.error}`),
94
+ };
85
95
  }
86
96
 
97
+ /**
98
+ * Same posture as run-dossier row files: malformed lines leave diagnostics on
99
+ * stderr and do not abort seal/relocate.
100
+ */
87
101
  function readProgressFile(path: string): TicketProgressLine[] {
88
- if (!existsSync(path)) return [];
89
- return parseProgressText(readFileSync(path, "utf8"), path);
102
+ const { lines, malformed } = decodeProgressFile(path);
103
+ for (const diagnostic of malformed) {
104
+ process.stderr.write(
105
+ `[ticket-progress] ${path} has malformed row(s); keeps reachable rows and retains the diagnostic: ${diagnostic}\n`,
106
+ );
107
+ }
108
+ return lines;
90
109
  }
91
110
 
92
111
  /**
@@ -167,6 +186,44 @@ function statusAndSummaryFromPayload(payload: unknown): {
167
186
  };
168
187
  }
169
188
 
189
+ /**
190
+ * #1200「审 谁#轮」as the ticket has it now: the audited leg's latest row. Read
191
+ * at the officer's admission, before the officer runs. An audited leg with no
192
+ * round yet (unbound, or no accepted receipt) has none. A progress file that
193
+ * cannot be read or has malformed rows has none either and returns the cause
194
+ * for the caller to retain — the officer still runs.
195
+ */
196
+ export function readAuditedRound(auditedRunDirectory: string): {
197
+ readonly for?: string;
198
+ readonly fault?: string;
199
+ } {
200
+ try {
201
+ const subjectDirectory = subjectDirectoryOfRun(auditedRunDirectory);
202
+ if (subjectDirectory === undefined) return {};
203
+ const path = join(subjectDirectory, CURRENT_FILENAME);
204
+ const { lines, malformed } = decodeProgressFile(path);
205
+ if (malformed.length > 0) {
206
+ throw new Error(`${path} has malformed row(s): ${malformed.join("; ")}`);
207
+ }
208
+ const receipts = `runs/${basename(auditedRunDirectory)}/`;
209
+ const latest = lines.filter((line) => line.receipt.startsWith(receipts)).at(-1);
210
+ return latest === undefined ? {} : { for: `${latest.seat}#${latest.round}` };
211
+ } catch (error) {
212
+ return { fault: `audited round unavailable for ${auditedRunDirectory}: ${errorText(error)}` };
213
+ }
214
+ }
215
+
216
+ /**
217
+ * The row's `for`: gate officers copy the admission pin; the fixer's receipt
218
+ * reports its own (copied when it is a string, never checked). No other seat has one.
219
+ */
220
+ function forOfSealedRow(runDirectory: string, seat: string, payload: unknown): string | undefined {
221
+ const reported = packagedGateStageLabel(seat) !== undefined
222
+ ? readPageSync(runDirectory, "admitted")?.for
223
+ : seat === "fixer" && isRecord(payload) ? payload.for : undefined;
224
+ return typeof reported === "string" ? reported : undefined;
225
+ }
226
+
170
227
  export type WorktreeHeadCapture = {
171
228
  readonly head: string;
172
229
  readonly fault?: string;
@@ -206,6 +263,40 @@ export function captureWorktreeHead(projectRoot: string): WorktreeHeadCapture {
206
263
  }
207
264
  }
208
265
 
266
+ /** The sealing tool call a progress row belongs to, as the submission ledger names it. */
267
+ export type ProgressRowCall = {
268
+ readonly attemptId: string;
269
+ readonly toolCallId: string;
270
+ };
271
+
272
+ /**
273
+ * #1201: the row just written rides the leg's submission ledger to the process
274
+ * that prints the terminal — settlement reads round and receipt beside the
275
+ * sealed payload, and never picks rows out of current.jsonl after the turn.
276
+ * A seal names its tool call; a publish (round filled at bind) names the receipt.
277
+ */
278
+ function carryProgressRow(
279
+ runDirectory: string,
280
+ line: TicketProgressLine,
281
+ call?: ProgressRowCall,
282
+ ): void {
283
+ const runId = runIdFromRunDirectory(runDirectory);
284
+ if (runId === undefined) return;
285
+ sitianReport({
286
+ level: "event",
287
+ kind: PROGRESS_RECORD_KIND,
288
+ subject: { runId, ...(call === undefined ? {} : { attemptId: call.attemptId }) },
289
+ payload: {
290
+ type: PROGRESS_RECORD_KIND,
291
+ ...(call === undefined ? {} : { toolCallId: call.toolCallId }),
292
+ receipt: line.receipt,
293
+ round: line.round,
294
+ },
295
+ source: "ticket-progress",
296
+ sessionParent: sessionFileOf(runDirectory),
297
+ });
298
+ }
299
+
209
300
  function progressSessionAbsolute(runDirectory: string, context: HostContext): string {
210
301
  const host = typeof context.host === "string" ? context.host.trim() : "";
211
302
  const sessionDirectory = sessionDirectoryOf(runDirectory);
@@ -238,6 +329,7 @@ export function landTicketProgressForSealedSubmission(input: {
238
329
  readonly accepted: unknown;
239
330
  readonly sealHead: WorktreeHeadCapture;
240
331
  readonly lens?: string;
332
+ readonly call: ProgressRowCall;
241
333
  }): TicketProgressLine | undefined {
242
334
  const runDirectory = runDirectoryFromHostContext(input.context);
243
335
  if (runDirectory === undefined) return undefined;
@@ -246,6 +338,7 @@ export function landTicketProgressForSealedSubmission(input: {
246
338
  role: input.role,
247
339
  accepted: input.accepted,
248
340
  sealHead: input.sealHead,
341
+ call: input.call,
249
342
  ...(input.lens === undefined ? {} : { lens: input.lens }),
250
343
  sessionFile: progressSessionAbsolute(runDirectory, input.context),
251
344
  instruction: typeof input.context.summonsInstruction === "string"
@@ -267,6 +360,7 @@ export function landTicketProgress(input: {
267
360
  readonly lens?: string;
268
361
  readonly sessionFile: string | undefined;
269
362
  readonly instruction: string;
363
+ readonly call: ProgressRowCall;
270
364
  }): TicketProgressLine | undefined {
271
365
  const { runDirectory } = input;
272
366
 
@@ -308,11 +402,13 @@ export function landTicketProgress(input: {
308
402
  ? ""
309
403
  : relative(subjectDirectory, input.sessionFile).split(sep).join("/");
310
404
  const { status, summary } = statusAndSummaryFromPayload(input.accepted);
405
+ const reviewed = forOfSealedRow(runDirectory, input.role, input.accepted);
311
406
  const instruction = input.instruction;
312
407
  const line: TicketProgressLine = {
313
408
  at: new Date().toISOString(),
314
409
  seat: input.role,
315
410
  round,
411
+ ...(reviewed === undefined ? {} : { for: reviewed }),
316
412
  instruction,
317
413
  head: input.sealHead.head,
318
414
  ...(status === undefined ? {} : { status }),
@@ -323,6 +419,7 @@ export function landTicketProgress(input: {
323
419
 
324
420
  mkdirSync(dirname(progressPath), { recursive: true });
325
421
  appendFileSync(progressPath, `${JSON.stringify(line)}\n`, "utf8");
422
+ carryProgressRow(runDirectory, line, input.call);
326
423
  // HEAD capture fault: keep the raw cause on stderr. Do not invent a second
327
424
  // dossier custom-frame channel beside post-admission's existing retain path.
328
425
  if (input.sealHead.fault !== undefined) {
@@ -394,4 +491,5 @@ export function relocateTicketProgressForLeg(input: {
394
491
  );
395
492
  // Append succeeded — drop staging. Failure above leaves progress.jsonl in place.
396
493
  rmSync(stagedPath, { force: true });
494
+ for (const moved of movedLines) carryProgressRow(input.runDirectory, moved);
397
495
  }