@akagilnc/pi-workflow-roles 0.1.5775 → 0.1.5797

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 (43) hide show
  1. package/dist/acp-host/production-host.js +556 -209
  2. package/dist/external-host-turn-loop.js +3 -0
  3. package/dist/headless-host/production-host.js +529 -182
  4. package/dist/migrate-book-topology.js +63 -23
  5. package/dist/pi/role-turn-host.js +6 -1
  6. package/dist/public-cli/instruction-seat-run.js +10 -7
  7. package/dist/public-cli/invocation.js +95 -39
  8. package/dist/public-cli/main.js +357 -147
  9. package/dist/public-cli/post-admission.js +2 -0
  10. package/dist/public-cli/run-lifecycle.js +10 -4
  11. package/dist/public-cli/turn-request.js +3 -0
  12. package/dist/report-ticket-tool.js +3 -3
  13. package/dist/role-run-placement.js +14 -2
  14. package/dist/role-run-relocation.js +2 -2
  15. package/dist/run-dossier.js +5 -4
  16. package/dist/session-identity.js +3 -2
  17. package/dist/sitian-appender.js +12 -3
  18. package/dist/submission-ledger.js +24 -0
  19. package/dist/ticket-progress.js +306 -0
  20. package/dist/user-dialogue-stdin.js +23 -17
  21. package/package.json +1 -1
  22. package/src/external-host-turn-loop.ts +7 -1
  23. package/src/host-contracts.ts +1 -1
  24. package/src/pi/adapter.ts +57 -45
  25. package/src/pi/role-turn-host.ts +6 -1
  26. package/src/prepared-role-turn.ts +6 -0
  27. package/src/public-cli/instruction-seat-run.ts +10 -7
  28. package/src/public-cli/invocation.ts +116 -38
  29. package/src/public-cli/post-admission.ts +3 -1
  30. package/src/public-cli/run-lifecycle.ts +10 -8
  31. package/src/public-cli/turn-request.ts +3 -0
  32. package/src/report-ticket-tool.ts +7 -3
  33. package/src/role-envelope.ts +5 -0
  34. package/src/role-run-placement.ts +19 -2
  35. package/src/role-run-relocation.ts +2 -2
  36. package/src/role-runtime.ts +14 -3
  37. package/src/run-dossier.ts +5 -3
  38. package/src/run-terminal-artifacts.ts +0 -1
  39. package/src/session-identity.ts +3 -2
  40. package/src/sitian-appender.ts +14 -3
  41. package/src/submission-ledger.ts +27 -0
  42. package/src/ticket-progress.ts +383 -0
  43. package/src/user-dialogue-stdin.ts +21 -14
@@ -1200,6 +1200,16 @@ function parseRunLeaf(name) {
1200
1200
  if (at <= 0 || at === name.length - 1) return void 0;
1201
1201
  return { runId: name.slice(0, at), role: name.slice(at + 1) };
1202
1202
  }
1203
+ function subjectDirectoryOfRun(runDirectory) {
1204
+ const runsParent = dirname2(runDirectory);
1205
+ if (basename2(runsParent) !== "runs") return void 0;
1206
+ const subjectDirectory = dirname2(runsParent);
1207
+ const subjectName = basename2(subjectDirectory);
1208
+ if (subjectName === "unbound" || /^[1-9]\d*$/.test(subjectName)) {
1209
+ return subjectDirectory;
1210
+ }
1211
+ return void 0;
1212
+ }
1203
1213
  function sessionDirectoryOf(runDirectory) {
1204
1214
  return join3(runDirectory, "session");
1205
1215
  }
@@ -1292,6 +1302,7 @@ function ensureRoleRunDirectory(ledgerHome, directory) {
1292
1302
  return ensureRealDirectoryTree(ledgerHome, directory);
1293
1303
  }
1294
1304
  function ensureRoleRunPlacement(ledgerHome, placement) {
1305
+ ensureRoleRunDirectory(ledgerHome, placement.runDirectory);
1295
1306
  ensureRoleRunDirectory(ledgerHome, placement.sessionDirectory);
1296
1307
  }
1297
1308
  var ROLE_RUN_SESSION_FILENAME;
