@akagilnc/pi-workflow-roles 0.1.5775 → 0.1.5805

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 (49) hide show
  1. package/dist/acp-host/production-host.js +630 -258
  2. package/dist/engine-detour-tool.js +51 -37
  3. package/dist/engine-detour.js +22 -11
  4. package/dist/external-host-turn-loop.js +3 -0
  5. package/dist/headless-host/production-host.js +603 -231
  6. package/dist/migrate-book-topology.js +63 -23
  7. package/dist/pi/role-turn-host.js +6 -1
  8. package/dist/public-cli/instruction-seat-run.js +10 -7
  9. package/dist/public-cli/invocation.js +95 -39
  10. package/dist/public-cli/main.js +357 -147
  11. package/dist/public-cli/post-admission.js +2 -0
  12. package/dist/public-cli/run-lifecycle.js +10 -4
  13. package/dist/public-cli/turn-request.js +3 -0
  14. package/dist/report-ticket-tool.js +3 -3
  15. package/dist/role-run-placement.js +14 -2
  16. package/dist/role-run-relocation.js +2 -2
  17. package/dist/run-dossier.js +5 -4
  18. package/dist/session-identity.js +3 -2
  19. package/dist/sitian-appender.js +12 -3
  20. package/dist/submission-ledger.js +24 -0
  21. package/dist/ticket-progress.js +306 -0
  22. package/dist/user-dialogue-stdin.js +23 -17
  23. package/package.json +1 -1
  24. package/resources/engine-dispatch.md +6 -6
  25. package/resources/engines/agy.md +1 -1
  26. package/src/engine-detour-tool.ts +88 -57
  27. package/src/engine-detour.ts +31 -14
  28. package/src/external-host-turn-loop.ts +7 -1
  29. package/src/host-contracts.ts +8 -1
  30. package/src/pi/adapter.ts +57 -45
  31. package/src/pi/role-turn-host.ts +6 -1
  32. package/src/prepared-role-turn.ts +6 -0
  33. package/src/public-cli/instruction-seat-run.ts +10 -7
  34. package/src/public-cli/invocation.ts +116 -38
  35. package/src/public-cli/post-admission.ts +3 -1
  36. package/src/public-cli/run-lifecycle.ts +10 -8
  37. package/src/public-cli/turn-request.ts +3 -0
  38. package/src/report-ticket-tool.ts +7 -3
  39. package/src/role-envelope.ts +8 -1
  40. package/src/role-run-placement.ts +19 -2
  41. package/src/role-run-relocation.ts +2 -2
  42. package/src/role-runtime.ts +15 -4
  43. package/src/run-dossier.ts +5 -3
  44. package/src/run-terminal-artifacts.ts +0 -1
  45. package/src/session-identity.ts +3 -2
  46. package/src/sitian-appender.ts +14 -3
  47. package/src/submission-ledger.ts +27 -0
  48. package/src/ticket-progress.ts +383 -0
  49. package/src/user-dialogue-stdin.ts +21 -14
