@akagilnc/pi-workflow-roles 0.1.4620 → 0.1.4641

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 (41) hide show
  1. package/README.zh-CN.md +1 -1
  2. package/dist/acp-host/production-host.js +962 -547
  3. package/dist/activation-ledger-topology.js +0 -4
  4. package/dist/gatekeeper-role.js +76 -6
  5. package/dist/headless-host/production-host.js +923 -508
  6. package/dist/migrate-book-topology.js +9 -0
  7. package/dist/pi/role-turn-host.js +0 -3
  8. package/dist/public-cli/auto-resume.js +26 -0
  9. package/dist/public-cli/countersign-run.js +31 -10
  10. package/dist/public-cli/main.js +1456 -1068
  11. package/dist/public-cli/post-admission.js +101 -7
  12. package/dist/public-cli/process-cancel.js +57 -0
  13. package/dist/public-cli/settlement.js +95 -2
  14. package/dist/public-role-summons.js +19 -0
  15. package/dist/secretariat-contracts.js +4 -0
  16. package/package.json +1 -1
  17. package/scripts/build-package.mjs +0 -1
  18. package/src/activation-ledger-topology.ts +1 -6
  19. package/src/activation-ledger.ts +5 -236
  20. package/src/analyst-entry.ts +19 -2
  21. package/src/analyst-ledger.ts +111 -6
  22. package/src/archivist-record-entry.ts +3 -3
  23. package/src/audit-escalation.ts +1 -1
  24. package/src/gatekeeper-pass-envelope.ts +37 -5
  25. package/src/gatekeeper-role.ts +125 -20
  26. package/src/host-contracts.ts +22 -2
  27. package/src/pi/adapter.ts +5 -1
  28. package/src/pi/role-turn-host.ts +0 -3
  29. package/src/public-cli/auto-resume.ts +34 -0
  30. package/src/public-cli/cli.ts +30 -0
  31. package/src/public-cli/countersign-run.ts +50 -13
  32. package/src/public-cli/main.ts +25 -3
  33. package/src/public-cli/post-admission.ts +173 -6
  34. package/src/public-cli/process-cancel.ts +75 -0
  35. package/src/public-cli/settlement.ts +117 -1
  36. package/src/public-role-summons.ts +30 -4
  37. package/src/role-envelope.ts +27 -10
  38. package/src/role-runtime.ts +146 -55
  39. package/src/secretariat-contracts.ts +18 -0
  40. package/dist/activation-reconciliation.js +0 -61
  41. package/src/activation-reconciliation.ts +0 -163