@@ -1592,6 +1603,12 @@ function appendSitianRecordBlock(input, block) {
1592
1603
  function resolveSitianVolumeCategory(kind) {
1593
1604
  return kind;
1594
1605
  }
1606
+ function runDirectoryOwningSessionParent(sessionParentDir) {
1607
+ if (basename4(sessionParentDir) !== "session") return void 0;
1608
+ const runDirectory = dirname4(sessionParentDir);
1609
+ if (parseRunLeaf(basename4(runDirectory)) === void 0) return void 0;
1610
+ return runDirectory;
1611
+ }
1595
1612
  function sitianVolumeDirectory(sessionDirectory, category) {
1596
1613
  return join4(sessionDirectory, category);
1597
1614
  }
@@ -1623,8 +1640,8 @@ function resolveSitianRecordPathInLedger(input, ledgerHome) {
1623
1640
  throw new Error("Sitian record ownership requires a parent session inside the ledger home");
1624
1641
  }
1625
1642
  const sessionParentDir = dirname4(input.sessionParent);
1626
- const runDirectory = dirname4(sessionParentDir);
1627
- if (basename4(sessionParentDir) === "session" && parseRunLeaf(basename4(runDirectory)) !== void 0) {
1643
+ const runDirectory = runDirectoryOwningSessionParent(sessionParentDir);
1644
+ if (runDirectory !== void 0) {
1628
1645
  sessionDir = runDirectory;
1629
1646
  recordFile = join4(runDirectory, RUN_HISTORY_KINDS.has(input.kind) ? RUN_HISTORY_FILE : RUN_STATE_KINDS.has(input.kind) ? RUN_STATE_FILE : RUN_LOG_FILE);
1630
1647
  } else {
@@ -1857,7 +1874,9 @@ function render(runDirectory, history, state, log, unreadable) {
1857
1874
  original = payload.landingPath;
1858
1875
  }
1859
1876
  }
1860
- if (typeof original === "string") original = join5(runDirectory, "session", basename5(original));
1877
+ if (typeof original === "string") {
1878
+ original = join5(sessionDirectoryOf(runDirectory), basename5(original));
1879
+ }
1861
1880
  whole.host = { sessions, ...original === void 0 ? {} : { original } };
1862
1881
  whole.submission = latest === void 0 ? {} : { latest };
1863
1882
  if (Object.keys(unreadable).length > 0) whole.unreadable = unreadable;
@@ -5864,7 +5883,8 @@ var init_role_activation_flags = __esm({
5864
5883
 
5865
5884
  // src/user-dialogue-stdin.ts
5866
5885
  function encodeUserDialogueStdin(body) {
5867
- return JSON.stringify({ kind: USER_DIALOGUE_STDIN_KIND, body });
5886
+ const envelope = { kind: USER_DIALOGUE_STDIN_KIND, body };
5887
+ return JSON.stringify(envelope);
5868
5888
  }
5869
5889
  var USER_DIALOGUE_STDIN_KIND;
5870
5890
  var init_user_dialogue_stdin = __esm({
@@ -5875,6 +5895,242 @@ var init_user_dialogue_stdin = __esm({
5875
5895
  }
5876
5896
  });
5877
5897
 
5898
+ // src/ticket-progress.ts
5899
+ import { spawnSync as spawnSync2 } from "node:child_process";
5900
+ import {
5901
+ appendFileSync as appendFileSync2,
5902
+ existsSync as existsSync3,
5903
+ mkdirSync as mkdirSync3,
5904
+ readFileSync as readFileSync3,
5905
+ readdirSync as readdirSync3,
5906
+ rmSync as rmSync3,
5907
+ writeFileSync as writeFileSync2
5908
+ } from "node:fs";
5909
+ import { basename as basename7, dirname as dirname8, join as join10, relative as relative3, sep as sep4 } from "node:path";
5910
+ function parseProgressText(text, pathForDiagnostic) {
5911
+ if (text.trim() === "") return [];
5912
+ const { records, diagnostics } = parseSitianRecordText(text);
5913
+ for (const diagnostic of diagnostics) {
5914
+ process.stderr.write(
5915
+ `[ticket-progress] ${pathForDiagnostic} has malformed row(s); keeps reachable rows and retains the diagnostic: line ${diagnostic.line}: ${diagnostic.error}
5916
+ `
5917
+ );
5918
+ }
5919
+ const lines = [];
5920
+ for (const record of records) {
5921
+ const parsed = record;
5922
+ if (!isRecord(parsed)) continue;
5923
+ if (typeof parsed.seat !== "string" || typeof parsed.round !== "string") continue;
5924
+ lines.push(parsed);
5925
+ }
5926
+ return lines;
5927
+ }
5928
+ function readProgressFile(path) {
5929
+ if (!existsSync3(path)) return [];
5930
+ return parseProgressText(readFileSync3(path, "utf8"), path);
5931
+ }
5932
+ function readTicketProgressLines(subjectDirectory) {
5933
+ if (basename7(subjectDirectory) === "unbound") {
5934
+ const runsDir = join10(subjectDirectory, "runs");
5935
+ if (!existsSync3(runsDir)) return [];
5936
+ const out = [];
5937
+ for (const name of readdirSync3(runsDir).sort()) {
5938
+ out.push(...readProgressFile(join10(runsDir, name, LEG_PROGRESS_FILENAME)));
5939
+ }
5940
+ return out;
5941
+ }
5942
+ return readProgressFile(join10(subjectDirectory, CURRENT_FILENAME));
5943
+ }
5944
+ function roundBaseNumber(round) {
5945
+ if (round.trim() === "") return 0;
5946
+ const base = round.includes(".") ? round.slice(0, round.indexOf(".")) : round;
5947
+ const n = Number(base);
5948
+ return Number.isSafeInteger(n) && n > 0 ? n : 0;
5949
+ }
5950
+ function roundLens(round) {
5951
+ return round.includes(".") ? round.slice(round.indexOf(".") + 1) : void 0;
5952
+ }
5953
+ function nextRoundFromLines(lines, seat, lens) {
5954
+ const want = lens === void 0 || lens.trim() === "" ? void 0 : lens;
5955
+ let max = 0;
5956
+ for (const line2 of lines) {
5957
+ if (line2.seat !== seat) continue;
5958
+ if (roundLens(line2.round) !== want) continue;
5959
+ max = Math.max(max, roundBaseNumber(line2.round));
5960
+ }
5961
+ const base = max + 1;
5962
+ return want === void 0 ? String(base) : `${base}.${want}`;
5963
+ }
5964
+ function nextLegReceiptIndex(runDirectory) {
5965
+ const dir = join10(runDirectory, RECEIPTS_DIRNAME);
5966
+ if (!existsSync3(dir)) return 1;
5967
+ let max = 0;
5968
+ for (const name of readdirSync3(dir)) {
5969
+ const match = /^(\d+)\.json$/.exec(name);
5970
+ if (match === null) continue;
5971
+ const n = Number(match[1]);
5972
+ if (Number.isSafeInteger(n) && n > max) max = n;
5973
+ }
5974
+ return max + 1;
5975
+ }
5976
+ function statusAndSummaryFromPayload(seat, payload) {
5977
+ if (!isRecord(payload)) return {};
5978
+ const toolName = packagedRoleOutputTool(seat);
5979
+ const status = toolName !== void 0 && isTerminatingToolName(toolName) ? acceptedFacts(toolName, payload).status : void 0;
5980
+ const summary = typeof payload.summary === "string" ? payload.summary : void 0;
5981
+ return {
5982
+ ...status === void 0 ? {} : { status },
5983
+ ...summary === void 0 ? {} : { summary }
5984
+ };
5985
+ }
5986
+ function captureWorktreeHead(projectRoot) {
5987
+ try {
5988
+ const result = spawnSync2("git", ["rev-parse", "HEAD"], {
5989
+ cwd: projectRoot,
5990
+ encoding: "utf8",
5991
+ maxBuffer: 1024 * 1024
5992
+ });
5993
+ if (result.error != null) {
5994
+ const err = result.error;
5995
+ const detail = err instanceof Error ? err.stack ?? err.message : String(err);
5996
+ return { head: "", fault: `git rev-parse HEAD spawn failed cwd=${projectRoot}: ${detail}` };
5997
+ }
5998
+ if (result.status !== 0) {
5999
+ const detail = [result.stderr, result.stdout].map((part) => typeof part === "string" ? part.trim() : "").filter((part) => part !== "").join(" | ");
6000
+ const status = result.status === null ? "null" : String(result.status);
6001
+ const signal = result.signal == null ? "" : ` signal=${result.signal}`;
6002
+ return {
6003
+ head: "",
6004
+ fault: detail === "" ? `git rev-parse HEAD failed (status=${status}${signal}) cwd=${projectRoot}` : `git rev-parse HEAD failed (status=${status}${signal}) cwd=${projectRoot}: ${detail}`
6005
+ };
6006
+ }
6007
+ return { head: (result.stdout ?? "").trim() };
6008
+ } catch (error) {
6009
+ const message = error instanceof Error ? error.stack ?? error.message : String(error);
6010
+ return { head: "", fault: `git rev-parse HEAD threw cwd=${projectRoot}: ${message}` };
6011
+ }
6012
+ }
6013
+ function progressSessionAbsolute(runDirectory, context) {
6014
+ const host = typeof context.host === "string" ? context.host.trim() : "";
6015
+ const sessionDirectory = sessionDirectoryOf(runDirectory);
6016
+ if (host !== "" && host !== "pi" && host !== "hermes") {
6017
+ return resolveHostDossierLandingPath({ host, sessionDirectory });
6018
+ }
6019
+ const issued = context.sessionManager.getSessionFile?.();
6020
+ if (typeof issued === "string" && issued.trim() !== "") {
6021
+ return issued;
6022
+ }
6023
+ return sessionFileOf(runDirectory);
6024
+ }
6025
+ function lensFromRunDirectory(runDirectory, role) {
6026
+ if (role !== "reviewer") return void 0;
6027
+ const lens = readPageSync(runDirectory, "admitted")?.lens;
6028
+ return lens === "completeness" || lens === "correctness" ? lens : void 0;
6029
+ }
6030
+ function landTicketProgressForSealedSubmission(input) {
6031
+ const runDirectory = runDirectoryFromHostContext(input.context);
6032
+ if (runDirectory === void 0) return void 0;
6033
+ const subjectDirectory = subjectDirectoryOfRun(runDirectory);
6034
+ if (subjectDirectory === void 0) return void 0;
6035
+ const lens = input.lens === "completeness" || input.lens === "correctness" ? input.lens : lensFromRunDirectory(runDirectory, input.role);
6036
+ const leaf = basename7(runDirectory);
6037
+ const unbound = basename7(subjectDirectory) === "unbound";
6038
+ const progressPath = unbound ? join10(runDirectory, LEG_PROGRESS_FILENAME) : join10(subjectDirectory, CURRENT_FILENAME);
6039
+ const receiptIndex = nextLegReceiptIndex(runDirectory);
6040
+ const relativePath = `runs/${leaf}/${RECEIPTS_DIRNAME}/${receiptIndex}.json`;
6041
+ const absolutePath = join10(subjectDirectory, relativePath);
6042
+ mkdirSync3(dirname8(absolutePath), { recursive: true });
6043
+ writeFileSync2(absolutePath, `${JSON.stringify(input.accepted, null, 2)}
6044
+ `, "utf8");
6045
+ if (!unbound) {
6046
+ relocateTicketProgressForLeg({ runDirectory });
6047
+ }
6048
+ const existing = unbound ? readProgressFile(progressPath) : readTicketProgressLines(subjectDirectory);
6049
+ const round = unbound ? "" : nextRoundFromLines(existing, input.role, lens);
6050
+ const sessionFile = progressSessionAbsolute(runDirectory, input.context);
6051
+ const sessionRelative = relative3(subjectDirectory, sessionFile).split(sep4).join("/");
6052
+ const { status, summary } = statusAndSummaryFromPayload(input.role, input.accepted);
6053
+ const instruction = typeof input.context.summonsInstruction === "string" ? input.context.summonsInstruction : "";
6054
+ const line2 = {
6055
+ at: (/* @__PURE__ */ new Date()).toISOString(),
6056
+ seat: input.role,
6057
+ round,
6058
+ instruction,
6059
+ head: input.sealHead.head,
6060
+ ...status === void 0 ? {} : { status },
6061
+ ...summary === void 0 ? {} : { summary },
6062
+ receipt: relativePath,
6063
+ session: sessionRelative
6064
+ };
6065
+ mkdirSync3(dirname8(progressPath), { recursive: true });
6066
+ appendFileSync2(progressPath, `${JSON.stringify(line2)}
6067
+ `, "utf8");
6068
+ if (input.sealHead.fault !== void 0) {
6069
+ process.stderr.write(`${input.sealHead.fault}
6070
+ `);
6071
+ }
6072
+ return line2;
6073
+ }
6074
+ function relocateTicketProgressForLeg(input) {
6075
+ if (isUnboundRunDirectory(input.runDirectory)) return;
6076
+ const subjectDirectory = subjectDirectoryOfRun(input.runDirectory);
6077
+ if (subjectDirectory === void 0) return;
6078
+ const stagedPath = join10(input.runDirectory, LEG_PROGRESS_FILENAME);
6079
+ const mine = readProgressFile(stagedPath);
6080
+ if (mine.length === 0) {
6081
+ if (existsSync3(stagedPath)) {
6082
+ rmSync3(stagedPath, { force: true });
6083
+ }
6084
+ return;
6085
+ }
6086
+ const ticketLines = [...readTicketProgressLines(subjectDirectory)];
6087
+ const publishedReceipts = new Set(
6088
+ ticketLines.map((line2) => line2.receipt).filter((receipt) => typeof receipt === "string" && receipt !== "")
6089
+ );
6090
+ const pending = mine.filter((line2) => !publishedReceipts.has(line2.receipt));
6091
+ if (pending.length === 0) {
6092
+ rmSync3(stagedPath, { force: true });
6093
+ return;
6094
+ }
6095
+ const movedLines = [];
6096
+ for (const line2 of pending) {
6097
+ const lens = lensFromRunDirectory(input.runDirectory, line2.seat);
6098
+ const round = nextRoundFromLines(ticketLines, line2.seat, lens);
6099
+ const moved = {
6100
+ ...line2,
6101
+ round
6102
+ };
6103
+ movedLines.push(moved);
6104
+ ticketLines.push(moved);
6105
+ }
6106
+ const newCurrent = join10(subjectDirectory, CURRENT_FILENAME);
6107
+ mkdirSync3(dirname8(newCurrent), { recursive: true });
6108
+ appendFileSync2(
6109
+ newCurrent,
6110
+ `${movedLines.map((line2) => JSON.stringify(line2)).join("\n")}
6111
+ `,
6112
+ "utf8"
6113
+ );
6114
+ rmSync3(stagedPath, { force: true });
6115
+ }
6116
+ var CURRENT_FILENAME, RECEIPTS_DIRNAME, LEG_PROGRESS_FILENAME;
6117
+ var init_ticket_progress = __esm({
6118
+ "src/ticket-progress.ts"() {
6119
+ "use strict";
6120
+ init_host_session_record();
6121
+ init_host_contracts();
6122
+ init_terminating_tools();
6123
+ init_packaged_role_registry();
6124
+ init_role_run_placement();
6125
+ init_run_dossier();
6126
+ init_sitian_reader();
6127
+ init_unknown_value();
6128
+ CURRENT_FILENAME = "current.jsonl";
6129
+ RECEIPTS_DIRNAME = "receipts";
6130
+ LEG_PROGRESS_FILENAME = "progress.jsonl";
6131
+ }
6132
+ });
6133
+
5878
6134
  // src/public-cli/github-remote.ts
5879
6135
  function ownerRepoFromGitHubRemoteUrl(remoteUrl) {
5880
6136
  const trimmed = remoteUrl.trim();
@@ -6140,13 +6396,13 @@ var init_session_dialogue = __esm({
6140
6396
 
6141
6397
  // src/ticket-provenance.ts
6142
6398
  import { readFile as readFile7 } from "node:fs/promises";
6143
- import { join as join10, resolve as resolve7 } from "node:path";
6399
+ import { join as join11, resolve as resolve7 } from "node:path";
6144
6400
  function dialogueSessionSourceRoots(home) {
6145
6401
  const machineHome = typeof home === "string" && home.trim() !== "" ? home : packageMachineHome();
6146
6402
  return [
6147
- join10(machineHome, ".claude", "projects"),
6148
- join10(machineHome, ".codex", "sessions"),
6149
- join10(machineHome, ".pi", "agent", "sessions")
6403
+ join11(machineHome, ".claude", "projects"),
6404
+ join11(machineHome, ".codex", "sessions"),
6405
+ join11(machineHome, ".pi", "agent", "sessions")
6150
6406
  ];
6151
6407
  }
6152
6408
  function isLedgerRoleSessionFile(absolute, home) {
@@ -6187,7 +6443,7 @@ async function rehomeUnboundTicketProvenance(runDirectory, ticketNumber, cwd, ho
6187
6443
  const ticketInput = ticketProvenanceRecordInput(ticketNumber, cwd, home);
6188
6444
  let history;
6189
6445
  try {
6190
- history = await readFile7(join10(runDirectory, RUN_HISTORY_FILE), "utf8");
6446
+ history = await readFile7(join11(runDirectory, RUN_HISTORY_FILE), "utf8");
6191
6447
  } catch (error) {
6192
6448
  if (errnoCode(error) === "ENOENT") return;
6193
6449
  throw error;
@@ -6379,7 +6635,7 @@ var init_ticket_provenance = __esm({
6379
6635
  });
6380
6636
 
6381
6637
  // src/notary-source-run.ts
6382
- import { dirname as dirname8, isAbsolute as isAbsolute4, join as join11, resolve as resolve8, basename as basename7 } from "node:path";
6638
+ import { dirname as dirname9, isAbsolute as isAbsolute4, join as join12, resolve as resolve8, basename as basename8 } from "node:path";
6383
6639
  import { lstat, realpath as realpath2 } from "node:fs/promises";
6384
6640
  async function readRetainedIdentity(runDirectory) {
6385
6641
  try {
@@ -6415,10 +6671,10 @@ async function requireRunDirectory(candidate, display) {
6415
6671
  `notary --source-run must be a run directory: ${display}`
6416
6672
  );
6417
6673
  }
6418
- const identity = parseRunLeaf(basename7(real));
6674
+ const identity = parseRunLeaf(basename8(real));
6419
6675
  if (identity === void 0) {
6420
6676
  throw new NotarySourceRunError(
6421
- `notary --source-run must be named <runId>@<role>: ${basename7(real)}`
6677
+ `notary --source-run must be named <runId>@<role>: ${basename8(real)}`
6422
6678
  );
6423
6679
  }
6424
6680
  return real;
@@ -6431,26 +6687,26 @@ async function resolveNotarySourceRunLocator(options) {
6431
6687
  const ledgerHome = resolveActivationLedgerHome(options.home);
6432
6688
  const bookKey = resolveBookKeyFromGit(options.projectRoot);
6433
6689
  const bookDirectory = activationBookDirectory(ledgerHome, bookKey);
6434
- const bookRunsRoot = join11(bookDirectory, "runs");
6690
+ const bookRunsRoot = join12(bookDirectory, "runs");
6435
6691
  let candidate;
6436
6692
  const bare = parseRunLeaf(raw);
6437
6693
  if (bare !== void 0 && !raw.includes("/") && !raw.includes("\\")) {
6438
- candidate = await findRunDirectoryById(options.home, bare.runId, bookKey, bare.role) ?? join11(bookRunsRoot, formatRunLeaf(bare.runId, bare.role));
6694
+ candidate = await findRunDirectoryById(options.home, bare.runId, bookKey, bare.role) ?? join12(bookRunsRoot, formatRunLeaf(bare.runId, bare.role));
6439
6695
  } else {
6440
6696
  candidate = isAbsolute4(raw) ? raw : resolve8(options.projectRoot, raw);
6441
- const identity2 = parseRunLeaf(basename7(candidate));
6442
- const subjectDirectory = dirname8(dirname8(candidate));
6443
- const isLegacyUnboundLocator = identity2 !== void 0 && basename7(dirname8(candidate)) === "runs" && basename7(subjectDirectory) === "unbound" && resolve8(dirname8(subjectDirectory)) === resolve8(bookDirectory);
6697
+ const identity2 = parseRunLeaf(basename8(candidate));
6698
+ const subjectDirectory = dirname9(dirname9(candidate));
6699
+ const isLegacyUnboundLocator = identity2 !== void 0 && basename8(dirname9(candidate)) === "runs" && basename8(subjectDirectory) === "unbound" && resolve8(dirname9(subjectDirectory)) === resolve8(bookDirectory);
6444
6700
  if (isLegacyUnboundLocator) {
6445
6701
  candidate = await resolveLiveRunDirectoryPath(candidate, options.home ?? ledgerHome, bookKey) ?? candidate;
6446
6702
  }
6447
6703
  }
6448
6704
  const real = await requireRunDirectory(candidate, raw);
6449
- const identity = parseRunLeaf(basename7(real));
6705
+ const identity = parseRunLeaf(basename8(real));
6450
6706
  const bookIdentity = physicalPathIdentity(bookDirectory);
6451
- const parentIdentity = physicalPathIdentity(dirname8(real));
6452
- const subjectBookIdentity = physicalPathIdentity(dirname8(dirname8(dirname8(real))));
6453
- if (parentIdentity !== physicalPathIdentity(bookRunsRoot) && !(basename7(dirname8(real)) === "runs" && subjectBookIdentity === bookIdentity)) {
6707
+ const parentIdentity = physicalPathIdentity(dirname9(real));
6708
+ const subjectBookIdentity = physicalPathIdentity(dirname9(dirname9(dirname9(real))));
6709
+ if (parentIdentity !== physicalPathIdentity(bookRunsRoot) && !(basename8(dirname9(real)) === "runs" && subjectBookIdentity === bookIdentity)) {
6454
6710
  throw new NotarySourceRunError(
6455
6711
  "notary --source-run must resolve to a retained run under the project machine-ledger book"
6456
6712
  );
@@ -6484,7 +6740,7 @@ async function resolveNotarySourceRunLocator(options) {
6484
6740
  }
6485
6741
  async function loadNotarySourceRunLocator(path) {
6486
6742
  const real = await requireRunDirectory(path, path);
6487
- const identity = parseRunLeaf(basename7(real));
6743
+ const identity = parseRunLeaf(basename8(real));
6488
6744
  const runState = await readRetainedIdentity(real);
6489
6745
  if (runState === void 0) {
6490
6746
  throw new NotarySourceRunError(
@@ -7578,14 +7834,14 @@ var init_option_definitions = __esm({
7578
7834
 
7579
7835
  // src/public-cli/invocation.ts
7580
7836
  import { execFileSync as execFileSync2 } from "node:child_process";
7581
- import { existsSync as existsSync3 } from "node:fs";
7837
+ import { existsSync as existsSync4 } from "node:fs";
7582
7838
  import {
7583
7839
  readFile as readFile8,
7584
7840
  realpath as realpath3,
7585
7841
  rename,
7586
7842
  writeFile as writeFile2
7587
7843
  } from "node:fs/promises";
7588
- import { dirname as dirname9, isAbsolute as isAbsolute5, join as join12, resolve as resolve9 } from "node:path";
7844
+ import { dirname as dirname10, isAbsolute as isAbsolute5, join as join13, resolve as resolve9 } from "node:path";
7589
7845
  function admittedSourceRunPath(admitted) {
7590
7846
  if (!isRecord(admitted)) return void 0;
7591
7847
  const path = admitted.sourceRunPath;
@@ -7744,35 +8000,36 @@ async function recordAdmittedCorrelation(admitted, correlationId) {
7744
8000
  mutable.correlationId = correlationId;
7745
8001
  mutable.correlationIds = correlationIds;
7746
8002
  }
7747
- async function relocateAdmittedRunToTicket(admitted, authority, heldLease) {
7748
- if (admitted.ticketNumber === void 0 || !isUnboundRunDirectory(admitted.runDirectory)) return void 0;
7749
- const oldRunDirectory = admitted.runDirectory;
7750
- const ledgerHome = resolveActivationLedgerHome(homeFromRunDirectory(oldRunDirectory));
7751
- const target = roleRunPlacement(ledgerHome, {
7752
- bookKey: admitted.bookKey,
7753
- subject: { ticketNumber: admitted.ticketNumber },
7754
- runId: admitted.runId,
7755
- role: admitted.role
7756
- });
7757
- ensureRoleRunDirectory(ledgerHome, dirname9(target.runDirectory));
7758
- const principal = authority.seal(target);
7759
- if (admitted.role !== "diarist") {
7760
- const childRunIds = readPageSync(oldRunDirectory, "admitted")?.childDiaristRunIds;
7761
- for (const childRunId of Array.isArray(childRunIds) ? childRunIds : []) {
7762
- if (typeof childRunId !== "string") continue;
7763
- const childDirectory = join12(dirname9(oldRunDirectory), formatRunLeaf(childRunId, "diarist"));
7764
- if (!existsSync3(childDirectory)) continue;
7765
- const childTarget = roleRunPlacement(ledgerHome, {
7766
- bookKey: admitted.bookKey,
7767
- subject: { ticketNumber: admitted.ticketNumber },
7768
- runId: childRunId,
7769
- role: "diarist"
8003
+ async function relocateRegisteredChildDiarists(input) {
8004
+ const childRunIds = readPageSync(input.parentRunDirectory, "admitted")?.childDiaristRunIds;
8005
+ for (const childRunId of Array.isArray(childRunIds) ? childRunIds : []) {
8006
+ if (typeof childRunId !== "string") continue;
8007
+ const childTarget = roleRunPlacement(input.ledgerHome, {
8008
+ bookKey: input.bookKey,
8009
+ subject: { ticketNumber: input.ticketNumber },
8010
+ runId: childRunId,
8011
+ role: "diarist"
8012
+ });
8013
+ const unboundChildDirectory = roleRunPlacement(input.ledgerHome, {
8014
+ bookKey: input.bookKey,
8015
+ subject: { unbound: true },
8016
+ runId: childRunId,
8017
+ role: "diarist"
8018
+ }).runDirectory;
8019
+ if (existsSync4(unboundChildDirectory)) {
8020
+ input.authority.seal(childTarget);
8021
+ await bindTicketNumberOnRunDirectory(unboundChildDirectory, input.ticketNumber);
8022
+ await rehomeUnboundTicketProvenance(
8023
+ unboundChildDirectory,
8024
+ input.ticketNumber,
8025
+ input.projectRoot,
8026
+ homeFromRunDirectory(input.parentRunDirectory)
8027
+ );
8028
+ ensureRoleRunDirectory(input.ledgerHome, dirname10(childTarget.runDirectory));
8029
+ await rename(unboundChildDirectory, childTarget.runDirectory);
8030
+ relocateTicketProgressForLeg({
8031
+ runDirectory: childTarget.runDirectory
7770
8032
  });
7771
- authority.seal(childTarget);
7772
- await bindTicketNumberOnRunDirectory(childDirectory, admitted.ticketNumber);
7773
- await rehomeUnboundTicketProvenance(childDirectory, admitted.ticketNumber, admitted.projectRoot, homeFromRunDirectory(oldRunDirectory));
7774
- ensureRoleRunDirectory(ledgerHome, dirname9(childTarget.runDirectory));
7775
- await rename(childDirectory, childTarget.runDirectory);
7776
8033
  try {
7777
8034
  renderCurrentSync(childTarget.runDirectory);
7778
8035
  } catch (error) {
@@ -7781,18 +8038,71 @@ async function relocateAdmittedRunToTicket(admitted, authority, heldLease) {
7781
8038
  `
7782
8039
  );
7783
8040
  }
8041
+ continue;
8042
+ }
8043
+ if (existsSync4(childTarget.runDirectory)) {
8044
+ relocateTicketProgressForLeg({
8045
+ runDirectory: childTarget.runDirectory
8046
+ });
8047
+ }
8048
+ }
8049
+ }
8050
+ async function relocateAdmittedRunToTicket(admitted, authority, heldLease) {
8051
+ if (admitted.ticketNumber === void 0) return void 0;
8052
+ const ledgerHome = resolveActivationLedgerHome(homeFromRunDirectory(admitted.runDirectory));
8053
+ if (!isUnboundRunDirectory(admitted.runDirectory)) {
8054
+ relocateTicketProgressForLeg({
8055
+ runDirectory: admitted.runDirectory
8056
+ });
8057
+ if (admitted.role !== "diarist") {
8058
+ await relocateRegisteredChildDiarists({
8059
+ parentRunDirectory: admitted.runDirectory,
8060
+ bookKey: admitted.bookKey,
8061
+ ticketNumber: admitted.ticketNumber,
8062
+ projectRoot: admitted.projectRoot,
8063
+ ledgerHome,
8064
+ authority
8065
+ });
7784
8066
  }
8067
+ return void 0;
8068
+ }
8069
+ const oldRunDirectory = admitted.runDirectory;
8070
+ const target = roleRunPlacement(ledgerHome, {
8071
+ bookKey: admitted.bookKey,
8072
+ subject: { ticketNumber: admitted.ticketNumber },
8073
+ runId: admitted.runId,
8074
+ role: admitted.role
8075
+ });
8076
+ ensureRoleRunDirectory(ledgerHome, dirname10(target.runDirectory));
8077
+ authority.seal(target);
8078
+ if (admitted.role !== "diarist") {
8079
+ await relocateRegisteredChildDiarists({
8080
+ parentRunDirectory: oldRunDirectory,
8081
+ bookKey: admitted.bookKey,
8082
+ ticketNumber: admitted.ticketNumber,
8083
+ projectRoot: admitted.projectRoot,
8084
+ ledgerHome,
8085
+ authority
8086
+ });
7785
8087
  }
7786
8088
  if (admitted.role === "diarist") {
7787
8089
  await rehomeUnboundTicketProvenance(oldRunDirectory, admitted.ticketNumber, admitted.projectRoot, homeFromRunDirectory(oldRunDirectory));
7788
8090
  }
7789
8091
  await rename(oldRunDirectory, target.runDirectory);
7790
8092
  heldLease?.relocate(target.runDirectory);
8093
+ const actualSessionDirectory = sessionDirectoryOf(target.runDirectory);
8094
+ const principal = authority.seal({
8095
+ sessionDirectory: actualSessionDirectory,
8096
+ sessionFile: sessionFileIn(actualSessionDirectory)
8097
+ });
7791
8098
  rewriteAdmittedRoleRunPage(
7792
8099
  admitted,
7793
8100
  [{ oldRunDirectory, newRunDirectory: target.runDirectory }]
7794
8101
  );
7795
8102
  admitted.principal = principal;
8103
+ relocateTicketProgressForLeg({
8104
+ runDirectory: target.runDirectory
8105
+ });
7796
8106
  renderCurrentSync(target.runDirectory);
7797
8107
  return { oldRunDirectory, newRunDirectory: target.runDirectory };
7798
8108
  }
@@ -7828,7 +8138,7 @@ async function recordLaunchedPiIdentity(runDirectory, identity) {
7828
8138
  async function observeLaunchedRolePackageIdentity(packageRoot, selectedRoleEntry) {
7829
8139
  const rolePackageRoot = packageRoot;
7830
8140
  const raw = JSON.parse(
7831
- await readFile8(join12(rolePackageRoot, "package.json"), "utf8")
8141
+ await readFile8(join13(rolePackageRoot, "package.json"), "utf8")
7832
8142
  );
7833
8143
  if (typeof raw.version !== "string" || raw.version.trim() === "") {
7834
8144
  throw new Error(
@@ -8386,7 +8696,7 @@ async function admitPublicRole(role, parsed, env, override) {
8386
8696
  resolutionScope: [...derived.resolutionScope],
8387
8697
  authorizedChecks: []
8388
8698
  });
8389
- const mergerInputPath = join12(placed.runDirectory, "merger-input.json");
8699
+ const mergerInputPath = join13(placed.runDirectory, "merger-input.json");
8390
8700
  await writeFile2(
8391
8701
  mergerInputPath,
8392
8702
  `${JSON.stringify(mergerInput, null, 2)}
@@ -8668,7 +8978,7 @@ function parseDoctorIssueNumber(raw) {
8668
8978
  }
8669
8979
  async function resolveDoctorCaseRunsPath(options) {
8670
8980
  const ledgerHome = resolveActivationLedgerHome(options.home);
8671
- const defaultRuns = join12(
8981
+ const defaultRuns = join13(
8672
8982
  activationBookDirectory(ledgerHome, options.bookKey),
8673
8983
  String(options.issueNumber),
8674
8984
  "runs"
@@ -8741,11 +9051,11 @@ function parseAnalystCohortIssueToken(raw, flag) {
8741
9051
  `${flag} requires a comma-separated list of N or book:N`
8742
9052
  );
8743
9053
  }
8744
- const sep5 = trimmed.lastIndexOf(":");
8745
- if (sep5 > 0) {
8746
- const rhs = trimmed.slice(sep5 + 1);
9054
+ const sep6 = trimmed.lastIndexOf(":");
9055
+ if (sep6 > 0) {
9056
+ const rhs = trimmed.slice(sep6 + 1);
8747
9057
  if (parseTicketNumber(rhs) !== void 0) {
8748
- const bookKey = trimmed.slice(0, sep5);
9058
+ const bookKey = trimmed.slice(0, sep6);
8749
9059
  if (bookKey.trim() === "") {
8750
9060
  throw new CliUsageError(
8751
9061
  `${flag} book:N requires a non-empty book key, got ${raw}`
@@ -8942,6 +9252,7 @@ var init_invocation = __esm({
8942
9252
  init_activation_ledger_topology();
8943
9253
  init_activation_ledger_git();
8944
9254
  init_role_run_placement();
9255
+ init_ticket_progress();
8945
9256
  init_packaged_role_registry();
8946
9257
  init_run_ticket_number();
8947
9258
  init_role_run_relocation();
@@ -8964,7 +9275,7 @@ var init_invocation = __esm({
8964
9275
 
8965
9276
  // src/report-ticket-tool.ts
8966
9277
  import { Type as Type16 } from "typebox";
8967
- import { existsSync as existsSync4 } from "node:fs";
9278
+ import { existsSync as existsSync5 } from "node:fs";
8968
9279
  function pageString(page, key) {
8969
9280
  const value = page?.[key];
8970
9281
  return typeof value === "string" && value.trim() !== "" ? value : void 0;
@@ -9006,7 +9317,7 @@ async function reportTicketFromHostContext(context, rawTicketNumber, authority =
9006
9317
  if (runDirectory === void 0) {
9007
9318
  throw new Error("ak_report_ticket requires a per-turn run directory");
9008
9319
  }
9009
- if (!existsSync4(runDirectory)) {
9320
+ if (!existsSync5(runDirectory)) {
9010
9321
  throw new Error(`ak_report_ticket run directory missing: ${runDirectory}`);
9011
9322
  }
9012
9323
  const admitted = admittedForLiveTicketReport(runDirectory, authority);
@@ -9025,7 +9336,11 @@ async function reportTicketFromHostContext(context, rawTicketNumber, authority =
9025
9336
  context.sessionManager.setSessionFile?.(projectedSessionFile);
9026
9337
  }
9027
9338
  };
9028
- const relocation = alreadyPlaced ? void 0 : await relocateAdmittedRunToTicket(admitted, authority, { relocate: applyLiveHandles });
9339
+ const relocation = await relocateAdmittedRunToTicket(
9340
+ admitted,
9341
+ authority,
9342
+ alreadyPlaced ? void 0 : { relocate: applyLiveHandles }
9343
+ );
9029
9344
  const nextDirectory = relocation?.newRunDirectory ?? admitted.runDirectory;
9030
9345
  if (relocation === void 0) applyLiveHandles(nextDirectory);
9031
9346
  return {
@@ -9282,6 +9597,7 @@ async function sealAcceptedSubmission(options) {
9282
9597
  const attemptId = attemptIdentity(options.context, runId);
9283
9598
  const sessionParent = sessionParentFromHostContext(options.context);
9284
9599
  const home = homeFromHostContext(options.context, options.home);
9600
+ const sealHead = captureWorktreeHead(options.context.cwd);
9285
9601
  sitianReport({
9286
9602
  level: "event",
9287
9603
  kind: "sealed",
@@ -9298,6 +9614,12 @@ async function sealAcceptedSubmission(options) {
9298
9614
  ...home !== void 0 ? { home } : {},
9299
9615
  ...sessionParent === void 0 ? {} : { sessionParent }
9300
9616
  });
9617
+ landTicketProgressForSealedSubmission({
9618
+ context: options.context,
9619
+ role: options.role,
9620
+ accepted: options.accepted,
9621
+ sealHead
9622
+ });
9301
9623
  }
9302
9624
  function createSubmissionLedgerHost(host, outputTools, failInfrastructure2 = (error) => {
9303
9625
  throw error;
@@ -9422,6 +9744,7 @@ function createSubmissionLedgerHost(host, outputTools, failInfrastructure2 = (er
9422
9744
  kind: "accepted",
9423
9745
  accepted: params
9424
9746
  };
9747
+ const sealHead = captureWorktreeHead(context.cwd);
9425
9748
  append({
9426
9749
  type: "sealed",
9427
9750
  attemptId,
@@ -9429,6 +9752,14 @@ function createSubmissionLedgerHost(host, outputTools, failInfrastructure2 = (er
9429
9752
  role,
9430
9753
  accepted: params
9431
9754
  });
9755
+ const rawLens = typeof host.getFlag === "function" ? host.getFlag("ak-review-lens") : void 0;
9756
+ landTicketProgressForSealedSubmission({
9757
+ context,
9758
+ role,
9759
+ accepted: params,
9760
+ sealHead,
9761
+ ...rawLens === "completeness" || rawLens === "correctness" ? { lens: rawLens } : {}
9762
+ });
9432
9763
  await projectClosure(closed, context);
9433
9764
  return result;
9434
9765
  }
@@ -9450,6 +9781,7 @@ var init_submission_ledger = __esm({
9450
9781
  init_report_ticket_tool();
9451
9782
  init_review_submission();
9452
9783
  init_run_ticket_number();
9784
+ init_ticket_progress();
9453
9785
  init_unknown_value();
9454
9786
  }
9455
9787
  });
@@ -9636,7 +9968,7 @@ var init_engine_detour_usage = __esm({
9636
9968
  });
9637
9969
 
9638
9970
  // src/dossier-resolution.ts
9639
- import { existsSync as existsSync5, statSync as statSync4 } from "node:fs";
9971
+ import { existsSync as existsSync6, statSync as statSync4 } from "node:fs";
9640
9972
  import { resolve as resolve10 } from "node:path";
9641
9973
  function isHostContext(value) {
9642
9974
  return "sessionManager" in value;
@@ -9656,7 +9988,7 @@ function resolveAuditDossier(source) {
9656
9988
  }
9657
9989
  const runDirectory = resolve10(raw);
9658
9990
  try {
9659
- if (!existsSync5(runDirectory) || !statSync4(runDirectory).isDirectory()) {
9991
+ if (!existsSync6(runDirectory) || !statSync4(runDirectory).isDirectory()) {
9660
9992
  return { status: "incomplete", observation: { kind: "missing-dossier" } };
9661
9993
  }
9662
9994
  } catch {
@@ -10745,12 +11077,12 @@ var init_settlement = __esm({
10745
11077
  });
10746
11078
 
10747
11079
  // src/external-host-turn-loop.ts
10748
- import { existsSync as existsSync6 } from "node:fs";
10749
- import { basename as basename8 } from "node:path";
11080
+ import { existsSync as existsSync7 } from "node:fs";
11081
+ import { basename as basename9 } from "node:path";
10750
11082
  async function syncTurnRequestLivePlacement(request, authority) {
10751
11083
  const live = await resolveLiveRunDirectoryPath(request.runDirectory, request.home);
10752
11084
  if (live === void 0) {
10753
- const parsed = parseRunLeaf(basename8(request.runDirectory));
11085
+ const parsed = parseRunLeaf(basename9(request.runDirectory));
10754
11086
  throw new Error(
10755
11087
  `admitted run ${parsed?.runId ?? "(unparseable)"} missing after host turn; not found under ${request.home}`
10756
11088
  );
@@ -10769,7 +11101,7 @@ async function trySyncTurnRequestLivePlacement(request, authority) {
10769
11101
  }
10770
11102
  async function retainPackageFaultBesideLivePlacement(request, input) {
10771
11103
  let runDirectory = request.runDirectory;
10772
- if (!existsSync6(runDirectory)) {
11104
+ if (!existsSync7(runDirectory)) {
10773
11105
  try {
10774
11106
  const found = await resolveLiveRunDirectoryPath(request.runDirectory, request.home);
10775
11107
  if (found === void 0) {
@@ -10911,6 +11243,7 @@ async function driveExternalRoleTurnRounds(prepared, request, driver) {
10911
11243
  }
10912
11244
  }
10913
11245
  prompt = closure.retry.message;
11246
+ prepared.recordSentInstruction?.(prompt);
10914
11247
  driver.afterRetry?.();
10915
11248
  }
10916
11249
  }
@@ -10953,9 +11286,9 @@ var init_external_host_turn_loop = __esm({
10953
11286
  });
10954
11287
 
10955
11288
  // src/session-identity.ts
10956
- import { dirname as dirname10, join as join13 } from "node:path";
11289
+ import { join as join14 } from "node:path";
10957
11290
  function createSessionIdentityAuthority(authority, hostName) {
10958
- const runDirectoryOf = (principal) => dirname10(authority.decode(principal).sessionDirectory);
11291
+ const runDirectoryOf = (principal) => runDirectoryFromSessionDirectory(authority.decode(principal).sessionDirectory);
10959
11292
  return {
10960
11293
  principalAuthority: authority,
10961
11294
  resolveSessionFile(principal) {
@@ -10963,7 +11296,7 @@ function createSessionIdentityAuthority(authority, hostName) {
10963
11296
  },
10964
11297
  async load(principal) {
10965
11298
  const runDirectory = runDirectoryOf(principal);
10966
- const { records, diagnostics } = await readSitianRecords(join13(runDirectory, RUN_STATE_FILE));
11299
+ const { records, diagnostics } = await readSitianRecords(join14(runDirectory, RUN_STATE_FILE));
10967
11300
  if (diagnostics.length > 0) {
10968
11301
  throw new Error(
10969
11302
  `${RUN_STATE_FILE} has ${diagnostics.length} malformed row(s); refusing stale session binding: ${runDirectory}`
@@ -11010,6 +11343,7 @@ var init_session_identity = __esm({
11010
11343
  "src/session-identity.ts"() {
11011
11344
  "use strict";
11012
11345
  init_host_descriptions();
11346
+ init_role_run_placement();
11013
11347
  init_run_dossier();
11014
11348
  init_sitian_facade();
11015
11349
  init_unknown_value();
@@ -11032,14 +11366,14 @@ __export(role_turn_host_exports, {
11032
11366
  });
11033
11367
  import { execFile as execFile2, spawn as spawn2 } from "node:child_process";
11034
11368
  import { constants } from "node:fs";
11035
- import { existsSync as existsSync7 } from "node:fs";
11369
+ import { existsSync as existsSync8 } from "node:fs";
11036
11370
  import { access as access2, appendFile, realpath as realpath4 } from "node:fs/promises";
11037
- import { delimiter, dirname as dirname11, isAbsolute as isAbsolute6, join as join14, resolve as resolve11 } from "node:path";
11371
+ import { delimiter, dirname as dirname11, isAbsolute as isAbsolute6, join as join15, resolve as resolve11 } from "node:path";
11038
11372
  import { platform } from "node:process";
11039
11373
  import { promisify as promisify2 } from "node:util";
11040
11374
  import { randomUUID as randomUUID4 } from "node:crypto";
11041
11375
  function resolveInternalRoleEntrypoint(packageRoot) {
11042
- return join14(packageRoot, INTERNAL_ROLE_ENTRYPOINT_RELATIVE2);
11376
+ return join15(packageRoot, INTERNAL_ROLE_ENTRYPOINT_RELATIVE2);
11043
11377
  }
11044
11378
  function buildExplicitInternalActivationArgs(selectedRoleEntry, extraArgs = []) {
11045
11379
  return ["--no-extensions", "-e", selectedRoleEntry, ...extraArgs];
@@ -11229,7 +11563,7 @@ function createDefaultPiSpawnRunner(options) {
11229
11563
  homeFromRunDirectory(spawnDir)
11230
11564
  );
11231
11565
  } catch (resolveError) {
11232
- runDirectory = existsSync7(spawnDir) ? spawnDir : void 0;
11566
+ runDirectory = existsSync8(spawnDir) ? spawnDir : void 0;
11233
11567
  const resolveDiagnostic = `live run path resolve failed beside Pi transport fault: ${describeErrorIdentity(resolveError)}`;
11234
11568
  if (runDirectory !== void 0) {
11235
11569
  await retainPackageFault({
@@ -11282,7 +11616,8 @@ function createPiRoleTurnHost(config) {
11282
11616
  config.extraPiArgs ?? []
11283
11617
  );
11284
11618
  const args = buildExplicitInternalActivationArgs(roleEntry, extraArgs);
11285
- const stdin = encodeUserDialogueStdin(piUserDialogueBody(turnRequest));
11619
+ const transportBody = piUserDialogueBody(turnRequest);
11620
+ const stdin = encodeUserDialogueStdin(transportBody);
11286
11621
  const env = {
11287
11622
  ...process.env,
11288
11623
  HOME: request.home,
@@ -11298,6 +11633,7 @@ function createPiRoleTurnHost(config) {
11298
11633
  else env.AK_ROLE_INVOCATION_SCOPE = request.invocationScopeId;
11299
11634
  if (request.host === void 0 || request.host.trim() === "") delete env.AK_ROLE_HOST;
11300
11635
  else env.AK_ROLE_HOST = request.host.trim();
11636
+ delete env.AK_ROLE_SUMMONS_INSTRUCTION;
11301
11637
  if (request.deliveryRequestLimit === void 0) delete env[RECEIPT_DELIVERY_LIMIT_ENV];
11302
11638
  else env[RECEIPT_DELIVERY_LIMIT_ENV] = String(request.deliveryRequestLimit);
11303
11639
  applyEngineChildEnv(env, request.engine);
@@ -11430,16 +11766,16 @@ var init_role_turn_host = __esm({
11430
11766
  });
11431
11767
 
11432
11768
  // src/public-cli/host-providers.ts
11433
- import { readFileSync as readFileSync3 } from "node:fs";
11434
- import { join as join15 } from "node:path";
11769
+ import { readFileSync as readFileSync4 } from "node:fs";
11770
+ import { join as join16 } from "node:path";
11435
11771
  function hostProvidersPath(home) {
11436
11772
  if (typeof home !== "string" || home.trim() === "") {
11437
11773
  throw new Error("home must be explicitly provided");
11438
11774
  }
11439
- return join15(home, ".ak-roles", "host-providers.json");
11775
+ return join16(home, ".ak-roles", "host-providers.json");
11440
11776
  }
11441
11777
  function hermesProviderModelsCachePath(home) {
11442
- return join15(home, ".hermes", "provider_models_cache.json");
11778
+ return join16(home, ".hermes", "provider_models_cache.json");
11443
11779
  }
11444
11780
  function parseHostProvidersTable(value) {
11445
11781
  if (!isRecord(value)) {
@@ -11476,7 +11812,7 @@ function parseHostProvidersTable(value) {
11476
11812
  function loadHostProvidersTable(home) {
11477
11813
  const path = hostProvidersPath(home);
11478
11814
  try {
11479
- const raw = readFileSync3(path, "utf8");
11815
+ const raw = readFileSync4(path, "utf8");
11480
11816
  return parseHostProvidersTable(JSON.parse(raw));
11481
11817
  } catch (error) {
11482
11818
  if (isEnoent(error)) return {};
@@ -11492,7 +11828,7 @@ function listHermesProvidersForModel(home, seatModel) {
11492
11828
  const path = hermesProviderModelsCachePath(home);
11493
11829
  let text;
11494
11830
  try {
11495
- text = readFileSync3(path, "utf8");
11831
+ text = readFileSync4(path, "utf8");
11496
11832
  } catch (error) {
11497
11833
  if (isEnoent(error)) return [];
11498
11834
  throw error;
@@ -11589,17 +11925,17 @@ var init_host_providers = __esm({
11589
11925
  });
11590
11926
 
11591
11927
  // src/public-cli/load-production-acp-host.ts
11592
- import { existsSync as existsSync8 } from "node:fs";
11593
- import { join as join16 } from "node:path";
11928
+ import { existsSync as existsSync9 } from "node:fs";
11929
+ import { join as join17 } from "node:path";
11594
11930
  import { pathToFileURL } from "node:url";
11595
11931
  async function loadProductionAcpHostFactory(packageRoot, host) {
11596
11932
  const description = lookupHostDescription(host);
11597
11933
  if (description === void 0) {
11598
11934
  throw new Error(`unregistered host: ${host}`);
11599
11935
  }
11600
- const built = join16(packageRoot, "dist/acp-host/production-host.js");
11601
- const source = join16(packageRoot, "src/acp-host/production-host.ts");
11602
- const target = existsSync8(built) ? built : source;
11936
+ const built = join17(packageRoot, "dist/acp-host/production-host.js");
11937
+ const source = join17(packageRoot, "src/acp-host/production-host.ts");
11938
+ const target = existsSync9(built) ? built : source;
11603
11939
  const href = pathToFileURL(target).href;
11604
11940
  const mod = await import(href);
11605
11941
  const create = mod.createProductionAcpRoleTurnHost;
@@ -11613,17 +11949,17 @@ var init_load_production_acp_host = __esm({
11613
11949
  });
11614
11950
 
11615
11951
  // src/public-cli/load-production-headless-host.ts
11616
- import { existsSync as existsSync9 } from "node:fs";
11617
- import { join as join17 } from "node:path";
11952
+ import { existsSync as existsSync10 } from "node:fs";
11953
+ import { join as join18 } from "node:path";
11618
11954
  import { pathToFileURL as pathToFileURL2 } from "node:url";
11619
11955
  async function loadProductionHeadlessHostFactory(packageRoot, host) {
11620
11956
  const description = lookupHeadlessHostDescription(host);
11621
11957
  if (description === void 0) {
11622
11958
  throw new Error(`unregistered headless host: ${host}`);
11623
11959
  }
11624
- const built = join17(packageRoot, "dist/headless-host/production-host.js");
11625
- const source = join17(packageRoot, "src/headless-host/production-host.ts");
11626
- const target = existsSync9(built) ? built : source;
11960
+ const built = join18(packageRoot, "dist/headless-host/production-host.js");
11961
+ const source = join18(packageRoot, "src/headless-host/production-host.ts");
11962
+ const target = existsSync10(built) ? built : source;
11627
11963
  const href = pathToFileURL2(target).href;
11628
11964
  const mod = await import(href);
11629
11965
  const create = mod.createProductionHeadlessRoleTurnHost;
@@ -11790,14 +12126,14 @@ var init_role_seat_runtime = __esm({
11790
12126
  });
11791
12127
 
11792
12128
  // src/session-opening-materials.ts
11793
- import { existsSync as existsSync10 } from "node:fs";
12129
+ import { existsSync as existsSync11 } from "node:fs";
11794
12130
  import { readFile as readFile9 } from "node:fs/promises";
11795
- import { dirname as dirname12, join as join18 } from "node:path";
12131
+ import { dirname as dirname12, join as join19 } from "node:path";
11796
12132
  import { fileURLToPath, pathToFileURL as pathToFileURL3 } from "node:url";
11797
12133
  function resolvePackageRootDir(moduleUrl = import.meta.url) {
11798
12134
  let dir = dirname12(fileURLToPath(moduleUrl));
11799
12135
  for (let i = 0; i < 8; i += 1) {
11800
- if (existsSync10(join18(dir, "package.json")) && existsSync10(join18(dir, "souls"))) {
12136
+ if (existsSync11(join19(dir, "package.json")) && existsSync11(join19(dir, "souls"))) {
11801
12137
  return dir;
11802
12138
  }
11803
12139
  const parent = dirname12(dir);
@@ -12157,7 +12493,7 @@ __export(auditor_soul_exports, {
12157
12493
  readAuditorResumeBinding: () => readAuditorResumeBinding,
12158
12494
  resolveAuditorSubject: () => resolveAuditorSubject
12159
12495
  });
12160
- import { basename as basename9 } from "node:path";
12496
+ import { basename as basename10 } from "node:path";
12161
12497
  function auditorSoulRelativePath(role) {
12162
12498
  return `souls/${role}-auditor.md`;
12163
12499
  }
@@ -12193,7 +12529,7 @@ function loadAuditorReferenceMaterialsFromSubjectInput(raw) {
12193
12529
  return loadAuditorReferenceMaterials(resolveAuditorSubject(raw));
12194
12530
  }
12195
12531
  function subjectFromSourceDirectory(sourceRunDirectory) {
12196
- const role = parseRunLeaf(basename9(sourceRunDirectory))?.role;
12532
+ const role = parseRunLeaf(basename10(sourceRunDirectory))?.role;
12197
12533
  return isAuditorSoulRole(role) ? role : void 0;
12198
12534
  }
12199
12535
  async function readAuditorResumeBinding(admitted) {
@@ -12236,16 +12572,16 @@ var init_auditor_soul = __esm({
12236
12572
  // src/public-cli/machine-method-skills.ts
12237
12573
  import { accessSync, constants as constants2, statSync as statSync5 } from "node:fs";
12238
12574
  import { lstat as lstat2, mkdir as mkdir2, symlink } from "node:fs/promises";
12239
- import { join as join20 } from "node:path";
12240
- import { spawnSync as spawnSync2 } from "node:child_process";
12575
+ import { join as join21 } from "node:path";
12576
+ import { spawnSync as spawnSync3 } from "node:child_process";
12241
12577
  function skillRoot(home) {
12242
- return join20(home, ".agents/skills");
12578
+ return join21(home, ".agents/skills");
12243
12579
  }
12244
12580
  function installedMethodSkillPath(home, name) {
12245
12581
  return installedSkillPath(skillRoot(home), name);
12246
12582
  }
12247
12583
  function installedSkillPath(root, name) {
12248
- const path = join20(root, name, "SKILL.md");
12584
+ const path = join21(root, name, "SKILL.md");
12249
12585
  try {
12250
12586
  if (!statSync5(path).isFile()) return void 0;
12251
12587
  accessSync(path, constants2.R_OK);
@@ -12258,9 +12594,9 @@ function installedSkillPath(root, name) {
12258
12594
  }
12259
12595
  function linkedSkillRoot(home, host) {
12260
12596
  if (host === "claude" || host === "claude-code") {
12261
- return join20(process.env.CLAUDE_CONFIG_DIR?.trim() || join20(home, ".claude"), "skills");
12597
+ return join21(process.env.CLAUDE_CONFIG_DIR?.trim() || join21(home, ".claude"), "skills");
12262
12598
  }
12263
- if (host === "hermes") return join20(home, ".hermes/skills");
12599
+ if (host === "hermes") return join21(home, ".hermes/skills");
12264
12600
  return void 0;
12265
12601
  }
12266
12602
  async function occupied(path) {
@@ -12288,7 +12624,7 @@ async function warnMissingMethodSkills(home, host, role, skills, stdout) {
12288
12624
  }
12289
12625
  }
12290
12626
  function runSkillsCli(args, home) {
12291
- const result = spawnSync2("npx", ["--yes", "skills", ...args], {
12627
+ const result = spawnSync3("npx", ["--yes", "skills", ...args], {
12292
12628
  stdio: "inherit",
12293
12629
  env: { ...process.env, HOME: home }
12294
12630
  });
@@ -12317,7 +12653,7 @@ async function runMachineSkillSetup(home, stdout) {
12317
12653
  const missingBySource = /* @__PURE__ */ new Map();
12318
12654
  let unsourced = false;
12319
12655
  for (const name of packagedMethodSkillNames()) {
12320
- const path = join20(canonical, name);
12656
+ const path = join21(canonical, name);
12321
12657
  if (await occupied(path)) {
12322
12658
  warnOccupied(path, stdout);
12323
12659
  continue;
@@ -12347,9 +12683,9 @@ async function runMachineSkillSetup(home, stdout) {
12347
12683
  throw error;
12348
12684
  }
12349
12685
  for (const name of packagedMethodSkillNames()) {
12350
- const target = join20(canonical, name);
12686
+ const target = join21(canonical, name);
12351
12687
  if (installedMethodSkillPath(home, name) === void 0) continue;
12352
- const link = join20(root, name);
12688
+ const link = join21(root, name);
12353
12689
  if (await occupied(link)) {
12354
12690
  warnOccupied(link, stdout);
12355
12691
  continue;
@@ -12409,7 +12745,8 @@ function projectRoleTurnRequest(admitted, roleDetails, options) {
12409
12745
  ...options.invocationScopeId === void 0 || options.invocationScopeId.length === 0 ? {} : { invocationScopeId: options.invocationScopeId },
12410
12746
  ...options.stationChild === void 0 ? {} : { stationChild: options.stationChild },
12411
12747
  ...options.navigatorByStatusPrepare === void 0 ? {} : { navigatorByStatusPrepare: options.navigatorByStatusPrepare },
12412
- ...options.deliveryRequestLimit === void 0 ? {} : { deliveryRequestLimit: options.deliveryRequestLimit }
12748
+ ...options.deliveryRequestLimit === void 0 ? {} : { deliveryRequestLimit: options.deliveryRequestLimit },
12749
+ ...options.host === void 0 || options.host.trim() === "" ? {} : { host: options.host.trim() }
12413
12750
  };
12414
12751
  }
12415
12752
  function packagedSettleSkill(admitted) {
@@ -14377,7 +14714,7 @@ async function resolveReviewSeatDialogueBody(input) {
14377
14714
  if (sourceRunPath === void 0) return void 0;
14378
14715
  return await loadLedgerPeerBody(sourceRunPath, input.projectRoot, input.home);
14379
14716
  }
14380
- async function resolveInitialPrompt(admitted, env) {
14717
+ async function resolveInitialTurnPrompt(admitted, env) {
14381
14718
  const record = roleRecord(admitted.role);
14382
14719
  if ("reaskPrompt" in record && record.reaskPrompt === true) {
14383
14720
  const sourceRunPath = admittedSourceRunPath(admitted);
@@ -14474,7 +14811,7 @@ async function dispatchAdmitted(admitted, env, io) {
14474
14811
  if (activeEnv.correlationId !== void 0 && activeEnv.correlationId.trim() !== "") {
14475
14812
  await recordAdmittedCorrelation(admitted, activeEnv.correlationId);
14476
14813
  }
14477
- const initialPromptText = await resolveInitialPrompt(admitted, activeEnv);
14814
+ const initialPrompt = await resolveInitialTurnPrompt(admitted, activeEnv);
14478
14815
  const auto = "inCallAutoResume" in record && record.inCallAutoResume === true;
14479
14816
  if (auto) {
14480
14817
  return await runPostAdmissionResumable({
@@ -14485,14 +14822,14 @@ async function dispatchAdmitted(admitted, env, io) {
14485
14822
  admitted,
14486
14823
  roleTurnOptions(activeEnv, admitted, {
14487
14824
  kind: "initial",
14488
- prompt: initialPromptText
14825
+ prompt: initialPrompt
14489
14826
  })
14490
14827
  ),
14491
14828
  buildResumeRequest: () => buildInstructionSeatTurnRequest(
14492
14829
  admitted,
14493
14830
  roleTurnOptions(activeEnv, admitted, {
14494
14831
  kind: "resume",
14495
- prompt: initialPromptText
14832
+ prompt: initialPrompt
14496
14833
  })
14497
14834
  ),
14498
14835
  adapters,
@@ -14507,7 +14844,7 @@ async function dispatchAdmitted(admitted, env, io) {
14507
14844
  admitted,
14508
14845
  roleTurnOptions(activeEnv, admitted, {
14509
14846
  kind: "initial",
14510
- prompt: initialPromptText
14847
+ prompt: initialPrompt
14511
14848
  })
14512
14849
  ),
14513
14850
  adapters,
@@ -14683,7 +15020,7 @@ async function runCountersignBody(parsed, env, io) {
14683
15020
  }
14684
15021
  const turnProjection = roleTurnOptions(env, admitted, {
14685
15022
  kind: "initial",
14686
- prompt: await resolveInitialPrompt(admitted, env)
15023
+ prompt: await resolveInitialTurnPrompt(admitted, env)
14687
15024
  });
14688
15025
  const turnRequest = buildInstructionSeatTurnRequest(admitted, turnProjection);
14689
15026
  const result = await runPostAdmissionOneShot({
@@ -15566,10 +15903,10 @@ var init_analyst_book_key = __esm({
15566
15903
  // src/atomic-write.ts
15567
15904
  import { randomUUID as randomUUID6 } from "node:crypto";
15568
15905
  import { rename as rename2, rm, writeFile as writeFile3 } from "node:fs/promises";
15569
- import { dirname as dirname14, join as join21 } from "node:path";
15906
+ import { dirname as dirname14, join as join22 } from "node:path";
15570
15907
  async function writeFileAtomically(destination, contents, options) {
15571
15908
  const parent = dirname14(destination);
15572
- const temporary = join21(parent, `.atomic-write-${randomUUID6()}.tmp`);
15909
+ const temporary = join22(parent, `.atomic-write-${randomUUID6()}.tmp`);
15573
15910
  try {
15574
15911
  await writeFile3(temporary, contents, options);
15575
15912
  await rename2(temporary, destination);
@@ -15586,12 +15923,12 @@ var init_atomic_write = __esm({
15586
15923
 
15587
15924
  // src/analyst-index.ts
15588
15925
  import { open, readFile as readFile10, unlink } from "node:fs/promises";
15589
- import { dirname as dirname15, join as join22 } from "node:path";
15926
+ import { dirname as dirname15, join as join23 } from "node:path";
15590
15927
  import { setTimeout as sleep } from "node:timers/promises";
15591
15928
  async function withAnalystLibraryIndexLock(ledgerHome, fn) {
15592
15929
  const indexPath = analystLibraryIndexPath(ledgerHome);
15593
15930
  ensureRealDirectoryTree(ledgerHome, dirname15(indexPath));
15594
- const lockPath = join22(dirname15(indexPath), LIBRARY_INDEX_LOCK_NAME);
15931
+ const lockPath = join23(dirname15(indexPath), LIBRARY_INDEX_LOCK_NAME);
15595
15932
  assertLedgerFileInsideHome(lockPath, ledgerHome);
15596
15933
  const startedAt = Date.now();
15597
15934
  while (true) {
@@ -15618,7 +15955,7 @@ async function withAnalystLibraryIndexLock(ledgerHome, fn) {
15618
15955
  }
15619
15956
  }
15620
15957
  function analystLibraryIndexPath(ledgerHome) {
15621
- return join22(ledgerHome, "analyst", "library-index.json");
15958
+ return join23(ledgerHome, "analyst", "library-index.json");
15622
15959
  }
15623
15960
  function rowFromIssueMetricsPage(page) {
15624
15961
  return {
@@ -15912,7 +16249,7 @@ var init_analyst_cohort = __esm({
15912
16249
  });
15913
16250
 
15914
16251
  // src/archivist-record-pointer.ts
15915
- import { basename as basename10, join as join23 } from "node:path";
16252
+ import { basename as basename11, join as join24 } from "node:path";
15916
16253
  async function resolveOfficerPointer(raw, parentRunDirectory) {
15917
16254
  const where = `${parentRunDirectory} officers`;
15918
16255
  if (!isRecord(raw) || raw.kind !== DIRECT_OFFICER_RUN_POINTER_KIND || raw.version !== 1) {
@@ -15925,7 +16262,7 @@ async function resolveOfficerPointer(raw, parentRunDirectory) {
15925
16262
  let runDirectory = typeof raw.runDirectory === "string" && raw.runDirectory.trim() !== "" ? raw.runDirectory : void 0;
15926
16263
  let sessionFile = raw.sessionFile;
15927
16264
  const recordedRunDirectory = runDirectory ?? runDirectoryOfSessionFile(sessionFile);
15928
- const leaf = parseRunLeaf(basename10(recordedRunDirectory));
16265
+ const leaf = parseRunLeaf(basename11(recordedRunDirectory));
15929
16266
  const parentIdentity = await readRoleRunIdentity(parentRunDirectory);
15930
16267
  if (leaf !== void 0 && parentIdentity !== void 0) {
15931
16268
  const currentRunDirectory = await resolveLiveRunDirectoryPath(
@@ -15945,7 +16282,7 @@ async function resolveOfficerPointer(raw, parentRunDirectory) {
15945
16282
  };
15946
16283
  }
15947
16284
  async function readBookedOfficerPointers(parentRunDirectory) {
15948
- const { records, diagnostics } = await readSitianRecords(join23(parentRunDirectory, RUN_HISTORY_FILE));
16285
+ const { records, diagnostics } = await readSitianRecords(join24(parentRunDirectory, RUN_HISTORY_FILE));
15949
16286
  if (diagnostics.length > 0) {
15950
16287
  throw new Error(
15951
16288
  `${RUN_HISTORY_FILE} has ${diagnostics.length} malformed row(s); officer pointers unreadable: ${parentRunDirectory}`
@@ -16228,7 +16565,7 @@ var init_analyst_gate_cycles_read = __esm({
16228
16565
 
16229
16566
  // src/analyst-ledger.ts
16230
16567
  import { readdir as readdir3 } from "node:fs/promises";
16231
- import { basename as basename11, join as join24 } from "node:path";
16568
+ import { basename as basename12, join as join25 } from "node:path";
16232
16569
  async function readExistingRunLifecycleState(runDirectory) {
16233
16570
  return (await readRoleRunIdentity(runDirectory))?.state;
16234
16571
  }
@@ -16248,7 +16585,7 @@ function ghostLeaseCheckFromAutopsy(autopsy) {
16248
16585
  }
16249
16586
  }
16250
16587
  async function classifyGhostCandidate(input) {
16251
- const autopsy = await autopsyWriterLock(join24(input.runDirectory, "writer.lock"));
16588
+ const autopsy = await autopsyWriterLock(join25(input.runDirectory, "writer.lock"));
16252
16589
  const leaseCheck = ghostLeaseCheckFromAutopsy(autopsy);
16253
16590
  if (leaseCheck === void 0) return { kind: "live" };
16254
16591
  return {
@@ -16538,7 +16875,7 @@ async function classifyScopedRun(input) {
16538
16875
  async function scanAnalystIssueRuns(input) {
16539
16876
  const ledgerHome = resolveActivationLedgerHome(input.home);
16540
16877
  const scopeTicketNumber = input.ticketNumber;
16541
- const booksRoot = join24(ledgerHome, "books");
16878
+ const booksRoot = join25(ledgerHome, "books");
16542
16879
  let wholeBook = false;
16543
16880
  let scopeRootIdentity;
16544
16881
  let bookNames;
@@ -16571,7 +16908,7 @@ async function scanAnalystIssueRuns(input) {
16571
16908
  const ghostLegs = [];
16572
16909
  const scopeConflicts = [];
16573
16910
  for (const book of bookNames) {
16574
- const bookDir = join24(booksRoot, book);
16911
+ const bookDir = join25(booksRoot, book);
16575
16912
  let runDirectories;
16576
16913
  try {
16577
16914
  runDirectories = await listBookRunDirectories(bookDir);
@@ -16580,7 +16917,7 @@ async function scanAnalystIssueRuns(input) {
16580
16917
  throw error;
16581
16918
  }
16582
16919
  for (const runDirectory of runDirectories) {
16583
- const runName = basename11(runDirectory);
16920
+ const runName = basename12(runDirectory);
16584
16921
  const parsed = parseRunLeaf(runName);
16585
16922
  if (parsed === void 0) continue;
16586
16923
  let scopeFields;
@@ -17317,7 +17654,7 @@ var init_analyst_metric_family = __esm({
17317
17654
  });
17318
17655
 
17319
17656
  // src/analyst-page.ts
17320
- import { dirname as dirname16, join as join25 } from "node:path";
17657
+ import { dirname as dirname16, join as join26 } from "node:path";
17321
17658
  function analystIssuePageKey(address) {
17322
17659
  const parts = ["book", address.bookKey];
17323
17660
  if (address.issueNumber !== void 0) {
@@ -17328,7 +17665,7 @@ function analystIssuePageKey(address) {
17328
17665
  return sha256Hex(parts.join("\0")).slice(0, 32);
17329
17666
  }
17330
17667
  function analystIssuePagePath(ledgerHome, address) {
17331
- return join25(ledgerHome, "analyst", "issues", `${analystIssuePageKey(address)}.json`);
17668
+ return join26(ledgerHome, "analyst", "issues", `${analystIssuePageKey(address)}.json`);
17332
17669
  }
17333
17670
  function analystIssuePageAddressFromPage(page) {
17334
17671
  return {
@@ -18884,9 +19221,9 @@ __export(public_role_summons_exports, {
18884
19221
  summonPublicRole: () => summonPublicRole
18885
19222
  });
18886
19223
  import { execFile as execFile3 } from "node:child_process";
18887
- import { existsSync as existsSync11 } from "node:fs";
19224
+ import { existsSync as existsSync12 } from "node:fs";
18888
19225
  import { realpath as realpath6 } from "node:fs/promises";
18889
- import { join as join26 } from "node:path";
19226
+ import { join as join27 } from "node:path";
18890
19227
  import { promisify as promisify3 } from "node:util";
18891
19228
  function createCapturingIo() {
18892
19229
  const chunks = [];
@@ -18910,7 +19247,7 @@ function parentDir(path) {
18910
19247
  function walkPackageRoot(start) {
18911
19248
  let dir = start;
18912
19249
  for (let i = 0; i < 12; i += 1) {
18913
- if (existsSync11(join26(dir, "package.json")) && existsSync11(join26(dir, "souls"))) {
19250
+ if (existsSync12(join27(dir, "package.json")) && existsSync12(join27(dir, "souls"))) {
18914
19251
  return dir;
18915
19252
  }
18916
19253
  const parent = parentDir(dir);
@@ -19458,7 +19795,7 @@ var init_compliance_transport = __esm({
19458
19795
  });
19459
19796
 
19460
19797
  // src/role-run-relocation.ts
19461
- import { dirname as dirname17, join as join27 } from "node:path";
19798
+ import { dirname as dirname17, join as join28 } from "node:path";
19462
19799
  async function retainedRunPathsMatch(recordedPath, currentPath, currentRunDirectory) {
19463
19800
  if (recordedPath === currentPath) return true;
19464
19801
  if (typeof recordedPath !== "string") return false;
@@ -19524,9 +19861,9 @@ __export(run_lifecycle_exports, {
19524
19861
  resolveLiveRunDirectoryPath: () => resolveLiveRunDirectoryPath,
19525
19862
  writeRoleRunState: () => writeRoleRunState
19526
19863
  });
19527
- import { existsSync as existsSync12 } from "node:fs";
19864
+ import { existsSync as existsSync13 } from "node:fs";
19528
19865
  import { chmod, lstat as lstat3, open as open2, readdir as readdir4, readFile as readFile14, unlink as unlink2 } from "node:fs/promises";
19529
- import { basename as basename12, join as join28 } from "node:path";
19866
+ import { basename as basename13, join as join29 } from "node:path";
19530
19867
  async function writeRoleRunState(runDirectory, record) {
19531
19868
  const payload = { ...record, runDirectory };
19532
19869
  writeSectionSync(runDirectory, "runState", { ...payload });
@@ -19608,13 +19945,14 @@ async function readRoleRunStateDisk(runDirectory) {
19608
19945
  if (typeof record.sessionDirectory !== "string") throw new TypeError("Invalid state.jsonl run-state");
19609
19946
  const storedRunDirectory = typeof record.runDirectory === "string" && record.runDirectory.trim() !== "" ? record.runDirectory : runDirectory;
19610
19947
  const runDir = runDirectory;
19948
+ const principalCoords = {
19949
+ sessionDirectory: record.sessionDirectory,
19950
+ ...typeof record.sessionFile === "string" ? { sessionFile: record.sessionFile } : {}
19951
+ };
19952
+ rewritePrincipalSessionPaths(principalCoords, storedRunDirectory, runDirectory);
19611
19953
  const principalWire = {
19612
- sessionDirectory: rewriteRunDirectoryPathValue(
19613
- record.sessionDirectory,
19614
- storedRunDirectory,
19615
- runDirectory
19616
- ),
19617
- ...typeof record.sessionFile === "string" ? { sessionFile: rewriteRunDirectoryPathValue(record.sessionFile, storedRunDirectory, runDirectory) } : {}
19954
+ sessionDirectory: principalCoords.sessionDirectory,
19955
+ ...typeof principalCoords.sessionFile === "string" ? { sessionFile: principalCoords.sessionFile } : {}
19618
19956
  };
19619
19957
  const phase = record.phase === "plan" || record.phase === "apply" ? record.phase : void 0;
19620
19958
  const currentCourt = parseCurrentCourtState(record.currentCourt);
@@ -19820,7 +20158,7 @@ async function createWriterLease(lockPath, runDirectory, reportCleanupFailure) {
19820
20158
  },
19821
20159
  relocate(nextRunDirectory) {
19822
20160
  currentRunDirectory = nextRunDirectory;
19823
- currentLockPath = join28(nextRunDirectory, WRITER_LOCK_FILE);
20161
+ currentLockPath = join29(nextRunDirectory, WRITER_LOCK_FILE);
19824
20162
  },
19825
20163
  async release() {
19826
20164
  if (released) return;
@@ -19859,10 +20197,10 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
19859
20197
  };
19860
20198
  const reportReadFailure = (error) => {
19861
20199
  reportDiagnostic(
19862
- `writer lease lock read failed (holder liveness unverifiable; lock left in place) at ${join28(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
20200
+ `writer lease lock read failed (holder liveness unverifiable; lock left in place) at ${join29(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
19863
20201
  );
19864
20202
  };
19865
- const lockPath = join28(runDirectory, WRITER_LOCK_FILE);
20203
+ const lockPath = join29(runDirectory, WRITER_LOCK_FILE);
19866
20204
  let lastAutopsy = { verdict: "absent" };
19867
20205
  let lastReclaimFailure;
19868
20206
  for (let reclaimsLeft = WRITER_LEASE_RECLAIM_ROUNDS; ; reclaimsLeft -= 1) {
@@ -19918,7 +20256,7 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
19918
20256
  }
19919
20257
  async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole, knownRunDirectory) {
19920
20258
  if (typeof knownRunDirectory === "string" && knownRunDirectory.trim() !== "") {
19921
- const parsed = parseRunLeaf(basename12(knownRunDirectory));
20259
+ const parsed = parseRunLeaf(basename13(knownRunDirectory));
19922
20260
  if (parsed === void 0 || parsed.runId !== runId) {
19923
20261
  throw new CliUsageError(
19924
20262
  `run directory does not match run id ${runId}: ${knownRunDirectory}`
@@ -19928,7 +20266,7 @@ async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole, knownRun
19928
20266
  }
19929
20267
  if (runId.trim() === "") return void 0;
19930
20268
  const ledgerHome = resolveActivationLedgerHome(home);
19931
- const booksRoot = join28(ledgerHome, "books");
20269
+ const booksRoot = join29(ledgerHome, "books");
19932
20270
  let bookKeys;
19933
20271
  try {
19934
20272
  bookKeys = await readdir4(booksRoot);
@@ -19943,8 +20281,8 @@ async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole, knownRun
19943
20281
  );
19944
20282
  }
19945
20283
  async function resolveLiveRunDirectoryPath(recordedPath, home, onlyBookKey) {
19946
- if (existsSync12(recordedPath)) return recordedPath;
19947
- const parsed = parseRunLeaf(basename12(recordedPath));
20284
+ if (existsSync13(recordedPath)) return recordedPath;
20285
+ const parsed = parseRunLeaf(basename13(recordedPath));
19948
20286
  const bookKey = onlyBookKey ?? tryBookKeyFromAkRolesPath(recordedPath);
19949
20287
  if (parsed === void 0 || bookKey === void 0) return void 0;
19950
20288
  return findRunDirectoryById(home, parsed.runId, bookKey, parsed.role);
@@ -19978,7 +20316,7 @@ async function findLatestRunForSeatTicket(input) {
19978
20316
  let runDirectories;
19979
20317
  try {
19980
20318
  runDirectories = await listBookRunDirectories(
19981
- input.ticketNumber === void 0 ? bookDir : join28(bookDir, String(input.ticketNumber))
20319
+ input.ticketNumber === void 0 ? bookDir : join29(bookDir, String(input.ticketNumber))
19982
20320
  );
19983
20321
  } catch (error) {
19984
20322
  if (errorCodeOf(error) === "ENOENT") return void 0;
@@ -19986,7 +20324,7 @@ async function findLatestRunForSeatTicket(input) {
19986
20324
  }
19987
20325
  let best;
19988
20326
  for (const runDirectory of runDirectories) {
19989
- const parsed = parseRunLeaf(basename12(runDirectory));
20327
+ const parsed = parseRunLeaf(basename13(runDirectory));
19990
20328
  if (parsed === void 0 || parsed.role !== input.role) continue;
19991
20329
  const runId = parsed.runId;
19992
20330
  const parentPath = await readRunParentPath(runDirectory);
@@ -20509,7 +20847,7 @@ import "typebox";
20509
20847
 
20510
20848
  // src/navigator-public-session.ts
20511
20849
  init_host_session_record();
20512
- import { basename as basename13 } from "node:path";
20850
+ import { basename as basename14 } from "node:path";
20513
20851
 
20514
20852
  // src/navigator-session-contracts.ts
20515
20853
  init_unknown_value();
@@ -20713,7 +21051,7 @@ async function resolveNavigatorLedgerHome(context) {
20713
21051
  return void 0;
20714
21052
  }
20715
21053
  function runIdFromNavigatorDirectory(runDirectory) {
20716
- const parsed = parseRunLeaf(basename13(runDirectory));
21054
+ const parsed = parseRunLeaf(basename14(runDirectory));
20717
21055
  if (parsed === void 0 || parsed.role !== "navigator") return void 0;
20718
21056
  return parsed.runId;
20719
21057
  }
@@ -21357,7 +21695,7 @@ init_filed_submission();
21357
21695
  init_report_ticket_tool();
21358
21696
  import { randomUUID as randomUUID7 } from "node:crypto";
21359
21697
  import { writeSync as writeSync2 } from "node:fs";
21360
- import { join as join30 } from "node:path";
21698
+ import { join as join31 } from "node:path";
21361
21699
  import { Value as Value3 } from "typebox/value";
21362
21700
 
21363
21701
  // src/activation-trace.ts
@@ -21407,7 +21745,7 @@ import {
21407
21745
  lstatSync as lstatSync2,
21408
21746
  realpathSync as realpathSync2,
21409
21747
  statSync as statSync7,
21410
- writeFileSync as writeFileSync2
21748
+ writeFileSync as writeFileSync3
21411
21749
  } from "node:fs";
21412
21750
  import { isAbsolute as isAbsolute10, resolve as resolve16 } from "node:path";
21413
21751
  var ActivationSessionFileMissingError = class extends Error {
@@ -21428,7 +21766,7 @@ function materializeDeferredSessionFile(sessionManager, resolvedFile) {
21428
21766
  throw new ActivationSessionFileMissingError(resolvedFile);
21429
21767
  }
21430
21768
  try {
21431
- writeFileSync2(resolvedFile, `${JSON.stringify(header)}
21769
+ writeFileSync3(resolvedFile, `${JSON.stringify(header)}
21432
21770
  `, { flag: "wx" });
21433
21771
  } catch (error) {
21434
21772
  if (errnoCode(error) !== "EEXIST") {
@@ -21864,10 +22202,10 @@ init_run_ticket_number();
21864
22202
 
21865
22203
  // src/audited-run-identity.ts
21866
22204
  init_role_run_placement();
21867
- import { basename as basename14 } from "node:path";
22205
+ import { basename as basename15 } from "node:path";
21868
22206
  var AUDITED_RUN_IDENTITY_KIND = "audited-run-identity";
21869
22207
  function auditedRunIdentityFromDirectory(runDirectory) {
21870
- const parsed = parseRunLeaf(basename14(runDirectory));
22208
+ const parsed = parseRunLeaf(basename15(runDirectory));
21871
22209
  if (parsed === void 0) return void 0;
21872
22210
  return formatRunLeaf(parsed.runId, parsed.role);
21873
22211
  }
@@ -22091,7 +22429,7 @@ init_unknown_value();
22091
22429
  init_submission_errors();
22092
22430
  init_worker_submission_contracts();
22093
22431
  import { execFileSync as execFileSync3 } from "node:child_process";
22094
- import { existsSync as existsSync13, lstatSync as lstatSync3, readdirSync as readdirSync3, readFileSync as readFileSync4, rmdirSync, rmSync as rmSync3 } from "node:fs";
22432
+ import { existsSync as existsSync14, lstatSync as lstatSync3, readdirSync as readdirSync4, readFileSync as readFileSync5, rmdirSync, rmSync as rmSync4 } from "node:fs";
22095
22433
  import { resolve as resolve17 } from "node:path";
22096
22434
  var WORKER_COMMIT_BASELINE_ENTRY_TYPE = "commit-baseline";
22097
22435
  var WORKER_COMMIT_REMINDER_BOUNCE_ENTRY_TYPE = "commit-reminder-bounce";
@@ -22121,7 +22459,7 @@ function statusOf(error) {
22121
22459
  return typeof error === "object" && error !== null && "status" in error ? error.status : void 0;
22122
22460
  }
22123
22461
  function tryGetAll(file, key) {
22124
- if (!existsSync13(file)) return [];
22462
+ if (!existsSync14(file)) return [];
22125
22463
  try {
22126
22464
  const out = gitFile(file, ["--get-all", key]);
22127
22465
  return out.length === 0 ? [] : out.split("\n");
@@ -22131,8 +22469,8 @@ function tryGetAll(file, key) {
22131
22469
  }
22132
22470
  }
22133
22471
  function ownedHook(path) {
22134
- if (!existsSync13(path)) return false;
22135
- return readFileSync4(path, "utf8").includes(HOOK_MARKER);
22472
+ if (!existsSync14(path)) return false;
22473
+ return readFileSync5(path, "utf8").includes(HOOK_MARKER);
22136
22474
  }
22137
22475
  function escapeGitConfigValueRegex(value) {
22138
22476
  return value.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
@@ -22157,13 +22495,13 @@ function unsetOwnedHooksPath(file) {
22157
22495
  function rmOwnedDir(dir) {
22158
22496
  const hookPath = resolve17(dir, HOOK_FILE);
22159
22497
  if (!ownedHook(hookPath)) return;
22160
- rmSync3(hookPath, { force: true });
22161
- if (existsSync13(dir) && readdirSync3(dir).length === 0) rmdirSync(dir);
22498
+ rmSync4(hookPath, { force: true });
22499
+ if (existsSync14(dir) && readdirSync4(dir).length === 0) rmdirSync(dir);
22162
22500
  }
22163
22501
  function linkedGitDirs(commonDir) {
22164
22502
  const root = resolve17(commonDir, "worktrees");
22165
- if (!existsSync13(root)) return [];
22166
- return readdirSync3(root).map((name) => resolve17(root, name)).filter((dir) => lstatSync3(dir).isDirectory());
22503
+ if (!existsSync14(root)) return [];
22504
+ return readdirSync4(root).map((name) => resolve17(root, name)).filter((dir) => lstatSync3(dir).isDirectory());
22167
22505
  }
22168
22506
  function uninstallPackageWorkerHooks(cwd) {
22169
22507
  let inside;
@@ -22181,7 +22519,7 @@ function uninstallPackageWorkerHooks(cwd) {
22181
22519
  clear(resolve17(commonDir, "config.worktree"));
22182
22520
  rmOwnedDir(resolve17(commonDir, HOOKS_DIR));
22183
22521
  const legacy = resolve17(commonDir, "hooks", HOOK_FILE);
22184
- if (ownedHook(legacy)) rmSync3(legacy, { force: true });
22522
+ if (ownedHook(legacy)) rmSync4(legacy, { force: true });
22185
22523
  for (const gitDir of linkedGitDirs(commonDir)) {
22186
22524
  clear(resolve17(gitDir, "config.worktree"));
22187
22525
  rmOwnedDir(resolve17(gitDir, HOOKS_DIR));
@@ -22259,11 +22597,11 @@ function reliableWindow(cwd, baseline, head) {
22259
22597
  const raw = git2(cwd, ["log", "--format=%P%x1e%s", range]);
22260
22598
  if (raw.length === 0) return [];
22261
22599
  return raw.split("\n").flatMap((line2) => {
22262
- const sep5 = line2.indexOf("");
22263
- if (sep5 < 0) return [];
22600
+ const sep6 = line2.indexOf("");
22601
+ if (sep6 < 0) return [];
22264
22602
  return [{
22265
- subject: line2.slice(sep5 + 1),
22266
- merge: line2.slice(0, sep5).trim().includes(" ")
22603
+ subject: line2.slice(sep6 + 1),
22604
+ merge: line2.slice(0, sep6).trim().includes(" ")
22267
22605
  }];
22268
22606
  });
22269
22607
  }
@@ -23001,7 +23339,7 @@ function readRoleRunCoordinates(ctx, label) {
23001
23339
  if (runDirectory === void 0) throw new Error(`${label} requires AK_ROLE_RUN_DIR`);
23002
23340
  const admitted = readPageSync(runDirectory, "admitted");
23003
23341
  if (typeof admitted?.projectRoot !== "string" || admitted.projectRoot.trim() === "") {
23004
- throw new Error(`${label} state.jsonl admitted-request row missing projectRoot (${join30(runDirectory, RUN_STATE_FILE)})`);
23342
+ throw new Error(`${label} state.jsonl admitted-request row missing projectRoot (${join31(runDirectory, RUN_STATE_FILE)})`);
23005
23343
  }
23006
23344
  return {
23007
23345
  runDirectory,
@@ -23267,7 +23605,10 @@ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
23267
23605
  settleNavigatorProjection
23268
23606
  );
23269
23607
  };
23270
- roleHost.on("input", (_event) => {
23608
+ roleHost.on("input", (event, ctx) => {
23609
+ if (typeof event.text === "string" && ctx.summonsInstruction === void 0) {
23610
+ ctx.summonsInstruction = event.text;
23611
+ }
23271
23612
  const role = roleHost.getFlag(ROLE_FLAG.name);
23272
23613
  if (role !== void 0 && !admitted) return { action: "handled" };
23273
23614
  return { action: "continue" };
@@ -23422,6 +23763,8 @@ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
23422
23763
  }
23423
23764
  if (receiptDelivery.nextAction() === "request-delivery") {
23424
23765
  receiptDelivery.recordDeliveryRequest();
23766
+ const deliveryContent = turnDialoguePrompt ?? "";
23767
+ ctx.summonsInstruction = deliveryContent;
23425
23768
  const scopeId = ctx.invocationScopeId?.trim() ?? "";
23426
23769
  envelopeHost.appendEntry(
23427
23770
  RECEIPT_DELIVERY_REQUEST_ENTRY,
@@ -23437,7 +23780,7 @@ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
23437
23780
  });
23438
23781
  envelopeHost.sendMessage({
23439
23782
  customType: "ak-receipt-delivery-prompt",
23440
- content: turnDialoguePrompt ?? "",
23783
+ content: deliveryContent,
23441
23784
  display: false
23442
23785
  }, { triggerTurn: true, deliverAs: "followUp" });
23443
23786
  } else if (receiptDelivery.nextAction() === "no-receipt" && !noReceiptRecorded) {
@@ -24420,6 +24763,7 @@ async function prepareRoleEnvelope(options) {
24420
24763
  const record = value;
24421
24764
  if (record.action === "transform" && typeof record.text === "string") prompt = record.text;
24422
24765
  }
24766
+ context.summonsInstruction = prompt;
24423
24767
  if (typeof prompt === "string" && prompt.trim() !== "") {
24424
24768
  sessionEntries.push({
24425
24769
  type: "message",
@@ -24461,6 +24805,9 @@ async function prepareRoleEnvelope(options) {
24461
24805
  }],
24462
24806
  systemPrompt: { body: systemPromptBody, materials: readingMaterials },
24463
24807
  prompt,
24808
+ recordSentInstruction(text) {
24809
+ context.summonsInstruction = text;
24810
+ },
24464
24811
  abortSignal: hostAbort.signal,
24465
24812
  closeRound,
24466
24813
  dispose,
@@ -24490,12 +24837,12 @@ init_role_run_placement();
24490
24837
  init_external_host_turn_loop();
24491
24838
  init_run_lifecycle();
24492
24839
  init_settlement();
24493
- import { spawn as spawn3, spawnSync as spawnSync3 } from "node:child_process";
24840
+ import { spawn as spawn3, spawnSync as spawnSync4 } from "node:child_process";
24494
24841
  import { randomUUID as randomUUID10 } from "node:crypto";
24495
- import { existsSync as existsSync14 } from "node:fs";
24842
+ import { existsSync as existsSync15 } from "node:fs";
24496
24843
  import { mkdtemp, rm as rm2, writeFile as writeFile6 } from "node:fs/promises";
24497
24844
  import { tmpdir } from "node:os";
24498
- import { dirname as dirname20, isAbsolute as isAbsolute11, join as join31, resolve as resolve18 } from "node:path";
24845
+ import { dirname as dirname20, isAbsolute as isAbsolute11, join as join32, resolve as resolve18 } from "node:path";
24499
24846
 
24500
24847
  // src/agent-start-materials.ts
24501
24848
  function renderAgentStartMaterials(body, materials) {
@@ -24882,7 +25229,7 @@ function formatCodexFailurePayload(payload) {
24882
25229
  function cwdIsGitWorkTree(cwd) {
24883
25230
  let dir = cwd;
24884
25231
  for (; ; ) {
24885
- if (existsSync14(join31(dir, ".git"))) return true;
25232
+ if (existsSync15(join32(dir, ".git"))) return true;
24886
25233
  const parent = dirname20(dir);
24887
25234
  if (parent === dir) return false;
24888
25235
  dir = parent;
@@ -24892,7 +25239,7 @@ function resolveGitCommonDir(cwd) {
24892
25239
  if (!cwdIsGitWorkTree(cwd)) return void 0;
24893
25240
  let result;
24894
25241
  try {
24895
- result = spawnSync3("git", ["rev-parse", "--git-common-dir"], {
25242
+ result = spawnSync4("git", ["rev-parse", "--git-common-dir"], {
24896
25243
  cwd,
24897
25244
  encoding: "utf8"
24898
25245
  });
@@ -25101,8 +25448,8 @@ function createHeadlessRoleTurnHost(config) {
25101
25448
  }
25102
25449
  const env = { ...process.env, ...config.env ?? {} };
25103
25450
  const liveSessionParent = () => config.sessionIdentity.resolveSessionFile(request.principal);
25104
- const inputsDirectory = await mkdtemp(join31(tmpdir(), "ak-role-headless-"));
25105
- const systemPromptPath = join31(inputsDirectory, "system-prompt.txt");
25451
+ const inputsDirectory = await mkdtemp(join32(tmpdir(), "ak-role-headless-"));
25452
+ const systemPromptPath = join32(inputsDirectory, "system-prompt.txt");
25106
25453
  let mcpConfigPath;
25107
25454
  let outputSchemaPath;
25108
25455
  let startedWithSchema;
@@ -25111,13 +25458,13 @@ function createHeadlessRoleTurnHost(config) {
25111
25458
  let deliveredSchema;
25112
25459
  if (codex) {
25113
25460
  if (!navigatorProseExit) {
25114
- outputSchemaPath = join31(inputsDirectory, "output-schema.json");
25461
+ outputSchemaPath = join32(inputsDirectory, "output-schema.json");
25115
25462
  deliveredSchema = closeJsonSchemaForCodex(prepared.jsonSchema);
25116
25463
  await writeFile6(outputSchemaPath, `${JSON.stringify(deliveredSchema, null, 2)}
25117
25464
  `, "utf8");
25118
25465
  }
25119
25466
  } else {
25120
- mcpConfigPath = join31(inputsDirectory, "mcp-config.json");
25467
+ mcpConfigPath = join32(inputsDirectory, "mcp-config.json");
25121
25468
  await writeFile6(
25122
25469
  mcpConfigPath,
25123
25470
  `${JSON.stringify(headlessMcpConfigDocument(prepared.mcpServers), null, 2)}