@@ -711,6 +711,12 @@ function appendSitianRecordBlock(input, block) {
711
711
  function resolveSitianVolumeCategory(kind) {
712
712
  return kind;
713
713
  }
714
+ function runDirectoryOwningSessionParent(sessionParentDir) {
715
+ if (basename3(sessionParentDir) !== "session") return void 0;
716
+ const runDirectory = dirname3(sessionParentDir);
717
+ if (parseRunLeaf(basename3(runDirectory)) === void 0) return void 0;
718
+ return runDirectory;
719
+ }
714
720
  function sitianVolumeDirectory(sessionDirectory, category) {
715
721
  return join3(sessionDirectory, category);
716
722
  }
@@ -742,8 +748,8 @@ function resolveSitianRecordPathInLedger(input, ledgerHome) {
742
748
  throw new Error("Sitian record ownership requires a parent session inside the ledger home");
743
749
  }
744
750
  const sessionParentDir = dirname3(input.sessionParent);
745
- const runDirectory = dirname3(sessionParentDir);
746
- if (basename3(sessionParentDir) === "session" && parseRunLeaf(basename3(runDirectory)) !== void 0) {
751
+ const runDirectory = runDirectoryOwningSessionParent(sessionParentDir);
752
+ if (runDirectory !== void 0) {
747
753
  sessionDir = runDirectory;
748
754
  recordFile = join3(runDirectory, RUN_HISTORY_KINDS.has(input.kind) ? RUN_HISTORY_FILE : RUN_STATE_KINDS.has(input.kind) ? RUN_STATE_FILE : RUN_LOG_FILE);
749
755
  } else {
@@ -976,7 +982,9 @@ function render(runDirectory, history, state, log, unreadable) {
976
982
  original = payload.landingPath;
977
983
  }
978
984
  }
979
- if (typeof original === "string") original = join4(runDirectory, "session", basename4(original));
985
+ if (typeof original === "string") {
986
+ original = join4(sessionDirectoryOf(runDirectory), basename4(original));
987
+ }
980
988
  whole.host = { sessions, ...original === void 0 ? {} : { original } };
981
989
  whole.submission = latest === void 0 ? {} : { latest };
982
990
  if (Object.keys(unreadable).length > 0) whole.unreadable = unreadable;
@@ -1214,6 +1222,16 @@ function parseRunLeaf(name) {
1214
1222
  if (at <= 0 || at === name.length - 1) return void 0;
1215
1223
  return { runId: name.slice(0, at), role: name.slice(at + 1) };
1216
1224
  }
1225
+ function subjectDirectoryOfRun(runDirectory) {
1226
+ const runsParent = dirname4(runDirectory);
1227
+ if (basename5(runsParent) !== "runs") return void 0;
1228
+ const subjectDirectory = dirname4(runsParent);
1229
+ const subjectName = basename5(subjectDirectory);
1230
+ if (subjectName === "unbound" || /^[1-9]\d*$/.test(subjectName)) {
1231
+ return subjectDirectory;
1232
+ }
1233
+ return void 0;
1234
+ }
1217
1235
  function sessionDirectoryOf(runDirectory) {
1218
1236
  return join6(runDirectory, "session");
1219
1237
  }
@@ -1306,6 +1324,7 @@ function ensureRoleRunDirectory(ledgerHome, directory) {
1306
1324
  return ensureRealDirectoryTree(ledgerHome, directory);
1307
1325
  }
1308
1326
  function ensureRoleRunPlacement(ledgerHome, placement) {
1327
+ ensureRoleRunDirectory(ledgerHome, placement.runDirectory);
1309
1328
  ensureRoleRunDirectory(ledgerHome, placement.sessionDirectory);
1310
1329
  }
1311
1330
  var ROLE_RUN_SESSION_FILENAME;
@@ -1406,18 +1425,29 @@ async function runEngineDetourOnce(input) {
1406
1425
  function isEngineDetourFailure(result) {
1407
1426
  return result.code !== 0 || result.stdout.trim() === "";
1408
1427
  }
1409
- function engineDetourFailureDiagnostic(result) {
1410
- if (result.stderr.trim().length > 0) return result.stderr;
1411
- if (result.stdout.trim() === "") return ENGINE_DETOUR_EMPTY_STDOUT_DIAGNOSTIC;
1412
- const rows = result.stdout.split("\n");
1413
- let lastRow = "";
1414
- for (let index = rows.length - 1; index >= 0; index -= 1) {
1415
- if (rows[index].trim() !== "") {
1416
- lastRow = rows[index];
1417
- break;
1418
- }
1428
+ function engineDetourFailureSeatText(result) {
1429
+ const parts = [];
1430
+ if (result.stdout.length > 0) parts.push(result.stdout);
1431
+ if (result.stderr.length > 0) parts.push(result.stderr);
1432
+ let text = "";
1433
+ if (parts.length > 0) {
1434
+ text = parts[0];
1435
+ for (let index = 1; index < parts.length; index += 1) {
1436
+ if (!text.endsWith("\n")) text += "\n";
1437
+ text += parts[index];
1438
+ }
1439
+ }
1440
+ const append = (line2) => {
1441
+ if (text.length > 0 && !text.endsWith("\n")) text += "\n";
1442
+ text += line2;
1443
+ };
1444
+ if (result.code !== 0) {
1445
+ append(`\u52B3\u52A1\u5F15\u64CE\u4EE5 code ${result.code} \u9000\u51FA`);
1419
1446
  }
1420
- return `\u52B3\u52A1\u5F15\u64CE\u4EE5 code ${result.code} \u9000\u51FA\uFF1A${lastRow}`;
1447
+ if (result.stdout.trim() === "") {
1448
+ append(ENGINE_DETOUR_EMPTY_STDOUT_DIAGNOSTIC);
1449
+ }
1450
+ return text.length > 0 ? text : ENGINE_DETOUR_EMPTY_STDOUT_DIAGNOSTIC;
1421
1451
  }
1422
1452
  function engineNameFromEnv() {
1423
1453
  return normalizeEngineName(
@@ -4110,7 +4140,8 @@ var init_role_activation_flags = __esm({
4110
4140
 
4111
4141
  // src/user-dialogue-stdin.ts
4112
4142
  function encodeUserDialogueStdin(body) {
4113
- return JSON.stringify({ kind: USER_DIALOGUE_STDIN_KIND, body });
4143
+ const envelope = { kind: USER_DIALOGUE_STDIN_KIND, body };
4144
+ return JSON.stringify(envelope);
4114
4145
  }
4115
4146
  var USER_DIALOGUE_STDIN_KIND;
4116
4147
  var init_user_dialogue_stdin = __esm({
@@ -4485,17 +4516,6 @@ var init_submission_correctable_error = __esm({
4485
4516
  }
4486
4517
  });
4487
4518
 
4488
- // src/sha256.ts
4489
- import { createHash } from "node:crypto";
4490
- function sha256Hex(bytes) {
4491
- return createHash("sha256").update(bytes).digest("hex");
4492
- }
4493
- var init_sha256 = __esm({
4494
- "src/sha256.ts"() {
4495
- "use strict";
4496
- }
4497
- });
4498
-
4499
4519
  // src/package-contracts/terminating-tools.ts
4500
4520
  function isTerminatingToolName(name) {
4501
4521
  return TERMINATING_TOOL_NAMES.includes(name);
@@ -4556,9 +4576,256 @@ var init_terminating_tools = __esm({
4556
4576
  }
4557
4577
  });
4558
4578
 
4579
+ // src/ticket-progress.ts
4580
+ import { spawnSync as spawnSync2 } from "node:child_process";
4581
+ import {
4582
+ appendFileSync as appendFileSync2,
4583
+ existsSync as existsSync2,
4584
+ mkdirSync as mkdirSync3,
4585
+ readFileSync as readFileSync2,
4586
+ readdirSync as readdirSync2,
4587
+ rmSync as rmSync3,
4588
+ writeFileSync as writeFileSync2
4589
+ } from "node:fs";
4590
+ import { basename as basename7, dirname as dirname6, join as join8, relative as relative2, sep as sep3 } from "node:path";
4591
+ function parseProgressText(text, pathForDiagnostic) {
4592
+ if (text.trim() === "") return [];
4593
+ const { records, diagnostics } = parseSitianRecordText(text);
4594
+ for (const diagnostic of diagnostics) {
4595
+ process.stderr.write(
4596
+ `[ticket-progress] ${pathForDiagnostic} has malformed row(s); keeps reachable rows and retains the diagnostic: line ${diagnostic.line}: ${diagnostic.error}
4597
+ `
4598
+ );
4599
+ }
4600
+ const lines = [];
4601
+ for (const record of records) {
4602
+ const parsed = record;
4603
+ if (!isRecord(parsed)) continue;
4604
+ if (typeof parsed.seat !== "string" || typeof parsed.round !== "string") continue;
4605
+ lines.push(parsed);
4606
+ }
4607
+ return lines;
4608
+ }
4609
+ function readProgressFile(path) {
4610
+ if (!existsSync2(path)) return [];
4611
+ return parseProgressText(readFileSync2(path, "utf8"), path);
4612
+ }
4613
+ function readTicketProgressLines(subjectDirectory) {
4614
+ if (basename7(subjectDirectory) === "unbound") {
4615
+ const runsDir = join8(subjectDirectory, "runs");
4616
+ if (!existsSync2(runsDir)) return [];
4617
+ const out = [];
4618
+ for (const name of readdirSync2(runsDir).sort()) {
4619
+ out.push(...readProgressFile(join8(runsDir, name, LEG_PROGRESS_FILENAME)));
4620
+ }
4621
+ return out;
4622
+ }
4623
+ return readProgressFile(join8(subjectDirectory, CURRENT_FILENAME));
4624
+ }
4625
+ function roundBaseNumber(round) {
4626
+ if (round.trim() === "") return 0;
4627
+ const base = round.includes(".") ? round.slice(0, round.indexOf(".")) : round;
4628
+ const n = Number(base);
4629
+ return Number.isSafeInteger(n) && n > 0 ? n : 0;
4630
+ }
4631
+ function roundLens(round) {
4632
+ return round.includes(".") ? round.slice(round.indexOf(".") + 1) : void 0;
4633
+ }
4634
+ function nextRoundFromLines(lines, seat, lens) {
4635
+ const want = lens === void 0 || lens.trim() === "" ? void 0 : lens;
4636
+ let max = 0;
4637
+ for (const line2 of lines) {
4638
+ if (line2.seat !== seat) continue;
4639
+ if (roundLens(line2.round) !== want) continue;
4640
+ max = Math.max(max, roundBaseNumber(line2.round));
4641
+ }
4642
+ const base = max + 1;
4643
+ return want === void 0 ? String(base) : `${base}.${want}`;
4644
+ }
4645
+ function nextLegReceiptIndex(runDirectory) {
4646
+ const dir = join8(runDirectory, RECEIPTS_DIRNAME);
4647
+ if (!existsSync2(dir)) return 1;
4648
+ let max = 0;
4649
+ for (const name of readdirSync2(dir)) {
4650
+ const match = /^(\d+)\.json$/.exec(name);
4651
+ if (match === null) continue;
4652
+ const n = Number(match[1]);
4653
+ if (Number.isSafeInteger(n) && n > max) max = n;
4654
+ }
4655
+ return max + 1;
4656
+ }
4657
+ function statusAndSummaryFromPayload(seat, payload) {
4658
+ if (!isRecord(payload)) return {};
4659
+ const toolName = packagedRoleOutputTool(seat);
4660
+ const status = toolName !== void 0 && isTerminatingToolName(toolName) ? acceptedFacts(toolName, payload).status : void 0;
4661
+ const summary = typeof payload.summary === "string" ? payload.summary : void 0;
4662
+ return {
4663
+ ...status === void 0 ? {} : { status },
4664
+ ...summary === void 0 ? {} : { summary }
4665
+ };
4666
+ }
4667
+ function captureWorktreeHead(projectRoot) {
4668
+ try {
4669
+ const result = spawnSync2("git", ["rev-parse", "HEAD"], {
4670
+ cwd: projectRoot,
4671
+ encoding: "utf8",
4672
+ maxBuffer: 1024 * 1024
4673
+ });
4674
+ if (result.error != null) {
4675
+ const err = result.error;
4676
+ const detail = err instanceof Error ? err.stack ?? err.message : String(err);
4677
+ return { head: "", fault: `git rev-parse HEAD spawn failed cwd=${projectRoot}: ${detail}` };
4678
+ }
4679
+ if (result.status !== 0) {
4680
+ const detail = [result.stderr, result.stdout].map((part) => typeof part === "string" ? part.trim() : "").filter((part) => part !== "").join(" | ");
4681
+ const status = result.status === null ? "null" : String(result.status);
4682
+ const signal = result.signal == null ? "" : ` signal=${result.signal}`;
4683
+ return {
4684
+ head: "",
4685
+ fault: detail === "" ? `git rev-parse HEAD failed (status=${status}${signal}) cwd=${projectRoot}` : `git rev-parse HEAD failed (status=${status}${signal}) cwd=${projectRoot}: ${detail}`
4686
+ };
4687
+ }
4688
+ return { head: (result.stdout ?? "").trim() };
4689
+ } catch (error) {
4690
+ const message = error instanceof Error ? error.stack ?? error.message : String(error);
4691
+ return { head: "", fault: `git rev-parse HEAD threw cwd=${projectRoot}: ${message}` };
4692
+ }
4693
+ }
4694
+ function progressSessionAbsolute(runDirectory, context) {
4695
+ const host = typeof context.host === "string" ? context.host.trim() : "";
4696
+ const sessionDirectory = sessionDirectoryOf(runDirectory);
4697
+ if (host !== "" && host !== "pi" && host !== "hermes") {
4698
+ return resolveHostDossierLandingPath({ host, sessionDirectory });
4699
+ }
4700
+ const issued = context.sessionManager.getSessionFile?.();
4701
+ if (typeof issued === "string" && issued.trim() !== "") {
4702
+ return issued;
4703
+ }
4704
+ return sessionFileOf(runDirectory);
4705
+ }
4706
+ function lensFromRunDirectory(runDirectory, role) {
4707
+ if (role !== "reviewer") return void 0;
4708
+ const lens = readPageSync(runDirectory, "admitted")?.lens;
4709
+ return lens === "completeness" || lens === "correctness" ? lens : void 0;
4710
+ }
4711
+ function landTicketProgressForSealedSubmission(input) {
4712
+ const runDirectory = runDirectoryFromHostContext(input.context);
4713
+ if (runDirectory === void 0) return void 0;
4714
+ const subjectDirectory = subjectDirectoryOfRun(runDirectory);
4715
+ if (subjectDirectory === void 0) return void 0;
4716
+ const lens = input.lens === "completeness" || input.lens === "correctness" ? input.lens : lensFromRunDirectory(runDirectory, input.role);
4717
+ const leaf = basename7(runDirectory);
4718
+ const unbound = basename7(subjectDirectory) === "unbound";
4719
+ const progressPath = unbound ? join8(runDirectory, LEG_PROGRESS_FILENAME) : join8(subjectDirectory, CURRENT_FILENAME);
4720
+ const receiptIndex = nextLegReceiptIndex(runDirectory);
4721
+ const relativePath = `runs/${leaf}/${RECEIPTS_DIRNAME}/${receiptIndex}.json`;
4722
+ const absolutePath = join8(subjectDirectory, relativePath);
4723
+ mkdirSync3(dirname6(absolutePath), { recursive: true });
4724
+ writeFileSync2(absolutePath, `${JSON.stringify(input.accepted, null, 2)}
4725
+ `, "utf8");
4726
+ if (!unbound) {
4727
+ relocateTicketProgressForLeg({ runDirectory });
4728
+ }
4729
+ const existing = unbound ? readProgressFile(progressPath) : readTicketProgressLines(subjectDirectory);
4730
+ const round = unbound ? "" : nextRoundFromLines(existing, input.role, lens);
4731
+ const sessionFile = progressSessionAbsolute(runDirectory, input.context);
4732
+ const sessionRelative = relative2(subjectDirectory, sessionFile).split(sep3).join("/");
4733
+ const { status, summary } = statusAndSummaryFromPayload(input.role, input.accepted);
4734
+ const instruction = typeof input.context.summonsInstruction === "string" ? input.context.summonsInstruction : "";
4735
+ const line2 = {
4736
+ at: (/* @__PURE__ */ new Date()).toISOString(),
4737
+ seat: input.role,
4738
+ round,
4739
+ instruction,
4740
+ head: input.sealHead.head,
4741
+ ...status === void 0 ? {} : { status },
4742
+ ...summary === void 0 ? {} : { summary },
4743
+ receipt: relativePath,
4744
+ session: sessionRelative
4745
+ };
4746
+ mkdirSync3(dirname6(progressPath), { recursive: true });
4747
+ appendFileSync2(progressPath, `${JSON.stringify(line2)}
4748
+ `, "utf8");
4749
+ if (input.sealHead.fault !== void 0) {
4750
+ process.stderr.write(`${input.sealHead.fault}
4751
+ `);
4752
+ }
4753
+ return line2;
4754
+ }
4755
+ function relocateTicketProgressForLeg(input) {
4756
+ if (isUnboundRunDirectory(input.runDirectory)) return;
4757
+ const subjectDirectory = subjectDirectoryOfRun(input.runDirectory);
4758
+ if (subjectDirectory === void 0) return;
4759
+ const stagedPath = join8(input.runDirectory, LEG_PROGRESS_FILENAME);
4760
+ const mine = readProgressFile(stagedPath);
4761
+ if (mine.length === 0) {
4762
+ if (existsSync2(stagedPath)) {
4763
+ rmSync3(stagedPath, { force: true });
4764
+ }
4765
+ return;
4766
+ }
4767
+ const ticketLines = [...readTicketProgressLines(subjectDirectory)];
4768
+ const publishedReceipts = new Set(
4769
+ ticketLines.map((line2) => line2.receipt).filter((receipt) => typeof receipt === "string" && receipt !== "")
4770
+ );
4771
+ const pending = mine.filter((line2) => !publishedReceipts.has(line2.receipt));
4772
+ if (pending.length === 0) {
4773
+ rmSync3(stagedPath, { force: true });
4774
+ return;
4775
+ }
4776
+ const movedLines = [];
4777
+ for (const line2 of pending) {
4778
+ const lens = lensFromRunDirectory(input.runDirectory, line2.seat);
4779
+ const round = nextRoundFromLines(ticketLines, line2.seat, lens);
4780
+ const moved = {
4781
+ ...line2,
4782
+ round
4783
+ };
4784
+ movedLines.push(moved);
4785
+ ticketLines.push(moved);
4786
+ }
4787
+ const newCurrent = join8(subjectDirectory, CURRENT_FILENAME);
4788
+ mkdirSync3(dirname6(newCurrent), { recursive: true });
4789
+ appendFileSync2(
4790
+ newCurrent,
4791
+ `${movedLines.map((line2) => JSON.stringify(line2)).join("\n")}
4792
+ `,
4793
+ "utf8"
4794
+ );
4795
+ rmSync3(stagedPath, { force: true });
4796
+ }
4797
+ var CURRENT_FILENAME, RECEIPTS_DIRNAME, LEG_PROGRESS_FILENAME;
4798
+ var init_ticket_progress = __esm({
4799
+ "src/ticket-progress.ts"() {
4800
+ "use strict";
4801
+ init_host_session_record();
4802
+ init_host_contracts();
4803
+ init_terminating_tools();
4804
+ init_packaged_role_registry();
4805
+ init_role_run_placement();
4806
+ init_run_dossier();
4807
+ init_sitian_reader();
4808
+ init_unknown_value();
4809
+ CURRENT_FILENAME = "current.jsonl";
4810
+ RECEIPTS_DIRNAME = "receipts";
4811
+ LEG_PROGRESS_FILENAME = "progress.jsonl";
4812
+ }
4813
+ });
4814
+
4815
+ // src/sha256.ts
4816
+ import { createHash } from "node:crypto";
4817
+ function sha256Hex(bytes) {
4818
+ return createHash("sha256").update(bytes).digest("hex");
4819
+ }
4820
+ var init_sha256 = __esm({
4821
+ "src/sha256.ts"() {
4822
+ "use strict";
4823
+ }
4824
+ });
4825
+
4559
4826
  // src/doctor-evidence.ts
4560
4827
  import { readdir as readdir2, readFile as readFile4, realpath, stat } from "node:fs/promises";
4561
- import { dirname as dirname6, relative as relative2, resolve as resolve4, sep as sep3 } from "node:path";
4828
+ import { dirname as dirname7, relative as relative3, resolve as resolve4, sep as sep4 } from "node:path";
4562
4829
  async function discoverCaseFiles(root) {
4563
4830
  const found = [];
4564
4831
  async function walk(dir, depth) {
@@ -4587,11 +4854,11 @@ async function stableRunsIdentity(root) {
4587
4854
  while (true) {
4588
4855
  try {
4589
4856
  const git3 = await stat(resolve4(cursor, ".git"));
4590
- if (git3.isDirectory() || git3.isFile()) return relative2(cursor, root).split(sep3).join("/");
4857
+ if (git3.isDirectory() || git3.isFile()) return relative3(cursor, root).split(sep4).join("/");
4591
4858
  } catch (error) {
4592
4859
  if (!isMissingPathError(error)) throw error;
4593
4860
  }
4594
- const parent = dirname6(cursor);
4861
+ const parent = dirname7(cursor);
4595
4862
  if (parent === cursor) return root;
4596
4863
  cursor = parent;
4597
4864
  }
@@ -4664,12 +4931,12 @@ async function loadDoctorCase(runsPath, projectRoot) {
4664
4931
  if (projectRoot !== void 0 && !physicallyContainedIn(projectRoot, root)) {
4665
4932
  throw new Error("doctor --runs escapes the project root");
4666
4933
  }
4667
- const match = root.split(sep3).join("/").match(/\/\.ak-roles\/books\/[^/]+\/(?:issues\/)?([1-9]\d*)\/runs$/);
4934
+ const match = root.split(sep4).join("/").match(/\/\.ak-roles\/books\/[^/]+\/(?:issues\/)?([1-9]\d*)\/runs$/);
4668
4935
  if (!match) throw new Error("Doctor case must be an .ak-roles/books/<book>/<n>/runs directory");
4669
4936
  const evidence = [], sessions = [], statuses = [], commits = [];
4670
4937
  const turns = { count: 0, sources: [] }, calls = { count: 0, sources: [] }, tokens = { count: 0, sources: [] };
4671
4938
  for (const path of await discoverCaseFiles(root)) {
4672
- const id = relative2(root, path).split(sep3).join("/");
4939
+ const id = relative3(root, path).split(sep4).join("/");
4673
4940
  const bytes = await readFile4(path);
4674
4941
  const content = bytes.toString("utf8");
4675
4942
  const kind = id.split("/").length === 2 && id.endsWith("/log.jsonl") ? "log" : "session";
@@ -4965,13 +5232,13 @@ var init_session_dialogue = __esm({
4965
5232
 
4966
5233
  // src/ticket-provenance.ts
4967
5234
  import { readFile as readFile6 } from "node:fs/promises";
4968
- import { join as join8, resolve as resolve6 } from "node:path";
5235
+ import { join as join9, resolve as resolve6 } from "node:path";
4969
5236
  function dialogueSessionSourceRoots(home) {
4970
5237
  const machineHome = typeof home === "string" && home.trim() !== "" ? home : packageMachineHome();
4971
5238
  return [
4972
- join8(machineHome, ".claude", "projects"),
4973
- join8(machineHome, ".codex", "sessions"),
4974
- join8(machineHome, ".pi", "agent", "sessions")
5239
+ join9(machineHome, ".claude", "projects"),
5240
+ join9(machineHome, ".codex", "sessions"),
5241
+ join9(machineHome, ".pi", "agent", "sessions")
4975
5242
  ];
4976
5243
  }
4977
5244
  function isLedgerRoleSessionFile(absolute, home) {
@@ -5012,7 +5279,7 @@ async function rehomeUnboundTicketProvenance(runDirectory, ticketNumber, cwd, ho
5012
5279
  const ticketInput = ticketProvenanceRecordInput(ticketNumber, cwd, home);
5013
5280
  let history;
5014
5281
  try {
5015
- history = await readFile6(join8(runDirectory, RUN_HISTORY_FILE), "utf8");
5282
+ history = await readFile6(join9(runDirectory, RUN_HISTORY_FILE), "utf8");
5016
5283
  } catch (error) {
5017
5284
  if (errnoCode(error) === "ENOENT") return;
5018
5285
  throw error;
@@ -5229,7 +5496,7 @@ var init_uuidv7 = __esm({
5229
5496
  });
5230
5497
 
5231
5498
  // src/notary-source-run.ts
5232
- import { dirname as dirname7, isAbsolute as isAbsolute4, join as join9, resolve as resolve7, basename as basename7 } from "node:path";
5499
+ import { dirname as dirname8, isAbsolute as isAbsolute4, join as join10, resolve as resolve7, basename as basename8 } from "node:path";
5233
5500
  import { lstat, realpath as realpath2 } from "node:fs/promises";
5234
5501
  async function readRetainedIdentity(runDirectory) {
5235
5502
  try {
@@ -5265,10 +5532,10 @@ async function requireRunDirectory(candidate, display) {
5265
5532
  `notary --source-run must be a run directory: ${display}`
5266
5533
  );
5267
5534
  }
5268
- const identity = parseRunLeaf(basename7(real));
5535
+ const identity = parseRunLeaf(basename8(real));
5269
5536
  if (identity === void 0) {
5270
5537
  throw new NotarySourceRunError(
5271
- `notary --source-run must be named <runId>@<role>: ${basename7(real)}`
5538
+ `notary --source-run must be named <runId>@<role>: ${basename8(real)}`
5272
5539
  );
5273
5540
  }
5274
5541
  return real;
@@ -5281,26 +5548,26 @@ async function resolveNotarySourceRunLocator(options) {
5281
5548
  const ledgerHome = resolveActivationLedgerHome(options.home);
5282
5549
  const bookKey = resolveBookKeyFromGit(options.projectRoot);
5283
5550
  const bookDirectory = activationBookDirectory(ledgerHome, bookKey);
5284
- const bookRunsRoot = join9(bookDirectory, "runs");
5551
+ const bookRunsRoot = join10(bookDirectory, "runs");
5285
5552
  let candidate;
5286
5553
  const bare = parseRunLeaf(raw);
5287
5554
  if (bare !== void 0 && !raw.includes("/") && !raw.includes("\\")) {
5288
- candidate = await findRunDirectoryById(options.home, bare.runId, bookKey, bare.role) ?? join9(bookRunsRoot, formatRunLeaf(bare.runId, bare.role));
5555
+ candidate = await findRunDirectoryById(options.home, bare.runId, bookKey, bare.role) ?? join10(bookRunsRoot, formatRunLeaf(bare.runId, bare.role));
5289
5556
  } else {
5290
5557
  candidate = isAbsolute4(raw) ? raw : resolve7(options.projectRoot, raw);
5291
- const identity2 = parseRunLeaf(basename7(candidate));
5292
- const subjectDirectory = dirname7(dirname7(candidate));
5293
- const isLegacyUnboundLocator = identity2 !== void 0 && basename7(dirname7(candidate)) === "runs" && basename7(subjectDirectory) === "unbound" && resolve7(dirname7(subjectDirectory)) === resolve7(bookDirectory);
5558
+ const identity2 = parseRunLeaf(basename8(candidate));
5559
+ const subjectDirectory = dirname8(dirname8(candidate));
5560
+ const isLegacyUnboundLocator = identity2 !== void 0 && basename8(dirname8(candidate)) === "runs" && basename8(subjectDirectory) === "unbound" && resolve7(dirname8(subjectDirectory)) === resolve7(bookDirectory);
5294
5561
  if (isLegacyUnboundLocator) {
5295
5562
  candidate = await resolveLiveRunDirectoryPath(candidate, options.home ?? ledgerHome, bookKey) ?? candidate;
5296
5563
  }
5297
5564
  }
5298
5565
  const real = await requireRunDirectory(candidate, raw);
5299
- const identity = parseRunLeaf(basename7(real));
5566
+ const identity = parseRunLeaf(basename8(real));
5300
5567
  const bookIdentity = physicalPathIdentity(bookDirectory);
5301
- const parentIdentity = physicalPathIdentity(dirname7(real));
5302
- const subjectBookIdentity = physicalPathIdentity(dirname7(dirname7(dirname7(real))));
5303
- if (parentIdentity !== physicalPathIdentity(bookRunsRoot) && !(basename7(dirname7(real)) === "runs" && subjectBookIdentity === bookIdentity)) {
5568
+ const parentIdentity = physicalPathIdentity(dirname8(real));
5569
+ const subjectBookIdentity = physicalPathIdentity(dirname8(dirname8(dirname8(real))));
5570
+ if (parentIdentity !== physicalPathIdentity(bookRunsRoot) && !(basename8(dirname8(real)) === "runs" && subjectBookIdentity === bookIdentity)) {
5304
5571
  throw new NotarySourceRunError(
5305
5572
  "notary --source-run must resolve to a retained run under the project machine-ledger book"
5306
5573
  );
@@ -5334,7 +5601,7 @@ async function resolveNotarySourceRunLocator(options) {
5334
5601
  }
5335
5602
  async function loadNotarySourceRunLocator(path) {
5336
5603
  const real = await requireRunDirectory(path, path);
5337
- const identity = parseRunLeaf(basename7(real));
5604
+ const identity = parseRunLeaf(basename8(real));
5338
5605
  const runState = await readRetainedIdentity(real);
5339
5606
  if (runState === void 0) {
5340
5607
  throw new NotarySourceRunError(
@@ -6502,14 +6769,14 @@ var init_option_definitions = __esm({
6502
6769
 
6503
6770
  // src/public-cli/invocation.ts
6504
6771
  import { execFileSync as execFileSync2 } from "node:child_process";
6505
- import { existsSync as existsSync2 } from "node:fs";
6772
+ import { existsSync as existsSync3 } from "node:fs";
6506
6773
  import {
6507
6774
  readFile as readFile7,
6508
6775
  realpath as realpath3,
6509
6776
  rename,
6510
6777
  writeFile
6511
6778
  } from "node:fs/promises";
6512
- import { dirname as dirname8, isAbsolute as isAbsolute5, join as join10, resolve as resolve8 } from "node:path";
6779
+ import { dirname as dirname9, isAbsolute as isAbsolute5, join as join11, resolve as resolve8 } from "node:path";
6513
6780
  function admittedSourceRunPath(admitted) {
6514
6781
  if (!isRecord(admitted)) return void 0;
6515
6782
  const path = admitted.sourceRunPath;
@@ -6668,35 +6935,36 @@ async function recordAdmittedCorrelation(admitted, correlationId) {
6668
6935
  mutable.correlationId = correlationId;
6669
6936
  mutable.correlationIds = correlationIds;
6670
6937
  }
6671
- async function relocateAdmittedRunToTicket(admitted, authority, heldLease) {
6672
- if (admitted.ticketNumber === void 0 || !isUnboundRunDirectory(admitted.runDirectory)) return void 0;
6673
- const oldRunDirectory = admitted.runDirectory;
6674
- const ledgerHome = resolveActivationLedgerHome(homeFromRunDirectory(oldRunDirectory));
6675
- const target = roleRunPlacement(ledgerHome, {
6676
- bookKey: admitted.bookKey,
6677
- subject: { ticketNumber: admitted.ticketNumber },
6678
- runId: admitted.runId,
6679
- role: admitted.role
6680
- });
6681
- ensureRoleRunDirectory(ledgerHome, dirname8(target.runDirectory));
6682
- const principal = authority.seal(target);
6683
- if (admitted.role !== "diarist") {
6684
- const childRunIds = readPageSync(oldRunDirectory, "admitted")?.childDiaristRunIds;
6685
- for (const childRunId of Array.isArray(childRunIds) ? childRunIds : []) {
6686
- if (typeof childRunId !== "string") continue;
6687
- const childDirectory = join10(dirname8(oldRunDirectory), formatRunLeaf(childRunId, "diarist"));
6688
- if (!existsSync2(childDirectory)) continue;
6689
- const childTarget = roleRunPlacement(ledgerHome, {
6690
- bookKey: admitted.bookKey,
6691
- subject: { ticketNumber: admitted.ticketNumber },
6692
- runId: childRunId,
6693
- role: "diarist"
6938
+ async function relocateRegisteredChildDiarists(input) {
6939
+ const childRunIds = readPageSync(input.parentRunDirectory, "admitted")?.childDiaristRunIds;
6940
+ for (const childRunId of Array.isArray(childRunIds) ? childRunIds : []) {
6941
+ if (typeof childRunId !== "string") continue;
6942
+ const childTarget = roleRunPlacement(input.ledgerHome, {
6943
+ bookKey: input.bookKey,
6944
+ subject: { ticketNumber: input.ticketNumber },
6945
+ runId: childRunId,
6946
+ role: "diarist"
6947
+ });
6948
+ const unboundChildDirectory = roleRunPlacement(input.ledgerHome, {
6949
+ bookKey: input.bookKey,
6950
+ subject: { unbound: true },
6951
+ runId: childRunId,
6952
+ role: "diarist"
6953
+ }).runDirectory;
6954
+ if (existsSync3(unboundChildDirectory)) {
6955
+ input.authority.seal(childTarget);
6956
+ await bindTicketNumberOnRunDirectory(unboundChildDirectory, input.ticketNumber);
6957
+ await rehomeUnboundTicketProvenance(
6958
+ unboundChildDirectory,
6959
+ input.ticketNumber,
6960
+ input.projectRoot,
6961
+ homeFromRunDirectory(input.parentRunDirectory)
6962
+ );
6963
+ ensureRoleRunDirectory(input.ledgerHome, dirname9(childTarget.runDirectory));
6964
+ await rename(unboundChildDirectory, childTarget.runDirectory);
6965
+ relocateTicketProgressForLeg({
6966
+ runDirectory: childTarget.runDirectory
6694
6967
  });
6695
- authority.seal(childTarget);
6696
- await bindTicketNumberOnRunDirectory(childDirectory, admitted.ticketNumber);
6697
- await rehomeUnboundTicketProvenance(childDirectory, admitted.ticketNumber, admitted.projectRoot, homeFromRunDirectory(oldRunDirectory));
6698
- ensureRoleRunDirectory(ledgerHome, dirname8(childTarget.runDirectory));
6699
- await rename(childDirectory, childTarget.runDirectory);
6700
6968
  try {
6701
6969
  renderCurrentSync(childTarget.runDirectory);
6702
6970
  } catch (error) {
@@ -6705,18 +6973,71 @@ async function relocateAdmittedRunToTicket(admitted, authority, heldLease) {
6705
6973
  `
6706
6974
  );
6707
6975
  }
6976
+ continue;
6977
+ }
6978
+ if (existsSync3(childTarget.runDirectory)) {
6979
+ relocateTicketProgressForLeg({
6980
+ runDirectory: childTarget.runDirectory
6981
+ });
6708
6982
  }
6709
6983
  }
6984
+ }
6985
+ async function relocateAdmittedRunToTicket(admitted, authority, heldLease) {
6986
+ if (admitted.ticketNumber === void 0) return void 0;
6987
+ const ledgerHome = resolveActivationLedgerHome(homeFromRunDirectory(admitted.runDirectory));
6988
+ if (!isUnboundRunDirectory(admitted.runDirectory)) {
6989
+ relocateTicketProgressForLeg({
6990
+ runDirectory: admitted.runDirectory
6991
+ });
6992
+ if (admitted.role !== "diarist") {
6993
+ await relocateRegisteredChildDiarists({
6994
+ parentRunDirectory: admitted.runDirectory,
6995
+ bookKey: admitted.bookKey,
6996
+ ticketNumber: admitted.ticketNumber,
6997
+ projectRoot: admitted.projectRoot,
6998
+ ledgerHome,
6999
+ authority
7000
+ });
7001
+ }
7002
+ return void 0;
7003
+ }
7004
+ const oldRunDirectory = admitted.runDirectory;
7005
+ const target = roleRunPlacement(ledgerHome, {
7006
+ bookKey: admitted.bookKey,
7007
+ subject: { ticketNumber: admitted.ticketNumber },
7008
+ runId: admitted.runId,
7009
+ role: admitted.role
7010
+ });
7011
+ ensureRoleRunDirectory(ledgerHome, dirname9(target.runDirectory));
7012
+ authority.seal(target);
7013
+ if (admitted.role !== "diarist") {
7014
+ await relocateRegisteredChildDiarists({
7015
+ parentRunDirectory: oldRunDirectory,
7016
+ bookKey: admitted.bookKey,
7017
+ ticketNumber: admitted.ticketNumber,
7018
+ projectRoot: admitted.projectRoot,
7019
+ ledgerHome,
7020
+ authority
7021
+ });
7022
+ }
6710
7023
  if (admitted.role === "diarist") {
6711
7024
  await rehomeUnboundTicketProvenance(oldRunDirectory, admitted.ticketNumber, admitted.projectRoot, homeFromRunDirectory(oldRunDirectory));
6712
7025
  }
6713
7026
  await rename(oldRunDirectory, target.runDirectory);
6714
7027
  heldLease?.relocate(target.runDirectory);
7028
+ const actualSessionDirectory = sessionDirectoryOf(target.runDirectory);
7029
+ const principal = authority.seal({
7030
+ sessionDirectory: actualSessionDirectory,
7031
+ sessionFile: sessionFileIn(actualSessionDirectory)
7032
+ });
6715
7033
  rewriteAdmittedRoleRunPage(
6716
7034
  admitted,
6717
7035
  [{ oldRunDirectory, newRunDirectory: target.runDirectory }]
6718
7036
  );
6719
7037
  admitted.principal = principal;
7038
+ relocateTicketProgressForLeg({
7039
+ runDirectory: target.runDirectory
7040
+ });
6720
7041
  renderCurrentSync(target.runDirectory);
6721
7042
  return { oldRunDirectory, newRunDirectory: target.runDirectory };
6722
7043
  }
@@ -6752,7 +7073,7 @@ async function recordLaunchedPiIdentity(runDirectory, identity) {
6752
7073
  async function observeLaunchedRolePackageIdentity(packageRoot, selectedRoleEntry) {
6753
7074
  const rolePackageRoot = packageRoot;
6754
7075
  const raw = JSON.parse(
6755
- await readFile7(join10(rolePackageRoot, "package.json"), "utf8")
7076
+ await readFile7(join11(rolePackageRoot, "package.json"), "utf8")
6756
7077
  );
6757
7078
  if (typeof raw.version !== "string" || raw.version.trim() === "") {
6758
7079
  throw new Error(
@@ -7310,7 +7631,7 @@ async function admitPublicRole(role, parsed, env, override) {
7310
7631
  resolutionScope: [...derived.resolutionScope],
7311
7632
  authorizedChecks: []
7312
7633
  });
7313
- const mergerInputPath = join10(placed.runDirectory, "merger-input.json");
7634
+ const mergerInputPath = join11(placed.runDirectory, "merger-input.json");
7314
7635
  await writeFile(
7315
7636
  mergerInputPath,
7316
7637
  `${JSON.stringify(mergerInput, null, 2)}
@@ -7592,7 +7913,7 @@ function parseDoctorIssueNumber(raw) {
7592
7913
  }
7593
7914
  async function resolveDoctorCaseRunsPath(options) {
7594
7915
  const ledgerHome = resolveActivationLedgerHome(options.home);
7595
- const defaultRuns = join10(
7916
+ const defaultRuns = join11(
7596
7917
  activationBookDirectory(ledgerHome, options.bookKey),
7597
7918
  String(options.issueNumber),
7598
7919
  "runs"
@@ -7665,11 +7986,11 @@ function parseAnalystCohortIssueToken(raw, flag) {
7665
7986
  `${flag} requires a comma-separated list of N or book:N`
7666
7987
  );
7667
7988
  }
7668
- const sep5 = trimmed.lastIndexOf(":");
7669
- if (sep5 > 0) {
7670
- const rhs = trimmed.slice(sep5 + 1);
7989
+ const sep6 = trimmed.lastIndexOf(":");
7990
+ if (sep6 > 0) {
7991
+ const rhs = trimmed.slice(sep6 + 1);
7671
7992
  if (parseTicketNumber(rhs) !== void 0) {
7672
- const bookKey = trimmed.slice(0, sep5);
7993
+ const bookKey = trimmed.slice(0, sep6);
7673
7994
  if (bookKey.trim() === "") {
7674
7995
  throw new CliUsageError(
7675
7996
  `${flag} book:N requires a non-empty book key, got ${raw}`
@@ -7866,6 +8187,7 @@ var init_invocation = __esm({
7866
8187
  init_activation_ledger_topology();
7867
8188
  init_activation_ledger_git();
7868
8189
  init_role_run_placement();
8190
+ init_ticket_progress();
7869
8191
  init_packaged_role_registry();
7870
8192
  init_run_ticket_number();
7871
8193
  init_role_run_relocation();
@@ -7888,7 +8210,7 @@ var init_invocation = __esm({
7888
8210
 
7889
8211
  // src/report-ticket-tool.ts
7890
8212
  import { Type as Type15 } from "typebox";
7891
- import { existsSync as existsSync3 } from "node:fs";
8213
+ import { existsSync as existsSync4 } from "node:fs";
7892
8214
  function pageString(page, key) {
7893
8215
  const value = page?.[key];
7894
8216
  return typeof value === "string" && value.trim() !== "" ? value : void 0;
@@ -7930,7 +8252,7 @@ async function reportTicketFromHostContext(context, rawTicketNumber, authority =
7930
8252
  if (runDirectory === void 0) {
7931
8253
  throw new Error("ak_report_ticket requires a per-turn run directory");
7932
8254
  }
7933
- if (!existsSync3(runDirectory)) {
8255
+ if (!existsSync4(runDirectory)) {
7934
8256
  throw new Error(`ak_report_ticket run directory missing: ${runDirectory}`);
7935
8257
  }
7936
8258
  const admitted = admittedForLiveTicketReport(runDirectory, authority);
@@ -7949,7 +8271,11 @@ async function reportTicketFromHostContext(context, rawTicketNumber, authority =
7949
8271
  context.sessionManager.setSessionFile?.(projectedSessionFile);
7950
8272
  }
7951
8273
  };
7952
- const relocation = alreadyPlaced ? void 0 : await relocateAdmittedRunToTicket(admitted, authority, { relocate: applyLiveHandles });
8274
+ const relocation = await relocateAdmittedRunToTicket(
8275
+ admitted,
8276
+ authority,
8277
+ alreadyPlaced ? void 0 : { relocate: applyLiveHandles }
8278
+ );
7953
8279
  const nextDirectory = relocation?.newRunDirectory ?? admitted.runDirectory;
7954
8280
  if (relocation === void 0) applyLiveHandles(nextDirectory);
7955
8281
  return {
@@ -8206,6 +8532,7 @@ async function sealAcceptedSubmission(options) {
8206
8532
  const attemptId = attemptIdentity(options.context, runId);
8207
8533
  const sessionParent = sessionParentFromHostContext(options.context);
8208
8534
  const home = homeFromHostContext(options.context, options.home);
8535
+ const sealHead = captureWorktreeHead(options.context.cwd);
8209
8536
  sitianReport({
8210
8537
  level: "event",
8211
8538
  kind: "sealed",
@@ -8222,6 +8549,12 @@ async function sealAcceptedSubmission(options) {
8222
8549
  ...home !== void 0 ? { home } : {},
8223
8550
  ...sessionParent === void 0 ? {} : { sessionParent }
8224
8551
  });
8552
+ landTicketProgressForSealedSubmission({
8553
+ context: options.context,
8554
+ role: options.role,
8555
+ accepted: options.accepted,
8556
+ sealHead
8557
+ });
8225
8558
  }
8226
8559
  function createSubmissionLedgerHost(host, outputTools, failInfrastructure2 = (error) => {
8227
8560
  throw error;
@@ -8346,6 +8679,7 @@ function createSubmissionLedgerHost(host, outputTools, failInfrastructure2 = (er
8346
8679
  kind: "accepted",
8347
8680
  accepted: params
8348
8681
  };
8682
+ const sealHead = captureWorktreeHead(context.cwd);
8349
8683
  append({
8350
8684
  type: "sealed",
8351
8685
  attemptId,
@@ -8353,6 +8687,14 @@ function createSubmissionLedgerHost(host, outputTools, failInfrastructure2 = (er
8353
8687
  role,
8354
8688
  accepted: params
8355
8689
  });
8690
+ const rawLens = typeof host.getFlag === "function" ? host.getFlag("ak-review-lens") : void 0;
8691
+ landTicketProgressForSealedSubmission({
8692
+ context,
8693
+ role,
8694
+ accepted: params,
8695
+ sealHead,
8696
+ ...rawLens === "completeness" || rawLens === "correctness" ? { lens: rawLens } : {}
8697
+ });
8356
8698
  await projectClosure(closed, context);
8357
8699
  return result;
8358
8700
  }
@@ -8374,6 +8716,7 @@ var init_submission_ledger = __esm({
8374
8716
  init_report_ticket_tool();
8375
8717
  init_review_submission();
8376
8718
  init_run_ticket_number();
8719
+ init_ticket_progress();
8377
8720
  init_unknown_value();
8378
8721
  }
8379
8722
  });
@@ -8560,7 +8903,7 @@ var init_engine_detour_usage = __esm({
8560
8903
  });
8561
8904
 
8562
8905
  // src/dossier-resolution.ts
8563
- import { existsSync as existsSync4, statSync as statSync4 } from "node:fs";
8906
+ import { existsSync as existsSync5, statSync as statSync4 } from "node:fs";
8564
8907
  import { resolve as resolve9 } from "node:path";
8565
8908
  function isHostContext(value) {
8566
8909
  return "sessionManager" in value;
@@ -8580,7 +8923,7 @@ function resolveAuditDossier(source) {
8580
8923
  }
8581
8924
  const runDirectory = resolve9(raw);
8582
8925
  try {
8583
- if (!existsSync4(runDirectory) || !statSync4(runDirectory).isDirectory()) {
8926
+ if (!existsSync5(runDirectory) || !statSync4(runDirectory).isDirectory()) {
8584
8927
  return { status: "incomplete", observation: { kind: "missing-dossier" } };
8585
8928
  }
8586
8929
  } catch {
@@ -9898,12 +10241,12 @@ var init_settlement = __esm({
9898
10241
  });
9899
10242
 
9900
10243
  // src/external-host-turn-loop.ts
9901
- import { existsSync as existsSync5 } from "node:fs";
9902
- import { basename as basename8 } from "node:path";
10244
+ import { existsSync as existsSync6 } from "node:fs";
10245
+ import { basename as basename9 } from "node:path";
9903
10246
  async function syncTurnRequestLivePlacement(request, authority) {
9904
10247
  const live = await resolveLiveRunDirectoryPath(request.runDirectory, request.home);
9905
10248
  if (live === void 0) {
9906
- const parsed = parseRunLeaf(basename8(request.runDirectory));
10249
+ const parsed = parseRunLeaf(basename9(request.runDirectory));
9907
10250
  throw new Error(
9908
10251
  `admitted run ${parsed?.runId ?? "(unparseable)"} missing after host turn; not found under ${request.home}`
9909
10252
  );
@@ -9922,7 +10265,7 @@ async function trySyncTurnRequestLivePlacement(request, authority) {
9922
10265
  }
9923
10266
  async function retainPackageFaultBesideLivePlacement(request, input) {
9924
10267
  let runDirectory = request.runDirectory;
9925
- if (!existsSync5(runDirectory)) {
10268
+ if (!existsSync6(runDirectory)) {
9926
10269
  try {
9927
10270
  const found = await resolveLiveRunDirectoryPath(request.runDirectory, request.home);
9928
10271
  if (found === void 0) {
@@ -10093,6 +10436,7 @@ async function driveExternalRoleTurnRounds(prepared, request, driver) {
10093
10436
  }
10094
10437
  }
10095
10438
  prompt = closure.retry.message;
10439
+ prepared.recordSentInstruction?.(prompt);
10096
10440
  driver.afterRetry?.();
10097
10441
  }
10098
10442
  }
@@ -10135,9 +10479,9 @@ var init_external_host_turn_loop = __esm({
10135
10479
  });
10136
10480
 
10137
10481
  // src/session-identity.ts
10138
- import { dirname as dirname9, join as join11 } from "node:path";
10482
+ import { join as join12 } from "node:path";
10139
10483
  function createSessionIdentityAuthority(authority, hostName) {
10140
- const runDirectoryOf = (principal) => dirname9(authority.decode(principal).sessionDirectory);
10484
+ const runDirectoryOf = (principal) => runDirectoryFromSessionDirectory(authority.decode(principal).sessionDirectory);
10141
10485
  return {
10142
10486
  principalAuthority: authority,
10143
10487
  resolveSessionFile(principal) {
@@ -10145,7 +10489,7 @@ function createSessionIdentityAuthority(authority, hostName) {
10145
10489
  },
10146
10490
  async load(principal) {
10147
10491
  const runDirectory = runDirectoryOf(principal);
10148
- const { records, diagnostics } = await readSitianRecords(join11(runDirectory, RUN_STATE_FILE));
10492
+ const { records, diagnostics } = await readSitianRecords(join12(runDirectory, RUN_STATE_FILE));
10149
10493
  if (diagnostics.length > 0) {
10150
10494
  throw new Error(
10151
10495
  `${RUN_STATE_FILE} has ${diagnostics.length} malformed row(s); refusing stale session binding: ${runDirectory}`
@@ -10192,6 +10536,7 @@ var init_session_identity = __esm({
10192
10536
  "src/session-identity.ts"() {
10193
10537
  "use strict";
10194
10538
  init_host_descriptions();
10539
+ init_role_run_placement();
10195
10540
  init_run_dossier();
10196
10541
  init_sitian_facade();
10197
10542
  init_unknown_value();
@@ -10214,14 +10559,14 @@ __export(role_turn_host_exports, {
10214
10559
  });
10215
10560
  import { execFile as execFile2, spawn as spawn2 } from "node:child_process";
10216
10561
  import { constants } from "node:fs";
10217
- import { existsSync as existsSync6 } from "node:fs";
10562
+ import { existsSync as existsSync7 } from "node:fs";
10218
10563
  import { access as access2, appendFile, realpath as realpath4 } from "node:fs/promises";
10219
- import { delimiter, dirname as dirname10, isAbsolute as isAbsolute6, join as join12, resolve as resolve11 } from "node:path";
10564
+ import { delimiter, dirname as dirname10, isAbsolute as isAbsolute6, join as join13, resolve as resolve11 } from "node:path";
10220
10565
  import { platform } from "node:process";
10221
10566
  import { promisify as promisify2 } from "node:util";
10222
10567
  import { randomUUID as randomUUID4 } from "node:crypto";
10223
10568
  function resolveInternalRoleEntrypoint(packageRoot) {
10224
- return join12(packageRoot, INTERNAL_ROLE_ENTRYPOINT_RELATIVE2);
10569
+ return join13(packageRoot, INTERNAL_ROLE_ENTRYPOINT_RELATIVE2);
10225
10570
  }
10226
10571
  function buildExplicitInternalActivationArgs(selectedRoleEntry, extraArgs = []) {
10227
10572
  return ["--no-extensions", "-e", selectedRoleEntry, ...extraArgs];
@@ -10411,7 +10756,7 @@ function createDefaultPiSpawnRunner(options) {
10411
10756
  homeFromRunDirectory(spawnDir)
10412
10757
  );
10413
10758
  } catch (resolveError) {
10414
- runDirectory = existsSync6(spawnDir) ? spawnDir : void 0;
10759
+ runDirectory = existsSync7(spawnDir) ? spawnDir : void 0;
10415
10760
  const resolveDiagnostic = `live run path resolve failed beside Pi transport fault: ${describeErrorIdentity(resolveError)}`;
10416
10761
  if (runDirectory !== void 0) {
10417
10762
  await retainPackageFault({
@@ -10464,7 +10809,8 @@ function createPiRoleTurnHost(config) {
10464
10809
  config.extraPiArgs ?? []
10465
10810
  );
10466
10811
  const args = buildExplicitInternalActivationArgs(roleEntry, extraArgs);
10467
- const stdin = encodeUserDialogueStdin(piUserDialogueBody(turnRequest));
10812
+ const transportBody = piUserDialogueBody(turnRequest);
10813
+ const stdin = encodeUserDialogueStdin(transportBody);
10468
10814
  const env = {
10469
10815
  ...process.env,
10470
10816
  HOME: request.home,
@@ -10480,6 +10826,7 @@ function createPiRoleTurnHost(config) {
10480
10826
  else env.AK_ROLE_INVOCATION_SCOPE = request.invocationScopeId;
10481
10827
  if (request.host === void 0 || request.host.trim() === "") delete env.AK_ROLE_HOST;
10482
10828
  else env.AK_ROLE_HOST = request.host.trim();
10829
+ delete env.AK_ROLE_SUMMONS_INSTRUCTION;
10483
10830
  if (request.deliveryRequestLimit === void 0) delete env[RECEIPT_DELIVERY_LIMIT_ENV];
10484
10831
  else env[RECEIPT_DELIVERY_LIMIT_ENV] = String(request.deliveryRequestLimit);
10485
10832
  applyEngineChildEnv(env, request.engine);
@@ -10612,8 +10959,8 @@ var init_role_turn_host = __esm({
10612
10959
  });
10613
10960
 
10614
10961
  // src/package-resources/engine-material.ts
10615
- import { existsSync as existsSync7, readdirSync as readdirSync2, readFileSync as readFileSync2 } from "node:fs";
10616
- import { join as join13 } from "node:path";
10962
+ import { existsSync as existsSync8, readdirSync as readdirSync3, readFileSync as readFileSync3 } from "node:fs";
10963
+ import { join as join14 } from "node:path";
10617
10964
  function pickEngineAxis(source) {
10618
10965
  return {
10619
10966
  ...source.engine === void 0 ? {} : { engine: source.engine },
@@ -10634,14 +10981,14 @@ function isEngineNameSyntax(name) {
10634
10981
  return true;
10635
10982
  }
10636
10983
  function resolveEngineMaterialDirectory(packageRoot) {
10637
- return join13(packageRoot, ENGINE_MATERIAL_RELATIVE_ROOT);
10984
+ return join14(packageRoot, ENGINE_MATERIAL_RELATIVE_ROOT);
10638
10985
  }
10639
10986
  function resolveEngineDispatchMaterialPath(packageRoot) {
10640
- return join13(packageRoot, ENGINE_DISPATCH_RELATIVE_PATH);
10987
+ return join14(packageRoot, ENGINE_DISPATCH_RELATIVE_PATH);
10641
10988
  }
10642
10989
  function resolveEngineMaterialPath(packageRoot, name) {
10643
10990
  const legal = assertLegalEngineName(name);
10644
- return join13(resolveEngineMaterialDirectory(packageRoot), `${legal}.md`);
10991
+ return join14(resolveEngineMaterialDirectory(packageRoot), `${legal}.md`);
10645
10992
  }
10646
10993
  function assertLegalEngineName(name) {
10647
10994
  if (!isEngineNameSyntax(name)) {
@@ -10658,12 +11005,12 @@ function engineSessionMaterialFromOptions(options) {
10658
11005
  const model = options.engineModel === void 0 ? void 0 : assertLegalEngineModel(options.engineModel);
10659
11006
  const materialPath = resolveEngineMaterialPath(options.packageRoot, name);
10660
11007
  const modelField = model === void 0 ? {} : { model };
10661
- if (!existsSync7(materialPath)) {
11008
+ if (!existsSync8(materialPath)) {
10662
11009
  return Object.freeze({ name, ...modelField });
10663
11010
  }
10664
- const handbook = readFileSync2(materialPath, "utf8");
11011
+ const handbook = readFileSync3(materialPath, "utf8");
10665
11012
  const dispatchPath = resolveEngineDispatchMaterialPath(options.packageRoot);
10666
- const dispatchField = existsSync7(dispatchPath) ? { dispatchHandbook: readFileSync2(dispatchPath, "utf8") } : {};
11013
+ const dispatchField = existsSync8(dispatchPath) ? { dispatchHandbook: readFileSync3(dispatchPath, "utf8") } : {};
10667
11014
  return Object.freeze({ name, handbook, ...dispatchField, ...modelField });
10668
11015
  }
10669
11016
  function engineSessionReadingMaterial(engineMaterial) {
@@ -10740,7 +11087,7 @@ __export(config_exports, {
10740
11087
  validatePublicCliConfigAxes: () => validatePublicCliConfigAxes
10741
11088
  });
10742
11089
  import { mkdir, readFile as readFile8, writeFile as writeFile2 } from "node:fs/promises";
10743
- import { dirname as dirname11, join as join14 } from "node:path";
11090
+ import { dirname as dirname11, join as join15 } from "node:path";
10744
11091
  function isGateOfficerSeat(value) {
10745
11092
  return packagedProvinceConfig(value);
10746
11093
  }
@@ -10748,7 +11095,7 @@ function publicCliConfigPath(home) {
10748
11095
  if (typeof home !== "string" || home.trim() === "") {
10749
11096
  throw new Error("home must be explicitly provided");
10750
11097
  }
10751
- return join14(home, ".ak-roles", "public-cli.json");
11098
+ return join15(home, ".ak-roles", "public-cli.json");
10752
11099
  }
10753
11100
  async function loadPublicCliConfig(home) {
10754
11101
  const path = publicCliConfigPath(home);
@@ -11208,11 +11555,11 @@ function credentialProvidersFromAuthData(data) {
11208
11555
  };
11209
11556
  }
11210
11557
  function resolvePublicAgentDir(explicit, home) {
11211
- return explicit ?? process.env.PI_CODING_AGENT_DIR ?? join14(home, ".pi", "agent");
11558
+ return explicit ?? process.env.PI_CODING_AGENT_DIR ?? join15(home, ".pi", "agent");
11212
11559
  }
11213
11560
  async function loadCredentialProviders(agentDir) {
11214
11561
  try {
11215
- const raw = await readFile8(join14(agentDir, "auth.json"), "utf8");
11562
+ const raw = await readFile8(join15(agentDir, "auth.json"), "utf8");
11216
11563
  return credentialProvidersFromAuthData(JSON.parse(raw));
11217
11564
  } catch (error) {
11218
11565
  if (isEnoent(error)) return { "openai-codex": false, xai: false };
@@ -11236,16 +11583,16 @@ var init_config = __esm({
11236
11583
  });
11237
11584
 
11238
11585
  // src/public-cli/host-providers.ts
11239
- import { readFileSync as readFileSync3 } from "node:fs";
11240
- import { join as join15 } from "node:path";
11586
+ import { readFileSync as readFileSync4 } from "node:fs";
11587
+ import { join as join16 } from "node:path";
11241
11588
  function hostProvidersPath(home) {
11242
11589
  if (typeof home !== "string" || home.trim() === "") {
11243
11590
  throw new Error("home must be explicitly provided");
11244
11591
  }
11245
- return join15(home, ".ak-roles", "host-providers.json");
11592
+ return join16(home, ".ak-roles", "host-providers.json");
11246
11593
  }
11247
11594
  function hermesProviderModelsCachePath(home) {
11248
- return join15(home, ".hermes", "provider_models_cache.json");
11595
+ return join16(home, ".hermes", "provider_models_cache.json");
11249
11596
  }
11250
11597
  function parseHostProvidersTable(value) {
11251
11598
  if (!isRecord(value)) {
@@ -11282,7 +11629,7 @@ function parseHostProvidersTable(value) {
11282
11629
  function loadHostProvidersTable(home) {
11283
11630
  const path = hostProvidersPath(home);
11284
11631
  try {
11285
- const raw = readFileSync3(path, "utf8");
11632
+ const raw = readFileSync4(path, "utf8");
11286
11633
  return parseHostProvidersTable(JSON.parse(raw));
11287
11634
  } catch (error) {
11288
11635
  if (isEnoent(error)) return {};
@@ -11298,7 +11645,7 @@ function listHermesProvidersForModel(home, seatModel) {
11298
11645
  const path = hermesProviderModelsCachePath(home);
11299
11646
  let text;
11300
11647
  try {
11301
- text = readFileSync3(path, "utf8");
11648
+ text = readFileSync4(path, "utf8");
11302
11649
  } catch (error) {
11303
11650
  if (isEnoent(error)) return [];
11304
11651
  throw error;
@@ -11395,17 +11742,17 @@ var init_host_providers = __esm({
11395
11742
  });
11396
11743
 
11397
11744
  // src/public-cli/load-production-acp-host.ts
11398
- import { existsSync as existsSync8 } from "node:fs";
11399
- import { join as join16 } from "node:path";
11745
+ import { existsSync as existsSync9 } from "node:fs";
11746
+ import { join as join17 } from "node:path";
11400
11747
  import { pathToFileURL } from "node:url";
11401
11748
  async function loadProductionAcpHostFactory(packageRoot, host) {
11402
11749
  const description = lookupHostDescription(host);
11403
11750
  if (description === void 0) {
11404
11751
  throw new Error(`unregistered host: ${host}`);
11405
11752
  }
11406
- const built = join16(packageRoot, "dist/acp-host/production-host.js");
11407
- const source = join16(packageRoot, "src/acp-host/production-host.ts");
11408
- const target = existsSync8(built) ? built : source;
11753
+ const built = join17(packageRoot, "dist/acp-host/production-host.js");
11754
+ const source = join17(packageRoot, "src/acp-host/production-host.ts");
11755
+ const target = existsSync9(built) ? built : source;
11409
11756
  const href = pathToFileURL(target).href;
11410
11757
  const mod = await import(href);
11411
11758
  const create = mod.createProductionAcpRoleTurnHost;
@@ -11419,17 +11766,17 @@ var init_load_production_acp_host = __esm({
11419
11766
  });
11420
11767
 
11421
11768
  // src/public-cli/load-production-headless-host.ts
11422
- import { existsSync as existsSync9 } from "node:fs";
11423
- import { join as join17 } from "node:path";
11769
+ import { existsSync as existsSync10 } from "node:fs";
11770
+ import { join as join18 } from "node:path";
11424
11771
  import { pathToFileURL as pathToFileURL2 } from "node:url";
11425
11772
  async function loadProductionHeadlessHostFactory(packageRoot, host) {
11426
11773
  const description = lookupHeadlessHostDescription(host);
11427
11774
  if (description === void 0) {
11428
11775
  throw new Error(`unregistered headless host: ${host}`);
11429
11776
  }
11430
- const built = join17(packageRoot, "dist/headless-host/production-host.js");
11431
- const source = join17(packageRoot, "src/headless-host/production-host.ts");
11432
- const target = existsSync9(built) ? built : source;
11777
+ const built = join18(packageRoot, "dist/headless-host/production-host.js");
11778
+ const source = join18(packageRoot, "src/headless-host/production-host.ts");
11779
+ const target = existsSync10(built) ? built : source;
11433
11780
  const href = pathToFileURL2(target).href;
11434
11781
  const mod = await import(href);
11435
11782
  const create = mod.createProductionHeadlessRoleTurnHost;
@@ -11596,14 +11943,14 @@ var init_role_seat_runtime = __esm({
11596
11943
  });
11597
11944
 
11598
11945
  // src/session-opening-materials.ts
11599
- import { existsSync as existsSync10 } from "node:fs";
11946
+ import { existsSync as existsSync11 } from "node:fs";
11600
11947
  import { readFile as readFile9 } from "node:fs/promises";
11601
- import { dirname as dirname12, join as join18 } from "node:path";
11948
+ import { dirname as dirname12, join as join19 } from "node:path";
11602
11949
  import { fileURLToPath, pathToFileURL as pathToFileURL3 } from "node:url";
11603
11950
  function resolvePackageRootDir(moduleUrl = import.meta.url) {
11604
11951
  let dir = dirname12(fileURLToPath(moduleUrl));
11605
11952
  for (let i = 0; i < 8; i += 1) {
11606
- if (existsSync10(join18(dir, "package.json")) && existsSync10(join18(dir, "souls"))) {
11953
+ if (existsSync11(join19(dir, "package.json")) && existsSync11(join19(dir, "souls"))) {
11607
11954
  return dir;
11608
11955
  }
11609
11956
  const parent = dirname12(dir);
@@ -11963,7 +12310,7 @@ __export(auditor_soul_exports, {
11963
12310
  readAuditorResumeBinding: () => readAuditorResumeBinding,
11964
12311
  resolveAuditorSubject: () => resolveAuditorSubject
11965
12312
  });
11966
- import { basename as basename9 } from "node:path";
12313
+ import { basename as basename10 } from "node:path";
11967
12314
  function auditorSoulRelativePath(role) {
11968
12315
  return `souls/${role}-auditor.md`;
11969
12316
  }
@@ -11999,7 +12346,7 @@ function loadAuditorReferenceMaterialsFromSubjectInput(raw) {
11999
12346
  return loadAuditorReferenceMaterials(resolveAuditorSubject(raw));
12000
12347
  }
12001
12348
  function subjectFromSourceDirectory(sourceRunDirectory) {
12002
- const role = parseRunLeaf(basename9(sourceRunDirectory))?.role;
12349
+ const role = parseRunLeaf(basename10(sourceRunDirectory))?.role;
12003
12350
  return isAuditorSoulRole(role) ? role : void 0;
12004
12351
  }
12005
12352
  async function readAuditorResumeBinding(admitted) {
@@ -12042,16 +12389,16 @@ var init_auditor_soul = __esm({
12042
12389
  // src/public-cli/machine-method-skills.ts
12043
12390
  import { accessSync, constants as constants2, statSync as statSync5 } from "node:fs";
12044
12391
  import { lstat as lstat2, mkdir as mkdir2, symlink } from "node:fs/promises";
12045
- import { join as join20 } from "node:path";
12046
- import { spawnSync as spawnSync2 } from "node:child_process";
12392
+ import { join as join21 } from "node:path";
12393
+ import { spawnSync as spawnSync3 } from "node:child_process";
12047
12394
  function skillRoot(home) {
12048
- return join20(home, ".agents/skills");
12395
+ return join21(home, ".agents/skills");
12049
12396
  }
12050
12397
  function installedMethodSkillPath(home, name) {
12051
12398
  return installedSkillPath(skillRoot(home), name);
12052
12399
  }
12053
12400
  function installedSkillPath(root, name) {
12054
- const path = join20(root, name, "SKILL.md");
12401
+ const path = join21(root, name, "SKILL.md");
12055
12402
  try {
12056
12403
  if (!statSync5(path).isFile()) return void 0;
12057
12404
  accessSync(path, constants2.R_OK);
@@ -12064,9 +12411,9 @@ function installedSkillPath(root, name) {
12064
12411
  }
12065
12412
  function linkedSkillRoot(home, host) {
12066
12413
  if (host === "claude" || host === "claude-code") {
12067
- return join20(process.env.CLAUDE_CONFIG_DIR?.trim() || join20(home, ".claude"), "skills");
12414
+ return join21(process.env.CLAUDE_CONFIG_DIR?.trim() || join21(home, ".claude"), "skills");
12068
12415
  }
12069
- if (host === "hermes") return join20(home, ".hermes/skills");
12416
+ if (host === "hermes") return join21(home, ".hermes/skills");
12070
12417
  return void 0;
12071
12418
  }
12072
12419
  async function occupied(path) {
@@ -12094,7 +12441,7 @@ async function warnMissingMethodSkills(home, host, role, skills, stdout) {
12094
12441
  }
12095
12442
  }
12096
12443
  function runSkillsCli(args, home) {
12097
- const result = spawnSync2("npx", ["--yes", "skills", ...args], {
12444
+ const result = spawnSync3("npx", ["--yes", "skills", ...args], {
12098
12445
  stdio: "inherit",
12099
12446
  env: { ...process.env, HOME: home }
12100
12447
  });
@@ -12123,7 +12470,7 @@ async function runMachineSkillSetup(home, stdout) {
12123
12470
  const missingBySource = /* @__PURE__ */ new Map();
12124
12471
  let unsourced = false;
12125
12472
  for (const name of packagedMethodSkillNames()) {
12126
- const path = join20(canonical, name);
12473
+ const path = join21(canonical, name);
12127
12474
  if (await occupied(path)) {
12128
12475
  warnOccupied(path, stdout);
12129
12476
  continue;
@@ -12153,9 +12500,9 @@ async function runMachineSkillSetup(home, stdout) {
12153
12500
  throw error;
12154
12501
  }
12155
12502
  for (const name of packagedMethodSkillNames()) {
12156
- const target = join20(canonical, name);
12503
+ const target = join21(canonical, name);
12157
12504
  if (installedMethodSkillPath(home, name) === void 0) continue;
12158
- const link = join20(root, name);
12505
+ const link = join21(root, name);
12159
12506
  if (await occupied(link)) {
12160
12507
  warnOccupied(link, stdout);
12161
12508
  continue;
@@ -12215,7 +12562,8 @@ function projectRoleTurnRequest(admitted, roleDetails, options) {
12215
12562
  ...options.invocationScopeId === void 0 || options.invocationScopeId.length === 0 ? {} : { invocationScopeId: options.invocationScopeId },
12216
12563
  ...options.stationChild === void 0 ? {} : { stationChild: options.stationChild },
12217
12564
  ...options.navigatorByStatusPrepare === void 0 ? {} : { navigatorByStatusPrepare: options.navigatorByStatusPrepare },
12218
- ...options.deliveryRequestLimit === void 0 ? {} : { deliveryRequestLimit: options.deliveryRequestLimit }
12565
+ ...options.deliveryRequestLimit === void 0 ? {} : { deliveryRequestLimit: options.deliveryRequestLimit },
12566
+ ...options.host === void 0 || options.host.trim() === "" ? {} : { host: options.host.trim() }
12219
12567
  };
12220
12568
  }
12221
12569
  function packagedSettleSkill(admitted) {
@@ -14183,7 +14531,7 @@ async function resolveReviewSeatDialogueBody(input) {
14183
14531
  if (sourceRunPath === void 0) return void 0;
14184
14532
  return await loadLedgerPeerBody(sourceRunPath, input.projectRoot, input.home);
14185
14533
  }
14186
- async function resolveInitialPrompt(admitted, env) {
14534
+ async function resolveInitialTurnPrompt(admitted, env) {
14187
14535
  const record = roleRecord(admitted.role);
14188
14536
  if ("reaskPrompt" in record && record.reaskPrompt === true) {
14189
14537
  const sourceRunPath = admittedSourceRunPath(admitted);
@@ -14280,7 +14628,7 @@ async function dispatchAdmitted(admitted, env, io) {
14280
14628
  if (activeEnv.correlationId !== void 0 && activeEnv.correlationId.trim() !== "") {
14281
14629
  await recordAdmittedCorrelation(admitted, activeEnv.correlationId);
14282
14630
  }
14283
- const initialPromptText = await resolveInitialPrompt(admitted, activeEnv);
14631
+ const initialPrompt = await resolveInitialTurnPrompt(admitted, activeEnv);
14284
14632
  const auto = "inCallAutoResume" in record && record.inCallAutoResume === true;
14285
14633
  if (auto) {
14286
14634
  return await runPostAdmissionResumable({
@@ -14291,14 +14639,14 @@ async function dispatchAdmitted(admitted, env, io) {
14291
14639
  admitted,
14292
14640
  roleTurnOptions(activeEnv, admitted, {
14293
14641
  kind: "initial",
14294
- prompt: initialPromptText
14642
+ prompt: initialPrompt
14295
14643
  })
14296
14644
  ),
14297
14645
  buildResumeRequest: () => buildInstructionSeatTurnRequest(
14298
14646
  admitted,
14299
14647
  roleTurnOptions(activeEnv, admitted, {
14300
14648
  kind: "resume",
14301
- prompt: initialPromptText
14649
+ prompt: initialPrompt
14302
14650
  })
14303
14651
  ),
14304
14652
  adapters,
@@ -14313,7 +14661,7 @@ async function dispatchAdmitted(admitted, env, io) {
14313
14661
  admitted,
14314
14662
  roleTurnOptions(activeEnv, admitted, {
14315
14663
  kind: "initial",
14316
- prompt: initialPromptText
14664
+ prompt: initialPrompt
14317
14665
  })
14318
14666
  ),
14319
14667
  adapters,
@@ -14489,7 +14837,7 @@ async function runCountersignBody(parsed, env, io) {
14489
14837
  }
14490
14838
  const turnProjection = roleTurnOptions(env, admitted, {
14491
14839
  kind: "initial",
14492
- prompt: await resolveInitialPrompt(admitted, env)
14840
+ prompt: await resolveInitialTurnPrompt(admitted, env)
14493
14841
  });
14494
14842
  const turnRequest = buildInstructionSeatTurnRequest(admitted, turnProjection);
14495
14843
  const result = await runPostAdmissionOneShot({
@@ -15372,10 +15720,10 @@ var init_analyst_book_key = __esm({
15372
15720
  // src/atomic-write.ts
15373
15721
  import { randomUUID as randomUUID6 } from "node:crypto";
15374
15722
  import { rename as rename2, rm, writeFile as writeFile3 } from "node:fs/promises";
15375
- import { dirname as dirname14, join as join21 } from "node:path";
15723
+ import { dirname as dirname14, join as join22 } from "node:path";
15376
15724
  async function writeFileAtomically(destination, contents, options) {
15377
15725
  const parent = dirname14(destination);
15378
- const temporary = join21(parent, `.atomic-write-${randomUUID6()}.tmp`);
15726
+ const temporary = join22(parent, `.atomic-write-${randomUUID6()}.tmp`);
15379
15727
  try {
15380
15728
  await writeFile3(temporary, contents, options);
15381
15729
  await rename2(temporary, destination);
@@ -15392,12 +15740,12 @@ var init_atomic_write = __esm({
15392
15740
 
15393
15741
  // src/analyst-index.ts
15394
15742
  import { open, readFile as readFile10, unlink } from "node:fs/promises";
15395
- import { dirname as dirname15, join as join22 } from "node:path";
15743
+ import { dirname as dirname15, join as join23 } from "node:path";
15396
15744
  import { setTimeout as sleep } from "node:timers/promises";
15397
15745
  async function withAnalystLibraryIndexLock(ledgerHome, fn) {
15398
15746
  const indexPath = analystLibraryIndexPath(ledgerHome);
15399
15747
  ensureRealDirectoryTree(ledgerHome, dirname15(indexPath));
15400
- const lockPath = join22(dirname15(indexPath), LIBRARY_INDEX_LOCK_NAME);
15748
+ const lockPath = join23(dirname15(indexPath), LIBRARY_INDEX_LOCK_NAME);
15401
15749
  assertLedgerFileInsideHome(lockPath, ledgerHome);
15402
15750
  const startedAt = Date.now();
15403
15751
  while (true) {
@@ -15424,7 +15772,7 @@ async function withAnalystLibraryIndexLock(ledgerHome, fn) {
15424
15772
  }
15425
15773
  }
15426
15774
  function analystLibraryIndexPath(ledgerHome) {
15427
- return join22(ledgerHome, "analyst", "library-index.json");
15775
+ return join23(ledgerHome, "analyst", "library-index.json");
15428
15776
  }
15429
15777
  function rowFromIssueMetricsPage(page) {
15430
15778
  return {
@@ -15718,7 +16066,7 @@ var init_analyst_cohort = __esm({
15718
16066
  });
15719
16067
 
15720
16068
  // src/archivist-record-pointer.ts
15721
- import { basename as basename10, join as join23 } from "node:path";
16069
+ import { basename as basename11, join as join24 } from "node:path";
15722
16070
  async function resolveOfficerPointer(raw, parentRunDirectory) {
15723
16071
  const where = `${parentRunDirectory} officers`;
15724
16072
  if (!isRecord(raw) || raw.kind !== DIRECT_OFFICER_RUN_POINTER_KIND || raw.version !== 1) {
@@ -15731,7 +16079,7 @@ async function resolveOfficerPointer(raw, parentRunDirectory) {
15731
16079
  let runDirectory = typeof raw.runDirectory === "string" && raw.runDirectory.trim() !== "" ? raw.runDirectory : void 0;
15732
16080
  let sessionFile = raw.sessionFile;
15733
16081
  const recordedRunDirectory = runDirectory ?? runDirectoryOfSessionFile(sessionFile);
15734
- const leaf = parseRunLeaf(basename10(recordedRunDirectory));
16082
+ const leaf = parseRunLeaf(basename11(recordedRunDirectory));
15735
16083
  const parentIdentity = await readRoleRunIdentity(parentRunDirectory);
15736
16084
  if (leaf !== void 0 && parentIdentity !== void 0) {
15737
16085
  const currentRunDirectory = await resolveLiveRunDirectoryPath(
@@ -15751,7 +16099,7 @@ async function resolveOfficerPointer(raw, parentRunDirectory) {
15751
16099
  };
15752
16100
  }
15753
16101
  async function readBookedOfficerPointers(parentRunDirectory) {
15754
- const { records, diagnostics } = await readSitianRecords(join23(parentRunDirectory, RUN_HISTORY_FILE));
16102
+ const { records, diagnostics } = await readSitianRecords(join24(parentRunDirectory, RUN_HISTORY_FILE));
15755
16103
  if (diagnostics.length > 0) {
15756
16104
  throw new Error(
15757
16105
  `${RUN_HISTORY_FILE} has ${diagnostics.length} malformed row(s); officer pointers unreadable: ${parentRunDirectory}`
@@ -16034,7 +16382,7 @@ var init_analyst_gate_cycles_read = __esm({
16034
16382
 
16035
16383
  // src/analyst-ledger.ts
16036
16384
  import { readdir as readdir3 } from "node:fs/promises";
16037
- import { basename as basename11, join as join24 } from "node:path";
16385
+ import { basename as basename12, join as join25 } from "node:path";
16038
16386
  async function readExistingRunLifecycleState(runDirectory) {
16039
16387
  return (await readRoleRunIdentity(runDirectory))?.state;
16040
16388
  }
@@ -16054,7 +16402,7 @@ function ghostLeaseCheckFromAutopsy(autopsy) {
16054
16402
  }
16055
16403
  }
16056
16404
  async function classifyGhostCandidate(input) {
16057
- const autopsy = await autopsyWriterLock(join24(input.runDirectory, "writer.lock"));
16405
+ const autopsy = await autopsyWriterLock(join25(input.runDirectory, "writer.lock"));
16058
16406
  const leaseCheck = ghostLeaseCheckFromAutopsy(autopsy);
16059
16407
  if (leaseCheck === void 0) return { kind: "live" };
16060
16408
  return {
@@ -16344,7 +16692,7 @@ async function classifyScopedRun(input) {
16344
16692
  async function scanAnalystIssueRuns(input) {
16345
16693
  const ledgerHome = resolveActivationLedgerHome(input.home);
16346
16694
  const scopeTicketNumber = input.ticketNumber;
16347
- const booksRoot = join24(ledgerHome, "books");
16695
+ const booksRoot = join25(ledgerHome, "books");
16348
16696
  let wholeBook = false;
16349
16697
  let scopeRootIdentity;
16350
16698
  let bookNames;
@@ -16377,7 +16725,7 @@ async function scanAnalystIssueRuns(input) {
16377
16725
  const ghostLegs = [];
16378
16726
  const scopeConflicts = [];
16379
16727
  for (const book of bookNames) {
16380
- const bookDir = join24(booksRoot, book);
16728
+ const bookDir = join25(booksRoot, book);
16381
16729
  let runDirectories;
16382
16730
  try {
16383
16731
  runDirectories = await listBookRunDirectories(bookDir);
@@ -16386,7 +16734,7 @@ async function scanAnalystIssueRuns(input) {
16386
16734
  throw error;
16387
16735
  }
16388
16736
  for (const runDirectory of runDirectories) {
16389
- const runName = basename11(runDirectory);
16737
+ const runName = basename12(runDirectory);
16390
16738
  const parsed = parseRunLeaf(runName);
16391
16739
  if (parsed === void 0) continue;
16392
16740
  let scopeFields;
@@ -17123,7 +17471,7 @@ var init_analyst_metric_family = __esm({
17123
17471
  });
17124
17472
 
17125
17473
  // src/analyst-page.ts
17126
- import { dirname as dirname16, join as join25 } from "node:path";
17474
+ import { dirname as dirname16, join as join26 } from "node:path";
17127
17475
  function analystIssuePageKey(address) {
17128
17476
  const parts = ["book", address.bookKey];
17129
17477
  if (address.issueNumber !== void 0) {
@@ -17134,7 +17482,7 @@ function analystIssuePageKey(address) {
17134
17482
  return sha256Hex(parts.join("\0")).slice(0, 32);
17135
17483
  }
17136
17484
  function analystIssuePagePath(ledgerHome, address) {
17137
- return join25(ledgerHome, "analyst", "issues", `${analystIssuePageKey(address)}.json`);
17485
+ return join26(ledgerHome, "analyst", "issues", `${analystIssuePageKey(address)}.json`);
17138
17486
  }
17139
17487
  function analystIssuePageAddressFromPage(page) {
17140
17488
  return {
@@ -18690,9 +19038,9 @@ __export(public_role_summons_exports, {
18690
19038
  summonPublicRole: () => summonPublicRole
18691
19039
  });
18692
19040
  import { execFile as execFile3 } from "node:child_process";
18693
- import { existsSync as existsSync11 } from "node:fs";
19041
+ import { existsSync as existsSync12 } from "node:fs";
18694
19042
  import { realpath as realpath6 } from "node:fs/promises";
18695
- import { join as join26 } from "node:path";
19043
+ import { join as join27 } from "node:path";
18696
19044
  import { promisify as promisify3 } from "node:util";
18697
19045
  function createCapturingIo() {
18698
19046
  const chunks = [];
@@ -18716,7 +19064,7 @@ function parentDir(path) {
18716
19064
  function walkPackageRoot(start) {
18717
19065
  let dir = start;
18718
19066
  for (let i = 0; i < 12; i += 1) {
18719
- if (existsSync11(join26(dir, "package.json")) && existsSync11(join26(dir, "souls"))) {
19067
+ if (existsSync12(join27(dir, "package.json")) && existsSync12(join27(dir, "souls"))) {
18720
19068
  return dir;
18721
19069
  }
18722
19070
  const parent = parentDir(dir);
@@ -19264,7 +19612,7 @@ var init_compliance_transport = __esm({
19264
19612
  });
19265
19613
 
19266
19614
  // src/role-run-relocation.ts
19267
- import { dirname as dirname17, join as join27 } from "node:path";
19615
+ import { dirname as dirname17, join as join28 } from "node:path";
19268
19616
  async function retainedRunPathsMatch(recordedPath, currentPath, currentRunDirectory) {
19269
19617
  if (recordedPath === currentPath) return true;
19270
19618
  if (typeof recordedPath !== "string") return false;
@@ -19330,9 +19678,9 @@ __export(run_lifecycle_exports, {
19330
19678
  resolveLiveRunDirectoryPath: () => resolveLiveRunDirectoryPath,
19331
19679
  writeRoleRunState: () => writeRoleRunState
19332
19680
  });
19333
- import { existsSync as existsSync12 } from "node:fs";
19681
+ import { existsSync as existsSync13 } from "node:fs";
19334
19682
  import { chmod, lstat as lstat3, open as open2, readdir as readdir4, readFile as readFile14, unlink as unlink2 } from "node:fs/promises";
19335
- import { basename as basename12, join as join28 } from "node:path";
19683
+ import { basename as basename13, join as join29 } from "node:path";
19336
19684
  async function writeRoleRunState(runDirectory, record) {
19337
19685
  const payload = { ...record, runDirectory };
19338
19686
  writeSectionSync(runDirectory, "runState", { ...payload });
@@ -19414,13 +19762,14 @@ async function readRoleRunStateDisk(runDirectory) {
19414
19762
  if (typeof record.sessionDirectory !== "string") throw new TypeError("Invalid state.jsonl run-state");
19415
19763
  const storedRunDirectory = typeof record.runDirectory === "string" && record.runDirectory.trim() !== "" ? record.runDirectory : runDirectory;
19416
19764
  const runDir = runDirectory;
19765
+ const principalCoords = {
19766
+ sessionDirectory: record.sessionDirectory,
19767
+ ...typeof record.sessionFile === "string" ? { sessionFile: record.sessionFile } : {}
19768
+ };
19769
+ rewritePrincipalSessionPaths(principalCoords, storedRunDirectory, runDirectory);
19417
19770
  const principalWire = {
19418
- sessionDirectory: rewriteRunDirectoryPathValue(
19419
- record.sessionDirectory,
19420
- storedRunDirectory,
19421
- runDirectory
19422
- ),
19423
- ...typeof record.sessionFile === "string" ? { sessionFile: rewriteRunDirectoryPathValue(record.sessionFile, storedRunDirectory, runDirectory) } : {}
19771
+ sessionDirectory: principalCoords.sessionDirectory,
19772
+ ...typeof principalCoords.sessionFile === "string" ? { sessionFile: principalCoords.sessionFile } : {}
19424
19773
  };
19425
19774
  const phase = record.phase === "plan" || record.phase === "apply" ? record.phase : void 0;
19426
19775
  const currentCourt = parseCurrentCourtState(record.currentCourt);
@@ -19626,7 +19975,7 @@ async function createWriterLease(lockPath, runDirectory, reportCleanupFailure) {
19626
19975
  },
19627
19976
  relocate(nextRunDirectory) {
19628
19977
  currentRunDirectory = nextRunDirectory;
19629
- currentLockPath = join28(nextRunDirectory, WRITER_LOCK_FILE);
19978
+ currentLockPath = join29(nextRunDirectory, WRITER_LOCK_FILE);
19630
19979
  },
19631
19980
  async release() {
19632
19981
  if (released) return;
@@ -19665,10 +20014,10 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
19665
20014
  };
19666
20015
  const reportReadFailure = (error) => {
19667
20016
  reportDiagnostic(
19668
- `writer lease lock read failed (holder liveness unverifiable; lock left in place) at ${join28(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
20017
+ `writer lease lock read failed (holder liveness unverifiable; lock left in place) at ${join29(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
19669
20018
  );
19670
20019
  };
19671
- const lockPath = join28(runDirectory, WRITER_LOCK_FILE);
20020
+ const lockPath = join29(runDirectory, WRITER_LOCK_FILE);
19672
20021
  let lastAutopsy = { verdict: "absent" };
19673
20022
  let lastReclaimFailure;
19674
20023
  for (let reclaimsLeft = WRITER_LEASE_RECLAIM_ROUNDS; ; reclaimsLeft -= 1) {
@@ -19724,7 +20073,7 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
19724
20073
  }
19725
20074
  async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole, knownRunDirectory) {
19726
20075
  if (typeof knownRunDirectory === "string" && knownRunDirectory.trim() !== "") {
19727
- const parsed = parseRunLeaf(basename12(knownRunDirectory));
20076
+ const parsed = parseRunLeaf(basename13(knownRunDirectory));
19728
20077
  if (parsed === void 0 || parsed.runId !== runId) {
19729
20078
  throw new CliUsageError(
19730
20079
  `run directory does not match run id ${runId}: ${knownRunDirectory}`
@@ -19734,7 +20083,7 @@ async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole, knownRun
19734
20083
  }
19735
20084
  if (runId.trim() === "") return void 0;
19736
20085
  const ledgerHome = resolveActivationLedgerHome(home);
19737
- const booksRoot = join28(ledgerHome, "books");
20086
+ const booksRoot = join29(ledgerHome, "books");
19738
20087
  let bookKeys;
19739
20088
  try {
19740
20089
  bookKeys = await readdir4(booksRoot);
@@ -19749,8 +20098,8 @@ async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole, knownRun
19749
20098
  );
19750
20099
  }
19751
20100
  async function resolveLiveRunDirectoryPath(recordedPath, home, onlyBookKey) {
19752
- if (existsSync12(recordedPath)) return recordedPath;
19753
- const parsed = parseRunLeaf(basename12(recordedPath));
20101
+ if (existsSync13(recordedPath)) return recordedPath;
20102
+ const parsed = parseRunLeaf(basename13(recordedPath));
19754
20103
  const bookKey = onlyBookKey ?? tryBookKeyFromAkRolesPath(recordedPath);
19755
20104
  if (parsed === void 0 || bookKey === void 0) return void 0;
19756
20105
  return findRunDirectoryById(home, parsed.runId, bookKey, parsed.role);
@@ -19784,7 +20133,7 @@ async function findLatestRunForSeatTicket(input) {
19784
20133
  let runDirectories;
19785
20134
  try {
19786
20135
  runDirectories = await listBookRunDirectories(
19787
- input.ticketNumber === void 0 ? bookDir : join28(bookDir, String(input.ticketNumber))
20136
+ input.ticketNumber === void 0 ? bookDir : join29(bookDir, String(input.ticketNumber))
19788
20137
  );
19789
20138
  } catch (error) {
19790
20139
  if (errorCodeOf(error) === "ENOENT") return void 0;
@@ -19792,7 +20141,7 @@ async function findLatestRunForSeatTicket(input) {
19792
20141
  }
19793
20142
  let best;
19794
20143
  for (const runDirectory of runDirectories) {
19795
- const parsed = parseRunLeaf(basename12(runDirectory));
20144
+ const parsed = parseRunLeaf(basename13(runDirectory));
19796
20145
  if (parsed === void 0 || parsed.role !== input.role) continue;
19797
20146
  const runId = parsed.runId;
19798
20147
  const parentPath = await readRunParentPath(runDirectory);
@@ -20547,7 +20896,7 @@ init_filed_submission();
20547
20896
  init_report_ticket_tool();
20548
20897
  import { randomUUID as randomUUID7 } from "node:crypto";
20549
20898
  import { writeSync as writeSync2 } from "node:fs";
20550
- import { join as join30 } from "node:path";
20899
+ import { join as join31 } from "node:path";
20551
20900
  import { Value as Value3 } from "typebox/value";
20552
20901
 
20553
20902
  // src/activation-trace.ts
@@ -20597,7 +20946,7 @@ import {
20597
20946
  lstatSync as lstatSync2,
20598
20947
  realpathSync as realpathSync2,
20599
20948
  statSync as statSync7,
20600
- writeFileSync as writeFileSync2
20949
+ writeFileSync as writeFileSync3
20601
20950
  } from "node:fs";
20602
20951
  import { isAbsolute as isAbsolute10, resolve as resolve14 } from "node:path";
20603
20952
  var ActivationSessionFileMissingError = class extends Error {
@@ -20618,7 +20967,7 @@ function materializeDeferredSessionFile(sessionManager, resolvedFile) {
20618
20967
  throw new ActivationSessionFileMissingError(resolvedFile);
20619
20968
  }
20620
20969
  try {
20621
- writeFileSync2(resolvedFile, `${JSON.stringify(header)}
20970
+ writeFileSync3(resolvedFile, `${JSON.stringify(header)}
20622
20971
  `, { flag: "wx" });
20623
20972
  } catch (error) {
20624
20973
  if (errnoCode(error) !== "EEXIST") {
@@ -20727,6 +21076,7 @@ init_engine_material();
20727
21076
  init_engine_detour();
20728
21077
  init_engine_detour_usage();
20729
21078
  init_run_terminal_artifacts();
21079
+ init_serialize_thrown_value();
20730
21080
  import { Type as Type18 } from "typebox";
20731
21081
  var engineDetourArgsSchema = Type18.Object(
20732
21082
  {
@@ -20747,6 +21097,27 @@ function isCallerCancellation(error, signal) {
20747
21097
  function asError(error, fallback) {
20748
21098
  return error instanceof Error ? error : new Error(String(error).trim() || fallback);
20749
21099
  }
21100
+ function engineFailureResult(input) {
21101
+ const details = {
21102
+ tool: ENGINE_DETOUR_TOOL_NAME,
21103
+ ...input.code === void 0 ? {} : { code: input.code },
21104
+ ...input.stdout === void 0 ? {} : { stdout: input.stdout },
21105
+ ...input.stderr === void 0 ? {} : { stderr: input.stderr },
21106
+ ...input.errorCode === void 0 ? {} : { errorCode: input.errorCode },
21107
+ ...input.ledgerError === void 0 ? {} : { ledgerError: input.ledgerError }
21108
+ };
21109
+ let text = input.text;
21110
+ if (input.ledgerError !== void 0 && input.ledgerError.length > 0) {
21111
+ if (text.length > 0 && !text.endsWith("\n")) text += "\n";
21112
+ text += input.ledgerError;
21113
+ }
21114
+ return {
21115
+ content: [{ type: "text", text }],
21116
+ details,
21117
+ // Identified detour failure is a tool error, not a seat-run death (#1213).
21118
+ isError: true
21119
+ };
21120
+ }
20750
21121
  function createEngineDetourToolDefinition(input) {
20751
21122
  const engineName = input.engineName;
20752
21123
  const engineModel = input.engineModel;
@@ -20760,13 +21131,6 @@ function createEngineDetourToolDefinition(input) {
20760
21131
  async execute(toolCallId, params, signal, _onUpdate, ctx) {
20761
21132
  const args = params;
20762
21133
  const argv = Array.isArray(args.argv) ? args.argv : [];
20763
- if (argv.length === 0 || argv.some((part) => typeof part !== "string" || part.length === 0)) {
20764
- input.fail(
20765
- new Error("\u52B3\u52A1\u5F15\u64CE argv \u987B\u4E3A\u975E\u7A7A\u5B57\u7B26\u4E32\u6570\u7EC4"),
20766
- toolCallId,
20767
- ctx
20768
- );
20769
- }
20770
21134
  const sessionParent = ctx.sessionManager?.getSessionFile?.();
20771
21135
  const startedAt = Date.now();
20772
21136
  const runDirectory = typeof ctx.runDirectory === "string" && ctx.runDirectory.length > 0 ? ctx.runDirectory : void 0;
@@ -20787,25 +21151,21 @@ function createEngineDetourToolDefinition(input) {
20787
21151
  ...observed2.stdoutByteLength === void 0 ? {} : { stdoutByteLength: observed2.stdoutByteLength }
20788
21152
  });
20789
21153
  };
20790
- const failAfterLedger = (engineCause, observed2, aggregateMessage) => {
21154
+ const recordCallOrLedgerError = (observed2) => {
20791
21155
  try {
20792
21156
  recordCall(observed2);
21157
+ return void 0;
20793
21158
  } catch (recordError) {
20794
- input.fail(
20795
- new AggregateError(
20796
- [
20797
- engineCause,
20798
- asError(recordError, "engine detour usage ledger write failed")
20799
- ],
20800
- aggregateMessage,
20801
- { cause: engineCause }
20802
- ),
20803
- toolCallId,
20804
- ctx
20805
- );
21159
+ return serializeThrownValue(recordError);
20806
21160
  }
20807
- input.fail(engineCause, toolCallId, ctx);
20808
21161
  };
21162
+ if (argv.length === 0 || argv.some((part) => typeof part !== "string" || part.length === 0)) {
21163
+ const ledgerError = recordCallOrLedgerError({});
21164
+ return engineFailureResult({
21165
+ text: "\u52B3\u52A1\u5F15\u64CE argv \u987B\u4E3A\u975E\u7A7A\u5B57\u7B26\u4E32\u6570\u7EC4",
21166
+ ...ledgerError === void 0 ? {} : { ledgerError }
21167
+ });
21168
+ }
20809
21169
  let result;
20810
21170
  try {
20811
21171
  result = await runEngineDetourOnce({
@@ -20815,20 +21175,26 @@ function createEngineDetourToolDefinition(input) {
20815
21175
  });
20816
21176
  } catch (error) {
20817
21177
  if (isCallerCancellation(error, signal)) throw error;
20818
- return failAfterLedger(
20819
- asError(error, "\u52B3\u52A1\u5F15\u64CE spawn \u5931\u8D25"),
20820
- {},
20821
- "engine detour spawn and usage ledger both failed"
20822
- );
21178
+ const engineError = asError(error, "\u52B3\u52A1\u5F15\u64CE spawn \u5931\u8D25");
21179
+ const ledgerError = recordCallOrLedgerError({});
21180
+ const errno = typeof engineError.code === "string" ? engineError.code : void 0;
21181
+ return engineFailureResult({
21182
+ text: engineError.message,
21183
+ ...errno === void 0 ? {} : { errorCode: errno },
21184
+ ...ledgerError === void 0 ? {} : { ledgerError }
21185
+ });
20823
21186
  }
20824
21187
  const stdoutByteLength = engineDetourStdoutByteLength(result.stdout);
20825
21188
  const observed = { code: result.code, stdoutByteLength };
20826
21189
  if (isEngineDetourFailure(result)) {
20827
- return failAfterLedger(
20828
- new Error(engineDetourFailureDiagnostic(result)),
20829
- observed,
20830
- "engine detour child-close and usage ledger both failed"
20831
- );
21190
+ const ledgerError = recordCallOrLedgerError(observed);
21191
+ return engineFailureResult({
21192
+ text: engineDetourFailureSeatText(result),
21193
+ code: result.code,
21194
+ stdout: result.stdout,
21195
+ stderr: result.stderr,
21196
+ ...ledgerError === void 0 ? {} : { ledgerError }
21197
+ });
20832
21198
  }
20833
21199
  recordCall(observed);
20834
21200
  return {
@@ -20842,7 +21208,7 @@ function createEngineDetourToolDefinition(input) {
20842
21208
  }
20843
21209
  };
20844
21210
  }
20845
- function registerEngineDetourTool(roleHost, hostActions) {
21211
+ function registerEngineDetourTool(roleHost) {
20846
21212
  const getFlag = (name) => roleHost.getFlag(name);
20847
21213
  const engineName = resolveEngineName(getFlag);
20848
21214
  if (engineName === void 0) {
@@ -20851,10 +21217,7 @@ function registerEngineDetourTool(roleHost, hostActions) {
20851
21217
  const engineModel = resolveEngineModel(getFlag);
20852
21218
  const definition = createEngineDetourToolDefinition({
20853
21219
  engineName,
20854
- ...engineModel === void 0 ? {} : { engineModel },
20855
- fail(error, toolCallId, ctx) {
20856
- hostActions.failInfrastructure(error, ctx, toolCallId);
20857
- }
21220
+ ...engineModel === void 0 ? {} : { engineModel }
20858
21221
  });
20859
21222
  roleHost.registerTool(definition);
20860
21223
  return true;
@@ -21054,10 +21417,10 @@ init_run_ticket_number();
21054
21417
 
21055
21418
  // src/audited-run-identity.ts
21056
21419
  init_role_run_placement();
21057
- import { basename as basename13 } from "node:path";
21420
+ import { basename as basename14 } from "node:path";
21058
21421
  var AUDITED_RUN_IDENTITY_KIND = "audited-run-identity";
21059
21422
  function auditedRunIdentityFromDirectory(runDirectory) {
21060
- const parsed = parseRunLeaf(basename13(runDirectory));
21423
+ const parsed = parseRunLeaf(basename14(runDirectory));
21061
21424
  if (parsed === void 0) return void 0;
21062
21425
  return formatRunLeaf(parsed.runId, parsed.role);
21063
21426
  }
@@ -21236,7 +21599,7 @@ import "typebox";
21236
21599
 
21237
21600
  // src/navigator-public-session.ts
21238
21601
  init_host_session_record();
21239
- import { basename as basename14 } from "node:path";
21602
+ import { basename as basename15 } from "node:path";
21240
21603
 
21241
21604
  // src/navigator-session-contracts.ts
21242
21605
  init_unknown_value();
@@ -21440,7 +21803,7 @@ async function resolveNavigatorLedgerHome(context) {
21440
21803
  return void 0;
21441
21804
  }
21442
21805
  function runIdFromNavigatorDirectory(runDirectory) {
21443
- const parsed = parseRunLeaf(basename14(runDirectory));
21806
+ const parsed = parseRunLeaf(basename15(runDirectory));
21444
21807
  if (parsed === void 0 || parsed.role !== "navigator") return void 0;
21445
21808
  return parsed.runId;
21446
21809
  }
@@ -22071,7 +22434,7 @@ init_unknown_value();
22071
22434
  init_submission_errors();
22072
22435
  init_worker_submission_contracts();
22073
22436
  import { execFileSync as execFileSync3 } from "node:child_process";
22074
- import { existsSync as existsSync13, lstatSync as lstatSync3, readdirSync as readdirSync3, readFileSync as readFileSync4, rmdirSync, rmSync as rmSync3 } from "node:fs";
22437
+ import { existsSync as existsSync14, lstatSync as lstatSync3, readdirSync as readdirSync4, readFileSync as readFileSync5, rmdirSync, rmSync as rmSync4 } from "node:fs";
22075
22438
  import { resolve as resolve16 } from "node:path";
22076
22439
  var WORKER_COMMIT_BASELINE_ENTRY_TYPE = "commit-baseline";
22077
22440
  var WORKER_COMMIT_REMINDER_BOUNCE_ENTRY_TYPE = "commit-reminder-bounce";
@@ -22101,7 +22464,7 @@ function statusOf(error) {
22101
22464
  return typeof error === "object" && error !== null && "status" in error ? error.status : void 0;
22102
22465
  }
22103
22466
  function tryGetAll(file, key) {
22104
- if (!existsSync13(file)) return [];
22467
+ if (!existsSync14(file)) return [];
22105
22468
  try {
22106
22469
  const out = gitFile(file, ["--get-all", key]);
22107
22470
  return out.length === 0 ? [] : out.split("\n");
@@ -22111,8 +22474,8 @@ function tryGetAll(file, key) {
22111
22474
  }
22112
22475
  }
22113
22476
  function ownedHook(path) {
22114
- if (!existsSync13(path)) return false;
22115
- return readFileSync4(path, "utf8").includes(HOOK_MARKER);
22477
+ if (!existsSync14(path)) return false;
22478
+ return readFileSync5(path, "utf8").includes(HOOK_MARKER);
22116
22479
  }
22117
22480
  function escapeGitConfigValueRegex(value) {
22118
22481
  return value.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
@@ -22137,13 +22500,13 @@ function unsetOwnedHooksPath(file) {
22137
22500
  function rmOwnedDir(dir) {
22138
22501
  const hookPath = resolve16(dir, HOOK_FILE);
22139
22502
  if (!ownedHook(hookPath)) return;
22140
- rmSync3(hookPath, { force: true });
22141
- if (existsSync13(dir) && readdirSync3(dir).length === 0) rmdirSync(dir);
22503
+ rmSync4(hookPath, { force: true });
22504
+ if (existsSync14(dir) && readdirSync4(dir).length === 0) rmdirSync(dir);
22142
22505
  }
22143
22506
  function linkedGitDirs(commonDir) {
22144
22507
  const root = resolve16(commonDir, "worktrees");
22145
- if (!existsSync13(root)) return [];
22146
- return readdirSync3(root).map((name) => resolve16(root, name)).filter((dir) => lstatSync3(dir).isDirectory());
22508
+ if (!existsSync14(root)) return [];
22509
+ return readdirSync4(root).map((name) => resolve16(root, name)).filter((dir) => lstatSync3(dir).isDirectory());
22147
22510
  }
22148
22511
  function uninstallPackageWorkerHooks(cwd) {
22149
22512
  let inside;
@@ -22161,7 +22524,7 @@ function uninstallPackageWorkerHooks(cwd) {
22161
22524
  clear(resolve16(commonDir, "config.worktree"));
22162
22525
  rmOwnedDir(resolve16(commonDir, HOOKS_DIR));
22163
22526
  const legacy = resolve16(commonDir, "hooks", HOOK_FILE);
22164
- if (ownedHook(legacy)) rmSync3(legacy, { force: true });
22527
+ if (ownedHook(legacy)) rmSync4(legacy, { force: true });
22165
22528
  for (const gitDir of linkedGitDirs(commonDir)) {
22166
22529
  clear(resolve16(gitDir, "config.worktree"));
22167
22530
  rmOwnedDir(resolve16(gitDir, HOOKS_DIR));
@@ -22239,11 +22602,11 @@ function reliableWindow(cwd, baseline, head) {
22239
22602
  const raw = git2(cwd, ["log", "--format=%P%x1e%s", range]);
22240
22603
  if (raw.length === 0) return [];
22241
22604
  return raw.split("\n").flatMap((line2) => {
22242
- const sep5 = line2.indexOf("");
22243
- if (sep5 < 0) return [];
22605
+ const sep6 = line2.indexOf("");
22606
+ if (sep6 < 0) return [];
22244
22607
  return [{
22245
- subject: line2.slice(sep5 + 1),
22246
- merge: line2.slice(0, sep5).trim().includes(" ")
22608
+ subject: line2.slice(sep6 + 1),
22609
+ merge: line2.slice(0, sep6).trim().includes(" ")
22247
22610
  }];
22248
22611
  });
22249
22612
  }
@@ -22981,7 +23344,7 @@ function readRoleRunCoordinates(ctx, label) {
22981
23344
  if (runDirectory === void 0) throw new Error(`${label} requires AK_ROLE_RUN_DIR`);
22982
23345
  const admitted = readPageSync(runDirectory, "admitted");
22983
23346
  if (typeof admitted?.projectRoot !== "string" || admitted.projectRoot.trim() === "") {
22984
- throw new Error(`${label} state.jsonl admitted-request row missing projectRoot (${join30(runDirectory, RUN_STATE_FILE)})`);
23347
+ throw new Error(`${label} state.jsonl admitted-request row missing projectRoot (${join31(runDirectory, RUN_STATE_FILE)})`);
22985
23348
  }
22986
23349
  return {
22987
23350
  runDirectory,
@@ -23247,7 +23610,10 @@ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
23247
23610
  settleNavigatorProjection
23248
23611
  );
23249
23612
  };
23250
- roleHost.on("input", (_event) => {
23613
+ roleHost.on("input", (event, ctx) => {
23614
+ if (typeof event.text === "string" && ctx.summonsInstruction === void 0) {
23615
+ ctx.summonsInstruction = event.text;
23616
+ }
23251
23617
  const role = roleHost.getFlag(ROLE_FLAG.name);
23252
23618
  if (role !== void 0 && !admitted) return { action: "handled" };
23253
23619
  return { action: "continue" };
@@ -23402,6 +23768,8 @@ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
23402
23768
  }
23403
23769
  if (receiptDelivery.nextAction() === "request-delivery") {
23404
23770
  receiptDelivery.recordDeliveryRequest();
23771
+ const deliveryContent = turnDialoguePrompt ?? "";
23772
+ ctx.summonsInstruction = deliveryContent;
23405
23773
  const scopeId = ctx.invocationScopeId?.trim() ?? "";
23406
23774
  envelopeHost.appendEntry(
23407
23775
  RECEIPT_DELIVERY_REQUEST_ENTRY,
@@ -23417,7 +23785,7 @@ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
23417
23785
  });
23418
23786
  envelopeHost.sendMessage({
23419
23787
  customType: "ak-receipt-delivery-prompt",
23420
- content: turnDialoguePrompt ?? "",
23788
+ content: deliveryContent,
23421
23789
  display: false
23422
23790
  }, { triggerTurn: true, deliverAs: "followUp" });
23423
23791
  } else if (receiptDelivery.nextAction() === "no-receipt" && !noReceiptRecorded) {
@@ -23785,7 +24153,7 @@ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
23785
24153
  ]);
23786
24154
  roleReferenceMaterials = await dependencies.loadRoleReferenceMaterials?.(entry.role) ?? "";
23787
24155
  if (!engineDetourRegistered) {
23788
- engineDetourRegistered = registerEngineDetourTool(roleHost, hostActions);
24156
+ engineDetourRegistered = registerEngineDetourTool(roleHost);
23789
24157
  }
23790
24158
  if (secretariat.claimsEngineDetour === true && engineDetourRegistered) {
23791
24159
  roleHost.setActiveTools([
@@ -24158,7 +24526,7 @@ async function prepareRoleEnvelope(options) {
24158
24526
  const projected = await projectToolResult(toolCallId, name, {
24159
24527
  content: result.content,
24160
24528
  details: result.details,
24161
- isError: false
24529
+ isError: result.isError === true
24162
24530
  });
24163
24531
  if (result.terminate === false) {
24164
24532
  rejection = {
@@ -24349,6 +24717,7 @@ async function prepareRoleEnvelope(options) {
24349
24717
  const record = value;
24350
24718
  if (record.action === "transform" && typeof record.text === "string") prompt = record.text;
24351
24719
  }
24720
+ context.summonsInstruction = prompt;
24352
24721
  if (typeof prompt === "string" && prompt.trim() !== "") {
24353
24722
  sessionEntries.push({
24354
24723
  type: "message",
@@ -24390,6 +24759,9 @@ async function prepareRoleEnvelope(options) {
24390
24759
  }],
24391
24760
  systemPrompt: { body: systemPromptBody, materials: readingMaterials },
24392
24761
  prompt,
24762
+ recordSentInstruction(text) {
24763
+ context.summonsInstruction = text;
24764
+ },
24393
24765
  abortSignal: hostAbort.signal,
24394
24766
  closeRound,
24395
24767
  dispose,
@@ -24970,12 +25342,12 @@ function createAcpRoleTurnHost(config) {
24970
25342
  // src/acp-host/seat-profile-soul.ts
24971
25343
  import { constants as constants3 } from "node:fs";
24972
25344
  import { access as access3, copyFile, lstat as lstat4, mkdir as mkdir4, readlink, symlink as symlink2, unlink as unlink3 } from "node:fs/promises";
24973
- import { dirname as dirname20, join as join31, relative as relative3, resolve as resolve18 } from "node:path";
25345
+ import { dirname as dirname20, join as join32, relative as relative4, resolve as resolve18 } from "node:path";
24974
25346
  function seatProfileName(spec, role) {
24975
25347
  return `${spec.namePrefix}${role}`;
24976
25348
  }
24977
25349
  function packageRoleSoulPath(packageRoot, role) {
24978
- return join31(packageRoot, "souls", `${role}.md`);
25350
+ return join32(packageRoot, "souls", `${role}.md`);
24979
25351
  }
24980
25352
  async function pathExists2(path) {
24981
25353
  try {
@@ -24992,21 +25364,21 @@ async function ensureSeatProfileSoul(options) {
24992
25364
  if (!await pathExists2(soulTarget)) {
24993
25365
  throw new Error(`packaged role soul missing: ${soulTarget}`);
24994
25366
  }
24995
- const profilesRoot = join31(operatorHome, ...spec.profilesRootFromHome);
24996
- const profileDir = join31(profilesRoot, profileName);
25367
+ const profilesRoot = join32(operatorHome, ...spec.profilesRootFromHome);
25368
+ const profileDir = join32(profilesRoot, profileName);
24997
25369
  const hostRoot = dirname20(profilesRoot);
24998
- const soulPath = join31(profileDir, spec.soulFileName);
25370
+ const soulPath = join32(profileDir, spec.soulFileName);
24999
25371
  if (!await pathExists2(profileDir)) {
25000
25372
  await mkdir4(profileDir, { recursive: true });
25001
25373
  for (const name of ["auth.json", ".env", "config.yaml"]) {
25002
- const source = join31(hostRoot, name);
25374
+ const source = join32(hostRoot, name);
25003
25375
  if (!await pathExists2(source)) continue;
25004
- await copyFile(source, join31(profileDir, name));
25376
+ await copyFile(source, join32(profileDir, name));
25005
25377
  }
25006
25378
  } else {
25007
25379
  await mkdir4(profileDir, { recursive: true });
25008
25380
  }
25009
- const desiredLink = relative3(profileDir, soulTarget);
25381
+ const desiredLink = relative4(profileDir, soulTarget);
25010
25382
  let current;
25011
25383
  try {
25012
25384
  const st = await lstat4(soulPath);