@@ -417,7 +417,7 @@ function normalizeReviewComment(raw) {
417
417
  function createGhApiRunner(options = {}) {
418
418
  const spawnImpl = options.spawnImpl ?? spawn;
419
419
  return async (args, runOptions = {}) => {
420
- return await new Promise((resolve22, reject) => {
420
+ return await new Promise((resolve21, reject) => {
421
421
  const signal = runOptions.signal;
422
422
  if (signal?.aborted) {
423
423
  reject(signal.reason ?? new Error("aborted"));
@@ -490,11 +490,11 @@ function createGhApiRunner(options = {}) {
490
490
  const value = line2.slice(idx + 1).trim();
491
491
  headers[name] = value;
492
492
  }
493
- resolve22({ status, headers, bodyText });
493
+ resolve21({ status, headers, bodyText });
494
494
  return;
495
495
  }
496
496
  if (code === 0) {
497
- resolve22({ status: 200, headers: {}, bodyText: stdout });
497
+ resolve21({ status: 200, headers: {}, bodyText: stdout });
498
498
  return;
499
499
  }
500
500
  const failure2 = new Error(
@@ -691,7 +691,6 @@ var activation_ledger_topology_exports = {};
691
691
  __export(activation_ledger_topology_exports, {
692
692
  ActivationLedgerError: () => ActivationLedgerError,
693
693
  activationBookDirectory: () => activationBookDirectory,
694
- activationWaitingLedgerPath: () => activationWaitingLedgerPath,
695
694
  assertLedgerFileInsideHome: () => assertLedgerFileInsideHome,
696
695
  ensureRealDirectoryTree: () => ensureRealDirectoryTree,
697
696
  errnoCode: () => errnoCode,
@@ -754,9 +753,6 @@ function resolveActivationLedgerHomeForPath(path) {
754
753
  function activationBookDirectory(ledgerHome, bookKey) {
755
754
  return join(ledgerHome, "books", bookKey);
756
755
  }
757
- function activationWaitingLedgerPath(ledgerHome, bookKey) {
758
- return join(activationBookDirectory(ledgerHome, bookKey), "waiting.jsonl");
759
- }
760
756
  function pathContainedIn(root, candidate) {
761
757
  const rel = relative(root, candidate);
762
758
  return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
@@ -968,6 +964,15 @@ var init_activation_ledger_topology = __esm({
968
964
  });
969
965
 
970
966
  // src/run-ticket-number.ts
967
+ var run_ticket_number_exports = {};
968
+ __export(run_ticket_number_exports, {
969
+ MIGRATION_TICKET_DERIVATION_PAGE: () => MIGRATION_TICKET_DERIVATION_PAGE,
970
+ isSafePositiveTicketNumber: () => isSafePositiveTicketNumber,
971
+ readBoardTicketNumber: () => readBoardTicketNumber,
972
+ readMigrationDerivedTicketNumber: () => readMigrationDerivedTicketNumber,
973
+ readRunTicketNumber: () => readRunTicketNumber,
974
+ requireSafePositiveTicketNumber: () => requireSafePositiveTicketNumber
975
+ });
971
976
  import { readFile as readFile3 } from "node:fs/promises";
972
977
  import { join as join2 } from "node:path";
973
978
  function isEnoent(error) {
@@ -1007,9 +1012,22 @@ async function readBoardPageTicketNumber(runDirectory, page) {
1007
1012
  async function readBoardTicketNumber(runDirectory) {
1008
1013
  return await readBoardPageTicketNumber(runDirectory, "admitted-request.json") ?? await readBoardPageTicketNumber(runDirectory, "invocation.json");
1009
1014
  }
1015
+ async function readMigrationDerivedTicketNumber(runDirectory) {
1016
+ const record4 = await readJsonObject(
1017
+ join2(runDirectory, MIGRATION_TICKET_DERIVATION_PAGE)
1018
+ );
1019
+ if (record4 === void 0) return void 0;
1020
+ if (record4.derivation !== "worktree-path-basename") return void 0;
1021
+ return ticketFromRecord(record4);
1022
+ }
1023
+ async function readRunTicketNumber(runDirectory) {
1024
+ return await readBoardTicketNumber(runDirectory) ?? await readMigrationDerivedTicketNumber(runDirectory);
1025
+ }
1026
+ var MIGRATION_TICKET_DERIVATION_PAGE;
1010
1027
  var init_run_ticket_number = __esm({
1011
1028
  "src/run-ticket-number.ts"() {
1012
1029
  "use strict";
1030
+ MIGRATION_TICKET_DERIVATION_PAGE = "migration-ticket-derivation.json";
1013
1031
  }
1014
1032
  });
1015
1033
 
@@ -1392,15 +1410,165 @@ var init_gatekeeper_output = __esm({
1392
1410
  }
1393
1411
  });
1394
1412
 
1413
+ // src/run-terminal-artifacts.ts
1414
+ var run_terminal_artifacts_exports = {};
1415
+ __export(run_terminal_artifacts_exports, {
1416
+ RUN_TERMINAL_ARTIFACT_FILES: () => RUN_TERMINAL_ARTIFACT_FILES,
1417
+ RUN_TERMINAL_ERROR_FALLBACK_RELATIVE_PATHS: () => RUN_TERMINAL_ERROR_FALLBACK_RELATIVE_PATHS,
1418
+ isUniqueErrorFallbackName: () => isUniqueErrorFallbackName,
1419
+ readRunTerminalArtifact: () => readRunTerminalArtifact,
1420
+ runIdFromRunDirectory: () => runIdFromRunDirectory
1421
+ });
1422
+ import { readdir as readdir2, readFile as readFile4 } from "node:fs/promises";
1423
+ import { basename as basename2, dirname as dirname4, join as join5 } from "node:path";
1424
+ function isMissingPathError2(error) {
1425
+ return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
1426
+ }
1427
+ function errorText2(error) {
1428
+ return error instanceof Error ? error.message : String(error);
1429
+ }
1430
+ function isRecord2(value) {
1431
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1432
+ }
1433
+ function readUsableTerminalArtifactBody(body) {
1434
+ if (body === null) {
1435
+ return { ok: false, reason: "terminal artifact JSON value is null" };
1436
+ }
1437
+ if (!isRecord2(body)) {
1438
+ return {
1439
+ ok: false,
1440
+ reason: `terminal artifact JSON value is not a typed object (${Array.isArray(body) ? "array" : typeof body})`
1441
+ };
1442
+ }
1443
+ if (typeof body.role !== "string" || body.role.trim() === "") {
1444
+ return {
1445
+ ok: false,
1446
+ reason: "terminal artifact missing nonblank producer-owned role field"
1447
+ };
1448
+ }
1449
+ return { ok: true, body };
1450
+ }
1451
+ async function readTerminalArtifactAtPath(path, file) {
1452
+ let raw;
1453
+ try {
1454
+ raw = await readFile4(path, "utf8");
1455
+ } catch (error) {
1456
+ if (isMissingPathError2(error)) return void 0;
1457
+ return {
1458
+ status: "unreadable",
1459
+ file,
1460
+ path,
1461
+ reason: errorText2(error)
1462
+ };
1463
+ }
1464
+ let parsed;
1465
+ try {
1466
+ parsed = JSON.parse(raw);
1467
+ } catch (error) {
1468
+ return {
1469
+ status: "unreadable",
1470
+ file,
1471
+ path,
1472
+ reason: error instanceof Error ? error.message : `terminal artifact JSON parse failed: ${String(error)}`
1473
+ };
1474
+ }
1475
+ const usable = readUsableTerminalArtifactBody(parsed);
1476
+ if (!usable.ok) {
1477
+ return {
1478
+ status: "unreadable",
1479
+ file,
1480
+ path,
1481
+ reason: usable.reason
1482
+ };
1483
+ }
1484
+ return { status: "present", file, path, body: usable.body };
1485
+ }
1486
+ async function listUniqueErrorFallbackPaths(directories) {
1487
+ const found = [];
1488
+ for (const dir of directories) {
1489
+ let names;
1490
+ try {
1491
+ names = await readdir2(dir);
1492
+ } catch (error) {
1493
+ if (isMissingPathError2(error)) continue;
1494
+ throw error;
1495
+ }
1496
+ for (const name of names.sort((a, b) => a.localeCompare(b))) {
1497
+ if (!UNIQUE_ERROR_FALLBACK_NAME.test(name)) continue;
1498
+ found.push(join5(dir, name));
1499
+ }
1500
+ }
1501
+ return found;
1502
+ }
1503
+ function runIdFromRunDirectory(runDirectory) {
1504
+ const name = basename2(runDirectory);
1505
+ const at = name.lastIndexOf("@");
1506
+ if (at <= 0 || at === name.length - 1) return void 0;
1507
+ return name.slice(0, at);
1508
+ }
1509
+ function presentUniqueFallbackBoundToRun(body, expectedRunId) {
1510
+ if (expectedRunId === void 0) return false;
1511
+ return typeof body.runId === "string" && body.runId === expectedRunId;
1512
+ }
1513
+ async function readRunTerminalArtifact(runDirectory) {
1514
+ const artifactsDir = roleRunArtifactsDirectory(runDirectory);
1515
+ for (const file of RUN_TERMINAL_ARTIFACT_FILES) {
1516
+ const path = join5(artifactsDir, file);
1517
+ const read = await readTerminalArtifactAtPath(path, file);
1518
+ if (read !== void 0) return read;
1519
+ }
1520
+ for (const relative4 of RUN_TERMINAL_ERROR_FALLBACK_RELATIVE_PATHS) {
1521
+ const path = join5(runDirectory, relative4);
1522
+ const read = await readTerminalArtifactAtPath(path, "error.json");
1523
+ if (read !== void 0) return read;
1524
+ }
1525
+ for (const path of await listUniqueErrorFallbackPaths([artifactsDir, runDirectory])) {
1526
+ const read = await readTerminalArtifactAtPath(path, "error.json");
1527
+ if (read !== void 0) return read;
1528
+ }
1529
+ const expectedRunId = runIdFromRunDirectory(runDirectory);
1530
+ for (const path of await listUniqueErrorFallbackPaths([dirname4(runDirectory)])) {
1531
+ const read = await readTerminalArtifactAtPath(path, "error.json");
1532
+ if (read === void 0) continue;
1533
+ if (read.status === "present") {
1534
+ if (!presentUniqueFallbackBoundToRun(read.body, expectedRunId)) continue;
1535
+ return read;
1536
+ }
1537
+ }
1538
+ return { status: "absent" };
1539
+ }
1540
+ function isUniqueErrorFallbackName(name) {
1541
+ return UNIQUE_ERROR_FALLBACK_NAME.test(basename2(name));
1542
+ }
1543
+ var RUN_TERMINAL_ARTIFACT_FILES, RUN_TERMINAL_ERROR_FALLBACK_RELATIVE_PATHS, UNIQUE_ERROR_FALLBACK_NAME;
1544
+ var init_run_terminal_artifacts = __esm({
1545
+ "src/run-terminal-artifacts.ts"() {
1546
+ "use strict";
1547
+ init_role_run_placement();
1548
+ RUN_TERMINAL_ARTIFACT_FILES = [
1549
+ "report.json",
1550
+ "error.json",
1551
+ "audit-incomplete.json"
1552
+ ];
1553
+ RUN_TERMINAL_ERROR_FALLBACK_RELATIVE_PATHS = [
1554
+ "artifacts/error.settlement.json",
1555
+ "error.settlement.json"
1556
+ ];
1557
+ UNIQUE_ERROR_FALLBACK_NAME = /^error\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.json$/i;
1558
+ }
1559
+ });
1560
+
1395
1561
  // src/gatekeeper-role.ts
1396
1562
  function gateSeatLabel(stage) {
1397
1563
  if (stage === "inspector") return "\u53F0\u9662";
1398
1564
  if (stage === "auditor") return "\u5BA1\u5211\u9662";
1565
+ if (stage === "countersign") return "\u7ED9\u4E8B\u4E2D";
1399
1566
  return "\u7B26\u5B9D\u90CE";
1400
1567
  }
1401
1568
  function gateOfficerForSubject(subject) {
1402
1569
  if (subject.kind === "worker_completion") return "inspector";
1403
1570
  if (subject.kind === "judge_compliance") return "auditor";
1571
+ if (subject.kind === "secretariat_verdict") return "countersign";
1404
1572
  return "notary";
1405
1573
  }
1406
1574
  function failureReason(error) {
@@ -1414,9 +1582,26 @@ function readRecord(value) {
1414
1582
  if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
1415
1583
  return value;
1416
1584
  }
1585
+ function gateStatusFromCountersign(status) {
1586
+ if (status === "converged") return "pass";
1587
+ if (status === "continue") return "bounce";
1588
+ if (status === "escalate") return "escalate";
1589
+ return void 0;
1590
+ }
1417
1591
  function projectOfficerDecision(officer, decision, fallbackStatus) {
1418
1592
  const receipt = retainedReceipt(decision);
1419
1593
  const record4 = readRecord(decision);
1594
+ if (officer === "countersign") {
1595
+ const countersignStatus = record4 !== void 0 && typeof record4.countersignStatus === "string" ? record4.countersignStatus : void 0;
1596
+ const status2 = typeof countersignStatus === "string" ? gateStatusFromCountersign(countersignStatus) : void 0;
1597
+ if (status2 === "pass") {
1598
+ return { status: "pass", officer, receipt };
1599
+ }
1600
+ if (status2 === "bounce" || status2 === "escalate") {
1601
+ return { status: status2, officer, receipt };
1602
+ }
1603
+ return { status: "needs_reask", officer, receipt };
1604
+ }
1420
1605
  const status = (record4 !== void 0 && typeof record4.status === "string" ? record4.status : void 0) ?? fallbackStatus;
1421
1606
  if (status === "pass") {
1422
1607
  return { status: "pass", officer, receipt };
@@ -1447,6 +1632,26 @@ function projectOfficerPayloads(officer, payloads, fallbackStatus) {
1447
1632
  }
1448
1633
  return projectOfficerDecision(officer, payloads[payloads.length - 1], fallbackStatus);
1449
1634
  }
1635
+ function officerRunIdFromSummoned(summoned) {
1636
+ if (typeof summoned.runDirectory === "string" && summoned.runDirectory.trim() !== "") {
1637
+ const fromDir = runIdFromRunDirectory(summoned.runDirectory);
1638
+ if (fromDir !== void 0) return fromDir;
1639
+ }
1640
+ const terminal = summoned.terminal;
1641
+ if (terminal !== void 0 && typeof terminal.runId === "string" && terminal.runId.trim() !== "") {
1642
+ return terminal.runId;
1643
+ }
1644
+ return void 0;
1645
+ }
1646
+ function withOfficerRunId(result, summoned) {
1647
+ if (result.status !== "pass" && result.status !== "bounce" && result.status !== "escalate" && result.status !== "needs_reask") {
1648
+ return result;
1649
+ }
1650
+ if (typeof result.runId === "string" && result.runId.trim() !== "") return result;
1651
+ const runId = officerRunIdFromSummoned(summoned);
1652
+ if (runId === void 0) return result;
1653
+ return { ...result, runId };
1654
+ }
1450
1655
  function projectOfficerTerminal(officer, summoned) {
1451
1656
  const terminal = summoned.terminal;
1452
1657
  const outcome = terminal?.roleOutcome;
@@ -1479,22 +1684,34 @@ function projectOfficerTerminal(officer, summoned) {
1479
1684
  };
1480
1685
  }
1481
1686
  if (outcome.kind === "audit_escalation") {
1482
- return {
1483
- status: "escalate",
1484
- officer,
1485
- // This-court receipt only (#879) — historical rows remain on terminal.submissions.
1486
- receipt: thisCourt.length > 0 ? thisCourt[thisCourt.length - 1] : retainedReceipt(outcome)
1487
- };
1687
+ return withOfficerRunId(
1688
+ {
1689
+ status: "escalate",
1690
+ officer,
1691
+ // This-court receipt only (#879) — historical rows remain on terminal.submissions.
1692
+ receipt: thisCourt.length > 0 ? thisCourt[thisCourt.length - 1] : retainedReceipt(outcome)
1693
+ },
1694
+ summoned
1695
+ );
1488
1696
  }
1489
1697
  if (outcome.kind === "accepted") {
1490
- return projectOfficerPayloads(officer, thisCourt, outcome.status);
1698
+ return withOfficerRunId(
1699
+ projectOfficerPayloads(officer, thisCourt, outcome.status),
1700
+ summoned
1701
+ );
1491
1702
  }
1492
- return {
1493
- status: "needs_reask",
1494
- officer,
1495
- // This-court receipt only (#879).
1496
- receipt: thisCourt.length > 0 ? thisCourt[thisCourt.length - 1] : retainedReceipt(outcome)
1497
- };
1703
+ return withOfficerRunId(
1704
+ {
1705
+ status: "needs_reask",
1706
+ officer,
1707
+ // This-court receipt only (#879).
1708
+ receipt: thisCourt.length > 0 ? thisCourt[thisCourt.length - 1] : retainedReceipt(outcome)
1709
+ },
1710
+ summoned
1711
+ );
1712
+ }
1713
+ function officerConclusionReask(officer) {
1714
+ return officer === "countersign" ? COUNTERSIGN_CONCLUSION_REASK : OFFICER_CONCLUSION_REASK;
1498
1715
  }
1499
1716
  async function projectGatekeeperRun(options) {
1500
1717
  const officer = gateOfficerForSubject(options.subject);
@@ -1530,7 +1747,7 @@ async function projectGatekeeperRun(options) {
1530
1747
  summoned
1531
1748
  };
1532
1749
  }
1533
- var GATEKEEPER_TOOL_SPEC, OFFICER_CONCLUSION_REASK;
1750
+ var GATEKEEPER_TOOL_SPEC, OFFICER_CONCLUSION_REASK, COUNTERSIGN_CONCLUSION_REASK;
1534
1751
  var init_gatekeeper_role = __esm({
1535
1752
  "src/gatekeeper-role.ts"() {
1536
1753
  "use strict";
@@ -1538,6 +1755,7 @@ var init_gatekeeper_role = __esm({
1538
1755
  init_submission_errors();
1539
1756
  init_inspector_contracts();
1540
1757
  init_gatekeeper_output();
1758
+ init_run_terminal_artifacts();
1541
1759
  init_submission_errors();
1542
1760
  GATEKEEPER_TOOL_SPEC = {
1543
1761
  name: GATEKEEPER_OUTPUT_TOOL_NAME,
@@ -1547,6 +1765,7 @@ var init_gatekeeper_role = __esm({
1547
1765
  parameters: gatekeeperOutputSchema
1548
1766
  };
1549
1767
  OFFICER_CONCLUSION_REASK = "\u4E0A\u6B21\u4EA4\u5377\u7684\u7ED3\u8BBA\u4E0D\u662F pass\u3001bounce\u3001escalate \u4E09\u6001\u4E4B\u4E00\u3002\u8BF7\u91CD\u65B0\u8F93\u51FA\uFF0C\u7ED3\u8BBA\u5B57\u6BB5\u5199\u660E\u5176\u4E00\uFF1B\u6253\u56DE\u6216\u4E0A\u5448\u7684\u8BDD\u5C31\u662F\u7ED9\u5BF9\u65B9\u770B\u7684\u539F\u6587\u3002";
1768
+ COUNTERSIGN_CONCLUSION_REASK = "\u4E0A\u6B21\u4EA4\u5377\u7684 countersignStatus \u4E0D\u662F converged\u3001continue\u3001escalate \u4E09\u6001\u4E4B\u4E00\u3002\u8BF7\u91CD\u65B0\u8F93\u51FA\uFF0CcountersignStatus \u5199\u660E\u5176\u4E00\uFF1B\u5C01\u9A73\u6216\u4E0A\u5448\u7684\u8BDD\u5C31\u662F\u7ED9\u5BF9\u65B9\u770B\u7684\u539F\u6587\u3002";
1550
1769
  }
1551
1770
  });
1552
1771
 
@@ -1557,12 +1776,12 @@ __export(session_assistant_usage_exports, {
1557
1776
  sessionFileFromPublicSummon: () => sessionFileFromPublicSummon,
1558
1777
  usageFromPublicSummon: () => usageFromPublicSummon
1559
1778
  });
1560
- import { join as join5 } from "node:path";
1779
+ import { join as join6 } from "node:path";
1561
1780
  async function readAssistantUsageFromSessionFile(sessionFile) {
1562
- const { readFile: readFile23 } = await import("node:fs/promises");
1781
+ const { readFile: readFile24 } = await import("node:fs/promises");
1563
1782
  let text;
1564
1783
  try {
1565
- text = await readFile23(sessionFile, "utf8");
1784
+ text = await readFile24(sessionFile, "utf8");
1566
1785
  } catch (error) {
1567
1786
  if (error?.code === "ENOENT") return void 0;
1568
1787
  throw error;
@@ -1627,7 +1846,7 @@ async function readAssistantUsageFromSessionFile(sessionFile) {
1627
1846
  }
1628
1847
  function sessionFileFromPublicSummon(summoned) {
1629
1848
  if (typeof summoned.runDirectory === "string" && summoned.runDirectory.trim() !== "") {
1630
- return join5(summoned.runDirectory, "session", "session.jsonl");
1849
+ return join6(summoned.runDirectory, "session", "session.jsonl");
1631
1850
  }
1632
1851
  const fromArtifacts = summoned.terminal?.artifacts?.map((a) => a.path).find((p) => typeof p === "string" && p.endsWith("session.jsonl"));
1633
1852
  if (fromArtifacts !== void 0) return fromArtifacts;
@@ -1636,7 +1855,7 @@ function sessionFileFromPublicSummon(summoned) {
1636
1855
  const facts = outcome.decisiveFacts;
1637
1856
  const pointer = facts?.runPointer;
1638
1857
  if (typeof pointer === "string" && pointer.trim() !== "") {
1639
- return join5(pointer, "session", "session.jsonl");
1858
+ return join6(pointer, "session", "session.jsonl");
1640
1859
  }
1641
1860
  return void 0;
1642
1861
  }
@@ -1653,7 +1872,7 @@ var init_session_assistant_usage = __esm({
1653
1872
 
1654
1873
  // src/package-resources/engine-material.ts
1655
1874
  import { existsSync, readdirSync } from "node:fs";
1656
- import { join as join6 } from "node:path";
1875
+ import { join as join7 } from "node:path";
1657
1876
  function pickEngineAxis(source) {
1658
1877
  return {
1659
1878
  ...source.engine === void 0 ? {} : { engine: source.engine },
@@ -1674,11 +1893,11 @@ function isEngineNameSyntax(name) {
1674
1893
  return true;
1675
1894
  }
1676
1895
  function resolveEngineMaterialDirectory(packageRoot) {
1677
- return join6(packageRoot, ENGINE_MATERIAL_RELATIVE_ROOT);
1896
+ return join7(packageRoot, ENGINE_MATERIAL_RELATIVE_ROOT);
1678
1897
  }
1679
1898
  function resolveEngineMaterialPath(packageRoot, name) {
1680
1899
  const legal = assertLegalEngineName(name);
1681
- return join6(resolveEngineMaterialDirectory(packageRoot), `${legal}.md`);
1900
+ return join7(resolveEngineMaterialDirectory(packageRoot), `${legal}.md`);
1682
1901
  }
1683
1902
  function assertLegalEngineName(name) {
1684
1903
  if (!isEngineNameSyntax(name)) {
@@ -1731,7 +1950,7 @@ var init_engine_material = __esm({
1731
1950
 
1732
1951
  // src/activation-ledger-git.ts
1733
1952
  import { execFileSync } from "node:child_process";
1734
- import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute2, resolve as resolve4 } from "node:path";
1953
+ import { basename as basename3, dirname as dirname5, isAbsolute as isAbsolute2, resolve as resolve4 } from "node:path";
1735
1954
  function envWithoutGitDiscovery(base = process.env) {
1736
1955
  const env = { ...base, LC_ALL: "C" };
1737
1956
  for (const key of GIT_DISCOVERY_ENV_KEYS) {
@@ -1776,8 +1995,8 @@ function resolveBookKeyFromGit(cwd) {
1776
1995
  throw new Error("git rev-parse --git-common-dir returned an empty path");
1777
1996
  }
1778
1997
  const absoluteCommon = isAbsolute2(commonDir) ? commonDir : resolve4(cwd, commonDir);
1779
- const hostDirectory = basename2(absoluteCommon) === ".git" ? dirname4(absoluteCommon) : absoluteCommon;
1780
- const bookKey = basename2(hostDirectory);
1998
+ const hostDirectory = basename3(absoluteCommon) === ".git" ? dirname5(absoluteCommon) : absoluteCommon;
1999
+ const bookKey = basename3(hostDirectory);
1781
2000
  if (bookKey.length === 0 || bookKey === "." || bookKey === "/") {
1782
2001
  throw new Error(`Unable to derive activation book key from git common dir: ${absoluteCommon}`);
1783
2002
  }
@@ -1817,7 +2036,7 @@ __export(durable_principal_exports, {
1817
2036
  piDurablePrincipalAuthority: () => piDurablePrincipalAuthority
1818
2037
  });
1819
2038
  import { lstat } from "node:fs/promises";
1820
- import { join as join7 } from "node:path";
2039
+ import { join as join8 } from "node:path";
1821
2040
  function encode(coordinates) {
1822
2041
  return coordinates;
1823
2042
  }
@@ -1867,7 +2086,7 @@ var init_durable_principal = __esm({
1867
2086
  }
1868
2087
  return {
1869
2088
  sessionDirectory: record4.sessionDirectory,
1870
- sessionFile: typeof record4.sessionFile === "string" && record4.sessionFile.trim() !== "" ? record4.sessionFile : join7(record4.sessionDirectory, "session.jsonl")
2089
+ sessionFile: typeof record4.sessionFile === "string" && record4.sessionFile.trim() !== "" ? record4.sessionFile : join8(record4.sessionDirectory, "session.jsonl")
1871
2090
  };
1872
2091
  },
1873
2092
  async isAvailable(principal) {
@@ -1919,7 +2138,7 @@ var init_host_contracts = __esm({
1919
2138
  import { spawn as spawn2 } from "node:child_process";
1920
2139
  import { mkdtemp, rm, writeFile } from "node:fs/promises";
1921
2140
  import { tmpdir } from "node:os";
1922
- import { join as join8 } from "node:path";
2141
+ import { join as join9 } from "node:path";
1923
2142
  function normalizeEngineName(engine) {
1924
2143
  if (engine === void 0) return void 0;
1925
2144
  const trimmed = engine.trim();
@@ -1964,7 +2183,7 @@ async function spawnEngineDetourOnce(input) {
1964
2183
  }
1965
2184
  const command = input.argv[0];
1966
2185
  const args = input.argv.slice(1);
1967
- return await new Promise((resolve22, reject) => {
2186
+ return await new Promise((resolve21, reject) => {
1968
2187
  let settled = false;
1969
2188
  const signal = input.signal;
1970
2189
  const child = spawn2(command, args, {
@@ -1994,7 +2213,7 @@ async function spawnEngineDetourOnce(input) {
1994
2213
  if (signal !== void 0) {
1995
2214
  signal.removeEventListener("abort", onAbort);
1996
2215
  }
1997
- resolve22(result);
2216
+ resolve21(result);
1998
2217
  };
1999
2218
  const onAbort = () => {
2000
2219
  fail4(signal !== void 0 ? abortReasonError(signal) : new Error("aborted"));
@@ -2020,8 +2239,8 @@ async function runEngineDetourOnce(input) {
2020
2239
  if (input.stagedPrompt === void 0) {
2021
2240
  return spawnEngineDetourOnce(input);
2022
2241
  }
2023
- const stagingDir = await mkdtemp(join8(tmpdir(), "ak-engine-detour-"));
2024
- const stagedPath = join8(stagingDir, "prompt.txt");
2242
+ const stagingDir = await mkdtemp(join9(tmpdir(), "ak-engine-detour-"));
2243
+ const stagedPath = join9(stagingDir, "prompt.txt");
2025
2244
  let result;
2026
2245
  let runError;
2027
2246
  try {
@@ -2657,7 +2876,7 @@ var init_auditor_output = __esm({
2657
2876
  });
2658
2877
 
2659
2878
  // src/ticket-provenance-contracts.ts
2660
- function isRecord2(value) {
2879
+ function isRecord3(value) {
2661
2880
  return typeof value === "object" && value !== null && !Array.isArray(value);
2662
2881
  }
2663
2882
  function positiveInteger(value) {
@@ -2680,7 +2899,7 @@ function projectSpeaker(value) {
2680
2899
  return value === "owner" || value === "runner" ? value : void 0;
2681
2900
  }
2682
2901
  function projectBound(value) {
2683
- if (!isRecord2(value)) return void 0;
2902
+ if (!isRecord3(value)) return void 0;
2684
2903
  const id = typeof value.id === "string" && value.id !== "" ? value.id : void 0;
2685
2904
  const line2 = positiveInteger(value.line);
2686
2905
  if (id === void 0 && line2 === void 0) return void 0;
@@ -2691,13 +2910,13 @@ function projectTicketProvenanceSessions(value) {
2691
2910
  if (value.length === 0) return [];
2692
2911
  const sessions = [];
2693
2912
  for (const raw of value) {
2694
- if (!isRecord2(raw)) return void 0;
2913
+ if (!isRecord3(raw)) return void 0;
2695
2914
  const path = raw.path;
2696
2915
  if (typeof path !== "string" || path.trim() === "") return void 0;
2697
2916
  if (!Array.isArray(raw.ranges) || raw.ranges.length === 0) return void 0;
2698
2917
  const ranges = [];
2699
2918
  for (const rawRange of raw.ranges) {
2700
- if (!isRecord2(rawRange)) return void 0;
2919
+ if (!isRecord3(rawRange)) return void 0;
2701
2920
  const from = projectBound(rawRange.from);
2702
2921
  const to = projectBound(rawRange.to);
2703
2922
  if (from === void 0 || to === void 0) return void 0;
@@ -2708,7 +2927,7 @@ function projectTicketProvenanceSessions(value) {
2708
2927
  return sessions;
2709
2928
  }
2710
2929
  function projectTicketProvenanceHeader(value) {
2711
- if (!isRecord2(value)) return void 0;
2930
+ if (!isRecord3(value)) return void 0;
2712
2931
  const ticket = positiveInteger(value.ticket);
2713
2932
  if (ticket === void 0) return void 0;
2714
2933
  if (typeof value.repo !== "string") return void 0;
@@ -2726,7 +2945,7 @@ function projectTicketProvenanceHeader(value) {
2726
2945
  };
2727
2946
  }
2728
2947
  function projectTicketProvenanceLine(value) {
2729
- if (!isRecord2(value)) return void 0;
2948
+ if (!isRecord3(value)) return void 0;
2730
2949
  const speaker = projectSpeaker(value.speaker);
2731
2950
  const s = nonNegativeInteger(value.s);
2732
2951
  if (speaker === void 0 || s === void 0) return void 0;
@@ -2842,13 +3061,23 @@ var init_diarist_contracts = __esm({
2842
3061
  });
2843
3062
 
2844
3063
  // src/secretariat-contracts.ts
2845
- var SECRETARIAT_OUTPUT_TOOL_NAME, SECRETARIAT_SUMMON_COUNTERSIGN_TOOL_NAME, SECRETARIAT_ACCEPTED_TEXT;
3064
+ var secretariat_contracts_exports = {};
3065
+ __export(secretariat_contracts_exports, {
3066
+ SECRETARIAT_ACCEPTED_TEXT: () => SECRETARIAT_ACCEPTED_TEXT,
3067
+ SECRETARIAT_COUNTERSIGN_TERMINAL_FACT_KEY: () => SECRETARIAT_COUNTERSIGN_TERMINAL_FACT_KEY,
3068
+ SECRETARIAT_GATE_OFFICER_ENTRY_TYPE: () => SECRETARIAT_GATE_OFFICER_ENTRY_TYPE,
3069
+ SECRETARIAT_OUTPUT_TOOL_NAME: () => SECRETARIAT_OUTPUT_TOOL_NAME,
3070
+ SECRETARIAT_SUMMON_COUNTERSIGN_TOOL_NAME: () => SECRETARIAT_SUMMON_COUNTERSIGN_TOOL_NAME
3071
+ });
3072
+ var SECRETARIAT_OUTPUT_TOOL_NAME, SECRETARIAT_SUMMON_COUNTERSIGN_TOOL_NAME, SECRETARIAT_ACCEPTED_TEXT, SECRETARIAT_GATE_OFFICER_ENTRY_TYPE, SECRETARIAT_COUNTERSIGN_TERMINAL_FACT_KEY;
2846
3073
  var init_secretariat_contracts = __esm({
2847
3074
  "src/secretariat-contracts.ts"() {
2848
3075
  "use strict";
2849
3076
  SECRETARIAT_OUTPUT_TOOL_NAME = "ak_secretariat_output";
2850
3077
  SECRETARIAT_SUMMON_COUNTERSIGN_TOOL_NAME = "ak_secretariat_summon_countersign";
2851
3078
  SECRETARIAT_ACCEPTED_TEXT = "\u4E2D\u4E66\u7701\u56DE\u6267\u5DF2\u63A5\u53D7";
3079
+ SECRETARIAT_GATE_OFFICER_ENTRY_TYPE = "ak-secretariat-gate-officer";
3080
+ SECRETARIAT_COUNTERSIGN_TERMINAL_FACT_KEY = "countersignTerminal";
2852
3081
  }
2853
3082
  });
2854
3083
 
@@ -3195,8 +3424,8 @@ import {
3195
3424
  unlinkSync,
3196
3425
  writeFileSync
3197
3426
  } from "node:fs";
3198
- import { dirname as dirname5, join as join9 } from "node:path";
3199
- function isRecord3(value) {
3427
+ import { dirname as dirname6, join as join10 } from "node:path";
3428
+ function isRecord4(value) {
3200
3429
  return typeof value === "object" && value !== null && !Array.isArray(value);
3201
3430
  }
3202
3431
  function errorCodeOf(error) {
@@ -3224,7 +3453,7 @@ function findIdentityPointer(recordFile, identity, kind, level) {
3224
3453
  if (!trimmed) continue;
3225
3454
  try {
3226
3455
  const parsed = JSON.parse(trimmed);
3227
- if (isRecord3(parsed) && parsed.identity === identity) {
3456
+ if (isRecord4(parsed) && parsed.identity === identity) {
3228
3457
  return { identity, recordFile, kind, level };
3229
3458
  }
3230
3459
  } catch {
@@ -3323,8 +3552,8 @@ function resolveSitianVolumeCategory(kind) {
3323
3552
  return kind;
3324
3553
  }
3325
3554
  function ticketProvenanceUnderBookPaths(ledgerHome, bookKey, ticketId) {
3326
- const sessionDir = join9(activationBookDirectory(ledgerHome, bookKey), ticketId);
3327
- return { sessionDir, recordFile: join9(sessionDir, SITIAN_RECORDS_LEAF) };
3555
+ const sessionDir = join10(activationBookDirectory(ledgerHome, bookKey), ticketId);
3556
+ return { sessionDir, recordFile: join10(sessionDir, SITIAN_RECORDS_LEAF) };
3328
3557
  }
3329
3558
  function resolveSitianRecordPathInLedger(input, ledgerHome) {
3330
3559
  const category = resolveSitianVolumeCategory(input.kind);
@@ -3343,14 +3572,14 @@ function resolveSitianRecordPathInLedger(input, ledgerHome) {
3343
3572
  if (input.sessionParent === void 0 || input.sessionParent.length === 0 || !physicallyContainedIn(ledgerHome, input.sessionParent)) {
3344
3573
  throw new Error("Sitian record ownership requires a parent session inside the ledger home");
3345
3574
  }
3346
- sessionDir = join9(dirname5(input.sessionParent), category);
3347
- recordFile = join9(sessionDir, SITIAN_RECORDS_LEAF);
3575
+ sessionDir = join10(dirname6(input.sessionParent), category);
3576
+ recordFile = join10(sessionDir, SITIAN_RECORDS_LEAF);
3348
3577
  }
3349
3578
  return { sessionDir, recordFile, ledgerHome };
3350
3579
  }
3351
3580
  function projectTicketRecordsPathShape() {
3352
3581
  const { recordFile } = ticketProvenanceUnderBookPaths(
3353
- join9("~", ".ak-roles"),
3582
+ join10("~", ".ak-roles"),
3354
3583
  "<\u7C3F>",
3355
3584
  "<\u7968\u53F7>"
3356
3585
  );
@@ -3412,15 +3641,15 @@ var init_sitian_appender = __esm({
3412
3641
 
3413
3642
  // src/sitian-reader.ts
3414
3643
  import { existsSync as existsSync3 } from "node:fs";
3415
- import { readFile as readFile4 } from "node:fs/promises";
3416
- function isRecord4(value) {
3644
+ import { readFile as readFile5 } from "node:fs/promises";
3645
+ function isRecord5(value) {
3417
3646
  return typeof value === "object" && value !== null && !Array.isArray(value);
3418
3647
  }
3419
3648
  async function readSitianRecords(recordFile) {
3420
3649
  if (!existsSync3(recordFile)) {
3421
3650
  return { records: [], diagnostics: [] };
3422
3651
  }
3423
- const text = await readFile4(recordFile, "utf8");
3652
+ const text = await readFile5(recordFile, "utf8");
3424
3653
  const lines = text.split("\n");
3425
3654
  const records = [];
3426
3655
  const diagnostics = [];
@@ -3429,7 +3658,7 @@ async function readSitianRecords(recordFile) {
3429
3658
  if (!line2.trim()) continue;
3430
3659
  try {
3431
3660
  const parsed = JSON.parse(line2);
3432
- if (isRecord4(parsed)) {
3661
+ if (isRecord5(parsed)) {
3433
3662
  records.push(parsed);
3434
3663
  } else {
3435
3664
  const typeDesc = parsed === null ? "null" : Array.isArray(parsed) ? "array" : typeof parsed;
@@ -3485,13 +3714,13 @@ __export(role_turn_host_exports, {
3485
3714
  });
3486
3715
  import { execFile, spawn as spawn3 } from "node:child_process";
3487
3716
  import { constants } from "node:fs";
3488
- import { access, appendFile, readFile as readFile5, realpath as realpath2 } from "node:fs/promises";
3489
- import { basename as basename3, delimiter, dirname as dirname6, isAbsolute as isAbsolute3, join as join10, resolve as resolve5 } from "node:path";
3717
+ import { access, appendFile, readFile as readFile6, realpath as realpath2 } from "node:fs/promises";
3718
+ import { basename as basename4, delimiter, dirname as dirname7, isAbsolute as isAbsolute3, join as join11, resolve as resolve5 } from "node:path";
3490
3719
  import { platform } from "node:process";
3491
3720
  import { promisify } from "node:util";
3492
3721
  import { randomUUID as randomUUID2 } from "node:crypto";
3493
3722
  function resolveInternalRoleEntrypoint(packageRoot) {
3494
- return join10(packageRoot, INTERNAL_ROLE_ENTRYPOINT_RELATIVE);
3723
+ return join11(packageRoot, INTERNAL_ROLE_ENTRYPOINT_RELATIVE);
3495
3724
  }
3496
3725
  function buildExplicitInternalActivationArgs(selectedRoleEntry, extraArgs = []) {
3497
3726
  return ["--no-extensions", "-e", selectedRoleEntry, ...extraArgs];
@@ -3527,7 +3756,7 @@ function buildMethodArgs(methods) {
3527
3756
  function applyPiNativeSkillInvocation(methods, prompt) {
3528
3757
  const skills = methods.filter((method) => method.kind === "skill");
3529
3758
  if (skills.length !== 1) return prompt;
3530
- const name = basename3(dirname6(skills[0].path));
3759
+ const name = basename4(dirname7(skills[0].path));
3531
3760
  if (name.length === 0) return prompt;
3532
3761
  const token = `/skill:${name}`;
3533
3762
  const trimmed = prompt.trimStart();
@@ -3746,9 +3975,6 @@ ${paths.join("\n")}`
3746
3975
  if (typeof process.env.AK_ROLE_AUDITOR_SUBJECT === "string" && process.env.AK_ROLE_AUDITOR_SUBJECT.trim() !== "") {
3747
3976
  env.AK_ROLE_AUDITOR_SUBJECT = process.env.AK_ROLE_AUDITOR_SUBJECT;
3748
3977
  }
3749
- if (request.correlationId !== void 0 && request.correlationId.trim() !== "") {
3750
- env.AK_CORRELATION_ID = request.correlationId;
3751
- }
3752
3978
  if (config.recordLaunchedRolePackageIdentity !== void 0 && config.observeLaunchedRolePackageIdentity !== void 0) {
3753
3979
  await config.recordLaunchedRolePackageIdentity(
3754
3980
  request.runDirectory,
@@ -3768,7 +3994,7 @@ ${paths.join("\n")}`
3768
3994
  }
3769
3995
  async function appendPiSessionCustomEntry(authority, principal, customType, data) {
3770
3996
  const { sessionFile } = authority.decode(principal);
3771
- const text = await readFile5(sessionFile, "utf8");
3997
+ const text = await readFile6(sessionFile, "utf8");
3772
3998
  let parentId = null;
3773
3999
  for (const line2 of text.trim().split("\n").filter(Boolean)) {
3774
4000
  const entry = JSON.parse(line2);
@@ -3921,8 +4147,8 @@ var init_host_descriptions = __esm({
3921
4147
 
3922
4148
  // src/role-run-relocation.ts
3923
4149
  import { existsSync as existsSync4 } from "node:fs";
3924
- import { readdir as readdir2, readFile as readFile6, writeFile as writeFile2 } from "node:fs/promises";
3925
- import { join as join11, sep as sep2 } from "node:path";
4150
+ import { readdir as readdir3, readFile as readFile7, writeFile as writeFile2 } from "node:fs/promises";
4151
+ import { join as join12, sep as sep2 } from "node:path";
3926
4152
  function isEnoent2(error) {
3927
4153
  return error instanceof Error && "code" in error && error.code === "ENOENT";
3928
4154
  }
@@ -4011,7 +4237,7 @@ function rewriteSummonsMaterials(value, rewrites) {
4011
4237
  }
4012
4238
  async function rewriteJsonObjectFile(path, fields, rewrites) {
4013
4239
  if (!existsSync4(path)) return;
4014
- const page = JSON.parse(await readFile6(path, "utf8"));
4240
+ const page = JSON.parse(await readFile7(path, "utf8"));
4015
4241
  if (!isPlainObject(page)) return;
4016
4242
  rewriteRunDirectoryPathFieldsAgainstRewrites(page, fields, rewrites);
4017
4243
  await writeFile2(path, `${JSON.stringify(page, null, 2)}
@@ -4019,7 +4245,7 @@ async function rewriteJsonObjectFile(path, fields, rewrites) {
4019
4245
  }
4020
4246
  async function rewriteOfficerPointerFile(path, rewrites) {
4021
4247
  if (!existsSync4(path)) return;
4022
- const page = JSON.parse(await readFile6(path, "utf8"));
4248
+ const page = JSON.parse(await readFile7(path, "utf8"));
4023
4249
  if (!isPlainObject(page)) return;
4024
4250
  if (page.kind !== "direct-officer-run-pointer") return;
4025
4251
  rewriteRunDirectoryPathFieldsAgainstRewrites(
@@ -4032,7 +4258,7 @@ async function rewriteOfficerPointerFile(path, rewrites) {
4032
4258
  }
4033
4259
  async function rewriteSitianRecordsJsonl(path, rewrites) {
4034
4260
  if (!existsSync4(path)) return;
4035
- const raw = await readFile6(path, "utf8");
4261
+ const raw = await readFile7(path, "utf8");
4036
4262
  if (raw.length === 0) return;
4037
4263
  const endsWithNewline = raw.endsWith("\n");
4038
4264
  const lines = raw.split("\n");
@@ -4083,7 +4309,7 @@ async function rewriteSitianRecordsJsonl(path, rewrites) {
4083
4309
  }
4084
4310
  async function rewriteSessionTranscriptBindings(path, rewrites) {
4085
4311
  if (!existsSync4(path)) return;
4086
- const raw = await readFile6(path, "utf8");
4312
+ const raw = await readFile7(path, "utf8");
4087
4313
  if (raw.length === 0) return;
4088
4314
  const endsWithNewline = raw.endsWith("\n");
4089
4315
  const lines = raw.split("\n");
@@ -4142,17 +4368,17 @@ async function rewriteSessionTranscriptBindings(path, rewrites) {
4142
4368
  );
4143
4369
  }
4144
4370
  async function rewriteNestedMachinePathPages(pagesDirectory, rewrites) {
4145
- const sessionRoot = join11(pagesDirectory, "session");
4371
+ const sessionRoot = join12(pagesDirectory, "session");
4146
4372
  async function walk(directory) {
4147
4373
  let entries;
4148
4374
  try {
4149
- entries = await readdir2(directory, { withFileTypes: true });
4375
+ entries = await readdir3(directory, { withFileTypes: true });
4150
4376
  } catch (error) {
4151
4377
  if (isEnoent2(error)) return;
4152
4378
  throw error;
4153
4379
  }
4154
4380
  for (const entry of entries) {
4155
- const path = join11(directory, entry.name);
4381
+ const path = join12(directory, entry.name);
4156
4382
  if (entry.isDirectory()) {
4157
4383
  await walk(path);
4158
4384
  continue;
@@ -4174,9 +4400,9 @@ async function rewriteNestedMachinePathPages(pagesDirectory, rewrites) {
4174
4400
  async function rewriteRoleRunDurablePages(input) {
4175
4401
  const { pagesDirectory } = input;
4176
4402
  const rewrites = collectRewrites(input);
4177
- const admittedPath = join11(pagesDirectory, "admitted-request.json");
4403
+ const admittedPath = join12(pagesDirectory, "admitted-request.json");
4178
4404
  if (existsSync4(admittedPath)) {
4179
- const page = JSON.parse(await readFile6(admittedPath, "utf8"));
4405
+ const page = JSON.parse(await readFile7(admittedPath, "utf8"));
4180
4406
  rewriteRunDirectoryPathFieldsAgainstRewrites(
4181
4407
  page,
4182
4408
  ADMITTED_PAGE_FIELDS,
@@ -4204,9 +4430,9 @@ async function rewriteRoleRunDurablePages(input) {
4204
4430
  await writeFile2(admittedPath, `${JSON.stringify(page, null, 2)}
4205
4431
  `, "utf8");
4206
4432
  }
4207
- const invocationPath = join11(pagesDirectory, "invocation.json");
4433
+ const invocationPath = join12(pagesDirectory, "invocation.json");
4208
4434
  if (existsSync4(invocationPath)) {
4209
- const page = JSON.parse(await readFile6(invocationPath, "utf8"));
4435
+ const page = JSON.parse(await readFile7(invocationPath, "utf8"));
4210
4436
  rewriteRunDirectoryPathFieldsAgainstRewrites(
4211
4437
  page,
4212
4438
  INVOCATION_PAGE_FIELDS,
@@ -4219,9 +4445,9 @@ async function rewriteRoleRunDurablePages(input) {
4219
4445
  "utf8"
4220
4446
  );
4221
4447
  }
4222
- const statePath = join11(pagesDirectory, "run-state.json");
4448
+ const statePath = join12(pagesDirectory, "run-state.json");
4223
4449
  if (existsSync4(statePath)) {
4224
- const page = JSON.parse(await readFile6(statePath, "utf8"));
4450
+ const page = JSON.parse(await readFile7(statePath, "utf8"));
4225
4451
  rewriteRunDirectoryPathFieldsAgainstRewrites(
4226
4452
  page,
4227
4453
  RUN_STATE_PAGE_FIELDS,
@@ -4409,15 +4635,15 @@ var init_terminating_tools = __esm({
4409
4635
  });
4410
4636
 
4411
4637
  // src/doctor-evidence.ts
4412
- import { readdir as readdir3, readFile as readFile7, realpath as realpath3, stat } from "node:fs/promises";
4413
- import { dirname as dirname7, relative as relative2, resolve as resolve6, sep as sep3 } from "node:path";
4638
+ import { readdir as readdir4, readFile as readFile8, realpath as realpath3, stat } from "node:fs/promises";
4639
+ import { dirname as dirname8, relative as relative2, resolve as resolve6, sep as sep3 } from "node:path";
4414
4640
  function record3(value) {
4415
4641
  return typeof value === "object" && value !== null && !Array.isArray(value);
4416
4642
  }
4417
4643
  async function discoverCaseFiles(root) {
4418
4644
  const found = [];
4419
4645
  async function walk(dir, depth) {
4420
- for (const item of await readdir3(dir, { withFileTypes: true })) {
4646
+ for (const item of await readdir4(dir, { withFileTypes: true })) {
4421
4647
  const path = resolve6(dir, item.name);
4422
4648
  if (item.isDirectory()) {
4423
4649
  await walk(path, depth + 1);
@@ -4437,7 +4663,7 @@ function accumulate(metric, value, source) {
4437
4663
  function timestamp(row) {
4438
4664
  return typeof row.timestamp === "string" && Number.isFinite(Date.parse(row.timestamp)) ? row.timestamp : void 0;
4439
4665
  }
4440
- function isMissingPathError2(error) {
4666
+ function isMissingPathError3(error) {
4441
4667
  return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
4442
4668
  }
4443
4669
  async function stableRunsIdentity(root) {
@@ -4447,9 +4673,9 @@ async function stableRunsIdentity(root) {
4447
4673
  const git3 = await stat(resolve6(cursor, ".git"));
4448
4674
  if (git3.isDirectory() || git3.isFile()) return relative2(cursor, root).split(sep3).join("/");
4449
4675
  } catch (error) {
4450
- if (!isMissingPathError2(error)) throw error;
4676
+ if (!isMissingPathError3(error)) throw error;
4451
4677
  }
4452
- const parent = dirname7(cursor);
4678
+ const parent = dirname8(cursor);
4453
4679
  if (parent === cursor) return root;
4454
4680
  cursor = parent;
4455
4681
  }
@@ -4525,7 +4751,7 @@ async function loadDoctorCase(runsPath) {
4525
4751
  const turns = { count: 0, sources: [] }, calls = { count: 0, sources: [] }, tokens = { count: 0, sources: [] };
4526
4752
  for (const path of await discoverCaseFiles(root)) {
4527
4753
  const id = relative2(root, path).split(sep3).join("/");
4528
- const bytes = await readFile7(path);
4754
+ const bytes = await readFile8(path);
4529
4755
  const content = bytes.toString("utf8");
4530
4756
  const kind = id.endsWith(".jsonl") ? "session" : "stderr";
4531
4757
  evidence.push({ id, kind, byteLength: bytes.byteLength, contentLength: content.length, sha256: sha256Hex(bytes), content });
@@ -4538,7 +4764,7 @@ async function loadDoctorCase(runsPath) {
4538
4764
  accumulate(calls, result.calls, id);
4539
4765
  accumulate(tokens, result.tokens, id);
4540
4766
  }
4541
- const runDirs = (await readdir3(root, { withFileTypes: true })).filter((item) => item.isDirectory()).map((item) => item.name).sort();
4767
+ const runDirs = (await readdir4(root, { withFileTypes: true })).filter((item) => item.isDirectory()).map((item) => item.name).sort();
4542
4768
  const legs = evidence.filter((entry) => entry.kind === "session").map((entry) => entry.id);
4543
4769
  const retryDirs = runDirs.filter((name) => /(?:^|[-_])retry(?:[-_]|$)/i.test(name));
4544
4770
  const rawBytes = evidence.filter((entry) => entry.kind === "session").reduce((sum, entry) => sum + entry.byteLength, 0);
@@ -4765,7 +4991,7 @@ var init_git_object_id = __esm({
4765
4991
 
4766
4992
  // src/merger-git-state.ts
4767
4993
  import { execFile as execFile2 } from "node:child_process";
4768
- import { access as access2, readFile as readFile8 } from "node:fs/promises";
4994
+ import { access as access2, readFile as readFile9 } from "node:fs/promises";
4769
4995
  import { constants as fsConstants } from "node:fs";
4770
4996
  import { isAbsolute as isAbsolute4, resolve as resolve7 } from "node:path";
4771
4997
  import { promisify as promisify2 } from "node:util";
@@ -4835,7 +5061,7 @@ function createProductionMergerGitState(repositoryRoot = process.cwd()) {
4835
5061
  const mergeHeadPath = isAbsolute4(mergeHeadReported) ? mergeHeadReported : resolve7(repositoryRoot, mergeHeadReported);
4836
5062
  let sourceObjectId = "";
4837
5063
  if (await pathExists(mergeHeadPath)) {
4838
- const raw = exactUtf8(await readFile8(mergeHeadPath), "Git MERGE_HEAD");
5064
+ const raw = exactUtf8(await readFile9(mergeHeadPath), "Git MERGE_HEAD");
4839
5065
  const mergeHeads = raw.trim().split(/\r?\n/).map((row) => row.trim()).filter(Boolean);
4840
5066
  if (mergeHeads.length === 0) throw new Error("Git MERGE_HEAD is empty");
4841
5067
  if (mergeHeads.length !== 1) throw new Error("Assigned repository does not have one ordinary in-progress merge");
@@ -4887,10 +5113,10 @@ var init_uuidv7 = __esm({
4887
5113
  });
4888
5114
 
4889
5115
  // src/typed-provider-http.ts
4890
- import { readFile as readFile9, unlink, writeFile as writeFile3 } from "node:fs/promises";
4891
- import { join as join12 } from "node:path";
5116
+ import { readFile as readFile10, unlink, writeFile as writeFile3 } from "node:fs/promises";
5117
+ import { join as join13 } from "node:path";
4892
5118
  function typedProviderHttpPath(runDirectory) {
4893
- return join12(runDirectory, TYPED_HTTP_FILE);
5119
+ return join13(runDirectory, TYPED_HTTP_FILE);
4894
5120
  }
4895
5121
  async function clearTypedProviderHttpObservation(runDirectory) {
4896
5122
  try {
@@ -4921,7 +5147,7 @@ async function recordTypedProviderHttpStatus(runDirectory, observation) {
4921
5147
  async function readLatestTypedProviderHttpObservation(runDirectory) {
4922
5148
  let text;
4923
5149
  try {
4924
- text = await readFile9(typedProviderHttpPath(runDirectory), "utf8");
5150
+ text = await readFile10(typedProviderHttpPath(runDirectory), "utf8");
4925
5151
  } catch (error) {
4926
5152
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
4927
5153
  return void 0;
@@ -5000,8 +5226,8 @@ __export(run_lifecycle_exports, {
5000
5226
  selectResumeContinuationPrompt: () => selectResumeContinuationPrompt,
5001
5227
  writeRoleRunState: () => writeRoleRunState
5002
5228
  });
5003
- import { chmod, lstat as lstat2, open, readdir as readdir4, readFile as readFile10, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
5004
- import { basename as basename4, join as join13 } from "node:path";
5229
+ import { chmod, lstat as lstat2, open, readdir as readdir5, readFile as readFile11, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
5230
+ import { basename as basename5, join as join14 } from "node:path";
5005
5231
  function selectResumeContinuationPrompt(message, engineMaterial) {
5006
5232
  const lines = message !== void 0 ? [message] : [];
5007
5233
  return appendEngineSessionMaterial(lines, engineMaterial).join("\n");
@@ -5040,7 +5266,7 @@ function renderResumeCommand(runId) {
5040
5266
  async function writeRoleRunState(runDirectory, record4) {
5041
5267
  const payload = { ...record4, runDirectory };
5042
5268
  await writeFile4(
5043
- join13(runDirectory, RUN_STATE_FILE),
5269
+ join14(runDirectory, RUN_STATE_FILE),
5044
5270
  `${JSON.stringify(payload, null, 2)}
5045
5271
  `,
5046
5272
  "utf8"
@@ -5090,7 +5316,7 @@ function parseCurrentCourtState(raw) {
5090
5316
  async function readRoleRunStateDisk(runDirectory) {
5091
5317
  let raw;
5092
5318
  try {
5093
- raw = JSON.parse(await readFile10(join13(runDirectory, RUN_STATE_FILE), "utf8"));
5319
+ raw = JSON.parse(await readFile11(join14(runDirectory, RUN_STATE_FILE), "utf8"));
5094
5320
  } catch (error) {
5095
5321
  if (errorCodeOf2(error) === "ENOENT") return void 0;
5096
5322
  throw error;
@@ -5158,7 +5384,7 @@ async function writeRoleRunStateDisk(runDirectory, disk) {
5158
5384
  ...disk.currentCourt === void 0 ? {} : { currentCourt: disk.currentCourt }
5159
5385
  };
5160
5386
  await writeFile4(
5161
- join13(runDirectory, RUN_STATE_FILE),
5387
+ join14(runDirectory, RUN_STATE_FILE),
5162
5388
  `${JSON.stringify(payload, null, 2)}
5163
5389
  `,
5164
5390
  "utf8"
@@ -5330,7 +5556,7 @@ function isProcessAlive(pid) {
5330
5556
  async function autopsyWriterLock(lockPath) {
5331
5557
  let content;
5332
5558
  try {
5333
- content = await readFile10(lockPath, "utf8");
5559
+ content = await readFile11(lockPath, "utf8");
5334
5560
  } catch (error) {
5335
5561
  if (errorCodeOf2(error) === "ENOENT") return { verdict: "absent" };
5336
5562
  return { verdict: "unknown", reason: "unreadable", readFailure: error };
@@ -5389,7 +5615,7 @@ async function createWriterLease(lockPath, runDirectory, reportCleanupFailure) {
5389
5615
  },
5390
5616
  relocate(nextRunDirectory) {
5391
5617
  currentRunDirectory = nextRunDirectory;
5392
- currentLockPath = join13(nextRunDirectory, WRITER_LOCK_FILE);
5618
+ currentLockPath = join14(nextRunDirectory, WRITER_LOCK_FILE);
5393
5619
  },
5394
5620
  async release() {
5395
5621
  if (released) return;
@@ -5428,10 +5654,10 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
5428
5654
  };
5429
5655
  const reportReadFailure = (error) => {
5430
5656
  reportDiagnostic(
5431
- `writer lease lock read failed (holder liveness unverifiable; lock left in place) at ${join13(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
5657
+ `writer lease lock read failed (holder liveness unverifiable; lock left in place) at ${join14(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
5432
5658
  );
5433
5659
  };
5434
- const lockPath = join13(runDirectory, WRITER_LOCK_FILE);
5660
+ const lockPath = join14(runDirectory, WRITER_LOCK_FILE);
5435
5661
  let lastAutopsy = { verdict: "absent" };
5436
5662
  let lastReclaimFailure;
5437
5663
  for (let reclaimsLeft = WRITER_LEASE_RECLAIM_ROUNDS; ; reclaimsLeft -= 1) {
@@ -5486,10 +5712,10 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
5486
5712
  async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole) {
5487
5713
  if (runId.trim() === "") return void 0;
5488
5714
  const ledgerHome = resolveActivationLedgerHome(home);
5489
- const booksRoot = join13(ledgerHome, "books");
5715
+ const booksRoot = join14(ledgerHome, "books");
5490
5716
  let bookKeys;
5491
5717
  try {
5492
- bookKeys = await readdir4(booksRoot);
5718
+ bookKeys = await readdir5(booksRoot);
5493
5719
  } catch (error) {
5494
5720
  if (errorCodeOf2(error) === "ENOENT") return void 0;
5495
5721
  throw error;
@@ -5506,7 +5732,7 @@ async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole) {
5506
5732
  throw error;
5507
5733
  }
5508
5734
  for (const runDirectory of runDirectories) {
5509
- const entry = basename4(runDirectory);
5735
+ const entry = basename5(runDirectory);
5510
5736
  if (onlyRole === void 0 && (entry === `${runId}@judge` || entry.startsWith(`${runId}@`)) || entry === `${runId}@${onlyRole}`) {
5511
5737
  matches.push(runDirectory);
5512
5738
  }
@@ -5527,7 +5753,7 @@ async function readRunParentPath(runDirectory) {
5527
5753
  let raw;
5528
5754
  try {
5529
5755
  raw = JSON.parse(
5530
- await readFile10(join13(runDirectory, "admitted-request.json"), "utf8")
5756
+ await readFile11(join14(runDirectory, "admitted-request.json"), "utf8")
5531
5757
  );
5532
5758
  } catch (error) {
5533
5759
  if (errorCodeOf2(error) === "ENOENT") return void 0;
@@ -5548,7 +5774,7 @@ async function readRunParentPath(runDirectory) {
5548
5774
  async function runHasFormedSessionPrincipal(runDirectory) {
5549
5775
  const disk = await readRoleRunStateDisk(runDirectory);
5550
5776
  if (disk === void 0) return false;
5551
- const sessionFile = typeof disk.principalWire.sessionFile === "string" && disk.principalWire.sessionFile.trim() !== "" ? disk.principalWire.sessionFile : join13(disk.principalWire.sessionDirectory, "session.jsonl");
5777
+ const sessionFile = typeof disk.principalWire.sessionFile === "string" && disk.principalWire.sessionFile.trim() !== "" ? disk.principalWire.sessionFile : join14(disk.principalWire.sessionDirectory, "session.jsonl");
5552
5778
  try {
5553
5779
  const stat2 = await lstat2(sessionFile);
5554
5780
  return stat2.isFile() && !stat2.isSymbolicLink();
@@ -5573,7 +5799,7 @@ async function findLatestRunIdForSeatTicket(input) {
5573
5799
  const suffix = `@${input.role}`;
5574
5800
  let best;
5575
5801
  for (const runDirectory of runDirectories) {
5576
- const entry = basename4(runDirectory);
5802
+ const entry = basename5(runDirectory);
5577
5803
  if (!entry.endsWith(suffix)) continue;
5578
5804
  const runId = entry.slice(0, entry.length - suffix.length);
5579
5805
  if (runId.length === 0) continue;
@@ -5696,7 +5922,7 @@ async function loadResumableRunRecord(home, runId, authority) {
5696
5922
  let sourceRun;
5697
5923
  try {
5698
5924
  const raw = JSON.parse(
5699
- await readFile10(run.admittedRequestPath, "utf8")
5925
+ await readFile11(run.admittedRequestPath, "utf8")
5700
5926
  );
5701
5927
  if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) {
5702
5928
  const record4 = raw;
@@ -5814,7 +6040,7 @@ async function loadResumableRunRecord(home, runId, authority) {
5814
6040
  let model;
5815
6041
  try {
5816
6042
  const invocationRaw = JSON.parse(
5817
- await readFile10(join13(run.runDirectory, "invocation.json"), "utf8")
6043
+ await readFile11(join14(run.runDirectory, "invocation.json"), "utf8")
5818
6044
  );
5819
6045
  if (invocationRaw !== null && typeof invocationRaw === "object" && !Array.isArray(invocationRaw)) {
5820
6046
  const rec = invocationRaw;
@@ -6283,7 +6509,7 @@ __export(notary_source_run_exports, {
6283
6509
  loadNotarySourceRunLocator: () => loadNotarySourceRunLocator,
6284
6510
  resolveNotarySourceRunLocator: () => resolveNotarySourceRunLocator
6285
6511
  });
6286
- import { dirname as dirname8, isAbsolute as isAbsolute6, join as join14, resolve as resolve8, basename as basename5 } from "node:path";
6512
+ import { dirname as dirname9, isAbsolute as isAbsolute6, join as join15, resolve as resolve8, basename as basename6 } from "node:path";
6287
6513
  import { lstat as lstat3, realpath as realpath4 } from "node:fs/promises";
6288
6514
  function parseRunDirectoryName(name) {
6289
6515
  const match = RUN_DIR_NAME.exec(name);
@@ -6314,10 +6540,10 @@ async function requireRunDirectory(candidate, display) {
6314
6540
  `notary --source-run must be a run directory: ${display}`
6315
6541
  );
6316
6542
  }
6317
- const identity = parseRunDirectoryName(basename5(real));
6543
+ const identity = parseRunDirectoryName(basename6(real));
6318
6544
  if (identity === void 0) {
6319
6545
  throw new NotarySourceRunError(
6320
- `notary --source-run must be named <runId>@<role>: ${basename5(real)}`
6546
+ `notary --source-run must be named <runId>@<role>: ${basename6(real)}`
6321
6547
  );
6322
6548
  }
6323
6549
  return real;
@@ -6329,20 +6555,20 @@ async function resolveNotarySourceRunLocator(options) {
6329
6555
  }
6330
6556
  const ledgerHome = resolveActivationLedgerHome(options.home);
6331
6557
  const bookKey = resolveBookKeyFromGit(options.projectRoot);
6332
- const bookRunsRoot = join14(activationBookDirectory(ledgerHome, bookKey), "runs");
6558
+ const bookRunsRoot = join15(activationBookDirectory(ledgerHome, bookKey), "runs");
6333
6559
  let candidate;
6334
6560
  const bare = parseRunDirectoryName(raw);
6335
6561
  if (bare !== void 0 && !raw.includes("/") && !raw.includes("\\")) {
6336
- candidate = await findRunDirectoryById(options.home, bare.runId, bookKey, bare.role) ?? join14(bookRunsRoot, `${bare.runId}@${bare.role}`);
6562
+ candidate = await findRunDirectoryById(options.home, bare.runId, bookKey, bare.role) ?? join15(bookRunsRoot, `${bare.runId}@${bare.role}`);
6337
6563
  } else {
6338
6564
  candidate = isAbsolute6(raw) ? raw : resolve8(options.projectRoot, raw);
6339
6565
  }
6340
6566
  const real = await requireRunDirectory(candidate, raw);
6341
- const identity = parseRunDirectoryName(basename5(real));
6567
+ const identity = parseRunDirectoryName(basename6(real));
6342
6568
  const bookIdentity = physicalPathIdentity(activationBookDirectory(ledgerHome, bookKey));
6343
- const parentIdentity = physicalPathIdentity(dirname8(real));
6344
- const subjectBookIdentity = physicalPathIdentity(dirname8(dirname8(dirname8(real))));
6345
- if (parentIdentity !== physicalPathIdentity(bookRunsRoot) && !(basename5(dirname8(real)) === "runs" && subjectBookIdentity === bookIdentity)) {
6569
+ const parentIdentity = physicalPathIdentity(dirname9(real));
6570
+ const subjectBookIdentity = physicalPathIdentity(dirname9(dirname9(dirname9(real))));
6571
+ if (parentIdentity !== physicalPathIdentity(bookRunsRoot) && !(basename6(dirname9(real)) === "runs" && subjectBookIdentity === bookIdentity)) {
6346
6572
  throw new NotarySourceRunError(
6347
6573
  "notary --source-run must resolve to a retained run under the project machine-ledger book"
6348
6574
  );
@@ -6376,7 +6602,7 @@ async function resolveNotarySourceRunLocator(options) {
6376
6602
  }
6377
6603
  async function loadNotarySourceRunLocator(path) {
6378
6604
  const real = await requireRunDirectory(path, path);
6379
- const identity = parseRunDirectoryName(basename5(real));
6605
+ const identity = parseRunDirectoryName(basename6(real));
6380
6606
  const runState = await readRoleRunIdentity(real);
6381
6607
  if (runState === void 0) {
6382
6608
  throw new NotarySourceRunError(
@@ -7525,14 +7751,14 @@ import { existsSync as existsSync5 } from "node:fs";
7525
7751
  import {
7526
7752
  lstat as lstat4,
7527
7753
  mkdtemp as mkdtemp2,
7528
- readFile as readFile11,
7754
+ readFile as readFile12,
7529
7755
  realpath as realpath5,
7530
7756
  rename,
7531
7757
  rm as rm2,
7532
7758
  writeFile as writeFile5
7533
7759
  } from "node:fs/promises";
7534
7760
  import { tmpdir as tmpdir2 } from "node:os";
7535
- import { basename as basename6, dirname as dirname9, isAbsolute as isAbsolute7, join as join15, resolve as resolve9, sep as sep4 } from "node:path";
7761
+ import { basename as basename7, dirname as dirname10, isAbsolute as isAbsolute7, join as join16, resolve as resolve9, sep as sep4 } from "node:path";
7536
7762
  function issueAdmissionPlacement(authority, request) {
7537
7763
  const ledgerHome = resolveActivationLedgerHome(request.home);
7538
7764
  const bookKey = resolveBookKeyFromGit(request.cwd);
@@ -7586,15 +7812,15 @@ async function writeRoleInvocationLedger(source, role, effectiveModel) {
7586
7812
  ...effectiveModelLedgerFields(effectiveModel)
7587
7813
  };
7588
7814
  await writeFile5(
7589
- join15(source.runDirectory, "invocation.json"),
7815
+ join16(source.runDirectory, "invocation.json"),
7590
7816
  `${JSON.stringify(identity, null, 2)}
7591
7817
  `,
7592
7818
  "utf8"
7593
7819
  );
7594
7820
  }
7595
7821
  async function recordEffectiveInvocationModel(runDirectory, model, engine, host, engineModel) {
7596
- const ledgerPath = join15(runDirectory, "invocation.json");
7597
- const current = JSON.parse(await readFile11(ledgerPath, "utf8"));
7822
+ const ledgerPath = join16(runDirectory, "invocation.json");
7823
+ const current = JSON.parse(await readFile12(ledgerPath, "utf8"));
7598
7824
  const next = { ...current };
7599
7825
  if (model !== void 0) {
7600
7826
  next.provider = model.provider;
@@ -7626,8 +7852,8 @@ async function recordEffectiveInvocationModel(runDirectory, model, engine, host,
7626
7852
  );
7627
7853
  }
7628
7854
  async function mergeInvocationIdentityPage(runDirectory, fields) {
7629
- const ledgerPath = join15(runDirectory, "invocation.json");
7630
- const current = JSON.parse(await readFile11(ledgerPath, "utf8"));
7855
+ const ledgerPath = join16(runDirectory, "invocation.json");
7856
+ const current = JSON.parse(await readFile12(ledgerPath, "utf8"));
7631
7857
  await writeFile5(
7632
7858
  ledgerPath,
7633
7859
  `${JSON.stringify({
@@ -7643,7 +7869,7 @@ async function persistAdmittedSourceRunPath(admitted, sourceRunPath) {
7643
7869
  throw new Error("persistAdmittedSourceRunPath requires a non-empty sourceRunPath");
7644
7870
  }
7645
7871
  const admittedPath = admitted.admittedRequestPath;
7646
- const current = JSON.parse(await readFile11(admittedPath, "utf8"));
7872
+ const current = JSON.parse(await readFile12(admittedPath, "utf8"));
7647
7873
  if (typeof current.sourceRunPath === "string") {
7648
7874
  if (current.sourceRunPath === sourceRunPath) return;
7649
7875
  throw new Error(
@@ -7669,7 +7895,7 @@ async function bindAdmittedTicketNumber(admitted, ticketNumber) {
7669
7895
  }
7670
7896
  async function recordAdmittedCorrelation(admitted, correlationId) {
7671
7897
  const current = JSON.parse(
7672
- await readFile11(admitted.admittedRequestPath, "utf8")
7898
+ await readFile12(admitted.admittedRequestPath, "utf8")
7673
7899
  );
7674
7900
  const prior = [
7675
7901
  ...Array.isArray(current.correlationIds) ? current.correlationIds.filter(
@@ -7717,7 +7943,7 @@ async function bindCourtTicketNumbersOnAdmitted(admitted, courtTicketNumbers) {
7717
7943
  }
7718
7944
  const frozen = Object.freeze([...projected]);
7719
7945
  const admittedPath = admitted.admittedRequestPath;
7720
- const current = JSON.parse(await readFile11(admittedPath, "utf8"));
7946
+ const current = JSON.parse(await readFile12(admittedPath, "utf8"));
7721
7947
  await writeFile5(
7722
7948
  admittedPath,
7723
7949
  `${JSON.stringify({ ...current, courtTicketNumbers: frozen }, null, 2)}
@@ -7739,7 +7965,7 @@ async function relocateAdmittedRunToTicket(admitted, authority, heldLease) {
7739
7965
  runId: admitted.runId,
7740
7966
  role: admitted.role
7741
7967
  });
7742
- ensureRoleRunDirectory(ledgerHome, dirname9(target.runDirectory));
7968
+ ensureRoleRunDirectory(ledgerHome, dirname10(target.runDirectory));
7743
7969
  await rename(oldRunDirectory, target.runDirectory);
7744
7970
  heldLease?.relocate(target.runDirectory);
7745
7971
  const admittedRecord = admitted;
@@ -7777,9 +8003,9 @@ async function bindTicketNumberOnRunDirectory(runDirectory, ticketNumber) {
7777
8003
  ticketNumber,
7778
8004
  "bindTicketNumberOnRunDirectory"
7779
8005
  );
7780
- const admittedPath = join15(runDirectory, "admitted-request.json");
7781
- const invocationPath = join15(runDirectory, "invocation.json");
7782
- const admitted = JSON.parse(await readFile11(admittedPath, "utf8"));
8006
+ const admittedPath = join16(runDirectory, "admitted-request.json");
8007
+ const invocationPath = join16(runDirectory, "invocation.json");
8008
+ const admitted = JSON.parse(await readFile12(admittedPath, "utf8"));
7783
8009
  const existing = admitted.ticketNumber;
7784
8010
  if (typeof existing === "number") {
7785
8011
  if (existing === ticketNumber) return;
@@ -7789,7 +8015,7 @@ async function bindTicketNumberOnRunDirectory(runDirectory, ticketNumber) {
7789
8015
  }
7790
8016
  if (existsSync5(invocationPath)) {
7791
8017
  const invocation = JSON.parse(
7792
- await readFile11(invocationPath, "utf8")
8018
+ await readFile12(invocationPath, "utf8")
7793
8019
  );
7794
8020
  if (typeof invocation.ticketNumber === "number" && invocation.ticketNumber !== ticketNumber) {
7795
8021
  throw new Error(
@@ -7814,7 +8040,7 @@ async function recordLaunchedPiIdentity(runDirectory, identity) {
7814
8040
  async function observeLaunchedRolePackageIdentity(packageRoot, selectedRoleEntry) {
7815
8041
  const rolePackageRoot = packageRoot;
7816
8042
  const raw = JSON.parse(
7817
- await readFile11(join15(rolePackageRoot, "package.json"), "utf8")
8043
+ await readFile12(join16(rolePackageRoot, "package.json"), "utf8")
7818
8044
  );
7819
8045
  if (typeof raw.version !== "string" || raw.version.trim() === "") {
7820
8046
  throw new Error(
@@ -8099,7 +8325,7 @@ async function readRegularFileAttachment(sourcePath) {
8099
8325
  );
8100
8326
  }
8101
8327
  try {
8102
- return { absolute, bytes: await readFile11(absolute) };
8328
+ return { absolute, bytes: await readFile12(absolute) };
8103
8329
  } catch (error) {
8104
8330
  throw new CliUsageError(
8105
8331
  `attachment is not a readable regular file: ${sourcePath}`,
@@ -8112,13 +8338,13 @@ async function removePreparedAttachmentDirectory(stagingDirectory) {
8112
8338
  }
8113
8339
  async function withPreparedAttachments(attachmentPaths, use) {
8114
8340
  if (attachmentPaths.length === 0) return await use([]);
8115
- const stagingDirectory = await mkdtemp2(join15(tmpdir2(), "ak-role-attachments-"));
8341
+ const stagingDirectory = await mkdtemp2(join16(tmpdir2(), "ak-role-attachments-"));
8116
8342
  const prepared = [];
8117
8343
  let result;
8118
8344
  try {
8119
8345
  for (let index = 0; index < attachmentPaths.length; index += 1) {
8120
8346
  const { absolute, bytes } = await readRegularFileAttachment(attachmentPaths[index]);
8121
- const snapshotPath = join15(stagingDirectory, String(index).padStart(6, "0"));
8347
+ const snapshotPath = join16(stagingDirectory, String(index).padStart(6, "0"));
8122
8348
  await writeFile5(snapshotPath, bytes);
8123
8349
  prepared.push({ absolute, snapshotPath });
8124
8350
  }
@@ -8139,9 +8365,9 @@ async function withPreparedAttachments(attachmentPaths, use) {
8139
8365
  return result;
8140
8366
  }
8141
8367
  async function freezeAttachmentBytes(provenancePath, bytes, destinationDir, index) {
8142
- const frozenPath = join15(
8368
+ const frozenPath = join16(
8143
8369
  destinationDir,
8144
- `${String(index).padStart(2, "0")}-${basename6(provenancePath)}`
8370
+ `${String(index).padStart(2, "0")}-${basename7(provenancePath)}`
8145
8371
  );
8146
8372
  await writeFile5(frozenPath, bytes);
8147
8373
  return {
@@ -8155,7 +8381,7 @@ async function freezeAttachmentBytes(provenancePath, bytes, destinationDir, inde
8155
8381
  async function freezePreparedAttachment(prepared, destinationDir, index) {
8156
8382
  return freezeAttachmentBytes(
8157
8383
  prepared.absolute,
8158
- await readFile11(prepared.snapshotPath),
8384
+ await readFile12(prepared.snapshotPath),
8159
8385
  destinationDir,
8160
8386
  index
8161
8387
  );
@@ -8182,14 +8408,14 @@ async function freezeAttachments(attachmentPaths, attachmentsDirectory) {
8182
8408
  async function freezeAttachmentsIntoRun(attachmentPaths, runDirectory, summonsKey = `s-${Date.now().toString(36)}`) {
8183
8409
  if (attachmentPaths.length === 0) return [];
8184
8410
  const ledgerHome = resolveActivationLedgerHome(homeFromRunDirectory(runDirectory));
8185
- const attachmentsDirectory = join15(runDirectory, "attachments", summonsKey);
8411
+ const attachmentsDirectory = join16(runDirectory, "attachments", summonsKey);
8186
8412
  ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
8187
8413
  return freezeAttachments(attachmentPaths, attachmentsDirectory);
8188
8414
  }
8189
8415
  async function freezePreparedAttachmentsIntoRun(prepared, runDirectory, summonsKey) {
8190
8416
  if (prepared.length === 0) return [];
8191
8417
  const ledgerHome = resolveActivationLedgerHome(homeFromRunDirectory(runDirectory));
8192
- const attachmentsDirectory = summonsKey === void 0 ? join15(runDirectory, "attachments") : join15(runDirectory, "attachments", summonsKey);
8418
+ const attachmentsDirectory = summonsKey === void 0 ? join16(runDirectory, "attachments") : join16(runDirectory, "attachments", summonsKey);
8193
8419
  ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
8194
8420
  const attachments = [];
8195
8421
  for (let index = 0; index < prepared.length; index += 1) {
@@ -8251,7 +8477,7 @@ async function admitStandardMaterialInvocation(role, options) {
8251
8477
  })),
8252
8478
  ...ticketFields
8253
8479
  };
8254
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
8480
+ const admittedRequestPath = join16(runDirectory, "admitted-request.json");
8255
8481
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
8256
8482
  sessionDirectory,
8257
8483
  sessionFile
@@ -8360,7 +8586,7 @@ async function admitCountersignInvocation(options) {
8360
8586
  mediaKind: a.mediaKind
8361
8587
  }))
8362
8588
  };
8363
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
8589
+ const admittedRequestPath = join16(runDirectory, "admitted-request.json");
8364
8590
  if (options.deferPersistence !== true) {
8365
8591
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
8366
8592
  sessionDirectory,
@@ -8411,7 +8637,7 @@ function buildCountersignTransportPrompt(admitted, engineMaterial) {
8411
8637
  async function loadAdmittedJudgeRequest(runDirectory) {
8412
8638
  try {
8413
8639
  const raw = JSON.parse(
8414
- await readFile11(join15(runDirectory, "admitted-request.json"), "utf8")
8640
+ await readFile12(join16(runDirectory, "admitted-request.json"), "utf8")
8415
8641
  );
8416
8642
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return void 0;
8417
8643
  const record4 = raw;
@@ -8466,7 +8692,7 @@ async function admitCoderInvocation(options) {
8466
8692
  home: options.home
8467
8693
  });
8468
8694
  const attachments = await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
8469
- const taskPath = join15(runDirectory, "task.md");
8695
+ const taskPath = join16(runDirectory, "task.md");
8470
8696
  await writeFile5(taskPath, instruction, "utf8");
8471
8697
  const admitted = {
8472
8698
  role: "coder",
@@ -8487,7 +8713,7 @@ async function admitCoderInvocation(options) {
8487
8713
  mediaKind: a.mediaKind
8488
8714
  }))
8489
8715
  };
8490
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
8716
+ const admittedRequestPath = join16(runDirectory, "admitted-request.json");
8491
8717
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
8492
8718
  sessionDirectory,
8493
8719
  sessionFile
@@ -8537,7 +8763,7 @@ async function admitFixerInvocation(options) {
8537
8763
  if (options.prerequisitesPath !== void 0) {
8538
8764
  const absolutePrereq = isAbsolute7(options.prerequisitesPath) ? options.prerequisitesPath : resolve9(options.prerequisitesPath);
8539
8765
  try {
8540
- prerequisitesSource = await readFile11(absolutePrereq, "utf8");
8766
+ prerequisitesSource = await readFile12(absolutePrereq, "utf8");
8541
8767
  } catch (error) {
8542
8768
  throw new CliUsageError(
8543
8769
  `fixer prerequisites path is unreadable: ${options.prerequisitesPath}`,
@@ -8573,7 +8799,7 @@ async function admitFixerInvocation(options) {
8573
8799
  const attachments = await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
8574
8800
  let prerequisitesPath;
8575
8801
  if (prerequisitesSource !== void 0) {
8576
- prerequisitesPath = join15(runDirectory, "prerequisites.json");
8802
+ prerequisitesPath = join16(runDirectory, "prerequisites.json");
8577
8803
  await writeFile5(
8578
8804
  prerequisitesPath,
8579
8805
  `${JSON.stringify(prerequisites, null, 2)}
@@ -8581,7 +8807,7 @@ async function admitFixerInvocation(options) {
8581
8807
  "utf8"
8582
8808
  );
8583
8809
  }
8584
- const packetPath = join15(runDirectory, "fix-packet.md");
8810
+ const packetPath = join16(runDirectory, "fix-packet.md");
8585
8811
  await writeFile5(packetPath, instruction, "utf8");
8586
8812
  const admitted = {
8587
8813
  role: "fixer",
@@ -8607,7 +8833,7 @@ async function admitFixerInvocation(options) {
8607
8833
  mediaKind: a.mediaKind
8608
8834
  }))
8609
8835
  };
8610
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
8836
+ const admittedRequestPath = join16(runDirectory, "admitted-request.json");
8611
8837
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
8612
8838
  sessionDirectory,
8613
8839
  sessionFile
@@ -8827,7 +9053,7 @@ async function admitCollectorInvocation(options) {
8827
9053
  const prNumber = target.kind === "bound" ? target.prNumber : void 0;
8828
9054
  let requestManifestPath;
8829
9055
  if (manifestCanonicalJson !== void 0) {
8830
- requestManifestPath = join15(runDirectory, "request-manifest.json");
9056
+ requestManifestPath = join16(runDirectory, "request-manifest.json");
8831
9057
  await writeFile5(requestManifestPath, manifestCanonicalJson, "utf8");
8832
9058
  }
8833
9059
  const admitted = {
@@ -8853,7 +9079,7 @@ async function admitCollectorInvocation(options) {
8853
9079
  mediaKind: a.mediaKind
8854
9080
  }))
8855
9081
  };
8856
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
9082
+ const admittedRequestPath = join16(runDirectory, "admitted-request.json");
8857
9083
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
8858
9084
  sessionDirectory,
8859
9085
  sessionFile
@@ -8951,7 +9177,7 @@ function parseDoctorArgv(args) {
8951
9177
  }
8952
9178
  async function resolveDoctorCaseRunsPath(options) {
8953
9179
  const ledgerHome = resolveActivationLedgerHome(options.home);
8954
- const defaultRuns = join15(
9180
+ const defaultRuns = join16(
8955
9181
  activationBookDirectory(ledgerHome, options.bookKey),
8956
9182
  String(options.issueNumber),
8957
9183
  "runs"
@@ -9082,7 +9308,7 @@ async function admitDoctorInvocation(options) {
9082
9308
  mediaKind: a.mediaKind
9083
9309
  }))
9084
9310
  };
9085
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
9311
+ const admittedRequestPath = join16(runDirectory, "admitted-request.json");
9086
9312
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
9087
9313
  sessionDirectory,
9088
9314
  sessionFile
@@ -9214,7 +9440,7 @@ async function admitNotaryInvocation(options) {
9214
9440
  ...ticketFields,
9215
9441
  ...options.correlationId === void 0 ? {} : { correlationId: options.correlationId }
9216
9442
  };
9217
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
9443
+ const admittedRequestPath = join16(runDirectory, "admitted-request.json");
9218
9444
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
9219
9445
  sessionDirectory,
9220
9446
  sessionFile
@@ -9317,7 +9543,7 @@ async function admitGleanerLeftInvocation(options) {
9317
9543
  attachments: [],
9318
9544
  ...options.correlationId === void 0 ? {} : { correlationId: options.correlationId }
9319
9545
  };
9320
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
9546
+ const admittedRequestPath = join16(runDirectory, "admitted-request.json");
9321
9547
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
9322
9548
  sessionDirectory,
9323
9549
  sessionFile
@@ -9456,7 +9682,7 @@ async function admitReviewerInvocation(options) {
9456
9682
  mediaKind: a.mediaKind
9457
9683
  }))
9458
9684
  };
9459
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
9685
+ const admittedRequestPath = join16(runDirectory, "admitted-request.json");
9460
9686
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
9461
9687
  sessionDirectory,
9462
9688
  sessionFile
@@ -9608,7 +9834,7 @@ async function admitMergerInvocation(options) {
9608
9834
  resolutionScope: [...derived.resolutionScope],
9609
9835
  authorizedChecks: []
9610
9836
  });
9611
- const mergerInputPath = join15(runDirectory, "merger-input.json");
9837
+ const mergerInputPath = join16(runDirectory, "merger-input.json");
9612
9838
  await writeFile5(
9613
9839
  mergerInputPath,
9614
9840
  `${JSON.stringify(mergerInput, null, 2)}
@@ -9639,7 +9865,7 @@ async function admitMergerInvocation(options) {
9639
9865
  mediaKind: a.mediaKind
9640
9866
  }))
9641
9867
  };
9642
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
9868
+ const admittedRequestPath = join16(runDirectory, "admitted-request.json");
9643
9869
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
9644
9870
  sessionDirectory,
9645
9871
  sessionFile
@@ -9923,15 +10149,15 @@ var init_invocation = __esm({
9923
10149
 
9924
10150
  // src/public-cli/load-production-acp-host.ts
9925
10151
  import { existsSync as existsSync6 } from "node:fs";
9926
- import { join as join16 } from "node:path";
10152
+ import { join as join17 } from "node:path";
9927
10153
  import { pathToFileURL } from "node:url";
9928
10154
  async function loadProductionAcpHostFactory(packageRoot, host) {
9929
10155
  const description = lookupHostDescription(host);
9930
10156
  if (description === void 0) {
9931
10157
  throw new Error(`unregistered host: ${host}`);
9932
10158
  }
9933
- const built = join16(packageRoot, "dist/acp-host/production-host.js");
9934
- const source = join16(packageRoot, "src/acp-host/production-host.ts");
10159
+ const built = join17(packageRoot, "dist/acp-host/production-host.js");
10160
+ const source = join17(packageRoot, "src/acp-host/production-host.ts");
9935
10161
  const target = existsSync6(built) ? built : source;
9936
10162
  const href = pathToFileURL(target).href;
9937
10163
  const mod = await import(href);
@@ -9947,15 +10173,15 @@ var init_load_production_acp_host = __esm({
9947
10173
 
9948
10174
  // src/public-cli/load-production-headless-host.ts
9949
10175
  import { existsSync as existsSync7 } from "node:fs";
9950
- import { join as join17 } from "node:path";
10176
+ import { join as join18 } from "node:path";
9951
10177
  import { pathToFileURL as pathToFileURL2 } from "node:url";
9952
10178
  async function loadProductionHeadlessHostFactory(packageRoot, host) {
9953
10179
  const description = lookupHeadlessHostDescription(host);
9954
10180
  if (description === void 0) {
9955
10181
  throw new Error(`unregistered headless host: ${host}`);
9956
10182
  }
9957
- const built = join17(packageRoot, "dist/headless-host/production-host.js");
9958
- const source = join17(packageRoot, "src/headless-host/production-host.ts");
10183
+ const built = join18(packageRoot, "dist/headless-host/production-host.js");
10184
+ const source = join18(packageRoot, "src/headless-host/production-host.ts");
9959
10185
  const target = existsSync7(built) ? built : source;
9960
10186
  const href = pathToFileURL2(target).href;
9961
10187
  const mod = await import(href);
@@ -10204,8 +10430,8 @@ __export(config_exports, {
10204
10430
  setPersistentSeatHost: () => setPersistentSeatHost,
10205
10431
  validatePublicCliConfigAxes: () => validatePublicCliConfigAxes
10206
10432
  });
10207
- import { mkdir, readFile as readFile12, writeFile as writeFile6 } from "node:fs/promises";
10208
- import { dirname as dirname10, join as join18 } from "node:path";
10433
+ import { mkdir, readFile as readFile13, writeFile as writeFile6 } from "node:fs/promises";
10434
+ import { dirname as dirname11, join as join19 } from "node:path";
10209
10435
  function isGateOfficerSeat(value) {
10210
10436
  return GATE_OFFICER_SEATS.includes(value);
10211
10437
  }
@@ -10213,12 +10439,12 @@ function publicCliConfigPath(home) {
10213
10439
  if (typeof home !== "string" || home.trim() === "") {
10214
10440
  throw new Error("home must be explicitly provided");
10215
10441
  }
10216
- return join18(home, ".ak-roles", "public-cli.json");
10442
+ return join19(home, ".ak-roles", "public-cli.json");
10217
10443
  }
10218
10444
  async function loadPublicCliConfig(home) {
10219
10445
  const path = publicCliConfigPath(home);
10220
10446
  try {
10221
- const raw = await readFile12(path, "utf8");
10447
+ const raw = await readFile13(path, "utf8");
10222
10448
  return parsePublicCliConfig(JSON.parse(raw));
10223
10449
  } catch (error) {
10224
10450
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -10229,7 +10455,7 @@ async function loadPublicCliConfig(home) {
10229
10455
  }
10230
10456
  async function savePublicCliConfig(config, home) {
10231
10457
  const path = publicCliConfigPath(home);
10232
- await mkdir(dirname10(path), { recursive: true });
10458
+ await mkdir(dirname11(path), { recursive: true });
10233
10459
  const normalized = parsePublicCliConfig(config);
10234
10460
  await writeFile6(
10235
10461
  path,
@@ -10676,7 +10902,7 @@ function credentialProvidersFromAuthData(data) {
10676
10902
  }
10677
10903
  async function loadCredentialProviders(agentDir) {
10678
10904
  try {
10679
- const raw = await readFile12(join18(agentDir, "auth.json"), "utf8");
10905
+ const raw = await readFile13(join19(agentDir, "auth.json"), "utf8");
10680
10906
  return credentialProvidersFromAuthData(JSON.parse(raw));
10681
10907
  } catch (error) {
10682
10908
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -10715,15 +10941,15 @@ __export(host_providers_exports, {
10715
10941
  renderHostProvidersTable: () => renderHostProvidersTable
10716
10942
  });
10717
10943
  import { readFileSync as readFileSync2 } from "node:fs";
10718
- import { join as join19 } from "node:path";
10944
+ import { join as join20 } from "node:path";
10719
10945
  function hostProvidersPath(home) {
10720
10946
  if (typeof home !== "string" || home.trim() === "") {
10721
10947
  throw new Error("home must be explicitly provided");
10722
10948
  }
10723
- return join19(home, ".ak-roles", "host-providers.json");
10949
+ return join20(home, ".ak-roles", "host-providers.json");
10724
10950
  }
10725
10951
  function hermesProviderModelsCachePath(home) {
10726
- return join19(home, ".hermes", "provider_models_cache.json");
10952
+ return join20(home, ".hermes", "provider_models_cache.json");
10727
10953
  }
10728
10954
  function parseHostProvidersTable(value) {
10729
10955
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -10878,12 +11104,12 @@ var init_host_providers = __esm({
10878
11104
  });
10879
11105
 
10880
11106
  // src/ledger-session-read.ts
10881
- import { readFile as readFile13 } from "node:fs/promises";
10882
- function isRecord5(value) {
11107
+ import { readFile as readFile14 } from "node:fs/promises";
11108
+ function isRecord6(value) {
10883
11109
  return typeof value === "object" && value !== null && !Array.isArray(value);
10884
11110
  }
10885
11111
  async function readLedgerSessionJsonlLines(path) {
10886
- const text = await readFile13(path, "utf8");
11112
+ const text = await readFile14(path, "utf8");
10887
11113
  const lines = text.split("\n");
10888
11114
  const out = [];
10889
11115
  for (let index = 0; index < lines.length; index += 1) {
@@ -10904,7 +11130,7 @@ async function readLedgerSessionJsonlLines(path) {
10904
11130
  });
10905
11131
  continue;
10906
11132
  }
10907
- if (!isRecord5(row)) {
11133
+ if (!isRecord6(row)) {
10908
11134
  const kind = row === null ? "null" : Array.isArray(row) ? "array" : typeof row;
10909
11135
  out.push({
10910
11136
  line: lineNumber,
@@ -10981,9 +11207,9 @@ var init_ledger_session_read = __esm({
10981
11207
  });
10982
11208
 
10983
11209
  // src/analyst-gate-cycles-read.ts
10984
- import { readdir as readdir5 } from "node:fs/promises";
10985
- import { join as join20 } from "node:path";
10986
- function isRecord6(value) {
11210
+ import { readdir as readdir6 } from "node:fs/promises";
11211
+ import { join as join21 } from "node:path";
11212
+ function isRecord7(value) {
10987
11213
  return typeof value === "object" && value !== null && !Array.isArray(value);
10988
11214
  }
10989
11215
  function isParentAttemptBindingRow(row) {
@@ -11013,7 +11239,7 @@ function isGateTerminatingToolName(toolName) {
11013
11239
  function acceptedGateReceiptIds(rows) {
11014
11240
  const accepted = /* @__PURE__ */ new Set();
11015
11241
  for (const row of rows) {
11016
- const message = isRecord6(row.message) ? row.message : void 0;
11242
+ const message = isRecord7(row.message) ? row.message : void 0;
11017
11243
  if (message?.role !== "toolResult") continue;
11018
11244
  if (typeof message.toolCallId !== "string" || message.toolCallId.length === 0) continue;
11019
11245
  if (message.isError === false) accepted.add(message.toolCallId);
@@ -11048,7 +11274,7 @@ function nearestAttemptBindingBefore(rows, beforeIndex) {
11048
11274
  for (let i = beforeIndex - 1; i >= 0; i -= 1) {
11049
11275
  const row = rows[i];
11050
11276
  if (!isParentAttemptBindingRow(row)) continue;
11051
- if (!isRecord6(row.data) || !isRecord6(row.data.parent)) continue;
11277
+ if (!isRecord7(row.data) || !isRecord7(row.data.parent)) continue;
11052
11278
  const id = row.data.parent.attemptEntryId;
11053
11279
  const sessionFile = row.data.parent.sessionFile;
11054
11280
  return {
@@ -11063,10 +11289,10 @@ function extractAllAcceptedGateToolCalls(rows) {
11063
11289
  const out = [];
11064
11290
  for (let rowIndex = 0; rowIndex < rows.length; rowIndex += 1) {
11065
11291
  const row = rows[rowIndex];
11066
- const message = isRecord6(row.message) ? row.message : void 0;
11292
+ const message = isRecord7(row.message) ? row.message : void 0;
11067
11293
  if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
11068
11294
  for (const part of message.content) {
11069
- if (!isRecord6(part) || part.type !== "toolCall") continue;
11295
+ if (!isRecord7(part) || part.type !== "toolCall") continue;
11070
11296
  if (typeof part.id !== "string" || part.id.length === 0) continue;
11071
11297
  if (typeof part.name !== "string" || part.name.length === 0) continue;
11072
11298
  if (!isGateTerminatingToolName(part.name)) continue;
@@ -11074,7 +11300,7 @@ function extractAllAcceptedGateToolCalls(rows) {
11074
11300
  const binding = nearestAttemptBindingBefore(rows, rowIndex);
11075
11301
  out.push({
11076
11302
  toolName: part.name,
11077
- args: isRecord6(part.arguments) ? part.arguments : void 0,
11303
+ args: isRecord7(part.arguments) ? part.arguments : void 0,
11078
11304
  accepted: true,
11079
11305
  rowIndex,
11080
11306
  ...binding
@@ -11197,17 +11423,17 @@ function pairGateRounds(volumes) {
11197
11423
  return rounds.sort((a, b) => a.officerStartedAt.localeCompare(b.officerStartedAt)).map((round, index) => ({ ...round, roundIndex: index + 1 }));
11198
11424
  }
11199
11425
  async function resolveOfficerSessionFromPointerFile(pointerPath) {
11200
- const { readFile: readFile23 } = await import("node:fs/promises");
11426
+ const { readFile: readFile24 } = await import("node:fs/promises");
11201
11427
  let raw;
11202
11428
  try {
11203
- raw = JSON.parse(await readFile23(pointerPath, "utf8"));
11429
+ raw = JSON.parse(await readFile24(pointerPath, "utf8"));
11204
11430
  } catch (error) {
11205
11431
  throw new Error(
11206
11432
  `direct officer run pointer unreadable in ${pointerPath}: ${error instanceof Error ? error.message : String(error)}`,
11207
11433
  { cause: error }
11208
11434
  );
11209
11435
  }
11210
- if (!isRecord6(raw) || raw.kind !== "direct-officer-run-pointer" || raw.version !== 1) {
11436
+ if (!isRecord7(raw) || raw.kind !== "direct-officer-run-pointer" || raw.version !== 1) {
11211
11437
  throw new Error(`direct officer run pointer has unknown shape in ${pointerPath}`);
11212
11438
  }
11213
11439
  const sessionFile = raw.sessionFile;
@@ -11223,7 +11449,7 @@ async function readAnalystGateCyclesFromAuditorRoles(auditorRolesDirectory, opti
11223
11449
  for (const directory of directories) {
11224
11450
  let names;
11225
11451
  try {
11226
- const entries = await readdir5(directory, { withFileTypes: true });
11452
+ const entries = await readdir6(directory, { withFileTypes: true });
11227
11453
  names = entries.filter(
11228
11454
  (e) => e.isFile() && (e.name.endsWith(".jsonl") || e.name.endsWith(".pointer.json"))
11229
11455
  ).map((e) => e.name).sort();
@@ -11232,7 +11458,7 @@ async function readAnalystGateCyclesFromAuditorRoles(auditorRolesDirectory, opti
11232
11458
  throw error;
11233
11459
  }
11234
11460
  for (const name of names) {
11235
- const path = join20(directory, name);
11461
+ const path = join21(directory, name);
11236
11462
  const fromPointer = name.endsWith(".pointer.json");
11237
11463
  const sessionPath = fromPointer ? await resolveOfficerSessionFromPointerFile(path) : path;
11238
11464
  if (sessionPath === void 0) continue;
@@ -11274,6 +11500,15 @@ var init_analyst_gate_cycles_read = __esm({
11274
11500
  });
11275
11501
 
11276
11502
  // src/audit-escalation.ts
11503
+ var audit_escalation_exports = {};
11504
+ __export(audit_escalation_exports, {
11505
+ AUDIT_ESCALATION_KIND: () => AUDIT_ESCALATION_KIND,
11506
+ buildAuditEscalationResult: () => buildAuditEscalationResult,
11507
+ disposeComplianceDecision: () => disposeComplianceDecision,
11508
+ isAuditEscalationProjection: () => isAuditEscalationProjection,
11509
+ isAuditEscalationResult: () => isAuditEscalationResult,
11510
+ projectAuditEscalation: () => projectAuditEscalation
11511
+ });
11277
11512
  function buildAuditEscalationResult(decision, deliveredOutput) {
11278
11513
  const auditOwned = {
11279
11514
  kind: AUDIT_ESCALATION_KIND
@@ -11370,21 +11605,6 @@ var init_audit_escalation = __esm({
11370
11605
  }
11371
11606
  });
11372
11607
 
11373
- // src/run-terminal-artifacts.ts
11374
- import { basename as basename7, dirname as dirname11, join as join21 } from "node:path";
11375
- function runIdFromRunDirectory(runDirectory) {
11376
- const name = basename7(runDirectory);
11377
- const at = name.lastIndexOf("@");
11378
- if (at <= 0 || at === name.length - 1) return void 0;
11379
- return name.slice(0, at);
11380
- }
11381
- var init_run_terminal_artifacts = __esm({
11382
- "src/run-terminal-artifacts.ts"() {
11383
- "use strict";
11384
- init_role_run_placement();
11385
- }
11386
- });
11387
-
11388
11608
  // src/submission-ledger.ts
11389
11609
  import { join as join22 } from "node:path";
11390
11610
  function runIdentity(context) {
@@ -11808,7 +12028,7 @@ var init_submission_ledger = __esm({
11808
12028
 
11809
12029
  // src/session-opening-materials.ts
11810
12030
  import { existsSync as existsSync8 } from "node:fs";
11811
- import { readFile as readFile14 } from "node:fs/promises";
12031
+ import { readFile as readFile15 } from "node:fs/promises";
11812
12032
  import { dirname as dirname12, join as join23 } from "node:path";
11813
12033
  import { fileURLToPath, pathToFileURL as pathToFileURL3 } from "node:url";
11814
12034
  function resolvePackageRootDir(moduleUrl = import.meta.url) {
@@ -11824,7 +12044,7 @@ function resolvePackageRootDir(moduleUrl = import.meta.url) {
11824
12044
  return fileURLToPath(new URL("..", moduleUrl));
11825
12045
  }
11826
12046
  async function readPackageMaterial(relativePath) {
11827
- return readFile14(fileURLToPath(new URL(relativePath, packageRootUrl)), "utf8");
12047
+ return readFile15(fileURLToPath(new URL(relativePath, packageRootUrl)), "utf8");
11828
12048
  }
11829
12049
  async function joinPackageMaterials(relativePaths) {
11830
12050
  const chunks = [];
@@ -12018,12 +12238,12 @@ function createSystemCollectorClock() {
12018
12238
  return {
12019
12239
  wallNow: () => /* @__PURE__ */ new Date(),
12020
12240
  monoNow: () => Number(process.hrtime.bigint() - start) / 1e6,
12021
- sleep: (ms, signal) => new Promise((resolve22, reject) => {
12241
+ sleep: (ms, signal) => new Promise((resolve21, reject) => {
12022
12242
  if (signal?.aborted) {
12023
12243
  reject(signal.reason ?? new Error("aborted"));
12024
12244
  return;
12025
12245
  }
12026
- const timer = setTimeout(resolve22, ms);
12246
+ const timer = setTimeout(resolve21, ms);
12027
12247
  const onAbort = () => {
12028
12248
  clearTimeout(timer);
12029
12249
  reject(signal?.reason ?? new Error("aborted"));
@@ -13225,11 +13445,11 @@ function reportEngineDetourCall(input) {
13225
13445
  recordPointer: pointer
13226
13446
  };
13227
13447
  }
13228
- function isRecord7(value) {
13448
+ function isRecord8(value) {
13229
13449
  return typeof value === "object" && value !== null && !Array.isArray(value);
13230
13450
  }
13231
13451
  function callFactFromSitianPayload(payload, pointer) {
13232
- if (!isRecord7(payload)) return void 0;
13452
+ if (!isRecord8(payload)) return void 0;
13233
13453
  if (payload.tool !== ENGINE_DETOUR_TOOL_NAME) return void 0;
13234
13454
  if (typeof payload.toolCallId !== "string" || payload.toolCallId.length === 0) {
13235
13455
  return void 0;
@@ -13246,11 +13466,11 @@ function callFactFromSitianPayload(payload, pointer) {
13246
13466
  };
13247
13467
  }
13248
13468
  function invocationScopeIdOfRecord(record4) {
13249
- if (isRecord7(record4.subject)) {
13469
+ if (isRecord8(record4.subject)) {
13250
13470
  const fromSubject = record4.subject.invocationScopeId;
13251
13471
  if (typeof fromSubject === "string" && fromSubject.length > 0) return fromSubject;
13252
13472
  }
13253
- if (isRecord7(record4.payload)) {
13473
+ if (isRecord8(record4.payload)) {
13254
13474
  const fromPayload = record4.payload.invocationScopeId;
13255
13475
  if (typeof fromPayload === "string" && fromPayload.length > 0) return fromPayload;
13256
13476
  }
@@ -13310,7 +13530,7 @@ function readInvocationRecord(runDirectory) {
13310
13530
  const raw = JSON.parse(
13311
13531
  readFileSync3(join24(runDirectory, "invocation.json"), "utf8")
13312
13532
  );
13313
- return isRecord7(raw) ? raw : void 0;
13533
+ return isRecord8(raw) ? raw : void 0;
13314
13534
  } catch (error) {
13315
13535
  if (error?.code === "ENOENT") return void 0;
13316
13536
  throw error;
@@ -13328,7 +13548,7 @@ function readInvocationSelectedHost(runDirectory) {
13328
13548
  }
13329
13549
  function withEngineDetourToolUsageFact(outcome, usage) {
13330
13550
  if (usage === void 0) return outcome;
13331
- const prior = isRecord7(outcome.decisiveFacts) ? outcome.decisiveFacts : {};
13551
+ const prior = isRecord8(outcome.decisiveFacts) ? outcome.decisiveFacts : {};
13332
13552
  return {
13333
13553
  ...outcome,
13334
13554
  decisiveFacts: {
@@ -13398,13 +13618,13 @@ function resolveAuditDossier(source) {
13398
13618
  }
13399
13619
  return { status: "ok", runDirectory };
13400
13620
  }
13401
- function isRecord8(value) {
13621
+ function isRecord9(value) {
13402
13622
  return typeof value === "object" && value !== null && !Array.isArray(value);
13403
13623
  }
13404
13624
  function readDoctorAuditSubjects(context) {
13405
13625
  const entries = context.sessionManager.getEntries?.() ?? [];
13406
13626
  for (const entry of entries) {
13407
- if (isRecord8(entry) && entry.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
13627
+ if (isRecord9(entry) && entry.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
13408
13628
  return { status: "ok" };
13409
13629
  }
13410
13630
  }
@@ -13438,7 +13658,7 @@ var init_dossier_resolution = __esm({
13438
13658
 
13439
13659
  // src/package-resources/method-skill.ts
13440
13660
  import { createHash as createHash6 } from "node:crypto";
13441
- import { readFile as readFile15, realpath as realpath6 } from "node:fs/promises";
13661
+ import { readFile as readFile16, realpath as realpath6 } from "node:fs/promises";
13442
13662
  import { join as join25 } from "node:path";
13443
13663
  function gitBlobOid(bytes) {
13444
13664
  const body = typeof bytes === "string" ? Buffer.from(bytes, "utf8") : Buffer.from(bytes);
@@ -13461,11 +13681,11 @@ function resolvePackagedMethodSkillRoot(packageRoot, name) {
13461
13681
  function resolvePackagedMethodSkillPath(packageRoot, name) {
13462
13682
  return join25(resolvePackagedMethodSkillRoot(packageRoot, name), "SKILL.md");
13463
13683
  }
13464
- function isRecord9(value) {
13684
+ function isRecord10(value) {
13465
13685
  return typeof value === "object" && value !== null && !Array.isArray(value);
13466
13686
  }
13467
13687
  function parseProvenance(raw, expectedName) {
13468
- if (!isRecord9(raw)) {
13688
+ if (!isRecord10(raw)) {
13469
13689
  throw new Error(`Packaged method provenance must be an object for ${expectedName}`);
13470
13690
  }
13471
13691
  if (raw.name !== expectedName) {
@@ -13479,7 +13699,7 @@ function parseProvenance(raw, expectedName) {
13479
13699
  if (typeof raw.packageAdaptation !== "string" || raw.packageAdaptation.trim() === "") {
13480
13700
  throw new Error(`Packaged method provenance packageAdaptation must be nonblank`);
13481
13701
  }
13482
- if (!isRecord9(raw.upstream)) {
13702
+ if (!isRecord10(raw.upstream)) {
13483
13703
  throw new Error(`Packaged method provenance upstream must be an object`);
13484
13704
  }
13485
13705
  const upstream = raw.upstream;
@@ -13506,12 +13726,12 @@ function parseProvenance(raw, expectedName) {
13506
13726
  `Packaged method provenance upstream must include nonblank tag or version`
13507
13727
  );
13508
13728
  }
13509
- if (!isRecord9(raw.files)) {
13729
+ if (!isRecord10(raw.files)) {
13510
13730
  throw new Error(`Packaged method provenance files must be an object`);
13511
13731
  }
13512
13732
  const files = {};
13513
13733
  for (const [rel, entry] of Object.entries(raw.files)) {
13514
- if (!isRecord9(entry)) {
13734
+ if (!isRecord10(entry)) {
13515
13735
  throw new Error(`Packaged method provenance file entry must be an object: ${rel}`);
13516
13736
  }
13517
13737
  if (typeof entry.sha256 !== "string" || !SHA256_RE.test(entry.sha256)) {
@@ -13557,7 +13777,7 @@ async function loadPackagedMethodSkillMaterial(packageRoot, name) {
13557
13777
  const provenancePath = join25(rootDirectory, "provenance.json");
13558
13778
  let provenanceRaw;
13559
13779
  try {
13560
- provenanceRaw = await readFile15(provenancePath, "utf8");
13780
+ provenanceRaw = await readFile16(provenancePath, "utf8");
13561
13781
  } catch (error) {
13562
13782
  throw new PackagedMethodSkillUnavailableError(name, provenancePath, error);
13563
13783
  }
@@ -13574,7 +13794,7 @@ async function loadPackagedMethodSkillMaterial(packageRoot, name) {
13574
13794
  const absolute = join25(rootDirectory, rel);
13575
13795
  let bytes;
13576
13796
  try {
13577
- bytes = await readFile15(absolute);
13797
+ bytes = await readFile16(absolute);
13578
13798
  } catch (error) {
13579
13799
  throw new PackagedMethodSkillUnavailableError(name, absolute, error);
13580
13800
  }
@@ -13590,7 +13810,7 @@ async function loadPackagedMethodSkillMaterial(packageRoot, name) {
13590
13810
  let raw;
13591
13811
  try {
13592
13812
  skillPath = await realpath6(skillPathConfigured);
13593
- raw = await readFile15(skillPath, "utf8");
13813
+ raw = await readFile16(skillPath, "utf8");
13594
13814
  } catch (error) {
13595
13815
  throw new PackagedMethodSkillUnavailableError(name, skillPathConfigured, error);
13596
13816
  }
@@ -13882,11 +14102,11 @@ var init_navigator_invocation_identity = __esm({
13882
14102
  });
13883
14103
 
13884
14104
  // src/receipt-delivery-policy.ts
13885
- function isRecord10(value) {
14105
+ function isRecord11(value) {
13886
14106
  return typeof value === "object" && value !== null && !Array.isArray(value);
13887
14107
  }
13888
14108
  function parseNoReceiptLifecycleFacts(input) {
13889
- if (!isRecord10(input) || typeof input.terminalToolCalled !== "boolean" || input.deliveryTurns !== RECEIPT_DELIVERY_TURN_LIMIT || input.sessionCompletion !== "settled-without-accepted-receipt" || input.acceptedReceipt !== false || typeof input.runPointer !== "string" || input.runPointer.trim() === "" || typeof input.attemptPointer !== "string" || input.attemptPointer.trim() === "" || !Array.isArray(input.rejectedReceipts) || !input.rejectedReceipts.every((item) => isRecord10(item) && typeof item.reason === "string")) {
14109
+ if (!isRecord11(input) || typeof input.terminalToolCalled !== "boolean" || input.deliveryTurns !== RECEIPT_DELIVERY_TURN_LIMIT || input.sessionCompletion !== "settled-without-accepted-receipt" || input.acceptedReceipt !== false || typeof input.runPointer !== "string" || input.runPointer.trim() === "" || typeof input.attemptPointer !== "string" || input.attemptPointer.trim() === "" || !Array.isArray(input.rejectedReceipts) || !input.rejectedReceipts.every((item) => isRecord11(item) && typeof item.reason === "string")) {
13890
14110
  throw new TypeError("malformed no-receipt lifecycle facts");
13891
14111
  }
13892
14112
  return {
@@ -14145,7 +14365,7 @@ __export(settlement_exports, {
14145
14365
  withSubmissions: () => withSubmissions
14146
14366
  });
14147
14367
  import { randomUUID as randomUUID4 } from "node:crypto";
14148
- import { appendFile as appendFile2, readFile as readFile16, readdir as readdir6, writeFile as writeFile7 } from "node:fs/promises";
14368
+ import { appendFile as appendFile2, readFile as readFile17, readdir as readdir7, writeFile as writeFile7 } from "node:fs/promises";
14149
14369
  import { dirname as dirname14, join as join26 } from "node:path";
14150
14370
  function sealedLedgerHome(admitted) {
14151
14371
  return homeFromRunDirectory(admitted.runDirectory);
@@ -14289,10 +14509,10 @@ function presentControlledFailure(failure2, io) {
14289
14509
  }
14290
14510
  async function inspectJudgeSession(sessionFile) {
14291
14511
  try {
14292
- await readFile16(sessionFile, "utf8");
14512
+ await readFile17(sessionFile, "utf8");
14293
14513
  return { state: "present" };
14294
14514
  } catch (error) {
14295
- if (isMissingPathError3(error)) return { state: "missing" };
14515
+ if (isMissingPathError4(error)) return { state: "missing" };
14296
14516
  return {
14297
14517
  state: "unreadable",
14298
14518
  diagnostic: error instanceof Error ? error.message || error.name : String(error)
@@ -14492,7 +14712,7 @@ function explicitInternalKnownFailureClassificationInput(failure2) {
14492
14712
  ...failure2.details === void 0 ? {} : { knownDetails: failure2.details }
14493
14713
  };
14494
14714
  }
14495
- function isMissingPathError3(error) {
14715
+ function isMissingPathError4(error) {
14496
14716
  return error instanceof Error && "code" in error && error.code === "ENOENT";
14497
14717
  }
14498
14718
  function sessionReadFailure(error, fallbackMessage) {
@@ -14521,7 +14741,7 @@ function sessionReadFailure(error, fallbackMessage) {
14521
14741
  return failed;
14522
14742
  }
14523
14743
  async function readBoundSessionEntries(sessionFile) {
14524
- const text = await readFile16(sessionFile, "utf8");
14744
+ const text = await readFile17(sessionFile, "utf8");
14525
14745
  const entries = [];
14526
14746
  for (const line2 of text.trim().split("\n").filter(Boolean)) {
14527
14747
  try {
@@ -14587,7 +14807,7 @@ async function readSitianRetainedAuditorProviderStop(sessionFile) {
14587
14807
  const { records } = await readSitianRecords(recordFile);
14588
14808
  for (let i = records.length - 1; i >= 0; i -= 1) {
14589
14809
  const payload = records[i]?.payload;
14590
- if (!isRecord11(payload) || !isRecord11(payload.response)) continue;
14810
+ if (!isRecord12(payload) || !isRecord12(payload.response)) continue;
14591
14811
  if (typeof payload.type === "string") continue;
14592
14812
  const stop = sessionProviderStopFromAssistant(payload.response);
14593
14813
  if (stop !== void 0) return stop;
@@ -14612,7 +14832,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
14612
14832
  try {
14613
14833
  parentEntries = await readBoundSessionEntries(sessionFile);
14614
14834
  } catch (error) {
14615
- if (isMissingPathError3(error)) return void 0;
14835
+ if (isMissingPathError4(error)) return void 0;
14616
14836
  throw sessionReadFailure(error, "failed to read parent session for auditor binding");
14617
14837
  }
14618
14838
  const parentId = parentEntries.find((entry) => entry.type === "session")?.id;
@@ -14623,10 +14843,10 @@ async function loadBoundAuditorVolumes(sessionFile) {
14623
14843
  for (const childDirectory of childDirectories) {
14624
14844
  let names;
14625
14845
  try {
14626
- names = await readdir6(childDirectory);
14846
+ names = await readdir7(childDirectory);
14627
14847
  sawAnyDirectory = true;
14628
14848
  } catch (error) {
14629
- if (isMissingPathError3(error)) continue;
14849
+ if (isMissingPathError4(error)) continue;
14630
14850
  throw sessionReadFailure(error, "failed to read bound auditor session directory");
14631
14851
  }
14632
14852
  for (const file of names.filter((name) => name.endsWith(".jsonl")).sort().reverse()) {
@@ -14637,7 +14857,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
14637
14857
  throw sessionReadFailure(error, "failed to read discovered auditor session");
14638
14858
  }
14639
14859
  const header = entries.find((entry) => entry.type === "session");
14640
- if (!isRecord11(header)) continue;
14860
+ if (!isRecord12(header)) continue;
14641
14861
  const bindingIndexes = [];
14642
14862
  for (let i = 0; i < entries.length; i += 1) {
14643
14863
  const entry = entries[i];
@@ -14651,7 +14871,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
14651
14871
  end: idx + 1 < bindingIndexes.length ? bindingIndexes[idx + 1] : entries.length
14652
14872
  })) : [{ entry: void 0, start: 0, end: entries.length }];
14653
14873
  for (const { entry: bindingEntry, start, end } of bindingPasses) {
14654
- const bindingParent = bindingEntry !== void 0 && isRecord11(bindingEntry.data) && isRecord11(bindingEntry.data.parent) ? bindingEntry.data.parent : void 0;
14874
+ const bindingParent = bindingEntry !== void 0 && isRecord12(bindingEntry.data) && isRecord12(bindingEntry.data.parent) ? bindingEntry.data.parent : void 0;
14655
14875
  const attemptEntryId = typeof bindingParent?.attemptEntryId === "string" ? bindingParent.attemptEntryId : void 0;
14656
14876
  const boundSessionFile = typeof bindingParent?.sessionFile === "string" ? bindingParent.sessionFile : typeof header.parentSession === "string" ? header.parentSession : void 0;
14657
14877
  if (boundSessionFile !== sessionFile) continue;
@@ -14675,12 +14895,12 @@ function complianceFailureFromAuditorVolumes(volumes) {
14675
14895
  if (stop === void 0) continue;
14676
14896
  for (let i = entries.length - 1; i >= 0; i -= 1) {
14677
14897
  const entry = entries[i];
14678
- if (entry?.type !== "custom" || entry.customType !== AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE || !isRecord11(entry.data)) continue;
14679
- const parent = isRecord11(entry.data.parent) ? entry.data.parent : void 0;
14680
- const failure2 = isRecord11(entry.data.failure) ? entry.data.failure : void 0;
14898
+ if (entry?.type !== "custom" || entry.customType !== AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE || !isRecord12(entry.data)) continue;
14899
+ const parent = isRecord12(entry.data.parent) ? entry.data.parent : void 0;
14900
+ const failure2 = isRecord12(entry.data.failure) ? entry.data.failure : void 0;
14681
14901
  if (parent?.sessionId !== parentId || parent.sessionFile !== sessionFile || parent.attemptEntryId !== attemptEntryId) continue;
14682
14902
  if (failure2 === void 0) continue;
14683
- const identity = isRecord11(failure2.identity) ? failure2.identity : void 0;
14903
+ const identity = isRecord12(failure2.identity) ? failure2.identity : void 0;
14684
14904
  const typedCause = failure2.cause === "provider" || failure2.cause === "activation" || failure2.cause === "session" || failure2.cause === "output" || failure2.cause === "timeout" ? failure2.cause : void 0;
14685
14905
  return {
14686
14906
  ...typedCause === void 0 ? {} : { cause: typedCause },
@@ -14689,7 +14909,7 @@ function complianceFailureFromAuditorVolumes(volumes) {
14689
14909
  ...typeof identity.code === "string" || typeof identity.code === "number" ? { code: identity.code } : {}
14690
14910
  } },
14691
14911
  ...typeof failure2.diagnostic === "string" ? { diagnostic: failure2.diagnostic } : {},
14692
- ...isRecord11(failure2.details) ? { details: failure2.details } : {}
14912
+ ...isRecord12(failure2.details) ? { details: failure2.details } : {}
14693
14913
  };
14694
14914
  }
14695
14915
  }
@@ -14736,9 +14956,9 @@ function typedFailedTerminatingToolKnownFailure(entries) {
14736
14956
  if (classification.kind !== "infrastructure") continue;
14737
14957
  if (typeof message.toolCallId !== "string" || typeof message.toolName !== "string") continue;
14738
14958
  if (boundRoleToolCallForResult(attemptEntries, i, message, message.toolName) === void 0) continue;
14739
- const textPart = Array.isArray(message.content) ? message.content.find((part) => isRecord11(part) && part.type === "text" && typeof part.text === "string") : void 0;
14740
- const diagnostic = isRecord11(textPart) ? textPart.text : void 0;
14741
- const details = isRecord11(message.details) ? message.details : classification.fact;
14959
+ const textPart = Array.isArray(message.content) ? message.content.find((part) => isRecord12(part) && part.type === "text" && typeof part.text === "string") : void 0;
14960
+ const diagnostic = isRecord12(textPart) ? textPart.text : void 0;
14961
+ const details = isRecord12(message.details) ? message.details : classification.fact;
14742
14962
  return {
14743
14963
  cause: "activation",
14744
14964
  identity: { name: message.toolName, code: message.toolCallId },
@@ -14774,7 +14994,7 @@ async function resolveAuditedRunnerFailureResolution(input) {
14774
14994
  );
14775
14995
  if (terminatingFailure !== void 0) return resolutionOf(terminatingFailure);
14776
14996
  } catch (error) {
14777
- if (!isMissingPathError3(error)) {
14997
+ if (!isMissingPathError4(error)) {
14778
14998
  const failure2 = sessionReadFailure(error, "failed to recover typed terminating-tool failure");
14779
14999
  return resolutionOf({
14780
15000
  cause: "session",
@@ -14875,7 +15095,7 @@ function controlledFailureInputFromResolution(resolution) {
14875
15095
  } : {}
14876
15096
  };
14877
15097
  }
14878
- function isRecord11(value) {
15098
+ function isRecord12(value) {
14879
15099
  return typeof value === "object" && value !== null && !Array.isArray(value);
14880
15100
  }
14881
15101
  function toolResultText(message) {
@@ -14900,7 +15120,7 @@ function extractCollectorTargetBindRejection(entries) {
14900
15120
  const diagnostic = toolResultText(message);
14901
15121
  if (diagnostic.length === 0) return void 0;
14902
15122
  const details = message.details;
14903
- const code = isRecord11(details) && typeof details.code === "string" && details.code.trim() !== "" ? details.code : void 0;
15123
+ const code = isRecord12(details) && typeof details.code === "string" && details.code.trim() !== "" ? details.code : void 0;
14904
15124
  return code === void 0 ? { diagnostic } : { diagnostic, code };
14905
15125
  }
14906
15126
  return void 0;
@@ -14982,7 +15202,7 @@ function boundRoleToolCallForResult(entries, resultIndex, message, outputToolNam
14982
15202
  const candidateMessage = entries[index]?.message;
14983
15203
  if (candidateMessage?.role === "assistant" && Array.isArray(candidateMessage.content)) {
14984
15204
  for (const part of candidateMessage.content) {
14985
- if (!isRecord11(part) || part.type !== "toolCall" || part.id !== callId) {
15205
+ if (!isRecord12(part) || part.type !== "toolCall" || part.id !== callId) {
14986
15206
  continue;
14987
15207
  }
14988
15208
  if (part.name !== outputToolName) return void 0;
@@ -15053,7 +15273,7 @@ function parseNavigatorAttendanceDetails(details) {
15053
15273
  if (typeof details.prose === "string" && details.prose.trim() !== "") {
15054
15274
  prose = details.prose;
15055
15275
  } else {
15056
- const next = isRecord11(details.next) && typeof details.next.role === "string" ? details.next.role : void 0;
15276
+ const next = isRecord12(details.next) && typeof details.next.role === "string" ? details.next.role : void 0;
15057
15277
  const reason = typeof details.reason === "string" && details.reason.trim() !== "" ? details.reason : void 0;
15058
15278
  const command = typeof details.command === "string" && details.command.trim() !== "" ? details.command : void 0;
15059
15279
  if (reason !== void 0 && next !== void 0) {
@@ -15162,7 +15382,7 @@ function detourGateContext(admitted, scope) {
15162
15382
  }
15163
15383
  async function withOptionalGateProjection(base, sessionDirectory, gateContext = {}) {
15164
15384
  const secondaryEvidence = base.roleOutcome.kind === "failure" ? base.roleOutcome.decisiveFacts.secondaryEvidence : void 0;
15165
- const skipGate = isRecord11(secondaryEvidence) && secondaryEvidence.kind === "role_infrastructure_failure" && (secondaryEvidence.stage === "gatekeeper" || secondaryEvidence.stage === "inspector" || secondaryEvidence.stage === "notary");
15385
+ const skipGate = isRecord12(secondaryEvidence) && secondaryEvidence.kind === "role_infrastructure_failure" && (secondaryEvidence.stage === "gatekeeper" || secondaryEvidence.stage === "inspector" || secondaryEvidence.stage === "notary");
15166
15386
  let next = base;
15167
15387
  if (!skipGate) {
15168
15388
  const gate = await extractGateFactFromSessionDirectory(sessionDirectory, gateContext);
@@ -15206,7 +15426,7 @@ function extractNavigatorFact(entries) {
15206
15426
  const entry = entries[i];
15207
15427
  if (entry?.type === "custom_message" && entry.customType === "ak-navigator-attendance") {
15208
15428
  const details = entry.message?.details ?? entry.details;
15209
- if (!isRecord11(details)) {
15429
+ if (!isRecord12(details)) {
15210
15430
  return {
15211
15431
  disposition: "unavailable",
15212
15432
  source: "unknown",
@@ -15239,7 +15459,7 @@ async function extractNavigatorFactFromAdmittedSession(sessionFile) {
15239
15459
  const entries = await readBoundSessionEntries(sessionFile);
15240
15460
  return extractNavigatorFact(entries);
15241
15461
  } catch (error) {
15242
- if (isMissingPathError3(error)) {
15462
+ if (isMissingPathError4(error)) {
15243
15463
  return {
15244
15464
  disposition: "unavailable",
15245
15465
  source: "unknown",
@@ -15352,7 +15572,7 @@ async function readLawfulSettlementEntries(sessionFile) {
15352
15572
  try {
15353
15573
  return await readBoundSessionEntries(sessionFile);
15354
15574
  } catch (error) {
15355
- if (isMissingPathError3(error)) return void 0;
15575
+ if (isMissingPathError4(error)) return void 0;
15356
15576
  throw error instanceof Error && error.knownCause === "session" ? error : sessionReadFailure(error, "session unreadable");
15357
15577
  }
15358
15578
  }
@@ -15616,7 +15836,7 @@ async function settleLawfulCollectorTerminalResult(admitted, authority, scope) {
15616
15836
  const residual = boundErroredToolCandidate(entries, index, message, COLLECTOR_WAIT_TOOL);
15617
15837
  if (residual === void 0) continue;
15618
15838
  const candidate = residual.candidate;
15619
- const details = isRecord11(candidate) ? candidate : { candidate };
15839
+ const details = isRecord12(candidate) ? candidate : { candidate };
15620
15840
  const failed = await settleFailureTerminalResult(
15621
15841
  admitted,
15622
15842
  {
@@ -15671,7 +15891,7 @@ function extractDoctorCandidateCostFact(entries) {
15671
15891
  const entry = entries[i];
15672
15892
  if (entry?.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
15673
15893
  const data = entry.data;
15674
- return isRecord11(data) ? data.cost : void 0;
15894
+ return isRecord12(data) ? data.cost : void 0;
15675
15895
  }
15676
15896
  }
15677
15897
  return void 0;
@@ -15682,7 +15902,7 @@ function extractDoctorCandidateAuditNoReceiptFact(entries) {
15682
15902
  const entry = entries[i];
15683
15903
  if (entry?.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
15684
15904
  const data = entry.data;
15685
- return isRecord11(data) ? data.auditNoReceipt : void 0;
15905
+ return isRecord12(data) ? data.auditNoReceipt : void 0;
15686
15906
  }
15687
15907
  }
15688
15908
  return void 0;
@@ -15847,7 +16067,7 @@ async function settleLawfulSeatAcceptedTerminalResult(admitted, authority, spec,
15847
16067
  );
15848
16068
  }
15849
16069
  if (residual !== void 0) {
15850
- const details = isRecord11(residual.candidate) ? residual.candidate : { candidate: residual.candidate };
16070
+ const details = isRecord12(residual.candidate) ? residual.candidate : { candidate: residual.candidate };
15851
16071
  const failed = await settleFailureTerminalResult(
15852
16072
  admitted,
15853
16073
  {
@@ -15925,11 +16145,75 @@ async function settleLawfulDiaristTerminalResult(admitted, authority, scope) {
15925
16145
  async function trySettleDiaristTerminalResult(admitted, authority, scope) {
15926
16146
  return settleLawfulDiaristTerminalResult(admitted, authority, scope);
15927
16147
  }
16148
+ function countersignTerminalFromEntries(entries) {
16149
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
16150
+ const entry = entries[index];
16151
+ if (entry?.type !== "custom") continue;
16152
+ if (entry.customType !== SECRETARIAT_GATE_OFFICER_ENTRY_TYPE) continue;
16153
+ const data = entry.data !== null && typeof entry.data === "object" && !Array.isArray(entry.data) ? entry.data : void 0;
16154
+ if (data?.officer !== "countersign") continue;
16155
+ if (data.receipt === void 0) continue;
16156
+ const runId = typeof data.runId === "string" && data.runId.trim() !== "" ? data.runId : void 0;
16157
+ return {
16158
+ receipt: data.receipt,
16159
+ ...runId === void 0 ? {} : { runId }
16160
+ };
16161
+ }
16162
+ return void 0;
16163
+ }
16164
+ function withCountersignTerminalFact(roleOutcome, officer) {
16165
+ const prior = roleOutcome.decisiveFacts !== void 0 && isRecord12(roleOutcome.decisiveFacts) ? roleOutcome.decisiveFacts : {};
16166
+ return {
16167
+ ...roleOutcome,
16168
+ decisiveFacts: {
16169
+ ...prior,
16170
+ [SECRETARIAT_COUNTERSIGN_TERMINAL_FACT_KEY]: officer
16171
+ }
16172
+ };
16173
+ }
16174
+ function acceptedSecretariatDefinesOfficerProjection(roleOutcome) {
16175
+ const payloads = roleOutcome.payloads ?? [];
16176
+ for (let index = payloads.length - 1; index >= 0; index -= 1) {
16177
+ const payload = payloads[index];
16178
+ if (!isRecord12(payload)) continue;
16179
+ const status = payload.secretariatStatus;
16180
+ if (typeof status !== "string") continue;
16181
+ return status === "converged";
16182
+ }
16183
+ return false;
16184
+ }
15928
16185
  async function settleLawfulSecretariatTerminalResult(admitted, authority, scope) {
15929
- return settleLawfulSeatAcceptedTerminalResult(admitted, authority, {
16186
+ const settled = await settleLawfulSeatAcceptedTerminalResult(admitted, authority, {
15930
16187
  role: "secretariat",
15931
16188
  toolName: SECRETARIAT_OUTPUT_TOOL_NAME
15932
16189
  }, scope);
16190
+ if (settled === void 0) return void 0;
16191
+ const coordinates = coordinatesFromAdmitted(authority, admitted);
16192
+ const entries = await readLawfulSettlementEntries(coordinates.sessionFile) ?? [];
16193
+ const officer = countersignTerminalFromEntries(entries);
16194
+ if (officer === void 0) return settled;
16195
+ if (settled.roleOutcome.kind === "audit_escalation") {
16196
+ return {
16197
+ ...settled,
16198
+ roleOutcome: withCountersignTerminalFact(
16199
+ {
16200
+ ...settled.roleOutcome,
16201
+ payloads: [officer.receipt]
16202
+ },
16203
+ officer
16204
+ )
16205
+ };
16206
+ }
16207
+ if (settled.roleOutcome.kind === "accepted") {
16208
+ if (!acceptedSecretariatDefinesOfficerProjection(settled.roleOutcome)) {
16209
+ return settled;
16210
+ }
16211
+ return {
16212
+ ...settled,
16213
+ roleOutcome: withCountersignTerminalFact(settled.roleOutcome, officer)
16214
+ };
16215
+ }
16216
+ return settled;
15933
16217
  }
15934
16218
  async function trySettleSecretariatTerminalResult(admitted, authority, scope) {
15935
16219
  return settleLawfulSecretariatTerminalResult(admitted, authority, scope);
@@ -16171,7 +16455,7 @@ async function settleLawfulMergerTerminalResult(admitted, authority, options, sc
16171
16455
  const residual = boundErroredToolCandidate(entries, index, message, MERGER_OUTPUT_TOOL_NAME);
16172
16456
  if (residual === void 0) continue;
16173
16457
  const candidate = residual.candidate;
16174
- const details = isRecord11(candidate) ? candidate : { candidate };
16458
+ const details = isRecord12(candidate) ? candidate : { candidate };
16175
16459
  const failed = await settleFailureTerminalResult(
16176
16460
  admitted,
16177
16461
  {
@@ -16500,10 +16784,10 @@ function presentFailureTerminal(terminal, io) {
16500
16784
  }
16501
16785
  function defaultNavigatorGraceSleep() {
16502
16786
  let timer;
16503
- const sleep = ((ms) => new Promise((resolve22) => {
16787
+ const sleep = ((ms) => new Promise((resolve21) => {
16504
16788
  timer = setTimeout(() => {
16505
16789
  timer = void 0;
16506
- resolve22();
16790
+ resolve21();
16507
16791
  }, ms);
16508
16792
  }));
16509
16793
  sleep.cancel = () => {
@@ -16515,7 +16799,7 @@ function defaultNavigatorGraceSleep() {
16515
16799
  return sleep;
16516
16800
  }
16517
16801
  function raceNavigatorGrace(work, graceMs = NAVIGATOR_POST_ROLE_GRACE_MS, sleep = defaultNavigatorGraceSleep()) {
16518
- return new Promise((resolve22, reject) => {
16802
+ return new Promise((resolve21, reject) => {
16519
16803
  let settled = false;
16520
16804
  const finish = (action) => {
16521
16805
  if (settled) return;
@@ -16524,11 +16808,11 @@ function raceNavigatorGrace(work, graceMs = NAVIGATOR_POST_ROLE_GRACE_MS, sleep
16524
16808
  action();
16525
16809
  };
16526
16810
  void work.then(
16527
- (value) => finish(() => resolve22({ status: "done", value })),
16811
+ (value) => finish(() => resolve21({ status: "done", value })),
16528
16812
  (error) => finish(() => reject(error))
16529
16813
  );
16530
16814
  void sleep(graceMs).then(() => {
16531
- finish(() => resolve22({ status: "timeout" }));
16815
+ finish(() => resolve21({ status: "timeout" }));
16532
16816
  });
16533
16817
  });
16534
16818
  }
@@ -16620,7 +16904,7 @@ var init_seat_ticket_binding = __esm({
16620
16904
  });
16621
16905
 
16622
16906
  // src/session-identity.ts
16623
- import { mkdir as mkdir3, readFile as readFile17, rename as rename2, writeFile as writeFile8 } from "node:fs/promises";
16907
+ import { mkdir as mkdir3, readFile as readFile18, rename as rename2, writeFile as writeFile8 } from "node:fs/promises";
16624
16908
  import { dirname as dirname15, join as join27 } from "node:path";
16625
16909
  function createSessionIdentityAuthority(authority, sessionBindingFile) {
16626
16910
  const bindingPath = (principal) => join27(authority.decode(principal).sessionDirectory, sessionBindingFile);
@@ -16630,7 +16914,7 @@ function createSessionIdentityAuthority(authority, sessionBindingFile) {
16630
16914
  },
16631
16915
  async load(principal) {
16632
16916
  try {
16633
- const value = JSON.parse(await readFile17(bindingPath(principal), "utf8"));
16917
+ const value = JSON.parse(await readFile18(bindingPath(principal), "utf8"));
16634
16918
  if (typeof value !== "object" || value === null || typeof value.sessionId !== "string") {
16635
16919
  throw new Error("durable session binding is invalid");
16636
16920
  }
@@ -16669,7 +16953,7 @@ var init_session_identity = __esm({
16669
16953
  });
16670
16954
 
16671
16955
  // src/session-dialogue.ts
16672
- function isRecord12(value) {
16956
+ function isRecord13(value) {
16673
16957
  return typeof value === "object" && value !== null && !Array.isArray(value);
16674
16958
  }
16675
16959
  function nativeEventId(row) {
@@ -16679,7 +16963,7 @@ function nativeEventId(row) {
16679
16963
  }
16680
16964
  for (const nestKey of ["message", "payload"]) {
16681
16965
  const nested = row[nestKey];
16682
- if (!isRecord12(nested)) continue;
16966
+ if (!isRecord13(nested)) continue;
16683
16967
  for (const key of ["uuid", "id"]) {
16684
16968
  const value = nested[key];
16685
16969
  if (typeof value === "string" && value !== "") return value;
@@ -16692,19 +16976,19 @@ function textParts(content) {
16692
16976
  if (!Array.isArray(content)) return [];
16693
16977
  const out = [];
16694
16978
  for (const part of content) {
16695
- if (!isRecord12(part) || !SPEAKER_TEXT_PART_TYPES.has(String(part.type))) continue;
16979
+ if (!isRecord13(part) || !SPEAKER_TEXT_PART_TYPES.has(String(part.type))) continue;
16696
16980
  const text = part.text;
16697
16981
  if (typeof text === "string" && text !== "") out.push(text);
16698
16982
  }
16699
16983
  return out;
16700
16984
  }
16701
16985
  function responseItemMessage(row) {
16702
- if (row.type !== "response_item" || !isRecord12(row.payload)) return void 0;
16986
+ if (row.type !== "response_item" || !isRecord13(row.payload)) return void 0;
16703
16987
  if (row.payload.type !== "message") return void 0;
16704
16988
  return row.payload;
16705
16989
  }
16706
16990
  function messageBody(row) {
16707
- if (isRecord12(row.message)) return row.message;
16991
+ if (isRecord13(row.message)) return row.message;
16708
16992
  return responseItemMessage(row);
16709
16993
  }
16710
16994
  function speakerOf(message) {
@@ -16714,7 +16998,7 @@ function speakerOf(message) {
16714
16998
  }
16715
16999
  function codexContentItemKinds(message) {
16716
17000
  const pass = message.internal_chat_message_metadata_passthrough;
16717
- if (!isRecord12(pass) || !Array.isArray(pass.content_item_kinds)) return void 0;
17001
+ if (!isRecord13(pass) || !Array.isArray(pass.content_item_kinds)) return void 0;
16718
17002
  const kinds = [];
16719
17003
  for (const kind of pass.content_item_kinds) {
16720
17004
  if (typeof kind === "string" && kind !== "") kinds.push(kind);
@@ -16743,7 +17027,7 @@ function isFixedNonOwnerEnqueueShape(content) {
16743
17027
  return hasFixedOpenTagPrefix(content, TASK_NOTIFICATION_OPEN_TAG);
16744
17028
  }
16745
17029
  function materializationOriginKind(row) {
16746
- if (!isRecord12(row.origin)) return void 0;
17030
+ if (!isRecord13(row.origin)) return void 0;
16747
17031
  const kind = row.origin.kind;
16748
17032
  return typeof kind === "string" && kind !== "" ? kind : void 0;
16749
17033
  }
@@ -16791,7 +17075,7 @@ var init_session_dialogue = __esm({
16791
17075
 
16792
17076
  // src/ticket-provenance.ts
16793
17077
  import { createHash as createHash7 } from "node:crypto";
16794
- import { readFile as readFile18 } from "node:fs/promises";
17078
+ import { readFile as readFile19 } from "node:fs/promises";
16795
17079
  import { basename as basename8, dirname as dirname16, join as join28, resolve as resolve12 } from "node:path";
16796
17080
  function dialogueSessionSourceRoots(home) {
16797
17081
  const machineHome = typeof home === "string" && home.trim() !== "" ? home : packageMachineHome();
@@ -16887,7 +17171,7 @@ async function readTicketProvenance(ticketNumber, cwd, home) {
16887
17171
  const { recordFile } = resolveTicketProvenanceVolume(ticketNumber, cwd, home);
16888
17172
  let text;
16889
17173
  try {
16890
- text = await readFile18(recordFile, "utf8");
17174
+ text = await readFile19(recordFile, "utf8");
16891
17175
  } catch (error) {
16892
17176
  if (error.code === "ENOENT") {
16893
17177
  return {
@@ -17367,7 +17651,7 @@ __export(case_dossier_delivery_exports, {
17367
17651
  loadCaseDossierReadingMaterial: () => loadCaseDossierReadingMaterial,
17368
17652
  projectCaseDossierPointerSection: () => projectCaseDossierPointerSection
17369
17653
  });
17370
- import { mkdtemp as mkdtemp3, readFile as readFile19, rm as rm3, writeFile as writeFile9 } from "node:fs/promises";
17654
+ import { mkdtemp as mkdtemp3, readFile as readFile20, rm as rm3, writeFile as writeFile9 } from "node:fs/promises";
17371
17655
  import { tmpdir as tmpdir3 } from "node:os";
17372
17656
  import { join as join29 } from "node:path";
17373
17657
  async function projectCaseDossierPointerSection(input) {
@@ -17419,7 +17703,7 @@ async function loadCaseDossierReadingMaterial(runDirectory) {
17419
17703
  );
17420
17704
  let section;
17421
17705
  try {
17422
- section = await readFile19(frozenPath, "utf8");
17706
+ section = await readFile20(frozenPath, "utf8");
17423
17707
  } catch (error) {
17424
17708
  if (error.code === "ENOENT") return void 0;
17425
17709
  throw error;
@@ -17442,7 +17726,7 @@ var init_case_dossier_delivery = __esm({
17442
17726
  });
17443
17727
 
17444
17728
  // src/host-transition-prior-native.ts
17445
- import { access as access3, readdir as readdir7 } from "node:fs/promises";
17729
+ import { access as access3, readdir as readdir8 } from "node:fs/promises";
17446
17730
  import { dirname as dirname17, join as join30 } from "node:path";
17447
17731
  function isEnoent3(error) {
17448
17732
  return typeof error === "object" && error !== null && error.code === "ENOENT";
@@ -17460,7 +17744,7 @@ async function listSitianRecordPaths(sessionParent) {
17460
17744
  const sessionRoot = dirname17(sessionParent);
17461
17745
  let entries;
17462
17746
  try {
17463
- entries = await readdir7(sessionRoot, { withFileTypes: true });
17747
+ entries = await readdir8(sessionRoot, { withFileTypes: true });
17464
17748
  } catch (error) {
17465
17749
  if (isEnoent3(error)) return [];
17466
17750
  throw error;
@@ -17534,6 +17818,24 @@ var init_public_run_credentials = __esm({
17534
17818
  }
17535
17819
  });
17536
17820
 
17821
+ // src/public-cli/process-cancel.ts
17822
+ function processCancelSignalName(signal) {
17823
+ if (signal === void 0 || signal.aborted !== true) return void 0;
17824
+ const reason = signal.reason;
17825
+ if (reason === "SIGTERM" || reason === "SIGINT" || reason === "SIGHUP") {
17826
+ return reason;
17827
+ }
17828
+ return void 0;
17829
+ }
17830
+ function processCancelDiagnostic(signalName) {
17831
+ return `ak-role terminated by ${signalName}`;
17832
+ }
17833
+ var init_process_cancel = __esm({
17834
+ "src/public-cli/process-cancel.ts"() {
17835
+ "use strict";
17836
+ }
17837
+ });
17838
+
17537
17839
  // src/public-cli/auto-resume.ts
17538
17840
  import { constants as fsConstants2 } from "node:fs";
17539
17841
  import { randomUUID as randomUUID5 } from "node:crypto";
@@ -17585,7 +17887,7 @@ async function ensureRealArtifactsDirectory(runDirectory) {
17585
17887
  throw new Error("run artifact retention: artifacts path is not a real directory");
17586
17888
  }
17587
17889
  } catch (error) {
17588
- if (!isMissingPathError4(error)) throw error;
17890
+ if (!isMissingPathError5(error)) throw error;
17589
17891
  await mkdir4(artifactsDir, { recursive: true });
17590
17892
  const created = await lstat6(artifactsDir);
17591
17893
  if (created.isSymbolicLink() || !created.isDirectory()) {
@@ -17617,7 +17919,7 @@ function serializeThrownValue(value, depth = 0, seen = /* @__PURE__ */ new WeakS
17617
17919
  }
17618
17920
  return value;
17619
17921
  }
17620
- function isMissingPathError4(error) {
17922
+ function isMissingPathError5(error) {
17621
17923
  return error instanceof Error && "code" in error && error.code === "ENOENT";
17622
17924
  }
17623
17925
  function transferNestedValue(value, depth, seen) {
@@ -17836,6 +18138,10 @@ async function runWithAutoResumeLoop(options) {
17836
18138
  if (terminal !== void 0) presentTerminal(terminal, options.io);
17837
18139
  return result;
17838
18140
  }
18141
+ if (processCancelSignalName(options.signal) !== void 0) {
18142
+ if (terminal !== void 0) presentTerminal(terminal, options.io);
18143
+ return result;
18144
+ }
17839
18145
  }
17840
18146
  if (result !== void 0) {
17841
18147
  const terminal = result.terminal;
@@ -17869,6 +18175,28 @@ async function runWithAutoResumeLoop(options) {
17869
18175
  terminal
17870
18176
  };
17871
18177
  }
18178
+ const cancelName = processCancelSignalName(options.signal);
18179
+ if (cancelName !== void 0) {
18180
+ const terminal = await attachDispatchExceptionTerminal(
18181
+ options.admitted,
18182
+ dispatchExceptionFailureTerminal({
18183
+ role: options.admitted.role,
18184
+ runId: options.admitted.runId,
18185
+ causeError: lastThrownError,
18186
+ errorFiles: retainedErrorFiles,
18187
+ autoResumeAttempts,
18188
+ endReason: `ak-role terminated by ${cancelName}`,
18189
+ everyAttemptThrew
18190
+ }),
18191
+ options.io
18192
+ );
18193
+ await finalizeExceptionRunBestEffort(options.admitted.runDirectory, options.io);
18194
+ presentTerminal(terminal, options.io);
18195
+ return {
18196
+ exitCode: 1,
18197
+ terminal
18198
+ };
18199
+ }
17872
18200
  if (!await isPrincipalAvailable(options.admitted.principal)) {
17873
18201
  const terminal = await attachDispatchExceptionTerminal(
17874
18202
  options.admitted,
@@ -17905,6 +18233,7 @@ var init_auto_resume = __esm({
17905
18233
  init_role_run_placement();
17906
18234
  init_run_lifecycle();
17907
18235
  init_config();
18236
+ init_process_cancel();
17908
18237
  init_terminal();
17909
18238
  init_settlement();
17910
18239
  dummyIo = { stdout: () => {
@@ -17937,6 +18266,36 @@ function describeCaughtError(error) {
17937
18266
  function isStationChildOfficerDialogue(role, env) {
17938
18267
  return env.stationChild === true && isOfficerReviewSeat(role);
17939
18268
  }
18269
+ function withProcessCancelSkipAutoResume(result, signal) {
18270
+ if (processCancelSignalName(signal) === void 0) {
18271
+ return result;
18272
+ }
18273
+ return { ...result, skipAutoResume: true };
18274
+ }
18275
+ async function settleProcessCancelAfterTurn(input) {
18276
+ const failed = await settleAfterTurnStarted(
18277
+ input.admitted,
18278
+ withEngineDetourInvocationScope(
18279
+ {
18280
+ timedOut: input.result.timedOut,
18281
+ code: input.result.code,
18282
+ stderr: input.result.stderr,
18283
+ knownDiagnostic: processCancelDiagnostic(input.cancelName)
18284
+ },
18285
+ input.invocationScopeId
18286
+ ),
18287
+ input.adapters,
18288
+ input.env.principalAuthority,
18289
+ input.io,
18290
+ input.persistRunState
18291
+ );
18292
+ return {
18293
+ ...failed,
18294
+ turnDispatched: true,
18295
+ skipAutoResume: true,
18296
+ ...input.deferredPersist
18297
+ };
18298
+ }
17940
18299
  function withOnceSuccessfulBeforeDispatch(adapters) {
17941
18300
  const hook = adapters.beforeDispatch;
17942
18301
  if (hook === void 0) return adapters;
@@ -18097,6 +18456,31 @@ async function dispatchPostAdmissionTurn(input) {
18097
18456
  const finishAfterTurn = async (result) => {
18098
18457
  if (afterDispatchApplied) return result;
18099
18458
  afterDispatchApplied = true;
18459
+ const cancelBeforeFinish = processCancelSignalName(env.signal);
18460
+ if (cancelBeforeFinish !== void 0 && result.terminal !== void 0 && isLawfulTypedTerminalOutcome(result.terminal.roleOutcome)) {
18461
+ result = {
18462
+ ...await settleAfterTurnStarted(
18463
+ admitted,
18464
+ withEngineDetourInvocationScope(
18465
+ {
18466
+ timedOut: false,
18467
+ code: null,
18468
+ stderr: "",
18469
+ knownDiagnostic: processCancelDiagnostic(cancelBeforeFinish),
18470
+ skipRunStateWrite: true
18471
+ },
18472
+ request.invocationScopeId
18473
+ ),
18474
+ adapters,
18475
+ env.principalAuthority,
18476
+ io,
18477
+ persistRunState
18478
+ ),
18479
+ turnDispatched: true,
18480
+ skipAutoResume: true,
18481
+ ...deferredPersist
18482
+ };
18483
+ }
18100
18484
  try {
18101
18485
  if (admitted.ticketNumber === void 0) {
18102
18486
  const rows = await readRecordedSubmissionRows(
@@ -18243,20 +18627,26 @@ async function dispatchPostAdmissionTurn(input) {
18243
18627
  try {
18244
18628
  result = await env.roleTurnHost.executeTurn(turnRequest);
18245
18629
  } catch (error) {
18630
+ const processCancelName = processCancelSignalName(env.signal);
18246
18631
  const settled2 = await settleAfterTurnStarted(
18247
18632
  admitted,
18248
18633
  withEngineDetourInvocationScope({
18249
18634
  timedOut: false,
18250
18635
  code: null,
18251
18636
  stderr: "",
18252
- thrown: error
18637
+ thrown: processCancelName === void 0 ? error : new Error(processCancelDiagnostic(processCancelName), { cause: error })
18253
18638
  }, request.invocationScopeId),
18254
18639
  adapters,
18255
18640
  env.principalAuthority,
18256
18641
  io,
18257
18642
  persistRunState
18258
18643
  );
18259
- return await finishAfterTurn({ ...settled2, turnDispatched: true, ...deferredPersist });
18644
+ return await finishAfterTurn(
18645
+ withProcessCancelSkipAutoResume(
18646
+ { ...settled2, turnDispatched: true, ...deferredPersist },
18647
+ env.signal
18648
+ )
18649
+ );
18260
18650
  }
18261
18651
  let stderrLogWriteFailure;
18262
18652
  try {
@@ -18296,7 +18686,8 @@ async function dispatchPostAdmissionTurn(input) {
18296
18686
  credential: credentialFailure,
18297
18687
  runDirectory: admitted.runDirectory
18298
18688
  });
18299
- const directHostFailureSignal = result.timedOut || result.knownFailure !== void 0 || runnerKnownFailure !== void 0 || credentialFailure !== void 0;
18689
+ const processCancelName = processCancelSignalName(env.signal);
18690
+ const directHostFailureSignal = result.timedOut || result.knownFailure !== void 0 || runnerKnownFailure !== void 0 || credentialFailure !== void 0 || processCancelName !== void 0;
18300
18691
  hostSignalFailed = directHostFailureSignal || result.code !== null && result.code !== 0 || resolution.knownFailure !== void 0;
18301
18692
  settled = await adapters.trySettle(admitted, env.principalAuthority, courtScope);
18302
18693
  if (settled !== void 0) {
@@ -18304,7 +18695,8 @@ async function dispatchPostAdmissionTurn(input) {
18304
18695
  }
18305
18696
  const settledIsFreshThisAttempt = settled === void 0 || settled.roleOutcome.kind !== "accepted" && settled.roleOutcome.kind !== "audit_escalation" ? true : await attemptProducedFreshSubmission(admitted, courtScope);
18306
18697
  const staleAcceptanceOutranksRealFailure = !settledIsFreshThisAttempt && hostSignalFailed;
18307
- if (settled !== void 0 && shouldPresent(settled) && !directHostFailureSignal && !staleAcceptanceOutranksRealFailure && stderrLogWriteFailure === void 0) {
18698
+ const cancelAfterSettle = processCancelSignalName(env.signal);
18699
+ if (settled !== void 0 && shouldPresent(settled) && !directHostFailureSignal && !staleAcceptanceOutranksRealFailure && stderrLogWriteFailure === void 0 && cancelAfterSettle === void 0) {
18308
18700
  if (settled.roleOutcome.kind === "accepted" && request.courtAttemptId !== void 0 && request.courtAttemptId.length > 0) {
18309
18701
  try {
18310
18702
  await clearCurrentCourt(admitted.runDirectory, request.courtAttemptId);
@@ -18341,6 +18733,22 @@ async function dispatchPostAdmissionTurn(input) {
18341
18733
  return await finishAfterTurn({ ...settledFailure, turnDispatched: true, ...deferredPersist });
18342
18734
  }
18343
18735
  if (settledOutcome !== void 0) {
18736
+ const lateCancel = processCancelSignalName(env.signal);
18737
+ if (lateCancel !== void 0) {
18738
+ return await finishAfterTurn(
18739
+ await settleProcessCancelAfterTurn({
18740
+ admitted,
18741
+ cancelName: lateCancel,
18742
+ result,
18743
+ adapters,
18744
+ env,
18745
+ io,
18746
+ persistRunState,
18747
+ deferredPersist,
18748
+ invocationScopeId: request.invocationScopeId
18749
+ })
18750
+ );
18751
+ }
18344
18752
  if (persistRunState) {
18345
18753
  try {
18346
18754
  await persistReturnedRunState(admitted, env.principalAuthority, { lawful: true });
@@ -18359,13 +18767,19 @@ async function dispatchPostAdmissionTurn(input) {
18359
18767
  io,
18360
18768
  persistRunState
18361
18769
  );
18362
- return await finishAfterTurn({ ...failed, turnDispatched: true, ...deferredPersist });
18770
+ return await finishAfterTurn(
18771
+ withProcessCancelSkipAutoResume(
18772
+ { ...failed, turnDispatched: true, ...deferredPersist },
18773
+ env.signal
18774
+ )
18775
+ );
18363
18776
  }
18364
18777
  }
18365
18778
  return await finishAfterTurn({ ...settledOutcome, ...deferredPersist });
18366
18779
  }
18367
18780
  if (hostSignalFailed) {
18368
18781
  const resolutionInput = controlledFailureInputFromResolution(resolution);
18782
+ const processCancelName = processCancelSignalName(env.signal);
18369
18783
  const stderrLogWriteDetails = stderrLogWriteFailure === void 0 ? void 0 : { stderrLogWriteFailure: describeCaughtError(stderrLogWriteFailure) };
18370
18784
  const failed = await settleAfterTurnStarted(
18371
18785
  admitted,
@@ -18374,6 +18788,7 @@ async function dispatchPostAdmissionTurn(input) {
18374
18788
  code: result.code,
18375
18789
  stderr: result.stderr,
18376
18790
  ...resolutionInput,
18791
+ ...processCancelName === void 0 ? {} : { knownDiagnostic: processCancelDiagnostic(processCancelName) },
18377
18792
  // Secondary fact only — never the cause. Rides on whichever channel
18378
18793
  // classification actually reads (knownFailure.details owns it when
18379
18794
  // a knownFailure exists; the top-level knownDetails otherwise).
@@ -18389,7 +18804,12 @@ async function dispatchPostAdmissionTurn(input) {
18389
18804
  io,
18390
18805
  persistRunState
18391
18806
  );
18392
- return await finishAfterTurn({ ...failed, turnDispatched: true, ...deferredPersist });
18807
+ return await finishAfterTurn(
18808
+ withProcessCancelSkipAutoResume(
18809
+ { ...failed, turnDispatched: true, ...deferredPersist },
18810
+ env.signal
18811
+ )
18812
+ );
18393
18813
  }
18394
18814
  if (stderrLogWriteFailure !== void 0) {
18395
18815
  const failed = await settleAfterTurnStarted(
@@ -18412,6 +18832,22 @@ async function dispatchPostAdmissionTurn(input) {
18412
18832
  await settleHostEndedNoReceipt(admitted, env.principalAuthority, courtScope),
18413
18833
  courtScope
18414
18834
  );
18835
+ const noReceiptCancel = processCancelSignalName(env.signal);
18836
+ if (noReceiptCancel !== void 0) {
18837
+ return await finishAfterTurn(
18838
+ await settleProcessCancelAfterTurn({
18839
+ admitted,
18840
+ cancelName: noReceiptCancel,
18841
+ result,
18842
+ adapters,
18843
+ env,
18844
+ io,
18845
+ persistRunState,
18846
+ deferredPersist,
18847
+ invocationScopeId: request.invocationScopeId
18848
+ })
18849
+ );
18850
+ }
18415
18851
  if (persistRunState) {
18416
18852
  try {
18417
18853
  await persistReturnedRunState(admitted, env.principalAuthority, { lawful: true });
@@ -18430,7 +18866,12 @@ async function dispatchPostAdmissionTurn(input) {
18430
18866
  io,
18431
18867
  persistRunState
18432
18868
  );
18433
- return await finishAfterTurn({ ...failed, turnDispatched: true, ...deferredPersist });
18869
+ return await finishAfterTurn(
18870
+ withProcessCancelSkipAutoResume(
18871
+ { ...failed, turnDispatched: true, ...deferredPersist },
18872
+ env.signal
18873
+ )
18874
+ );
18434
18875
  }
18435
18876
  }
18436
18877
  return await finishAfterTurn({
@@ -18626,6 +19067,7 @@ async function runPostAdmissionSeatResume(input) {
18626
19067
  io: input.io,
18627
19068
  sessionAppender: env.sessionAppender,
18628
19069
  autoResumeLimit: env.autoResumeLimit,
19070
+ ...env.signal === void 0 ? {} : { signal: env.signal },
18629
19071
  buildInitialPayload: () => ({ resumeTurn: false }),
18630
19072
  buildResumePayload: () => ({ resumeTurn: true }),
18631
19073
  // Same as public manual resume: prior-court sealed acceptance is not a
@@ -18729,6 +19171,7 @@ async function runPostAdmissionResumable(input) {
18729
19171
  io,
18730
19172
  sessionAppender: env.sessionAppender,
18731
19173
  autoResumeLimit: env.autoResumeLimit,
19174
+ ...env.signal === void 0 ? {} : { signal: env.signal },
18732
19175
  buildInitialPayload: buildScopedInitial,
18733
19176
  buildResumePayload: buildScopedResume,
18734
19177
  dispatch: async (request, lease, _isFirst, attemptIo) => {
@@ -18837,6 +19280,7 @@ var init_post_admission = __esm({
18837
19280
  init_host_transition_prior_native();
18838
19281
  init_public_run_credentials();
18839
19282
  init_run_lifecycle();
19283
+ init_process_cancel();
18840
19284
  init_activation_ledger_topology();
18841
19285
  init_settlement();
18842
19286
  init_terminal();
@@ -20097,7 +20541,9 @@ async function runPublicCountersign(argv, env, io, parseCountersignArgv2) {
20097
20541
  {
20098
20542
  instruction: parsed.instruction,
20099
20543
  projectRoot: admitted.projectRoot,
20100
- failureLabel: "unbound summons"
20544
+ failureLabel: "unbound summons",
20545
+ // #969: parent durable ticket is the resume/bind key (ADR 0079).
20546
+ ...env.boundTicketNumber === void 0 ? {} : { boundTicketNumber: env.boundTicketNumber }
20101
20547
  },
20102
20548
  env,
20103
20549
  io
@@ -20149,12 +20595,16 @@ async function runPublicCountersign(argv, env, io, parseCountersignArgv2) {
20149
20595
  );
20150
20596
  }
20151
20597
  if (outcome.identity.kind === "ticket") {
20152
- const assertedTicket = outcome.identity.ticketNumber;
20153
- typedTicket = assertedTicket;
20598
+ typedTicket = isSafePositiveTicketNumber(env.boundTicketNumber) ? env.boundTicketNumber : outcome.identity.ticketNumber;
20154
20599
  typedCourtTicketNumbers = outcome.identity.courtTicketNumbers;
20600
+ } else if (isSafePositiveTicketNumber(env.boundTicketNumber)) {
20601
+ typedTicket = env.boundTicketNumber;
20602
+ }
20603
+ if (typedTicket !== void 0) {
20604
+ const resumeInstruction = env.reviewReask ?? env.gateReviewInstruction ?? parsed.instruction;
20155
20605
  const summons = {
20156
- instruction: parsed.instruction,
20157
- instructionEmpty: parsed.instruction.trim() === ""
20606
+ instruction: resumeInstruction,
20607
+ instructionEmpty: resumeInstruction.trim() === ""
20158
20608
  };
20159
20609
  const resumed = await tryResumeSameTicketSeatRun({
20160
20610
  home: env.home,
@@ -20236,7 +20686,9 @@ async function runPublicCountersign(argv, env, io, parseCountersignArgv2) {
20236
20686
  ...env.correlationId === void 0 || env.correlationId.trim() === "" ? {} : { correlationId: env.correlationId },
20237
20687
  continuation: {
20238
20688
  kind: "initial",
20239
- prompt: buildCountersignTransportPrompt(
20689
+ // #969/#879: gate path first mint carries parent payload as dialogue content;
20690
+ // ordinary public entry keeps package transport prompt.
20691
+ prompt: env.reviewReask ?? env.gateReviewInstruction ?? buildCountersignTransportPrompt(
20240
20692
  admitted,
20241
20693
  engineSessionMaterialFromOptions({
20242
20694
  ...pickEngineAxis(env),
@@ -21378,6 +21830,25 @@ async function summonGateOfficer(options) {
21378
21830
  ...common
21379
21831
  });
21380
21832
  }
21833
+ if (options.officer === "countersign") {
21834
+ const { runIdFromRunDirectory: runIdFromRunDirectory2 } = await Promise.resolve().then(() => (init_run_terminal_artifacts(), run_terminal_artifacts_exports));
21835
+ const correlationId = runIdFromRunDirectory2(options.sourceRunDirectory);
21836
+ if (correlationId === void 0 || correlationId.trim() === "") {
21837
+ throw new Error(
21838
+ `countersign gate summon requires parent runId from sourceRunDirectory: ${options.sourceRunDirectory}`
21839
+ );
21840
+ }
21841
+ const { readBoardTicketNumber: readBoardTicketNumber2 } = await Promise.resolve().then(() => (init_run_ticket_number(), run_ticket_number_exports));
21842
+ const parentTicket = await readBoardTicketNumber2(options.sourceRunDirectory);
21843
+ const instruction = options.reask ?? gateReviewInstruction ?? "";
21844
+ return summonPublicRole({
21845
+ role: "countersign",
21846
+ argv: ["--project", options.cwd, "--", instruction],
21847
+ ...common,
21848
+ correlationId,
21849
+ ...parentTicket === void 0 ? {} : { boundTicketNumber: parentTicket }
21850
+ });
21851
+ }
21381
21852
  return summonPublicRole({
21382
21853
  role: "inspector",
21383
21854
  argv: [`\u5377\u5B97\u6307\u9488\uFF1A${options.sourceRunDirectory}`],
@@ -21931,7 +22402,7 @@ var init_archivist_record_entry = __esm({
21931
22402
  import { randomUUID as randomUUID11 } from "node:crypto";
21932
22403
 
21933
22404
  // src/role-runtime-dependencies.ts
21934
- import { readFile as readFile22 } from "node:fs/promises";
22405
+ import { readFile as readFile23 } from "node:fs/promises";
21935
22406
  import { join as join40 } from "node:path";
21936
22407
 
21937
22408
  // src/canonical-skill-binding.ts
@@ -22953,7 +23424,7 @@ ${helpContext}
22953
23424
  // src/navigator-work-context.ts
22954
23425
  init_doctor_evidence();
22955
23426
  init_host_contracts();
22956
- import { readFile as readFile20 } from "node:fs/promises";
23427
+ import { readFile as readFile21 } from "node:fs/promises";
22957
23428
  import { resolve as resolve17 } from "node:path";
22958
23429
  init_notary_source_run();
22959
23430
  init_packaged_role_registry();
@@ -22966,7 +23437,7 @@ function navigatorInputReference(getFlag, role) {
22966
23437
  }
22967
23438
  async function loadNavigatorWorkContext(options) {
22968
23439
  const reference = navigatorInputReference(options.getFlag, options.role);
22969
- const input = reference === void 0 || options.role === "doctor" || options.role === "notary" ? void 0 : await readFile20(reference, "utf8");
23440
+ const input = reference === void 0 || options.role === "doctor" || options.role === "notary" ? void 0 : await readFile21(reference, "utf8");
22970
23441
  const subjectRoot = subjectPath(reference ?? options.context.sessionManager.getSessionDir(), options.context.cwd);
22971
23442
  let subjectKey = reference === void 0 ? subjectRoot : navigatorSubjectKeyForInput(subjectRoot, reference, options.context.cwd);
22972
23443
  let subject = input ?? `work subject: ${subjectKey}`;
@@ -23023,7 +23494,7 @@ async function loadNavigatorWorkContext(options) {
23023
23494
  let authorityMaterial;
23024
23495
  for (const path of authorityFiles) {
23025
23496
  try {
23026
- const content = await readFile20(path, "utf8");
23497
+ const content = await readFile21(path, "utf8");
23027
23498
  if (content.trim() !== "") {
23028
23499
  authorityMaterial = content;
23029
23500
  break;
@@ -23082,7 +23553,7 @@ init_sitian_facade();
23082
23553
  init_submission_ledger();
23083
23554
  init_collector_ledger();
23084
23555
  import { randomUUID as randomUUID8 } from "node:crypto";
23085
- import { readFileSync as readFileSync6, writeSync as writeSync4 } from "node:fs";
23556
+ import { readFileSync as readFileSync6, writeSync as writeSync3 } from "node:fs";
23086
23557
  import { join as join39 } from "node:path";
23087
23558
  import { Value as Value4 } from "typebox/value";
23088
23559
 
@@ -23124,16 +23595,7 @@ function namedActivationCause(error) {
23124
23595
  init_activation_ledger_topology();
23125
23596
 
23126
23597
  // src/activation-ledger.ts
23127
- init_activation_ledger_topology();
23128
23598
  init_activation_ledger_git();
23129
- import {
23130
- constants as constants2,
23131
- closeSync as closeSync2,
23132
- fstatSync,
23133
- openSync as openSync2,
23134
- writeSync
23135
- } from "node:fs";
23136
- import { dirname as dirname21, isAbsolute as isAbsolute10, resolve as resolve19 } from "node:path";
23137
23599
 
23138
23600
  // src/activation-ledger-session.ts
23139
23601
  init_activation_ledger_topology();
@@ -23237,129 +23699,11 @@ function durableSessionPointer(sessionManager) {
23237
23699
 
23238
23700
  // src/activation-ledger.ts
23239
23701
  init_activation_ledger_topology();
23240
- var ACTIVATION_LEDGER_APPEND_OPEN_FLAGS = constants2.O_APPEND | constants2.O_CREAT | constants2.O_WRONLY | constants2.O_NOFOLLOW;
23241
- var ACCEPTED_ACTIVATION_EVENT = "accepted-activation";
23242
- var ACCEPTED_ACTIVATION_FACT_KEYS = Object.freeze([
23243
- "event",
23244
- "role",
23245
- "observedAt",
23246
- "bookKey",
23247
- "session",
23248
- "correlation"
23249
- ]);
23250
- function correlationIdentityFromEnv(env = process.env) {
23251
- const raw = env.AK_CORRELATION_ID;
23252
- if (typeof raw === "string" && raw.trim().length > 0) {
23253
- return { kind: "caller", id: raw };
23254
- }
23255
- return { kind: "absent" };
23256
- }
23257
- function projectAcceptedActivationFact(input) {
23258
- const closed = {
23259
- event: ACCEPTED_ACTIVATION_EVENT,
23260
- role: input.role,
23261
- observedAt: input.observedAt,
23262
- bookKey: input.bookKey,
23263
- session: { kind: "session-file", path: input.session.path },
23264
- correlation: input.correlation.kind === "caller" ? { kind: "caller", id: input.correlation.id } : { kind: "absent" }
23265
- };
23266
- return Object.fromEntries(
23267
- ACCEPTED_ACTIVATION_FACT_KEYS.map((key) => [key, closed[key]])
23268
- );
23269
- }
23270
- function buildAcceptedActivationFact(input) {
23271
- return projectAcceptedActivationFact(input);
23272
- }
23273
- function serializeAcceptedActivationFact(fact) {
23274
- return `${JSON.stringify(projectAcceptedActivationFact(fact))}
23275
- `;
23276
- }
23277
- function appendActivationLedgerLine(ledgerPath, line2, options) {
23278
- if (!isAbsolute10(options.ledgerHome)) {
23279
- throw new ActivationLedgerError(
23280
- `activation ledger home must be absolute: ${options.ledgerHome}`
23281
- );
23282
- }
23283
- const resolvedLedger = resolve19(ledgerPath);
23284
- const resolvedHome = resolve19(options.ledgerHome);
23285
- const parent = dirname21(resolvedLedger);
23286
- ensureRealDirectoryTree(resolvedHome, parent);
23287
- assertLedgerFileInsideHome(resolvedLedger, resolvedHome);
23288
- if (typeof constants2.O_NOFOLLOW !== "number") {
23289
- throw new ActivationLedgerError(
23290
- "activation ledger append requires O_NOFOLLOW open-flag support (anti-symlink TOCTOU protection must not be silently dropped); refusing to append"
23291
- );
23292
- }
23293
- const bytes = Buffer.isBuffer(line2) ? line2 : Buffer.from(line2);
23294
- let ledgerFd;
23295
- let primaryFailure;
23296
- try {
23297
- try {
23298
- ledgerFd = openSync2(resolvedLedger, ACTIVATION_LEDGER_APPEND_OPEN_FLAGS, 420);
23299
- } catch (error) {
23300
- throw new ActivationLedgerError(
23301
- `activation ledger failed to open ledger file (${resolvedLedger}): ${errorText(error)}`,
23302
- { cause: error }
23303
- );
23304
- }
23305
- let opened;
23306
- try {
23307
- opened = fstatSync(ledgerFd);
23308
- } catch (error) {
23309
- throw new ActivationLedgerError(
23310
- `activation ledger failed to fstat ledger file (${resolvedLedger}): ${errorText(error)}`,
23311
- { cause: error }
23312
- );
23313
- }
23314
- if (!opened.isFile()) {
23315
- throw new ActivationLedgerError(
23316
- `activation ledger is not a regular file: ${resolvedLedger}`
23317
- );
23318
- }
23319
- const written = writeSync(ledgerFd, bytes, 0, bytes.length, null);
23320
- if (written !== bytes.length) {
23321
- throw new ActivationLedgerError(
23322
- `activation ledger short write: wrote ${written} of ${bytes.length} bytes to ${resolvedLedger}`
23323
- );
23324
- }
23325
- } catch (error) {
23326
- primaryFailure = error;
23327
- }
23328
- if (ledgerFd !== void 0) {
23329
- try {
23330
- closeSync2(ledgerFd);
23331
- } catch (closeFailure) {
23332
- if (primaryFailure !== void 0) {
23333
- throw new AggregateError(
23334
- [primaryFailure, closeFailure],
23335
- "activation ledger operation and close failed",
23336
- { cause: primaryFailure }
23337
- );
23338
- }
23339
- throw closeFailure;
23340
- }
23341
- }
23342
- if (primaryFailure !== void 0) throw primaryFailure;
23343
- }
23344
- function appendAcceptedActivationFact(ledgerPath, fact, options) {
23345
- appendActivationLedgerLine(
23346
- ledgerPath,
23347
- Buffer.from(serializeAcceptedActivationFact(fact), "utf8"),
23348
- { ledgerHome: options.ledgerHome }
23349
- );
23350
- }
23351
- function appendAcceptedActivationToBook(options) {
23352
- appendAcceptedActivationFact(
23353
- activationWaitingLedgerPath(options.ledgerHome, options.fact.bookKey),
23354
- options.fact,
23355
- { ledgerHome: options.ledgerHome }
23356
- );
23357
- }
23358
23702
 
23359
23703
  // src/stderr-jsonl.ts
23360
- import { writeSync as writeSync2 } from "node:fs";
23704
+ import { writeSync } from "node:fs";
23361
23705
  var STDERR_JSONL_WRITE_RETRY_LIMIT = 100;
23362
- function writeStderrJsonlRecord(record4, write = writeSync2) {
23706
+ function writeStderrJsonlRecord(record4, write = writeSync) {
23363
23707
  const bytes = Buffer.from(`${JSON.stringify(record4)}
23364
23708
  `);
23365
23709
  let offset = 0;
@@ -23379,7 +23723,7 @@ function writeStderrJsonlRecord(record4, write = writeSync2) {
23379
23723
  }
23380
23724
 
23381
23725
  // src/tool-execution-observation.ts
23382
- import { writeSync as writeSync3 } from "node:fs";
23726
+ import { writeSync as writeSync2 } from "node:fs";
23383
23727
  import { Type as Type15 } from "typebox";
23384
23728
  import { Value as Value3 } from "typebox/value";
23385
23729
  var TOOL_EXECUTION_UPDATE_THROTTLE_MS = 3e4;
@@ -23410,7 +23754,7 @@ function validateToolExecutionObservationRecord(record4) {
23410
23754
  }
23411
23755
  return record4;
23412
23756
  }
23413
- function writeToolExecutionObservationRecord(record4, write = writeSync3) {
23757
+ function writeToolExecutionObservationRecord(record4, write = writeSync2) {
23414
23758
  writeStderrJsonlRecord(validateToolExecutionObservationRecord(record4), write);
23415
23759
  }
23416
23760
  function isProducingToolUpdate(partialResult) {
@@ -23641,15 +23985,15 @@ init_collector_evidence();
23641
23985
  init_collector_github();
23642
23986
 
23643
23987
  // src/collector-handbook.ts
23644
- import { readFile as readFile21 } from "node:fs/promises";
23988
+ import { readFile as readFile22 } from "node:fs/promises";
23645
23989
  import { join as join38, sep as sep6 } from "node:path";
23646
23990
 
23647
23991
  // src/atomic-write.ts
23648
23992
  import { randomUUID as randomUUID7 } from "node:crypto";
23649
23993
  import { rename as rename3, rm as rm5, writeFile as writeFile11 } from "node:fs/promises";
23650
- import { dirname as dirname22, join as join37 } from "node:path";
23994
+ import { dirname as dirname21, join as join37 } from "node:path";
23651
23995
  async function writeFileAtomically(destination, contents) {
23652
- const parent = dirname22(destination);
23996
+ const parent = dirname21(destination);
23653
23997
  const temporary = join37(parent, `.atomic-write-${randomUUID7()}.tmp`);
23654
23998
  try {
23655
23999
  await writeFile11(temporary, contents);
@@ -23804,7 +24148,7 @@ function createCollectorHandbookStore(input) {
23804
24148
  ensureRealDirectoryTree(input.ledgerHome, parentDir2);
23805
24149
  assertLedgerFileInsideHome(path, input.ledgerHome);
23806
24150
  try {
23807
- const body = await readFile21(path, "utf8");
24151
+ const body = await readFile22(path, "utf8");
23808
24152
  assertHandbookBudget(body, "\u6B63\u6587");
23809
24153
  return body;
23810
24154
  } catch (error) {
@@ -25155,7 +25499,7 @@ init_submission_errors();
25155
25499
  init_submission_errors();
25156
25500
  import { execFileSync as execFileSync4 } from "node:child_process";
25157
25501
  import { existsSync as existsSync12, lstatSync as lstatSync3, readdirSync as readdirSync3, readFileSync as readFileSync5, rmdirSync, rmSync } from "node:fs";
25158
- import { resolve as resolve20 } from "node:path";
25502
+ import { resolve as resolve19 } from "node:path";
25159
25503
  var WORKER_SUBMISSION_GATE_RECORD_KIND = WORKER_SUBMISSION_GATE_KIND;
25160
25504
  var WORKER_COMMIT_BASELINE_ENTRY_TYPE = "commit-baseline";
25161
25505
  var WORKER_COMMIT_REMINDER_BOUNCE_ENTRY_TYPE = "commit-reminder-bounce";
@@ -25204,7 +25548,7 @@ function escapeGitConfigValueRegex(value) {
25204
25548
  function unsetOwnedHooksPath(file) {
25205
25549
  const owned = [];
25206
25550
  for (const value of tryGetAll(file, "core.hooksPath")) {
25207
- if (!ownedHook(resolve20(value, HOOK_FILE))) continue;
25551
+ if (!ownedHook(resolve19(value, HOOK_FILE))) continue;
25208
25552
  try {
25209
25553
  gitFile(file, [
25210
25554
  "--unset-all",
@@ -25219,15 +25563,15 @@ function unsetOwnedHooksPath(file) {
25219
25563
  return owned;
25220
25564
  }
25221
25565
  function rmOwnedDir(dir) {
25222
- const hookPath = resolve20(dir, HOOK_FILE);
25566
+ const hookPath = resolve19(dir, HOOK_FILE);
25223
25567
  if (!ownedHook(hookPath)) return;
25224
25568
  rmSync(hookPath, { force: true });
25225
25569
  if (existsSync12(dir) && readdirSync3(dir).length === 0) rmdirSync(dir);
25226
25570
  }
25227
25571
  function linkedGitDirs(commonDir) {
25228
- const root = resolve20(commonDir, "worktrees");
25572
+ const root = resolve19(commonDir, "worktrees");
25229
25573
  if (!existsSync12(root)) return [];
25230
- return readdirSync3(root).map((name) => resolve20(root, name)).filter((dir) => lstatSync3(dir).isDirectory());
25574
+ return readdirSync3(root).map((name) => resolve19(root, name)).filter((dir) => lstatSync3(dir).isDirectory());
25231
25575
  }
25232
25576
  function uninstallPackageWorkerHooks(cwd) {
25233
25577
  let inside;
@@ -25241,17 +25585,17 @@ function uninstallPackageWorkerHooks(cwd) {
25241
25585
  const clear = (configFile) => {
25242
25586
  for (const hooks of unsetOwnedHooksPath(configFile)) rmOwnedDir(hooks);
25243
25587
  };
25244
- clear(resolve20(commonDir, "config"));
25245
- clear(resolve20(commonDir, "config.worktree"));
25246
- rmOwnedDir(resolve20(commonDir, HOOKS_DIR));
25247
- const legacy = resolve20(commonDir, "hooks", HOOK_FILE);
25588
+ clear(resolve19(commonDir, "config"));
25589
+ clear(resolve19(commonDir, "config.worktree"));
25590
+ rmOwnedDir(resolve19(commonDir, HOOKS_DIR));
25591
+ const legacy = resolve19(commonDir, "hooks", HOOK_FILE);
25248
25592
  if (ownedHook(legacy)) rmSync(legacy, { force: true });
25249
25593
  for (const gitDir of linkedGitDirs(commonDir)) {
25250
- clear(resolve20(gitDir, "config.worktree"));
25251
- rmOwnedDir(resolve20(gitDir, HOOKS_DIR));
25594
+ clear(resolve19(gitDir, "config.worktree"));
25595
+ rmOwnedDir(resolve19(gitDir, HOOKS_DIR));
25252
25596
  }
25253
25597
  }
25254
- function isRecord13(value) {
25598
+ function isRecord14(value) {
25255
25599
  return typeof value === "object" && value !== null && !Array.isArray(value);
25256
25600
  }
25257
25601
  function unfinishedReasonPresent(details) {
@@ -25267,7 +25611,7 @@ function readGateState(session) {
25267
25611
  if (entry.type !== "custom") continue;
25268
25612
  if (entry.customType === WORKER_COMMIT_BASELINE_ENTRY_TYPE) {
25269
25613
  const data = entry.data;
25270
- if (isRecord13(data) && (data.head === null || typeof data.head === "string")) {
25614
+ if (isRecord14(data) && (data.head === null || typeof data.head === "string")) {
25271
25615
  baseline = data.head;
25272
25616
  }
25273
25617
  } else if (entry.customType === WORKER_COMMIT_REMINDER_BOUNCE_ENTRY_TYPE) {
@@ -25818,7 +26162,6 @@ ${JSON.stringify(admitted)}
25818
26162
  // src/role-runtime.ts
25819
26163
  init_navigator_invocation_identity();
25820
26164
  init_gatekeeper_role();
25821
- init_gatekeeper_role();
25822
26165
  init_submission_errors();
25823
26166
  init_doctor_contracts();
25824
26167
  init_doctor_evidence();
@@ -26001,7 +26344,7 @@ async function executeActivationStage(role, stage, infrastructure) {
26001
26344
  throw activationError;
26002
26345
  }
26003
26346
  }
26004
- function writeActivationTraceRecord(record4, write = writeSync4) {
26347
+ function writeActivationTraceRecord(record4, write = writeSync3) {
26005
26348
  writeStderrJsonlRecord(record4, write);
26006
26349
  }
26007
26350
  var ActivationBarrierError = class extends Error {
@@ -26301,15 +26644,80 @@ ${error.message}`
26301
26644
  }
26302
26645
  var COUNTERSIGN_QUEUE_STATUSES = /* @__PURE__ */ new Set(["converged", "continue", "escalate"]);
26303
26646
  var COUNTERSIGN_STATUS_REASK = "countersignStatus \u4E0D\u662F converged\u3001continue\u3001escalate \u4E09\u6001\u4E4B\u4E00\u3002\u8BF7\u91CD\u65B0\u4EA4\u5377\uFF0Cstatus \u5199\u660E\u5176\u4E00\u3002";
26304
- function createSecretariatRoleRuntime(roleHost, dependencies) {
26647
+ var SECRETARIAT_SUBMISSION_GATE_HOSTS = /* @__PURE__ */ new Set(["codex", "claude", "grok-build"]);
26648
+ var SECRETARIAT_QUEUE_STATUSES = /* @__PURE__ */ new Set(["converged", "escalate"]);
26649
+ var SECRETARIAT_STATUS_REASK = "secretariatStatus \u4E0D\u662F converged\u3001escalate \u4E4B\u4E00\u3002\u8BF7\u91CD\u65B0\u4EA4\u5377\uFF0Cstatus \u5199\u660E\u5176\u4E00\u3002";
26650
+ function createSecretariatRoleRuntime(roleHost, dependencies, hostActions) {
26305
26651
  let parentInstruction = "";
26652
+ const beforeAccept = hostActions !== void 0 && roleHost.requireGatekeeperPass !== void 0 ? async ({ toolCallId, parameters, signal, ctx }) => {
26653
+ const host = typeof ctx.host === "string" && ctx.host.trim() !== "" ? ctx.host.trim() : void 0;
26654
+ if (host === void 0 || !SECRETARIAT_SUBMISSION_GATE_HOSTS.has(host)) {
26655
+ return void 0;
26656
+ }
26657
+ const record4 = parameters !== null && typeof parameters === "object" && !Array.isArray(parameters) ? parameters : void 0;
26658
+ const status = record4 !== void 0 && typeof record4.secretariatStatus === "string" ? record4.secretariatStatus : void 0;
26659
+ if (status === void 0 || !SECRETARIAT_QUEUE_STATUSES.has(status)) {
26660
+ throw new ParentQueueReaskError(SECRETARIAT_STATUS_REASK);
26661
+ }
26662
+ if (status === "escalate") {
26663
+ return void 0;
26664
+ }
26665
+ try {
26666
+ const pass = await roleHost.requireGatekeeperPass({
26667
+ context: ctx,
26668
+ subject: { kind: "secretariat_verdict" },
26669
+ ...signal === void 0 ? {} : { signal },
26670
+ hostActions,
26671
+ toolCallId,
26672
+ // #879: this-turn typed payload — identity-bound at submit site.
26673
+ submission: parameters
26674
+ });
26675
+ if (pass !== void 0 && pass !== null && typeof pass === "object" && "receipt" in pass) {
26676
+ const {
26677
+ SECRETARIAT_GATE_OFFICER_ENTRY_TYPE: SECRETARIAT_GATE_OFFICER_ENTRY_TYPE2
26678
+ } = await Promise.resolve().then(() => (init_secretariat_contracts(), secretariat_contracts_exports));
26679
+ const runId = typeof pass.runId === "string" && pass.runId.trim() !== "" ? pass.runId : void 0;
26680
+ ctx.sessionManager.appendCustomEntry?.(SECRETARIAT_GATE_OFFICER_ENTRY_TYPE2, {
26681
+ officer: "countersign",
26682
+ receipt: pass.receipt,
26683
+ ...runId === void 0 ? {} : { runId }
26684
+ });
26685
+ }
26686
+ return void 0;
26687
+ } catch (error) {
26688
+ if (error instanceof GatekeeperDecisionError && error.result.status === "escalate") {
26689
+ const receipt = error.result.receipt;
26690
+ const receiptRecord = receipt !== null && typeof receipt === "object" && !Array.isArray(receipt) ? receipt : void 0;
26691
+ const runId = typeof error.result.runId === "string" && error.result.runId.trim() !== "" ? error.result.runId : void 0;
26692
+ const {
26693
+ SECRETARIAT_GATE_OFFICER_ENTRY_TYPE: SECRETARIAT_GATE_OFFICER_ENTRY_TYPE2
26694
+ } = await Promise.resolve().then(() => (init_secretariat_contracts(), secretariat_contracts_exports));
26695
+ ctx.sessionManager.appendCustomEntry?.(SECRETARIAT_GATE_OFFICER_ENTRY_TYPE2, {
26696
+ officer: "countersign",
26697
+ receipt,
26698
+ ...runId === void 0 ? {} : { runId }
26699
+ });
26700
+ const { buildAuditEscalationResult: buildAuditEscalationResult2 } = await Promise.resolve().then(() => (init_audit_escalation(), audit_escalation_exports));
26701
+ return buildAuditEscalationResult2(
26702
+ {
26703
+ status: "escalate",
26704
+ officer: "countersign",
26705
+ ...receiptRecord !== void 0 && Object.prototype.hasOwnProperty.call(receiptRecord, "decisionGate") ? { decisionGate: receiptRecord.decisionGate } : {}
26706
+ },
26707
+ receipt
26708
+ );
26709
+ }
26710
+ throw error;
26711
+ }
26712
+ } : void 0;
26306
26713
  const base = createFiledOfficerRuntime(
26307
26714
  roleHost,
26308
26715
  {
26309
26716
  role: "secretariat",
26310
26717
  tool: SECRETARIAT_OUTPUT_TOOL_SPEC,
26311
26718
  acceptedText: SECRETARIAT_ACCEPTED_TEXT,
26312
- soulTag: "secretariat"
26719
+ soulTag: "secretariat",
26720
+ ...beforeAccept === void 0 ? {} : { beforeAccept }
26313
26721
  },
26314
26722
  dependencies
26315
26723
  );
@@ -26991,8 +27399,9 @@ function createRoleRuntimeExtension(dependencies) {
26991
27399
  if (!dependencies.loadSecretariatSoul) throw new Error("Secretariat runtime dependencies are not configured");
26992
27400
  return dependencies.loadSecretariatSoul();
26993
27401
  },
26994
- ...dependencies.packageRoot === void 0 ? {} : { packageRoot: dependencies.packageRoot }
26995
- });
27402
+ ...dependencies.packageRoot === void 0 ? {} : { packageRoot: dependencies.packageRoot },
27403
+ ...dependencies.hostAdapters === void 0 ? {} : { hostAdapters: dependencies.hostAdapters }
27404
+ }, hostActions);
26996
27405
  const merger = createMergerRoleRuntime(roleHost, {
26997
27406
  async loadSoul() {
26998
27407
  if (!dependencies.loadMergerSoul) throw new Error("Merger runtime dependencies are not configured");
@@ -27233,11 +27642,8 @@ function createRoleRuntimeExtension(dependencies) {
27233
27642
  }
27234
27643
  };
27235
27644
  try {
27236
- const bookKey = resolveBookKeyFromGit(ctx.cwd);
27237
- const correlation = correlationIdentityFromEnv();
27238
- const sessionFile = ctx.sessionManager.getSessionFile?.() || ctx.sessionManager.getSessionDir?.();
27239
- const ledgerHome = resolveActivationLedgerHomeForPath(sessionFile);
27240
- const session = durableSessionPointer(ctx.sessionManager);
27645
+ resolveBookKeyFromGit(ctx.cwd);
27646
+ durableSessionPointer(ctx.sessionManager);
27241
27647
  const isStationChild = roleHost.getFlag(STATION_CHILD_FLAG.name) === true;
27242
27648
  if (dependencies.createNavigatorAttendance !== void 0 && entry.role !== "navigator" && !isStationChild) {
27243
27649
  navigatorSessionParent = ctx.sessionManager.getSessionFile();
@@ -27324,16 +27730,6 @@ function createRoleRuntimeExtension(dependencies) {
27324
27730
  if (entry.role === "coder") coder.armSubmissionGate(ctx.cwd, ctx.sessionManager);
27325
27731
  else fixer.armSubmissionGate(ctx.cwd, ctx.sessionManager);
27326
27732
  }
27327
- appendAcceptedActivationToBook({
27328
- ledgerHome,
27329
- fact: buildAcceptedActivationFact({
27330
- role: entry.role,
27331
- observedAt: clock(),
27332
- bookKey,
27333
- session,
27334
- correlation
27335
- })
27336
- });
27337
27733
  admitted = true;
27338
27734
  } catch (error) {
27339
27735
  failInfrastructure(error, ctx);
@@ -27358,12 +27754,12 @@ function createRoleRuntimeDependencies(packageRoot) {
27358
27754
  loadRoleReferenceMaterials: loadPackagedRoleReferenceMaterials,
27359
27755
  loadJudgeSoul: () => loadMainRoleSessionMaterials("judge"),
27360
27756
  loadFixerSoul: () => loadMainRoleSessionMaterials("fixer"),
27361
- loadFixPacket: (path) => readFile22(path, "utf8"),
27757
+ loadFixPacket: (path) => readFile23(path, "utf8"),
27362
27758
  loadCoderSoul: () => loadMainRoleSessionMaterials("coder"),
27363
- loadCoderTask: (path) => readFile22(path, "utf8"),
27759
+ loadCoderTask: (path) => readFile23(path, "utf8"),
27364
27760
  loadReviewerSoul: () => loadMainRoleSessionMaterials("reviewer"),
27365
27761
  loadCollectorSoul: () => loadMainRoleSessionMaterials("collector"),
27366
- loadCollectorHandbookSeed: () => readFile22(collectorHandbookSeedPath, "utf8"),
27762
+ loadCollectorHandbookSeed: () => readFile23(collectorHandbookSeedPath, "utf8"),
27367
27763
  createCollectorTransport: () => createGhCollectorGitHubTransport(),
27368
27764
  loadDoctorSoul: () => loadMainRoleSessionMaterials("doctor"),
27369
27765
  loadDoctorCase,
@@ -27378,7 +27774,7 @@ function createRoleRuntimeDependencies(packageRoot) {
27378
27774
  loadSecretariatSoul: () => loadMainRoleSessionMaterials("secretariat"),
27379
27775
  loadNotarySourceRun: loadNotarySourceRunLocator,
27380
27776
  loadMergerSoul: () => loadMainRoleSessionMaterials("merger"),
27381
- loadMergerInput: async (path) => JSON.parse(await readFile22(path, "utf8")),
27777
+ loadMergerInput: async (path) => JSON.parse(await readFile23(path, "utf8")),
27382
27778
  async loadCanonicalSkillBinding(name) {
27383
27779
  if (name === "tdd") {
27384
27780
  return loadPackagedCanonicalSkillBinding(packageRoot, "tdd");
@@ -27404,7 +27800,7 @@ function createRoleRuntimeDependencies(packageRoot) {
27404
27800
  authority: options.authority,
27405
27801
  invocationId: options.invocationId,
27406
27802
  loadSoul: () => loadMainRoleSessionMaterials("navigator"),
27407
- loadRoutePlaybook: () => readFile22(navigatorRoutePlaybookPath, "utf8"),
27803
+ loadRoutePlaybook: () => readFile23(navigatorRoutePlaybookPath, "utf8"),
27408
27804
  loadRoleHelp: async (role) => formatNavigatorRoleHelp(role),
27409
27805
  createSession: navigatorSessionFactory,
27410
27806
  ...options.contextError === void 0 ? {} : { contextError: options.contextError },
@@ -27418,7 +27814,7 @@ init_engine_detour();
27418
27814
  import { randomUUID as randomUUID9 } from "node:crypto";
27419
27815
  import { appendFile as appendFile3, mkdir as mkdir7, writeFile as writeFile12 } from "node:fs/promises";
27420
27816
  import { createServer } from "node:net";
27421
- import { dirname as dirname24, join as join42 } from "node:path";
27817
+ import { dirname as dirname23, join as join42 } from "node:path";
27422
27818
  import { fileURLToPath as fileURLToPath2 } from "node:url";
27423
27819
 
27424
27820
  // src/gatekeeper-pass-envelope.ts
@@ -27438,6 +27834,7 @@ function createDefaultGateOfficerSummon(options) {
27438
27834
  ...options.home === void 0 ? {} : { home: options.home },
27439
27835
  ...options.packageRoot === void 0 ? {} : { packageRoot: options.packageRoot },
27440
27836
  ...options.roleTurnHost === void 0 ? {} : { roleTurnHost: options.roleTurnHost },
27837
+ ...options.hostAdapters === void 0 ? {} : { hostAdapters: options.hostAdapters },
27441
27838
  ...options.createRunId === void 0 ? {} : { createRunId: options.createRunId }
27442
27839
  });
27443
27840
  };
@@ -27486,9 +27883,15 @@ async function requireGatekeeperPass(options) {
27486
27883
  options.hostActions.failInfrastructure(error, options.context, options.toolCallId);
27487
27884
  }
27488
27885
  }
27489
- if (gatekeeper.status === "pass") return;
27886
+ if (gatekeeper.status === "pass") {
27887
+ return {
27888
+ officer: projected.officer,
27889
+ receipt: gatekeeper.receipt,
27890
+ ...typeof gatekeeper.runId === "string" && gatekeeper.runId.trim() !== "" ? { runId: gatekeeper.runId } : {}
27891
+ };
27892
+ }
27490
27893
  if (gatekeeper.status === "needs_reask") {
27491
- reask = OFFICER_CONCLUSION_REASK;
27894
+ reask = officerConclusionReask(projected.officer);
27492
27895
  continue;
27493
27896
  }
27494
27897
  if (gatekeeper.status === "transport_failure") {
@@ -27498,6 +27901,9 @@ async function requireGatekeeperPass(options) {
27498
27901
  });
27499
27902
  options.hostActions.failInfrastructure(failure2, options.context, options.toolCallId);
27500
27903
  }
27904
+ if (gatekeeper.status === "escalate" && options.subject.kind === "secretariat_verdict") {
27905
+ throw new GatekeeperDecisionError(gatekeeper);
27906
+ }
27501
27907
  options.hostActions.bindSubmissionNonPass(options.toolCallId, gatekeeper);
27502
27908
  throw new GatekeeperDecisionError(gatekeeper);
27503
27909
  }
@@ -27505,14 +27911,14 @@ async function requireGatekeeperPass(options) {
27505
27911
 
27506
27912
  // src/host-native-method.ts
27507
27913
  import { lstat as lstat7, mkdir as mkdir6, readlink, realpath as realpath8, symlink } from "node:fs/promises";
27508
- import { basename as basename10, dirname as dirname23, join as join41 } from "node:path";
27914
+ import { basename as basename10, dirname as dirname22, join as join41 } from "node:path";
27509
27915
  var HOST_METHOD_PLUGIN_NAME = "ak-methods";
27510
27916
  var packagedMethodsDir = (root) => join41(root, "resources", "methods");
27511
27917
  var packagedMethodPluginDir = (root) => join41(root, "dist", "method-host-plugin");
27512
27918
  function hostMethodSkills(methods) {
27513
27919
  return Object.freeze(methods.flatMap((method) => {
27514
27920
  if (method.kind !== "skill") return [];
27515
- const name = basename10(dirname23(method.path));
27921
+ const name = basename10(dirname22(method.path));
27516
27922
  return name ? [Object.freeze({ name })] : [];
27517
27923
  }));
27518
27924
  }
@@ -27549,7 +27955,7 @@ async function installWorkspaceMethodSkills(cwd, packageRoot) {
27549
27955
  } catch (error) {
27550
27956
  if (error.code !== "ENOENT") throw error;
27551
27957
  }
27552
- await mkdir6(dirname23(link), { recursive: true });
27958
+ await mkdir6(dirname22(link), { recursive: true });
27553
27959
  try {
27554
27960
  await symlink(target, link);
27555
27961
  } catch (error) {
@@ -27566,11 +27972,11 @@ init_role_activation_flags();
27566
27972
  init_submission_correctable_error();
27567
27973
  init_navigator_invocation_identity();
27568
27974
  async function listen(server, path) {
27569
- await new Promise((resolve22, reject) => {
27975
+ await new Promise((resolve21, reject) => {
27570
27976
  server.once("error", reject);
27571
27977
  server.listen(path, () => {
27572
27978
  server.off("error", reject);
27573
- resolve22();
27979
+ resolve21();
27574
27980
  });
27575
27981
  });
27576
27982
  }
@@ -27606,7 +28012,7 @@ async function prepareRoleEnvelope(options) {
27606
28012
  const runId = request.runDirectory.split("/").filter(Boolean).at(-1) ?? randomUUID9();
27607
28013
  await mkdir7(request.runDirectory, { recursive: true });
27608
28014
  let sessionFile = options.sessionFile ?? join42(request.runDirectory, "session", "session.jsonl");
27609
- await mkdir7(dirname24(sessionFile), { recursive: true });
28015
+ await mkdir7(dirname23(sessionFile), { recursive: true });
27610
28016
  if (request.continuation.kind !== "resume") {
27611
28017
  try {
27612
28018
  await writeFile12(
@@ -27656,7 +28062,7 @@ async function prepareRoleEnvelope(options) {
27656
28062
  getLeafEntry: () => sessionEntries.at(-1),
27657
28063
  getLeafId: () => runId,
27658
28064
  getEntries: () => sessionEntries,
27659
- getSessionDir: () => dirname24(sessionFile),
28065
+ getSessionDir: () => dirname23(sessionFile),
27660
28066
  getSessionFile: () => sessionFile,
27661
28067
  getHeader: () => ({ type: "session", id: runId }),
27662
28068
  setSessionFile(path) {
@@ -27720,17 +28126,26 @@ async function prepareRoleEnvelope(options) {
27720
28126
  getActiveTools() {
27721
28127
  return [...preferredTools];
27722
28128
  },
27723
- async requireGatekeeperPass(options2) {
27724
- await requireGatekeeperPass({
27725
- context: options2.context,
27726
- subject: options2.subject,
27727
- ...options2.signal === void 0 ? {} : { signal: options2.signal },
28129
+ async requireGatekeeperPass(gateOptions) {
28130
+ const packageRoot = typeof options.dependencies.packageRoot === "string" ? options.dependencies.packageRoot : void 0;
28131
+ return requireGatekeeperPass({
28132
+ context: gateOptions.context,
28133
+ subject: gateOptions.subject,
28134
+ ...gateOptions.signal === void 0 ? {} : { signal: gateOptions.signal },
27728
28135
  hostActions: {
27729
- failInfrastructure: (error, _context, toolCallId) => options2.hostActions.failInfrastructure(error, options2.context, toolCallId),
27730
- bindSubmissionNonPass: options2.hostActions.bindSubmissionNonPass
28136
+ failInfrastructure: (error, _context, toolCallId) => gateOptions.hostActions.failInfrastructure(error, gateOptions.context, toolCallId),
28137
+ bindSubmissionNonPass: gateOptions.hostActions.bindSubmissionNonPass
27731
28138
  },
27732
- toolCallId: options2.toolCallId,
27733
- ...options2.submission === void 0 ? {} : { submission: options2.submission }
28139
+ toolCallId: gateOptions.toolCallId,
28140
+ ...gateOptions.submission === void 0 ? {} : { submission: gateOptions.submission },
28141
+ // #969: package root + home reach nested 给事中/符宝郎 summons.
28142
+ // hostAdapters (when set on deps) forward nested seat selection — production unset.
28143
+ summonOfficer: createDefaultGateOfficerSummon({
28144
+ cwd: gateOptions.context.cwd ?? request.cwd,
28145
+ home: request.home,
28146
+ ...packageRoot === void 0 ? {} : { packageRoot },
28147
+ ...options.dependencies.hostAdapters === void 0 ? {} : { hostAdapters: options.dependencies.hostAdapters }
28148
+ })
27734
28149
  });
27735
28150
  },
27736
28151
  on(...registration) {
@@ -28003,8 +28418,8 @@ async function prepareRoleEnvelope(options) {
28003
28418
  try {
28004
28419
  const closeAll = server.closeAllConnections;
28005
28420
  if (typeof closeAll === "function") closeAll.call(server);
28006
- await new Promise((resolve22, reject) => {
28007
- server.close((error) => error ? reject(error) : resolve22());
28421
+ await new Promise((resolve21, reject) => {
28422
+ server.close((error) => error ? reject(error) : resolve21());
28008
28423
  });
28009
28424
  } catch (error) {
28010
28425
  cleanupFailures.push(error);
@@ -28410,7 +28825,7 @@ import { spawn as spawn4, spawnSync } from "node:child_process";
28410
28825
  import { randomUUID as randomUUID10 } from "node:crypto";
28411
28826
  import { existsSync as existsSync13 } from "node:fs";
28412
28827
  import { writeFile as writeFile13 } from "node:fs/promises";
28413
- import { dirname as dirname25, isAbsolute as isAbsolute11, join as join44, resolve as resolve21 } from "node:path";
28828
+ import { dirname as dirname24, isAbsolute as isAbsolute10, join as join44, resolve as resolve20 } from "node:path";
28414
28829
 
28415
28830
  // src/external-host-turn-loop.ts
28416
28831
  init_host_contracts();
@@ -28631,7 +29046,7 @@ function cwdIsGitWorkTree(cwd) {
28631
29046
  let dir = cwd;
28632
29047
  for (; ; ) {
28633
29048
  if (existsSync13(join44(dir, ".git"))) return true;
28634
- const parent = dirname25(dir);
29049
+ const parent = dirname24(dir);
28635
29050
  if (parent === dir) return false;
28636
29051
  dir = parent;
28637
29052
  }
@@ -28659,10 +29074,10 @@ function resolveGitCommonDir(cwd) {
28659
29074
  if (raw === "") {
28660
29075
  throw new Error("git rev-parse --git-common-dir returned empty stdout");
28661
29076
  }
28662
- return isAbsolute11(raw) ? raw : resolve21(cwd, raw);
29077
+ return isAbsolute10(raw) ? raw : resolve20(cwd, raw);
28663
29078
  }
28664
29079
  function spawnHeadlessTurn(options) {
28665
- return new Promise((resolve22, reject) => {
29080
+ return new Promise((resolve21, reject) => {
28666
29081
  if (options.signal?.aborted) {
28667
29082
  reject(hostAbortedError("headless host aborted"));
28668
29083
  return;
@@ -28737,7 +29152,7 @@ function spawnHeadlessTurn(options) {
28737
29152
  reject(stdinDeliveryError);
28738
29153
  return;
28739
29154
  }
28740
- resolve22({ code, stdout: resultStdout, stderr, timedOut });
29155
+ resolve21({ code, stdout: resultStdout, stderr, timedOut });
28741
29156
  };
28742
29157
  const onAbort = () => {
28743
29158
  child.kill("SIGTERM");