@akagilnc/pi-workflow-roles 0.1.4035 → 0.1.4193

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 (108) hide show
  1. package/dist/acp-host/production-host.js +2368 -1155
  2. package/dist/archivist-record-entry.js +204 -20
  3. package/dist/archivist-record-topology.js +36 -16
  4. package/dist/auditor-dossier-tool.js +2 -1
  5. package/dist/diarist-contracts.js +96 -0
  6. package/dist/doctor-auditor.js +1 -1
  7. package/dist/doctor-evidence.js +3 -2
  8. package/dist/dossier-resolution.js +21 -8
  9. package/dist/gatekeeper-role.js +34 -27
  10. package/dist/headless-host/description.js +7 -8
  11. package/dist/headless-host/production-host.js +2375 -1149
  12. package/dist/host-contracts.js +16 -0
  13. package/dist/inspector-contracts.js +8 -0
  14. package/dist/migrate-book-topology.js +278917 -0
  15. package/dist/navigator-public-session.js +22 -25
  16. package/dist/notary-source-run.js +7 -4
  17. package/dist/packaged-role-registry.js +1 -1
  18. package/dist/pi/durable-principal.js +9 -6
  19. package/dist/pi/role-turn-host.js +43 -13
  20. package/dist/public-cli/auto-resume.js +2 -5
  21. package/dist/public-cli/case-dossier-delivery.js +60 -1
  22. package/dist/public-cli/diarist-run.js +27 -25
  23. package/dist/public-cli/inspector-run.js +17 -3
  24. package/dist/public-cli/instruction-seat-run.js +17 -17
  25. package/dist/public-cli/invocation.js +127 -63
  26. package/dist/public-cli/main.js +1685 -696
  27. package/dist/public-cli/notary-run.js +7 -4
  28. package/dist/public-cli/option-definitions.js +2 -2
  29. package/dist/public-cli/post-admission.js +113 -71
  30. package/dist/public-cli/run-lifecycle.js +209 -58
  31. package/dist/public-cli/seat-ticket-binding.js +3 -6
  32. package/dist/public-cli/settlement.js +29 -10
  33. package/dist/public-role-summons.js +8 -0
  34. package/dist/role-run-placement.js +84 -0
  35. package/dist/role-run-relocation.js +358 -0
  36. package/dist/run-terminal-artifacts.js +2 -1
  37. package/dist/run-ticket-number.js +51 -32
  38. package/dist/sitian-appender.js +11 -26
  39. package/dist/submission-ledger.js +106 -25
  40. package/dist/ticket-provenance.js +3 -1
  41. package/dist/user-dialogue-stdin.js +33 -0
  42. package/extensions/role-runtime.ts +1 -0
  43. package/package.json +3 -2
  44. package/resources/836-deleted-machine-instruction-inventory.md +1 -1
  45. package/scripts/build-package.mjs +34 -2
  46. package/souls/fixer.md +3 -2
  47. package/src/analyst-ledger.ts +14 -15
  48. package/src/archivist-record-entry.ts +285 -38
  49. package/src/archivist-record-topology.ts +43 -18
  50. package/src/auditor-dossier-tool.ts +2 -1
  51. package/src/book-topology-migration-placement.ts +493 -0
  52. package/src/book-topology-migration.ts +220 -0
  53. package/src/book-topology-migrators-t11.ts +856 -0
  54. package/src/book-topology-mixed-volume-migrators.ts +470 -0
  55. package/src/book-topology-partition-migrators.ts +25 -0
  56. package/src/book-topology-record-class-migrators.ts +779 -0
  57. package/src/book-topology-runs-migrator.ts +244 -0
  58. package/src/diarist-contracts.ts +116 -0
  59. package/src/diarist-role.ts +6 -0
  60. package/src/diarist.ts +2 -0
  61. package/src/doctor-auditor.ts +1 -1
  62. package/src/doctor-evidence.ts +4 -1
  63. package/src/doctor-role.ts +1 -1
  64. package/src/dossier-resolution.ts +26 -8
  65. package/src/external-host-turn-loop.ts +9 -0
  66. package/src/gatekeeper-pass-envelope.ts +6 -0
  67. package/src/gatekeeper-role.ts +47 -28
  68. package/src/headless-host/description.ts +8 -11
  69. package/src/headless-host/role-turn-host.ts +20 -5
  70. package/src/host-contracts.ts +22 -3
  71. package/src/inspector-contracts.ts +7 -0
  72. package/src/judge-role.ts +4 -0
  73. package/src/navigator-public-session.ts +33 -30
  74. package/src/navigator-work-context.ts +3 -4
  75. package/src/notary-role.ts +1 -0
  76. package/src/notary-source-run.ts +9 -4
  77. package/src/packaged-role-registry.ts +1 -1
  78. package/src/pi/adapter.ts +19 -4
  79. package/src/pi/durable-principal.ts +9 -13
  80. package/src/pi/role-turn-host.ts +48 -14
  81. package/src/public-cli/auto-resume.ts +2 -6
  82. package/src/public-cli/case-dossier-delivery.ts +86 -1
  83. package/src/public-cli/countersign-run.ts +182 -32
  84. package/src/public-cli/diarist-run.ts +34 -26
  85. package/src/public-cli/inspector-run.ts +26 -2
  86. package/src/public-cli/instruction-seat-run.ts +24 -20
  87. package/src/public-cli/invocation.ts +194 -58
  88. package/src/public-cli/notary-run.ts +13 -4
  89. package/src/public-cli/option-definitions.ts +2 -2
  90. package/src/public-cli/post-admission.ts +147 -78
  91. package/src/public-cli/run-lifecycle.ts +258 -65
  92. package/src/public-cli/seat-ticket-binding.ts +3 -6
  93. package/src/public-cli/settlement.ts +38 -10
  94. package/src/public-role-summons.ts +31 -7
  95. package/src/role-envelope.ts +9 -30
  96. package/src/role-run-placement.ts +128 -0
  97. package/src/role-run-relocation.ts +491 -0
  98. package/src/role-runtime-dependencies.ts +1 -0
  99. package/src/role-runtime.ts +106 -24
  100. package/src/run-terminal-artifacts.ts +3 -1
  101. package/src/run-ticket-number.ts +80 -20
  102. package/src/sitian-appender.ts +25 -28
  103. package/src/submission-ledger.ts +148 -30
  104. package/src/ticket-provenance.ts +4 -1
  105. package/src/ticket-trajectory.ts +22 -35
  106. package/src/user-dialogue-stdin.ts +37 -0
  107. package/src/worker-role.ts +8 -4
  108. package/src/worker-submission-gates.ts +6 -6
@@ -377,6 +377,146 @@ var init_activation_ledger_topology = __esm({
377
377
  }
378
378
  });
379
379
 
380
+ // src/run-ticket-number.ts
381
+ import { readFile } from "node:fs/promises";
382
+ import { join as join3 } from "node:path";
383
+ function isEnoent(error) {
384
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
385
+ }
386
+ function isSafePositiveTicketNumber(value) {
387
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
388
+ }
389
+ function requireSafePositiveTicketNumber(ticketNumber, context = "ticketNumber") {
390
+ if (!isSafePositiveTicketNumber(ticketNumber)) {
391
+ throw new Error(
392
+ `${context} requires a safe positive integer, got ${String(ticketNumber)}`
393
+ );
394
+ }
395
+ return ticketNumber;
396
+ }
397
+ function ticketFromRecord(record4) {
398
+ return isSafePositiveTicketNumber(record4.ticketNumber) ? record4.ticketNumber : void 0;
399
+ }
400
+ async function readJsonObject(path) {
401
+ try {
402
+ const raw = JSON.parse(await readFile(path, "utf8"));
403
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
404
+ return void 0;
405
+ }
406
+ return raw;
407
+ } catch (error) {
408
+ if (isEnoent(error)) return void 0;
409
+ throw error;
410
+ }
411
+ }
412
+ async function readBoardPageTicketNumber(runDirectory, page) {
413
+ const record4 = await readJsonObject(join3(runDirectory, page));
414
+ if (record4 === void 0) return void 0;
415
+ return ticketFromRecord(record4);
416
+ }
417
+ async function readBoardTicketNumber(runDirectory) {
418
+ return await readBoardPageTicketNumber(runDirectory, "admitted-request.json") ?? await readBoardPageTicketNumber(runDirectory, "invocation.json");
419
+ }
420
+ async function readMigrationDerivedTicketNumber(runDirectory) {
421
+ const record4 = await readJsonObject(
422
+ join3(runDirectory, MIGRATION_TICKET_DERIVATION_PAGE)
423
+ );
424
+ if (record4 === void 0) return void 0;
425
+ if (record4.derivation !== "worktree-path-basename") return void 0;
426
+ return ticketFromRecord(record4);
427
+ }
428
+ async function readRunTicketNumber(runDirectory) {
429
+ return await readBoardTicketNumber(runDirectory) ?? await readMigrationDerivedTicketNumber(runDirectory);
430
+ }
431
+ var MIGRATION_TICKET_DERIVATION_PAGE;
432
+ var init_run_ticket_number = __esm({
433
+ "src/run-ticket-number.ts"() {
434
+ "use strict";
435
+ MIGRATION_TICKET_DERIVATION_PAGE = "migration-ticket-derivation.json";
436
+ }
437
+ });
438
+
439
+ // src/role-run-placement.ts
440
+ import { readdir } from "node:fs/promises";
441
+ import { join as join4 } from "node:path";
442
+ function isMissingPathError(error) {
443
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
444
+ }
445
+ async function listBookRunDirectories(bookDir) {
446
+ const out = [];
447
+ const seen = /* @__PURE__ */ new Set();
448
+ const collect = async (runsDir) => {
449
+ let entries;
450
+ try {
451
+ entries = await readdir(runsDir, { withFileTypes: true });
452
+ } catch (error) {
453
+ if (isMissingPathError(error)) return;
454
+ throw error;
455
+ }
456
+ for (const entry of entries) {
457
+ if (!entry.isDirectory()) continue;
458
+ const runDir = join4(runsDir, entry.name);
459
+ if (seen.has(runDir)) continue;
460
+ seen.add(runDir);
461
+ out.push(runDir);
462
+ }
463
+ };
464
+ await collect(join4(bookDir, "runs"));
465
+ let subjects;
466
+ try {
467
+ subjects = await readdir(bookDir, { withFileTypes: true });
468
+ } catch (error) {
469
+ if (isMissingPathError(error)) return out.sort();
470
+ throw error;
471
+ }
472
+ for (const subject of subjects) {
473
+ if (!subject.isDirectory() || subject.name === "runs") continue;
474
+ await collect(join4(bookDir, subject.name, "runs"));
475
+ }
476
+ return out.sort();
477
+ }
478
+ function roleRunPlacement(ledgerHome, input) {
479
+ const subjectDirectory = "ticketNumber" in input.subject ? String(requireSafePositiveTicketNumber(
480
+ input.subject.ticketNumber,
481
+ "roleRunPlacement subject.ticketNumber"
482
+ )) : "unbound";
483
+ const runDirectory = join4(
484
+ activationBookDirectory(ledgerHome, input.bookKey),
485
+ subjectDirectory,
486
+ "runs",
487
+ `${input.runId}@${input.role}`
488
+ );
489
+ const sessionDirectory = join4(runDirectory, "session");
490
+ return {
491
+ runDirectory,
492
+ sessionDirectory,
493
+ sessionFile: join4(sessionDirectory, "session.jsonl"),
494
+ artifactsDirectory: roleRunArtifactsDirectory(runDirectory),
495
+ attachmentsDirectory: join4(runDirectory, "attachments")
496
+ };
497
+ }
498
+ function roleRunArtifactsDirectory(runDirectory) {
499
+ return join4(runDirectory, "artifacts");
500
+ }
501
+ function ensureRoleRunDirectory(ledgerHome, directory) {
502
+ return ensureRealDirectoryTree(ledgerHome, directory);
503
+ }
504
+ function ensureRoleRunPlacement(ledgerHome, placement) {
505
+ for (const directory of [
506
+ placement.sessionDirectory,
507
+ placement.attachmentsDirectory
508
+ ]) {
509
+ ensureRoleRunDirectory(ledgerHome, directory);
510
+ }
511
+ }
512
+ var init_role_run_placement = __esm({
513
+ "src/role-run-placement.ts"() {
514
+ "use strict";
515
+ init_activation_ledger_topology();
516
+ init_run_ticket_number();
517
+ }
518
+ });
519
+
380
520
  // src/pi/durable-principal.ts
381
521
  var durable_principal_exports = {};
382
522
  __export(durable_principal_exports, {
@@ -384,25 +524,23 @@ __export(durable_principal_exports, {
384
524
  piDurablePrincipalAuthority: () => piDurablePrincipalAuthority
385
525
  });
386
526
  import { lstat } from "node:fs/promises";
387
- import { join as join3 } from "node:path";
527
+ import { join as join5 } from "node:path";
388
528
  function encode(coordinates) {
389
529
  return coordinates;
390
530
  }
391
531
  function issuePiDurablePrincipalCoordinates(request) {
392
532
  const ledgerHome = resolveActivationLedgerHome(request.home);
393
533
  const bookKey = resolveBookKeyFromGit(request.cwd);
394
- const runDirectory = join3(
395
- activationBookDirectory(ledgerHome, bookKey),
396
- "runs",
397
- `${request.runId}@${request.role}`
398
- );
399
- const sessionDirectory = join3(runDirectory, "session");
534
+ const placement = roleRunPlacement(ledgerHome, {
535
+ bookKey,
536
+ subject: { unbound: true },
537
+ runId: request.runId,
538
+ role: request.role
539
+ });
400
540
  return {
401
541
  ledgerHome,
402
542
  bookKey,
403
- runDirectory,
404
- sessionDirectory,
405
- sessionFile: join3(sessionDirectory, "session.jsonl")
543
+ ...placement
406
544
  };
407
545
  }
408
546
  var piDurablePrincipalAuthority;
@@ -411,6 +549,7 @@ var init_durable_principal = __esm({
411
549
  "use strict";
412
550
  init_activation_ledger_git();
413
551
  init_activation_ledger_topology();
552
+ init_role_run_placement();
414
553
  piDurablePrincipalAuthority = {
415
554
  issue(request) {
416
555
  const coordinates = issuePiDurablePrincipalCoordinates(request);
@@ -435,7 +574,7 @@ var init_durable_principal = __esm({
435
574
  }
436
575
  return {
437
576
  sessionDirectory: record4.sessionDirectory,
438
- sessionFile: typeof record4.sessionFile === "string" && record4.sessionFile.trim() !== "" ? record4.sessionFile : join3(record4.sessionDirectory, "session.jsonl")
577
+ sessionFile: typeof record4.sessionFile === "string" && record4.sessionFile.trim() !== "" ? record4.sessionFile : join5(record4.sessionDirectory, "session.jsonl")
439
578
  };
440
579
  },
441
580
  async isAvailable(principal) {
@@ -453,7 +592,7 @@ var init_durable_principal = __esm({
453
592
 
454
593
  // src/package-resources/engine-material.ts
455
594
  import { existsSync as existsSync2, readdirSync } from "node:fs";
456
- import { join as join4 } from "node:path";
595
+ import { join as join6 } from "node:path";
457
596
  function pickEngineAxis(source) {
458
597
  return {
459
598
  ...source.engine === void 0 ? {} : { engine: source.engine },
@@ -474,11 +613,11 @@ function isEngineNameSyntax(name) {
474
613
  return true;
475
614
  }
476
615
  function resolveEngineMaterialDirectory(packageRoot2) {
477
- return join4(packageRoot2, ENGINE_MATERIAL_RELATIVE_ROOT);
616
+ return join6(packageRoot2, ENGINE_MATERIAL_RELATIVE_ROOT);
478
617
  }
479
618
  function resolveEngineMaterialPath(packageRoot2, name) {
480
619
  const legal = assertLegalEngineName(name);
481
- return join4(resolveEngineMaterialDirectory(packageRoot2), `${legal}.md`);
620
+ return join6(resolveEngineMaterialDirectory(packageRoot2), `${legal}.md`);
482
621
  }
483
622
  function assertLegalEngineName(name) {
484
623
  if (!isEngineNameSyntax(name)) {
@@ -14710,10 +14849,84 @@ var init_auditor_output = __esm({
14710
14849
  });
14711
14850
 
14712
14851
  // src/diarist-contracts.ts
14852
+ function projectCourtTicketNumbers(raw, options) {
14853
+ if (!Array.isArray(raw)) return null;
14854
+ const out = [];
14855
+ const seen = /* @__PURE__ */ new Set();
14856
+ for (const item of raw) {
14857
+ if (!isSafePositiveTicketNumber(item)) continue;
14858
+ if (seen.has(item)) continue;
14859
+ seen.add(item);
14860
+ out.push(item);
14861
+ }
14862
+ const principal = options?.principalTicket;
14863
+ if (principal === void 0) return out;
14864
+ requireSafePositiveTicketNumber(principal, "projectCourtTicketNumbers principalTicket");
14865
+ if (seen.has(principal)) return out;
14866
+ return [principal, ...out];
14867
+ }
14868
+ function interpretDurableCourtTicketNumbers(record4, options) {
14869
+ if (!Object.hasOwn(record4, "courtTicketNumbers")) {
14870
+ return { kind: "absent" };
14871
+ }
14872
+ const raw = record4.courtTicketNumbers;
14873
+ if (!Array.isArray(raw)) {
14874
+ return {
14875
+ kind: "damage",
14876
+ reason: "courtTicketNumbers is present but not an array"
14877
+ };
14878
+ }
14879
+ if (raw.length === 0) {
14880
+ return {
14881
+ kind: "damage",
14882
+ reason: "courtTicketNumbers is present but empty"
14883
+ };
14884
+ }
14885
+ for (let i = 0; i < raw.length; i += 1) {
14886
+ const item = raw[i];
14887
+ if (!isSafePositiveTicketNumber(item)) {
14888
+ return {
14889
+ kind: "damage",
14890
+ reason: `courtTicketNumbers[${i}] is not a safe positive integer`
14891
+ };
14892
+ }
14893
+ }
14894
+ const tickets = projectCourtTicketNumbers(raw);
14895
+ if (tickets === null || tickets.length === 0) {
14896
+ return {
14897
+ kind: "damage",
14898
+ reason: "courtTicketNumbers projected empty after lawful members"
14899
+ };
14900
+ }
14901
+ const principal = options?.principalTicket;
14902
+ if (principal !== void 0) {
14903
+ if (!isSafePositiveTicketNumber(principal)) {
14904
+ return {
14905
+ kind: "damage",
14906
+ reason: "courtTicketNumbers principal ticket is not a safe positive integer"
14907
+ };
14908
+ }
14909
+ if (!tickets.includes(principal)) {
14910
+ return {
14911
+ kind: "damage",
14912
+ reason: `courtTicketNumbers is missing principal ticket #${principal}`
14913
+ };
14914
+ }
14915
+ }
14916
+ return { kind: "ok", tickets: Object.freeze([...tickets]) };
14917
+ }
14918
+ function sameCourtTicketNumbers(left, right) {
14919
+ if (left.length !== right.length) return false;
14920
+ for (let i = 0; i < left.length; i += 1) {
14921
+ if (left[i] !== right[i]) return false;
14922
+ }
14923
+ return true;
14924
+ }
14713
14925
  var DIARIST_OUTPUT_TOOL_NAME;
14714
14926
  var init_diarist_contracts = __esm({
14715
14927
  "src/diarist-contracts.ts"() {
14716
14928
  "use strict";
14929
+ init_run_ticket_number();
14717
14930
  DIARIST_OUTPUT_TOOL_NAME = "ak_diarist_output";
14718
14931
  }
14719
14932
  });
@@ -14892,7 +15105,7 @@ var init_packaged_role_registry = __esm({
14892
15105
  role: "inspector",
14893
15106
  phases: [null],
14894
15107
  outputTool: INSPECTOR_OUTPUT_TOOL_NAME,
14895
- inputFlag: void 0,
15108
+ inputFlag: "ak-inspector-source-run",
14896
15109
  phaseFlag: void 0,
14897
15110
  activationStage: "load-and-install",
14898
15111
  sessionMaterials: INSPECTOR_SESSION_MATERIALS
@@ -15229,8 +15442,8 @@ __export(config_exports, {
15229
15442
  setPersistentSeatHost: () => setPersistentSeatHost,
15230
15443
  validatePublicCliConfigAxes: () => validatePublicCliConfigAxes
15231
15444
  });
15232
- import { mkdir, readFile, writeFile } from "node:fs/promises";
15233
- import { dirname as dirname4, join as join5 } from "node:path";
15445
+ import { mkdir, readFile as readFile2, writeFile } from "node:fs/promises";
15446
+ import { dirname as dirname4, join as join7 } from "node:path";
15234
15447
  function isGateOfficerSeat(value) {
15235
15448
  return GATE_OFFICER_SEATS.includes(value);
15236
15449
  }
@@ -15238,12 +15451,12 @@ function publicCliConfigPath(home) {
15238
15451
  if (typeof home !== "string" || home.trim() === "") {
15239
15452
  throw new Error("home must be explicitly provided");
15240
15453
  }
15241
- return join5(home, ".ak-roles", "public-cli.json");
15454
+ return join7(home, ".ak-roles", "public-cli.json");
15242
15455
  }
15243
15456
  async function loadPublicCliConfig(home) {
15244
15457
  const path = publicCliConfigPath(home);
15245
15458
  try {
15246
- const raw = await readFile(path, "utf8");
15459
+ const raw = await readFile2(path, "utf8");
15247
15460
  return parsePublicCliConfig(JSON.parse(raw));
15248
15461
  } catch (error) {
15249
15462
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -15706,7 +15919,7 @@ function credentialProvidersFromAuthData(data) {
15706
15919
  }
15707
15920
  async function loadCredentialProviders(agentDir) {
15708
15921
  try {
15709
- const raw = await readFile(join5(agentDir, "auth.json"), "utf8");
15922
+ const raw = await readFile2(join7(agentDir, "auth.json"), "utf8");
15710
15923
  return credentialProvidersFromAuthData(JSON.parse(raw));
15711
15924
  } catch (error) {
15712
15925
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -15745,15 +15958,15 @@ __export(host_providers_exports, {
15745
15958
  renderHostProvidersTable: () => renderHostProvidersTable
15746
15959
  });
15747
15960
  import { readFileSync } from "node:fs";
15748
- import { join as join6 } from "node:path";
15961
+ import { join as join8 } from "node:path";
15749
15962
  function hostProvidersPath(home) {
15750
15963
  if (typeof home !== "string" || home.trim() === "") {
15751
15964
  throw new Error("home must be explicitly provided");
15752
15965
  }
15753
- return join6(home, ".ak-roles", "host-providers.json");
15966
+ return join8(home, ".ak-roles", "host-providers.json");
15754
15967
  }
15755
15968
  function hermesProviderModelsCachePath(home) {
15756
- return join6(home, ".hermes", "provider_models_cache.json");
15969
+ return join8(home, ".hermes", "provider_models_cache.json");
15757
15970
  }
15758
15971
  function parseHostProvidersTable(value) {
15759
15972
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -15926,6 +16139,9 @@ var init_cli_errors = __esm({
15926
16139
  });
15927
16140
 
15928
16141
  // src/host-contracts.ts
16142
+ function isOfficerReviewSeat(role) {
16143
+ return role === "notary" || role === "inspector" || role === "auditor";
16144
+ }
15929
16145
  var ExplicitInternalActivationError;
15930
16146
  var init_host_contracts = __esm({
15931
16147
  "src/host-contracts.ts"() {
@@ -15963,12 +16179,13 @@ function applyEngineChildEnv(childEnv, engine) {
15963
16179
  childEnv[AK_ROLE_ENGINE_ENV] = void 0;
15964
16180
  }
15965
16181
  }
15966
- var ENGINE_DETOUR_TOOL_NAME, AK_ROLE_ENGINE_ENV;
16182
+ var ENGINE_DETOUR_TOOL_NAME, AK_ROLE_ENGINE_ENV, ENGINE_MODEL_FLAG_NAME;
15967
16183
  var init_engine_detour = __esm({
15968
16184
  "src/engine-detour.ts"() {
15969
16185
  "use strict";
15970
16186
  ENGINE_DETOUR_TOOL_NAME = "ak_engine_detour";
15971
16187
  AK_ROLE_ENGINE_ENV = "AK_ROLE_ENGINE";
16188
+ ENGINE_MODEL_FLAG_NAME = "ak-engine-model";
15972
16189
  }
15973
16190
  });
15974
16191
 
@@ -16019,6 +16236,18 @@ var init_role_activation_flags = __esm({
16019
16236
  }
16020
16237
  });
16021
16238
 
16239
+ // src/user-dialogue-stdin.ts
16240
+ function encodeUserDialogueStdin(body) {
16241
+ return JSON.stringify({ kind: USER_DIALOGUE_STDIN_KIND, body });
16242
+ }
16243
+ var USER_DIALOGUE_STDIN_KIND;
16244
+ var init_user_dialogue_stdin = __esm({
16245
+ "src/user-dialogue-stdin.ts"() {
16246
+ "use strict";
16247
+ USER_DIALOGUE_STDIN_KIND = "ak-user-dialogue";
16248
+ }
16249
+ });
16250
+
16022
16251
  // src/sitian-contracts.ts
16023
16252
  function attachDirectErrnoCode(error, cause) {
16024
16253
  if (cause === null || typeof cause !== "object" || !("code" in cause)) return;
@@ -16049,7 +16278,7 @@ import {
16049
16278
  unlinkSync,
16050
16279
  writeFileSync
16051
16280
  } from "node:fs";
16052
- import { basename as basename3, dirname as dirname5, join as join7, resolve as resolve3 } from "node:path";
16281
+ import { dirname as dirname5, join as join9 } from "node:path";
16053
16282
  function isRecord(value) {
16054
16283
  return typeof value === "object" && value !== null && !Array.isArray(value);
16055
16284
  }
@@ -16176,38 +16405,23 @@ function resolveSitianVolumeCategory(kind) {
16176
16405
  }
16177
16406
  return kind;
16178
16407
  }
16179
- function safeBookKey(cwd) {
16180
- try {
16181
- return resolveBookKeyFromGit(cwd);
16182
- } catch {
16183
- return basename3(resolve3(cwd)) || "default";
16184
- }
16185
- }
16186
16408
  function resolveSitianRecordPathInLedger(input, ledgerHome) {
16187
- const cwd = input.cwd ?? process.cwd();
16188
16409
  const category = resolveSitianVolumeCategory(input.kind);
16410
+ const ticketNumber = category === "ticket-provenance" ? typeof input.subject === "string" && /^[1-9][0-9]*$/.test(input.subject) ? input.subject : typeof input.subject === "object" && typeof input.subject.ticketNumber === "number" && Number.isSafeInteger(input.subject.ticketNumber) && input.subject.ticketNumber > 0 ? String(input.subject.ticketNumber) : void 0 : void 0;
16189
16411
  let sessionDir;
16190
- if (input.sessionParent !== void 0 && input.sessionParent.length > 0 && physicallyContainedIn(ledgerHome, input.sessionParent)) {
16191
- sessionDir = join7(dirname5(input.sessionParent), category);
16412
+ if (ticketNumber !== void 0) {
16413
+ const bookDir = activationBookDirectory(
16414
+ ledgerHome,
16415
+ resolveBookKeyFromGit(input.cwd ?? process.cwd())
16416
+ );
16417
+ sessionDir = join9(bookDir, ticketNumber);
16192
16418
  } else {
16193
- const bookKey = safeBookKey(cwd);
16194
- const bookDir = activationBookDirectory(ledgerHome, bookKey);
16195
- if (input.subject !== void 0) {
16196
- let subjectStr;
16197
- if (typeof input.subject === "string") {
16198
- subjectStr = input.subject;
16199
- } else if (typeof input.subject.runId === "string" && input.subject.runId.length > 0) {
16200
- subjectStr = input.subject.runId;
16201
- } else {
16202
- subjectStr = JSON.stringify(input.subject);
16203
- }
16204
- const digest = createHash("sha256").update(subjectStr).digest("hex").slice(0, 32);
16205
- sessionDir = join7(bookDir, category, digest);
16206
- } else {
16207
- sessionDir = join7(bookDir, category);
16419
+ if (input.sessionParent === void 0 || input.sessionParent.length === 0 || !physicallyContainedIn(ledgerHome, input.sessionParent)) {
16420
+ throw new Error("Sitian record ownership requires a parent session inside the ledger home");
16208
16421
  }
16422
+ sessionDir = join9(dirname5(input.sessionParent), category);
16209
16423
  }
16210
- const recordFile = join7(sessionDir, "records.jsonl");
16424
+ const recordFile = join9(sessionDir, "records.jsonl");
16211
16425
  return { sessionDir, recordFile, ledgerHome };
16212
16426
  }
16213
16427
  function resolveSitianRecordPath(input) {
@@ -16265,7 +16479,7 @@ var init_sitian_appender = __esm({
16265
16479
 
16266
16480
  // src/sitian-reader.ts
16267
16481
  import { existsSync as existsSync4 } from "node:fs";
16268
- import { readFile as readFile2 } from "node:fs/promises";
16482
+ import { readFile as readFile3 } from "node:fs/promises";
16269
16483
  function isRecord2(value) {
16270
16484
  return typeof value === "object" && value !== null && !Array.isArray(value);
16271
16485
  }
@@ -16273,7 +16487,7 @@ async function readSitianRecords(recordFile) {
16273
16487
  if (!existsSync4(recordFile)) {
16274
16488
  return { records: [], diagnostics: [] };
16275
16489
  }
16276
- const text = await readFile2(recordFile, "utf8");
16490
+ const text = await readFile3(recordFile, "utf8");
16277
16491
  const lines = text.split("\n");
16278
16492
  const records = [];
16279
16493
  const diagnostics = [];
@@ -16338,13 +16552,13 @@ __export(role_turn_host_exports, {
16338
16552
  });
16339
16553
  import { execFile, spawn } from "node:child_process";
16340
16554
  import { constants } from "node:fs";
16341
- import { access, appendFile, readFile as readFile3, realpath } from "node:fs/promises";
16342
- import { basename as basename4, delimiter as delimiter2, dirname as dirname6, isAbsolute as isAbsolute3, join as join8, resolve as resolve4 } from "node:path";
16555
+ import { access, appendFile, readFile as readFile4, realpath } from "node:fs/promises";
16556
+ import { basename as basename3, delimiter as delimiter2, dirname as dirname6, isAbsolute as isAbsolute3, join as join10, resolve as resolve3 } from "node:path";
16343
16557
  import { platform } from "node:process";
16344
16558
  import { promisify } from "node:util";
16345
16559
  import { randomUUID as randomUUID2 } from "node:crypto";
16346
16560
  function resolveInternalRoleEntrypoint(packageRoot2) {
16347
- return join8(packageRoot2, INTERNAL_ROLE_ENTRYPOINT_RELATIVE2);
16561
+ return join10(packageRoot2, INTERNAL_ROLE_ENTRYPOINT_RELATIVE2);
16348
16562
  }
16349
16563
  function buildExplicitInternalActivationArgs(selectedRoleEntry, extraArgs = []) {
16350
16564
  return ["--no-extensions", "-e", selectedRoleEntry, ...extraArgs];
@@ -16380,7 +16594,7 @@ function buildMethodArgs(methods) {
16380
16594
  function applyPiNativeSkillInvocation(methods, prompt) {
16381
16595
  const skills = methods.filter((method) => method.kind === "skill");
16382
16596
  if (skills.length !== 1) return prompt;
16383
- const name = basename4(dirname6(skills[0].path));
16597
+ const name = basename3(dirname6(skills[0].path));
16384
16598
  if (name.length === 0) return prompt;
16385
16599
  const token = `/skill:${name}`;
16386
16600
  const trimmed = prompt.trimStart();
@@ -16392,11 +16606,6 @@ function applyPiNativeSkillInvocation(methods, prompt) {
16392
16606
  }
16393
16607
  function buildPiTurnExtraArgs(request, authority, extraPiArgs = []) {
16394
16608
  const { sessionFile, sessionDirectory } = authority.decode(request.principal);
16395
- const rawPrompt = request.continuation.kind === "initial" || request.continuation.kind === "resume" ? request.continuation.prompt : (() => {
16396
- const _exhaustive = request.continuation;
16397
- return _exhaustive;
16398
- })();
16399
- const prompt = applyPiNativeSkillInvocation(request.methods, rawPrompt);
16400
16609
  return [
16401
16610
  "--no-skills",
16402
16611
  ...buildMethodArgs(request.methods),
@@ -16410,15 +16619,27 @@ function buildPiTurnExtraArgs(request, authority, extraPiArgs = []) {
16410
16619
  ...extraPiArgs,
16411
16620
  // Envelope assembly = projectActivationFlags; pi only renders argv pairs.
16412
16621
  ...activationFlagsToPiArgv(projectActivationFlags(request)),
16622
+ ...piEngineModelArgs(request),
16413
16623
  "--mode",
16414
16624
  "json",
16415
- ...buildSeatModelCliArgs2(request.model),
16416
- prompt
16625
+ ...buildSeatModelCliArgs2(request.model)
16417
16626
  ];
16418
16627
  }
16628
+ function piEngineModelArgs(request) {
16629
+ const model = normalizeEngineName(request.engineModel);
16630
+ if (model === void 0) return [];
16631
+ return [`--${ENGINE_MODEL_FLAG_NAME}`, model];
16632
+ }
16633
+ function piUserDialogueBody(request) {
16634
+ const rawPrompt = request.continuation.kind === "initial" || request.continuation.kind === "resume" ? request.continuation.prompt : (() => {
16635
+ const _exhaustive = request.continuation;
16636
+ return _exhaustive;
16637
+ })();
16638
+ return applyPiNativeSkillInvocation(request.methods, rawPrompt);
16639
+ }
16419
16640
  async function resolveSelectedPi(command, cwd, env) {
16420
16641
  const searchPath = env.PATH ?? (platform === "win32" ? process.env.PATH ?? "" : "/usr/bin:/bin");
16421
- const candidates = isAbsolute3(command) || command.includes("/") ? [resolve4(cwd, command)] : searchPath.split(delimiter2).map((dir) => resolve4(cwd, dir, command));
16642
+ const candidates = isAbsolute3(command) || command.includes("/") ? [resolve3(cwd, command)] : searchPath.split(delimiter2).map((dir) => resolve3(cwd, dir, command));
16422
16643
  for (const candidate of candidates) {
16423
16644
  try {
16424
16645
  await access(candidate, constants.X_OK);
@@ -16455,11 +16676,22 @@ function createDefaultPiSpawnRunner(options) {
16455
16676
  const child = spawn(piIdentity.executable, [...args], {
16456
16677
  cwd: spawnOptions.cwd,
16457
16678
  env: spawnOptions.env,
16458
- stdio: ["ignore", "ignore", "pipe"]
16679
+ stdio: ["pipe", "ignore", "pipe"]
16459
16680
  });
16681
+ if (child.stdin === null) {
16682
+ throw new Error("Pi child stdin pipe was not created");
16683
+ }
16460
16684
  if (child.stderr === null) {
16461
16685
  throw new Error("Pi child stderr pipe was not created");
16462
16686
  }
16687
+ let stdinDeliveryError;
16688
+ child.stdin.on("error", (error) => {
16689
+ stdinDeliveryError ??= error;
16690
+ });
16691
+ if (spawnOptions.stdin !== void 0) {
16692
+ child.stdin.write(spawnOptions.stdin);
16693
+ }
16694
+ child.stdin.end();
16463
16695
  let stderr = "";
16464
16696
  let timedOut = false;
16465
16697
  let timer;
@@ -16512,6 +16744,10 @@ function createDefaultPiSpawnRunner(options) {
16512
16744
  reject(executionError);
16513
16745
  return;
16514
16746
  }
16747
+ if (stdinDeliveryError !== void 0) {
16748
+ reject(stdinDeliveryError);
16749
+ return;
16750
+ }
16515
16751
  resolveResult({
16516
16752
  code,
16517
16753
  stderr,
@@ -16535,7 +16771,8 @@ function createPiRoleTurnHost(config) {
16535
16771
  return {
16536
16772
  async executeTurn(request) {
16537
16773
  let turnRequest = request;
16538
- const paths = request.hostTransition?.priorNativeKind === "sitian" ? request.hostTransition.priorNativePaths : void 0;
16774
+ const officerStationChild = request.stationChild === true && isOfficerReviewSeat(request.activation.role);
16775
+ const paths = !officerStationChild && request.hostTransition?.priorNativeKind === "sitian" ? request.hostTransition.priorNativePaths : void 0;
16539
16776
  if (request.continuation.kind === "resume" && paths !== void 0 && paths.length > 0) {
16540
16777
  turnRequest = {
16541
16778
  ...request,
@@ -16553,6 +16790,7 @@ ${paths.join("\n")}`
16553
16790
  config.extraPiArgs ?? []
16554
16791
  );
16555
16792
  const args = buildExplicitInternalActivationArgs(roleEntry, extraArgs);
16793
+ const stdin = encodeUserDialogueStdin(piUserDialogueBody(turnRequest));
16556
16794
  const env = {
16557
16795
  ...process.env,
16558
16796
  HOME: request.home,
@@ -16584,6 +16822,7 @@ ${paths.join("\n")}`
16584
16822
  return await spawnRunner(args, {
16585
16823
  cwd: request.cwd,
16586
16824
  env,
16825
+ stdin,
16587
16826
  ...timeoutMs === void 0 ? {} : { timeoutMs },
16588
16827
  ...request.signal === void 0 ? {} : { signal: request.signal }
16589
16828
  });
@@ -16592,7 +16831,7 @@ ${paths.join("\n")}`
16592
16831
  }
16593
16832
  async function appendPiSessionCustomEntry(authority, principal, customType, data) {
16594
16833
  const { sessionFile } = authority.decode(principal);
16595
- const text = await readFile3(sessionFile, "utf8");
16834
+ const text = await readFile4(sessionFile, "utf8");
16596
16835
  let parentId = null;
16597
16836
  for (const line2 of text.trim().split("\n").filter(Boolean)) {
16598
16837
  const entry = JSON.parse(line2);
@@ -16627,6 +16866,7 @@ var init_role_turn_host = __esm({
16627
16866
  init_host_contracts();
16628
16867
  init_engine_detour();
16629
16868
  init_role_activation_flags();
16869
+ init_user_dialogue_stdin();
16630
16870
  init_sitian_facade();
16631
16871
  INTERNAL_ROLE_ENTRYPOINT_RELATIVE2 = "extensions/role-runtime.ts";
16632
16872
  EXPLICIT_INTERNAL_LOAD_PROBE_ARGS = [
@@ -16641,37 +16881,423 @@ var init_role_turn_host = __esm({
16641
16881
  }
16642
16882
  });
16643
16883
 
16644
- // src/run-ticket-number.ts
16645
- import { readFile as readFile4 } from "node:fs/promises";
16646
- import { join as join9 } from "node:path";
16647
- function isEnoent(error) {
16884
+ // src/auditor-dossier-tool.ts
16885
+ var init_auditor_dossier_tool = __esm({
16886
+ "src/auditor-dossier-tool.ts"() {
16887
+ "use strict";
16888
+ init_role_run_placement();
16889
+ init_build();
16890
+ }
16891
+ });
16892
+
16893
+ // src/readable-gate-item.ts
16894
+ var readable_gate_item_exports = {};
16895
+ __export(readable_gate_item_exports, {
16896
+ joinReadableGateItems: () => joinReadableGateItems,
16897
+ readableGateItem: () => readableGateItem
16898
+ });
16899
+ function readableGateItem(value) {
16900
+ return typeof value === "string" ? value : JSON.stringify(value);
16901
+ }
16902
+ function joinReadableGateItems(items, separator = "; ") {
16903
+ return items.map(readableGateItem).join(separator);
16904
+ }
16905
+ var init_readable_gate_item = __esm({
16906
+ "src/readable-gate-item.ts"() {
16907
+ "use strict";
16908
+ }
16909
+ });
16910
+
16911
+ // src/submission-errors.ts
16912
+ var init_submission_errors = __esm({
16913
+ "src/submission-errors.ts"() {
16914
+ "use strict";
16915
+ init_readable_gate_item();
16916
+ }
16917
+ });
16918
+
16919
+ // src/gatekeeper-role.ts
16920
+ var init_gatekeeper_role = __esm({
16921
+ "src/gatekeeper-role.ts"() {
16922
+ "use strict";
16923
+ init_auditor_dossier_tool();
16924
+ init_submission_errors();
16925
+ init_inspector_contracts();
16926
+ init_gatekeeper_output();
16927
+ init_submission_errors();
16928
+ }
16929
+ });
16930
+
16931
+ // src/compliance-transport.ts
16932
+ var AUDITOR_PARENT_ATTEMPT_BINDING_ENTRY_TYPE, AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE;
16933
+ var init_compliance_transport = __esm({
16934
+ "src/compliance-transport.ts"() {
16935
+ "use strict";
16936
+ init_auditor_dossier_tool();
16937
+ init_gatekeeper_role();
16938
+ AUDITOR_PARENT_ATTEMPT_BINDING_ENTRY_TYPE = "ak_auditor_parent_attempt_binding";
16939
+ AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE = "ak_auditor_compliance_failure";
16940
+ }
16941
+ });
16942
+
16943
+ // src/role-run-relocation.ts
16944
+ import { existsSync as existsSync5 } from "node:fs";
16945
+ import { readdir as readdir2, readFile as readFile5, writeFile as writeFile2 } from "node:fs/promises";
16946
+ import { join as join11, sep as sep2 } from "node:path";
16947
+ function isEnoent2(error) {
16648
16948
  return error instanceof Error && "code" in error && error.code === "ENOENT";
16649
16949
  }
16650
- function ticketFromRecord(record4) {
16651
- const ticketNumber = record4.ticketNumber;
16652
- if (typeof ticketNumber === "number" && Number.isSafeInteger(ticketNumber) && ticketNumber >= 1) {
16653
- return ticketNumber;
16950
+ function rewriteRunDirectoryPathValue(value, oldRunDirectory, newRunDirectory) {
16951
+ if (typeof value !== "string") return value;
16952
+ if (value === oldRunDirectory) return newRunDirectory;
16953
+ const prefix = `${oldRunDirectory}${sep2}`;
16954
+ if (value.startsWith(prefix)) {
16955
+ return `${newRunDirectory}${value.slice(oldRunDirectory.length)}`;
16654
16956
  }
16655
- return void 0;
16957
+ return value;
16656
16958
  }
16657
- async function readPageTicketNumber(runDirectory, page) {
16658
- try {
16659
- const raw = JSON.parse(await readFile4(join9(runDirectory, page), "utf8"));
16660
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
16661
- return void 0;
16959
+ function rewriteRunDirectoryPathValueAgainstRewrites(value, rewrites) {
16960
+ if (typeof value !== "string" || rewrites.length === 0) return value;
16961
+ let best;
16962
+ for (const rewrite of rewrites) {
16963
+ if (value === rewrite.oldRunDirectory || value.startsWith(`${rewrite.oldRunDirectory}${sep2}`)) {
16964
+ if (best === void 0 || rewrite.oldRunDirectory.length > best.oldRunDirectory.length) {
16965
+ best = rewrite;
16966
+ }
16662
16967
  }
16663
- return ticketFromRecord(raw);
16664
- } catch (error) {
16665
- if (isEnoent(error)) return void 0;
16666
- throw error;
16667
16968
  }
16969
+ if (best === void 0) return value;
16970
+ return rewriteRunDirectoryPathValue(
16971
+ value,
16972
+ best.oldRunDirectory,
16973
+ best.newRunDirectory
16974
+ );
16668
16975
  }
16669
- async function readRunTicketNumber(runDirectory) {
16670
- return await readPageTicketNumber(runDirectory, "admitted-request.json") ?? await readPageTicketNumber(runDirectory, "invocation.json");
16976
+ function rewriteRunDirectoryPathFields(record4, fields, oldRunDirectory, newRunDirectory) {
16977
+ rewriteRunDirectoryPathFieldsAgainstRewrites(record4, fields, [
16978
+ { oldRunDirectory, newRunDirectory }
16979
+ ]);
16671
16980
  }
16672
- var init_run_ticket_number = __esm({
16673
- "src/run-ticket-number.ts"() {
16981
+ function rewriteRunDirectoryPathFieldsAgainstRewrites(record4, fields, rewrites) {
16982
+ for (const field of fields) {
16983
+ if (field in record4) {
16984
+ record4[field] = rewriteRunDirectoryPathValueAgainstRewrites(
16985
+ record4[field],
16986
+ rewrites
16987
+ );
16988
+ }
16989
+ }
16990
+ }
16991
+ function collectRewrites(input) {
16992
+ const own = {
16993
+ oldRunDirectory: input.oldRunDirectory,
16994
+ newRunDirectory: input.newRunDirectory
16995
+ };
16996
+ if (input.crossRunRewrites === void 0 || input.crossRunRewrites.length === 0) {
16997
+ return [own];
16998
+ }
16999
+ const seen = /* @__PURE__ */ new Set([own.oldRunDirectory]);
17000
+ const out = [own];
17001
+ for (const rewrite of input.crossRunRewrites) {
17002
+ if (seen.has(rewrite.oldRunDirectory)) continue;
17003
+ seen.add(rewrite.oldRunDirectory);
17004
+ out.push(rewrite);
17005
+ }
17006
+ return out;
17007
+ }
17008
+ function isPlainObject(value) {
17009
+ return value !== null && typeof value === "object" && !Array.isArray(value);
17010
+ }
17011
+ function rewriteSourceRunLocator(value, rewrites) {
17012
+ if (!isPlainObject(value)) return;
17013
+ rewriteRunDirectoryPathFieldsAgainstRewrites(
17014
+ value,
17015
+ SOURCE_RUN_LOCATOR_FIELDS,
17016
+ rewrites
17017
+ );
17018
+ }
17019
+ function rewriteSummonsMaterials(value, rewrites) {
17020
+ if (!isPlainObject(value)) return;
17021
+ rewriteRunDirectoryPathFieldsAgainstRewrites(
17022
+ value,
17023
+ SUMMONS_PATH_FIELDS,
17024
+ rewrites
17025
+ );
17026
+ rewriteSourceRunLocator(value.sourceRun, rewrites);
17027
+ if (Array.isArray(value.attachmentPaths)) {
17028
+ value.attachmentPaths = value.attachmentPaths.map(
17029
+ (path) => rewriteRunDirectoryPathValueAgainstRewrites(path, rewrites)
17030
+ );
17031
+ }
17032
+ }
17033
+ async function rewriteJsonObjectFile(path, fields, rewrites) {
17034
+ if (!existsSync5(path)) return;
17035
+ const page = JSON.parse(await readFile5(path, "utf8"));
17036
+ if (!isPlainObject(page)) return;
17037
+ rewriteRunDirectoryPathFieldsAgainstRewrites(page, fields, rewrites);
17038
+ await writeFile2(path, `${JSON.stringify(page, null, 2)}
17039
+ `, "utf8");
17040
+ }
17041
+ async function rewriteOfficerPointerFile(path, rewrites) {
17042
+ if (!existsSync5(path)) return;
17043
+ const page = JSON.parse(await readFile5(path, "utf8"));
17044
+ if (!isPlainObject(page)) return;
17045
+ if (page.kind !== "direct-officer-run-pointer") return;
17046
+ rewriteRunDirectoryPathFieldsAgainstRewrites(
17047
+ page,
17048
+ OFFICER_POINTER_FIELDS,
17049
+ rewrites
17050
+ );
17051
+ await writeFile2(path, `${JSON.stringify(page)}
17052
+ `, "utf8");
17053
+ }
17054
+ async function rewriteSitianRecordsJsonl(path, rewrites) {
17055
+ if (!existsSync5(path)) return;
17056
+ const raw = await readFile5(path, "utf8");
17057
+ if (raw.length === 0) return;
17058
+ const endsWithNewline = raw.endsWith("\n");
17059
+ const lines = raw.split("\n");
17060
+ let changed = false;
17061
+ const out = [];
17062
+ for (let i = 0; i < lines.length; i += 1) {
17063
+ const line2 = lines[i];
17064
+ if (line2 === "" && i === lines.length - 1 && endsWithNewline) {
17065
+ out.push("");
17066
+ continue;
17067
+ }
17068
+ if (line2.trim() === "") {
17069
+ out.push(line2);
17070
+ continue;
17071
+ }
17072
+ let parsed;
17073
+ try {
17074
+ parsed = JSON.parse(line2);
17075
+ } catch {
17076
+ out.push(line2);
17077
+ continue;
17078
+ }
17079
+ if (!isPlainObject(parsed)) {
17080
+ out.push(line2);
17081
+ continue;
17082
+ }
17083
+ if (!("sessionParent" in parsed)) {
17084
+ out.push(line2);
17085
+ continue;
17086
+ }
17087
+ const before = parsed.sessionParent;
17088
+ rewriteRunDirectoryPathFieldsAgainstRewrites(
17089
+ parsed,
17090
+ SITIAN_RECORD_FIELDS,
17091
+ rewrites
17092
+ );
17093
+ if (parsed.sessionParent !== before) changed = true;
17094
+ out.push(JSON.stringify(parsed));
17095
+ }
17096
+ if (!changed) return;
17097
+ const body = out.join("\n");
17098
+ await writeFile2(
17099
+ path,
17100
+ endsWithNewline && !body.endsWith("\n") ? `${body}
17101
+ ` : body,
17102
+ "utf8"
17103
+ );
17104
+ }
17105
+ async function rewriteSessionTranscriptBindings(path, rewrites) {
17106
+ if (!existsSync5(path)) return;
17107
+ const raw = await readFile5(path, "utf8");
17108
+ if (raw.length === 0) return;
17109
+ const endsWithNewline = raw.endsWith("\n");
17110
+ const lines = raw.split("\n");
17111
+ let changed = false;
17112
+ const out = [];
17113
+ for (let i = 0; i < lines.length; i += 1) {
17114
+ const line2 = lines[i];
17115
+ if (line2 === "" && i === lines.length - 1 && endsWithNewline) {
17116
+ out.push("");
17117
+ continue;
17118
+ }
17119
+ if (line2.trim() === "") {
17120
+ out.push(line2);
17121
+ continue;
17122
+ }
17123
+ let parsed;
17124
+ try {
17125
+ parsed = JSON.parse(line2);
17126
+ } catch {
17127
+ out.push(line2);
17128
+ continue;
17129
+ }
17130
+ if (!isPlainObject(parsed)) {
17131
+ out.push(line2);
17132
+ continue;
17133
+ }
17134
+ let lineChanged = false;
17135
+ if (parsed.type === "session" && "parentSession" in parsed) {
17136
+ const before = parsed.parentSession;
17137
+ rewriteRunDirectoryPathFieldsAgainstRewrites(
17138
+ parsed,
17139
+ SESSION_HEADER_FIELDS,
17140
+ rewrites
17141
+ );
17142
+ if (parsed.parentSession !== before) lineChanged = true;
17143
+ } else if (parsed.type === "custom" && parsed.customType === AUDITOR_PARENT_ATTEMPT_BINDING_ENTRY_TYPE && isPlainObject(parsed.data) && isPlainObject(parsed.data.parent)) {
17144
+ const parent = parsed.data.parent;
17145
+ const before = parent.sessionFile;
17146
+ rewriteRunDirectoryPathFieldsAgainstRewrites(
17147
+ parent,
17148
+ BINDING_PARENT_FIELDS,
17149
+ rewrites
17150
+ );
17151
+ if (parent.sessionFile !== before) lineChanged = true;
17152
+ }
17153
+ if (lineChanged) changed = true;
17154
+ out.push(lineChanged ? JSON.stringify(parsed) : line2);
17155
+ }
17156
+ if (!changed) return;
17157
+ const body = out.join("\n");
17158
+ await writeFile2(
17159
+ path,
17160
+ endsWithNewline && !body.endsWith("\n") ? `${body}
17161
+ ` : body,
17162
+ "utf8"
17163
+ );
17164
+ }
17165
+ async function rewriteNestedMachinePathPages(pagesDirectory, rewrites) {
17166
+ const sessionRoot = join11(pagesDirectory, "session");
17167
+ async function walk(directory) {
17168
+ let entries;
17169
+ try {
17170
+ entries = await readdir2(directory, { withFileTypes: true });
17171
+ } catch (error) {
17172
+ if (isEnoent2(error)) return;
17173
+ throw error;
17174
+ }
17175
+ for (const entry of entries) {
17176
+ const path = join11(directory, entry.name);
17177
+ if (entry.isDirectory()) {
17178
+ await walk(path);
17179
+ continue;
17180
+ }
17181
+ if (!entry.isFile()) continue;
17182
+ if (entry.name === "current-session.json") {
17183
+ await rewriteJsonObjectFile(path, CURRENT_SESSION_FIELDS, rewrites);
17184
+ } else if (entry.name.endsWith(".pointer.json")) {
17185
+ await rewriteOfficerPointerFile(path, rewrites);
17186
+ } else if (entry.name === "records.jsonl") {
17187
+ await rewriteSitianRecordsJsonl(path, rewrites);
17188
+ } else if (entry.name.endsWith(".jsonl")) {
17189
+ await rewriteSessionTranscriptBindings(path, rewrites);
17190
+ }
17191
+ }
17192
+ }
17193
+ await walk(sessionRoot);
17194
+ }
17195
+ async function rewriteRoleRunDurablePages(input) {
17196
+ const { pagesDirectory } = input;
17197
+ const rewrites = collectRewrites(input);
17198
+ const admittedPath = join11(pagesDirectory, "admitted-request.json");
17199
+ if (existsSync5(admittedPath)) {
17200
+ const page = JSON.parse(await readFile5(admittedPath, "utf8"));
17201
+ rewriteRunDirectoryPathFieldsAgainstRewrites(
17202
+ page,
17203
+ ADMITTED_PAGE_FIELDS,
17204
+ rewrites
17205
+ );
17206
+ rewriteSourceRunLocator(page.sourceRun, rewrites);
17207
+ if (Array.isArray(page.attachments)) {
17208
+ for (const attachment of page.attachments) {
17209
+ if (isPlainObject(attachment)) {
17210
+ rewriteRunDirectoryPathFieldsAgainstRewrites(
17211
+ attachment,
17212
+ ["frozenPath"],
17213
+ rewrites
17214
+ );
17215
+ }
17216
+ }
17217
+ }
17218
+ if (isPlainObject(page.principal)) {
17219
+ rewriteRunDirectoryPathFieldsAgainstRewrites(
17220
+ page.principal,
17221
+ ["sessionDirectory", "sessionFile"],
17222
+ rewrites
17223
+ );
17224
+ }
17225
+ await writeFile2(admittedPath, `${JSON.stringify(page, null, 2)}
17226
+ `, "utf8");
17227
+ }
17228
+ const invocationPath = join11(pagesDirectory, "invocation.json");
17229
+ if (existsSync5(invocationPath)) {
17230
+ const page = JSON.parse(await readFile5(invocationPath, "utf8"));
17231
+ rewriteRunDirectoryPathFieldsAgainstRewrites(
17232
+ page,
17233
+ INVOCATION_PAGE_FIELDS,
17234
+ rewrites
17235
+ );
17236
+ await writeFile2(
17237
+ invocationPath,
17238
+ `${JSON.stringify(page, null, 2)}
17239
+ `,
17240
+ "utf8"
17241
+ );
17242
+ }
17243
+ const statePath = join11(pagesDirectory, "run-state.json");
17244
+ if (existsSync5(statePath)) {
17245
+ const page = JSON.parse(await readFile5(statePath, "utf8"));
17246
+ rewriteRunDirectoryPathFieldsAgainstRewrites(
17247
+ page,
17248
+ RUN_STATE_PAGE_FIELDS,
17249
+ rewrites
17250
+ );
17251
+ if (isPlainObject(page.principal)) {
17252
+ rewriteRunDirectoryPathFieldsAgainstRewrites(
17253
+ page.principal,
17254
+ ["sessionDirectory", "sessionFile"],
17255
+ rewrites
17256
+ );
17257
+ }
17258
+ if (isPlainObject(page.currentCourt)) {
17259
+ rewriteSummonsMaterials(page.currentCourt.summons, rewrites);
17260
+ }
17261
+ await writeFile2(statePath, `${JSON.stringify(page, null, 2)}
17262
+ `, "utf8");
17263
+ }
17264
+ await rewriteNestedMachinePathPages(pagesDirectory, rewrites);
17265
+ }
17266
+ var ADMITTED_PAGE_FIELDS, INVOCATION_PAGE_FIELDS, RUN_STATE_PAGE_FIELDS, SOURCE_RUN_LOCATOR_FIELDS, SUMMONS_PATH_FIELDS, CURRENT_SESSION_FIELDS, OFFICER_POINTER_FIELDS, SITIAN_RECORD_FIELDS, SESSION_HEADER_FIELDS, BINDING_PARENT_FIELDS;
17267
+ var init_role_run_relocation = __esm({
17268
+ "src/role-run-relocation.ts"() {
16674
17269
  "use strict";
17270
+ init_compliance_transport();
17271
+ ADMITTED_PAGE_FIELDS = [
17272
+ "runDirectory",
17273
+ "admittedRequestPath",
17274
+ "sessionDirectory",
17275
+ "sessionFile",
17276
+ "taskPath",
17277
+ "packetPath",
17278
+ "prerequisitesPath",
17279
+ "requestManifestPath",
17280
+ "mergerInputPath",
17281
+ "sourceRunPath"
17282
+ ];
17283
+ INVOCATION_PAGE_FIELDS = [
17284
+ "runDirectory",
17285
+ "sessionDirectory",
17286
+ "sessionFile"
17287
+ ];
17288
+ RUN_STATE_PAGE_FIELDS = [
17289
+ "runDirectory",
17290
+ "admittedRequestPath",
17291
+ "sessionDirectory",
17292
+ "sessionFile"
17293
+ ];
17294
+ SOURCE_RUN_LOCATOR_FIELDS = ["runDirectory"];
17295
+ SUMMONS_PATH_FIELDS = ["sourceRunPath"];
17296
+ CURRENT_SESSION_FIELDS = ["sessionFile"];
17297
+ OFFICER_POINTER_FIELDS = ["sessionFile", "runDirectory"];
17298
+ SITIAN_RECORD_FIELDS = ["sessionParent"];
17299
+ SESSION_HEADER_FIELDS = ["parentSession"];
17300
+ BINDING_PARENT_FIELDS = ["sessionFile"];
16675
17301
  }
16676
17302
  });
16677
17303
 
@@ -16686,21 +17312,6 @@ var init_sha256 = __esm({
16686
17312
  }
16687
17313
  });
16688
17314
 
16689
- // src/readable-gate-item.ts
16690
- var init_readable_gate_item = __esm({
16691
- "src/readable-gate-item.ts"() {
16692
- "use strict";
16693
- }
16694
- });
16695
-
16696
- // src/submission-errors.ts
16697
- var init_submission_errors = __esm({
16698
- "src/submission-errors.ts"() {
16699
- "use strict";
16700
- init_readable_gate_item();
16701
- }
16702
- });
16703
-
16704
17315
  // src/submission-correctable-error.ts
16705
17316
  var correctableSubmissionErrorBrand, CorrectableSubmissionError;
16706
17317
  var init_submission_correctable_error = __esm({
@@ -16791,16 +17402,16 @@ var init_terminating_tools = __esm({
16791
17402
  });
16792
17403
 
16793
17404
  // src/doctor-evidence.ts
16794
- import { readdir, readFile as readFile5, realpath as realpath2, stat } from "node:fs/promises";
16795
- import { dirname as dirname7, relative as relative2, resolve as resolve5, sep as sep2 } from "node:path";
17405
+ import { readdir as readdir3, readFile as readFile6, realpath as realpath2, stat } from "node:fs/promises";
17406
+ import { dirname as dirname7, relative as relative2, resolve as resolve4, sep as sep3 } from "node:path";
16796
17407
  function record2(value) {
16797
17408
  return typeof value === "object" && value !== null && !Array.isArray(value);
16798
17409
  }
16799
17410
  async function discoverCaseFiles(root) {
16800
17411
  const found = [];
16801
17412
  async function walk(dir, depth) {
16802
- for (const item of await readdir(dir, { withFileTypes: true })) {
16803
- const path = resolve5(dir, item.name);
17413
+ for (const item of await readdir3(dir, { withFileTypes: true })) {
17414
+ const path = resolve4(dir, item.name);
16804
17415
  if (item.isDirectory()) {
16805
17416
  await walk(path, depth + 1);
16806
17417
  } else if (item.isFile() && (item.name.endsWith(".jsonl") || item.name === "stderr.log" && depth === 1)) found.push(path);
@@ -16819,17 +17430,17 @@ function accumulate(metric, value, source) {
16819
17430
  function timestamp(row) {
16820
17431
  return typeof row.timestamp === "string" && Number.isFinite(Date.parse(row.timestamp)) ? row.timestamp : void 0;
16821
17432
  }
16822
- function isMissingPathError(error) {
17433
+ function isMissingPathError2(error) {
16823
17434
  return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
16824
17435
  }
16825
17436
  async function stableRunsIdentity(root) {
16826
17437
  let cursor = root;
16827
17438
  while (true) {
16828
17439
  try {
16829
- const git2 = await stat(resolve5(cursor, ".git"));
16830
- if (git2.isDirectory() || git2.isFile()) return relative2(cursor, root).split(sep2).join("/");
17440
+ const git2 = await stat(resolve4(cursor, ".git"));
17441
+ if (git2.isDirectory() || git2.isFile()) return relative2(cursor, root).split(sep3).join("/");
16831
17442
  } catch (error) {
16832
- if (!isMissingPathError(error)) throw error;
17443
+ if (!isMissingPathError2(error)) throw error;
16833
17444
  }
16834
17445
  const parent = dirname7(cursor);
16835
17446
  if (parent === cursor) return root;
@@ -16901,13 +17512,13 @@ function deriveSession(content, id) {
16901
17512
  }
16902
17513
  async function loadDoctorCase(runsPath) {
16903
17514
  const root = await realpath2(runsPath);
16904
- const match = root.split(sep2).join("/").match(/\/\.ak-roles\/books\/[^/]+\/issues\/([1-9]\d*)\/runs$/);
16905
- if (!match) throw new Error("Doctor case must be an .ak-roles/books/<book>/issues/<n>/runs directory");
17515
+ const match = root.split(sep3).join("/").match(/\/\.ak-roles\/books\/[^/]+\/(?:issues\/)?([1-9]\d*)\/runs$/);
17516
+ if (!match) throw new Error("Doctor case must be an .ak-roles/books/<book>/<n>/runs directory");
16906
17517
  const evidence = [], sessions = [], statuses = [], commits = [];
16907
17518
  const turns = { count: 0, sources: [] }, calls = { count: 0, sources: [] }, tokens = { count: 0, sources: [] };
16908
17519
  for (const path of await discoverCaseFiles(root)) {
16909
- const id = relative2(root, path).split(sep2).join("/");
16910
- const bytes = await readFile5(path);
17520
+ const id = relative2(root, path).split(sep3).join("/");
17521
+ const bytes = await readFile6(path);
16911
17522
  const content = bytes.toString("utf8");
16912
17523
  const kind = id.endsWith(".jsonl") ? "session" : "stderr";
16913
17524
  evidence.push({ id, kind, byteLength: bytes.byteLength, contentLength: content.length, sha256: sha256Hex(bytes), content });
@@ -16920,7 +17531,7 @@ async function loadDoctorCase(runsPath) {
16920
17531
  accumulate(calls, result2.calls, id);
16921
17532
  accumulate(tokens, result2.tokens, id);
16922
17533
  }
16923
- const runDirs = (await readdir(root, { withFileTypes: true })).filter((item) => item.isDirectory()).map((item) => item.name).sort();
17534
+ const runDirs = (await readdir3(root, { withFileTypes: true })).filter((item) => item.isDirectory()).map((item) => item.name).sort();
16924
17535
  const legs = evidence.filter((entry) => entry.kind === "session").map((entry) => entry.id);
16925
17536
  const retryDirs = runDirs.filter((name) => /(?:^|[-_])retry(?:[-_]|$)/i.test(name));
16926
17537
  const rawBytes = evidence.filter((entry) => entry.kind === "session").reduce((sum, entry) => sum + entry.byteLength, 0);
@@ -16937,7 +17548,7 @@ var init_doctor_evidence = __esm({
16937
17548
 
16938
17549
  // src/collector-config.ts
16939
17550
  import { createHash as createHash3 } from "node:crypto";
16940
- import { readFile as readFile6 } from "node:fs/promises";
17551
+ import { readFile as readFile7 } from "node:fs/promises";
16941
17552
  function fail3(message, cause) {
16942
17553
  throw new Error(message, cause === void 0 ? void 0 : { cause });
16943
17554
  }
@@ -16980,7 +17591,7 @@ function emptyCollectorManifest() {
16980
17591
  async function loadCollectorManifest(path) {
16981
17592
  let bytes;
16982
17593
  try {
16983
- bytes = await readFile6(path);
17594
+ bytes = await readFile7(path);
16984
17595
  } catch (error) {
16985
17596
  fail3(`Collector request manifest is unreadable at ${path}`, error);
16986
17597
  }
@@ -17084,7 +17695,7 @@ async function listPullRequestNumbersByCommit(runner, input) {
17084
17695
  function createGhApiRunner(options = {}) {
17085
17696
  const spawnImpl = options.spawnImpl ?? spawn2;
17086
17697
  return async (args, runOptions = {}) => {
17087
- return await new Promise((resolve11, reject) => {
17698
+ return await new Promise((resolve10, reject) => {
17088
17699
  const signal = runOptions.signal;
17089
17700
  if (signal?.aborted) {
17090
17701
  reject(signal.reason ?? new Error("aborted"));
@@ -17157,11 +17768,11 @@ function createGhApiRunner(options = {}) {
17157
17768
  const value = line2.slice(idx + 1).trim();
17158
17769
  headers[name] = value;
17159
17770
  }
17160
- resolve11({ status, headers, bodyText });
17771
+ resolve10({ status, headers, bodyText });
17161
17772
  return;
17162
17773
  }
17163
17774
  if (code === 0) {
17164
- resolve11({ status: 200, headers: {}, bodyText: stdout });
17775
+ resolve10({ status: 200, headers: {}, bodyText: stdout });
17165
17776
  return;
17166
17777
  }
17167
17778
  const failure = new Error(
@@ -17371,9 +17982,9 @@ var init_git_object_id = __esm({
17371
17982
 
17372
17983
  // src/merger-git-state.ts
17373
17984
  import { execFile as execFile2 } from "node:child_process";
17374
- import { access as access2, readFile as readFile7 } from "node:fs/promises";
17985
+ import { access as access2, readFile as readFile8 } from "node:fs/promises";
17375
17986
  import { constants as fsConstants } from "node:fs";
17376
- import { isAbsolute as isAbsolute4, resolve as resolve6 } from "node:path";
17987
+ import { isAbsolute as isAbsolute4, resolve as resolve5 } from "node:path";
17377
17988
  import { promisify as promisify2 } from "node:util";
17378
17989
  async function git(cwd, args) {
17379
17990
  const { stdout } = await execFileAsync2("git", args, { cwd, encoding: "buffer", maxBuffer: 16 * 1024 * 1024 });
@@ -17438,10 +18049,10 @@ function createProductionMergerGitState(repositoryRoot = process.cwd()) {
17438
18049
  await requireInsideWorkTree(repositoryRoot);
17439
18050
  const targetObjectId = await resolveHeadMaterial(repositoryRoot);
17440
18051
  const mergeHeadReported = line(await git(repositoryRoot, ["rev-parse", "--git-path", "MERGE_HEAD"]), "Git MERGE_HEAD path");
17441
- const mergeHeadPath = isAbsolute4(mergeHeadReported) ? mergeHeadReported : resolve6(repositoryRoot, mergeHeadReported);
18052
+ const mergeHeadPath = isAbsolute4(mergeHeadReported) ? mergeHeadReported : resolve5(repositoryRoot, mergeHeadReported);
17442
18053
  let sourceObjectId = "";
17443
18054
  if (await pathExists(mergeHeadPath)) {
17444
- const raw = exactUtf8(await readFile7(mergeHeadPath), "Git MERGE_HEAD");
18055
+ const raw = exactUtf8(await readFile8(mergeHeadPath), "Git MERGE_HEAD");
17445
18056
  const mergeHeads = raw.trim().split(/\r?\n/).map((row) => row.trim()).filter(Boolean);
17446
18057
  if (mergeHeads.length === 0) throw new Error("Git MERGE_HEAD is empty");
17447
18058
  if (mergeHeads.length !== 1) throw new Error("Assigned repository does not have one ordinary in-progress merge");
@@ -17493,10 +18104,10 @@ var init_uuidv7 = __esm({
17493
18104
  });
17494
18105
 
17495
18106
  // src/typed-provider-http.ts
17496
- import { readFile as readFile8, unlink, writeFile as writeFile2 } from "node:fs/promises";
17497
- import { join as join10 } from "node:path";
18107
+ import { readFile as readFile9, unlink, writeFile as writeFile3 } from "node:fs/promises";
18108
+ import { join as join12 } from "node:path";
17498
18109
  function typedProviderHttpPath(runDirectory) {
17499
- return join10(runDirectory, TYPED_HTTP_FILE);
18110
+ return join12(runDirectory, TYPED_HTTP_FILE);
17500
18111
  }
17501
18112
  async function clearTypedProviderHttpObservation(runDirectory) {
17502
18113
  try {
@@ -17511,7 +18122,7 @@ async function clearTypedProviderHttpObservation(runDirectory) {
17511
18122
  async function readLatestTypedProviderHttpObservation(runDirectory) {
17512
18123
  let text;
17513
18124
  try {
17514
- text = await readFile8(typedProviderHttpPath(runDirectory), "utf8");
18125
+ text = await readFile9(typedProviderHttpPath(runDirectory), "utf8");
17515
18126
  } catch (error) {
17516
18127
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
17517
18128
  return void 0;
@@ -17540,8 +18151,8 @@ var init_typed_provider_http = __esm({
17540
18151
  });
17541
18152
 
17542
18153
  // src/public-cli/run-lifecycle.ts
17543
- import { chmod, open, readdir as readdir2, readFile as readFile9, unlink as unlink2, writeFile as writeFile3 } from "node:fs/promises";
17544
- import { join as join11 } from "node:path";
18154
+ import { chmod, lstat as lstat2, open, readdir as readdir4, readFile as readFile10, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
18155
+ import { basename as basename4, join as join13 } from "node:path";
17545
18156
  function selectResumeContinuationPrompt(message, engineMaterial) {
17546
18157
  const lines = message !== void 0 ? [message] : [];
17547
18158
  return appendEngineSessionMaterial(lines, engineMaterial).join("\n");
@@ -17570,8 +18181,8 @@ function renderResumeCommand(runId) {
17570
18181
  }
17571
18182
  async function writeRoleRunState(runDirectory, record4) {
17572
18183
  const payload = { ...record4, runDirectory };
17573
- await writeFile3(
17574
- join11(runDirectory, RUN_STATE_FILE),
18184
+ await writeFile4(
18185
+ join13(runDirectory, RUN_STATE_FILE),
17575
18186
  `${JSON.stringify(payload, null, 2)}
17576
18187
  `,
17577
18188
  "utf8"
@@ -17621,7 +18232,7 @@ function parseCurrentCourtState(raw) {
17621
18232
  async function readRoleRunStateDisk(runDirectory) {
17622
18233
  let raw;
17623
18234
  try {
17624
- raw = JSON.parse(await readFile9(join11(runDirectory, RUN_STATE_FILE), "utf8"));
18235
+ raw = JSON.parse(await readFile10(join13(runDirectory, RUN_STATE_FILE), "utf8"));
17625
18236
  } catch (error) {
17626
18237
  if (errorCodeOf2(error) === "ENOENT") return void 0;
17627
18238
  throw error;
@@ -17688,8 +18299,8 @@ async function writeRoleRunStateDisk(runDirectory, disk) {
17688
18299
  ...disk.resumable === void 0 ? {} : { resumable: disk.resumable },
17689
18300
  ...disk.currentCourt === void 0 ? {} : { currentCourt: disk.currentCourt }
17690
18301
  };
17691
- await writeFile3(
17692
- join11(runDirectory, RUN_STATE_FILE),
18302
+ await writeFile4(
18303
+ join13(runDirectory, RUN_STATE_FILE),
17693
18304
  `${JSON.stringify(payload, null, 2)}
17694
18305
  `,
17695
18306
  "utf8"
@@ -17856,15 +18467,19 @@ function isProcessAlive(pid) {
17856
18467
  async function autopsyWriterLock(lockPath) {
17857
18468
  let content;
17858
18469
  try {
17859
- content = await readFile9(lockPath, "utf8");
18470
+ content = await readFile10(lockPath, "utf8");
17860
18471
  } catch (error) {
17861
18472
  if (errorCodeOf2(error) === "ENOENT") return { verdict: "absent" };
17862
- return { verdict: "absent", readFailure: error };
18473
+ return { verdict: "unknown", reason: "unreadable", readFailure: error };
17863
18474
  }
17864
18475
  const normalized = content.trim();
17865
- if (!/^[1-9]\d*$/.test(normalized)) return { verdict: "absent" };
18476
+ if (!/^[1-9]\d*$/.test(normalized)) {
18477
+ return { verdict: "unknown", reason: "unparseable", content };
18478
+ }
17866
18479
  const pid = Number.parseInt(normalized, 10);
17867
- if (!Number.isSafeInteger(pid) || pid <= 0) return { verdict: "absent" };
18480
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
18481
+ return { verdict: "unknown", reason: "unparseable", content };
18482
+ }
17868
18483
  return isProcessAlive(pid) ? { verdict: "alive", pid } : { verdict: "dead", pid };
17869
18484
  }
17870
18485
  function describeAutopsy(autopsy) {
@@ -17874,7 +18489,9 @@ function describeAutopsy(autopsy) {
17874
18489
  case "dead":
17875
18490
  return `dead pid ${autopsy.pid}`;
17876
18491
  case "absent":
17877
- return autopsy.readFailure !== void 0 ? "unreadable lock" : "absent or unparseable holder";
18492
+ return "absent holder";
18493
+ case "unknown":
18494
+ return autopsy.reason === "unreadable" ? "unreadable lock" : "unparseable holder";
17878
18495
  }
17879
18496
  }
17880
18497
  async function reclaimStaleWriterLock(lockPath, runDirectory) {
@@ -17901,24 +18518,32 @@ async function createWriterLease(lockPath, runDirectory, reportCleanupFailure) {
17901
18518
  throw error;
17902
18519
  }
17903
18520
  let released = false;
18521
+ let currentRunDirectory = runDirectory;
18522
+ let currentLockPath = lockPath;
17904
18523
  return {
17905
- lockPath,
18524
+ get lockPath() {
18525
+ return currentLockPath;
18526
+ },
18527
+ relocate(nextRunDirectory) {
18528
+ currentRunDirectory = nextRunDirectory;
18529
+ currentLockPath = join13(nextRunDirectory, WRITER_LOCK_FILE);
18530
+ },
17906
18531
  async release() {
17907
18532
  if (released) return;
17908
18533
  released = true;
17909
18534
  await handle.close().catch(() => void 0);
17910
18535
  try {
17911
- await unlink2(lockPath);
18536
+ await unlink2(currentLockPath);
17912
18537
  } catch (error) {
17913
18538
  if (errorCodeOf2(error) === "EACCES") {
17914
18539
  try {
17915
- await chmod(runDirectory, 493);
17916
- await unlink2(lockPath);
18540
+ await chmod(currentRunDirectory, 493);
18541
+ await unlink2(currentLockPath);
17917
18542
  } catch (retryError) {
17918
- reportCleanupFailure(retryError);
18543
+ reportCleanupFailure(retryError, currentLockPath);
17919
18544
  }
17920
18545
  } else {
17921
- reportCleanupFailure(error);
18546
+ reportCleanupFailure(error, currentLockPath);
17922
18547
  }
17923
18548
  }
17924
18549
  }
@@ -17933,17 +18558,17 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
17933
18558
  } catch {
17934
18559
  }
17935
18560
  };
17936
- const reportCleanupFailure = (error) => {
18561
+ const reportCleanupFailure = (error, lockPath2) => {
17937
18562
  reportDiagnostic(
17938
- `writer lease lock cleanup failed (release is best-effort; residual lock left in place) at ${join11(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
18563
+ `writer lease lock cleanup failed (release is best-effort; residual lock left in place) at ${lockPath2}: ${describeErrorIdentity(error)}`
17939
18564
  );
17940
18565
  };
17941
18566
  const reportReadFailure = (error) => {
17942
18567
  reportDiagnostic(
17943
- `writer lease lock read failed (holder liveness unverifiable; lock left in place) at ${join11(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
18568
+ `writer lease lock read failed (holder liveness unverifiable; lock left in place) at ${join13(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
17944
18569
  );
17945
18570
  };
17946
- const lockPath = join11(runDirectory, WRITER_LOCK_FILE);
18571
+ const lockPath = join13(runDirectory, WRITER_LOCK_FILE);
17947
18572
  let lastAutopsy = { verdict: "absent" };
17948
18573
  let lastReclaimFailure;
17949
18574
  for (let reclaimsLeft = WRITER_LEASE_RECLAIM_ROUNDS; ; reclaimsLeft -= 1) {
@@ -17953,7 +18578,7 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
17953
18578
  if (errorCodeOf2(error) !== "EEXIST") throw error;
17954
18579
  }
17955
18580
  lastAutopsy = await autopsyWriterLock(lockPath);
17956
- if (lastAutopsy.verdict === "absent" && lastAutopsy.readFailure !== void 0) {
18581
+ if (lastAutopsy.verdict === "unknown" && lastAutopsy.reason === "unreadable") {
17957
18582
  reportReadFailure(lastAutopsy.readFailure);
17958
18583
  }
17959
18584
  if (lastAutopsy.verdict === "alive") {
@@ -17961,9 +18586,14 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
17961
18586
  `role run writer lease is already held by live pid ${lastAutopsy.pid} at ${lockPath}`
17962
18587
  );
17963
18588
  }
18589
+ if (lastAutopsy.verdict === "unknown") {
18590
+ throw new RunWriterLeaseHeldError(
18591
+ lastAutopsy.reason === "unreadable" ? `role run writer lease lock is unreadable at ${lockPath}: ${describeErrorIdentity(lastAutopsy.readFailure)}; holder liveness unverifiable, lock left in place` : `role run writer lease lock at ${lockPath} has no verifiable holder pid (empty or unparseable); holder liveness unverifiable, lock left in place`
18592
+ );
18593
+ }
17964
18594
  if (lastAutopsy.verdict === "absent") {
17965
18595
  throw new RunWriterLeaseHeldError(
17966
- lastAutopsy.readFailure !== void 0 ? `role run writer lease lock is unreadable at ${lockPath}: ${describeErrorIdentity(lastAutopsy.readFailure)}; holder liveness unverifiable, lock left in place` : `role run writer lease lock at ${lockPath} has no verifiable holder pid (empty or unparseable); holder liveness unverifiable, lock left in place`
18596
+ `role run writer lease disappeared before holder autopsy at ${lockPath}`
17967
18597
  );
17968
18598
  }
17969
18599
  if (reclaimsLeft <= 0) break;
@@ -17990,31 +18620,40 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
17990
18620
  lastReclaimFailure !== void 0 ? `role run writer lease stayed contested at ${lockPath} after ${WRITER_LEASE_RECLAIM_ROUNDS} reclaims (last autopsy: ${describeAutopsy(lastAutopsy)}; last reclaim failure: ${describeErrorIdentity(lastReclaimFailure)})` : `role run writer lease stayed contested at ${lockPath} after ${WRITER_LEASE_RECLAIM_ROUNDS} reclaims (last autopsy: ${describeAutopsy(lastAutopsy)})`
17991
18621
  );
17992
18622
  }
17993
- async function findRunDirectoryById(home, runId) {
18623
+ async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole) {
17994
18624
  if (runId.trim() === "") return void 0;
17995
18625
  const ledgerHome = resolveActivationLedgerHome(home);
17996
- const booksRoot = join11(ledgerHome, "books");
18626
+ const booksRoot = join13(ledgerHome, "books");
17997
18627
  let bookKeys;
17998
18628
  try {
17999
- bookKeys = await readdir2(booksRoot);
18000
- } catch {
18001
- return void 0;
18629
+ bookKeys = await readdir4(booksRoot);
18630
+ } catch (error) {
18631
+ if (errorCodeOf2(error) === "ENOENT") return void 0;
18632
+ throw error;
18002
18633
  }
18634
+ const matches = [];
18003
18635
  for (const bookKey of bookKeys) {
18004
- const runsDir = join11(activationBookDirectory(ledgerHome, bookKey), "runs");
18005
- let entries;
18636
+ if (onlyBookKey !== void 0 && bookKey !== onlyBookKey) continue;
18637
+ const bookDir = activationBookDirectory(ledgerHome, bookKey);
18638
+ let runDirectories;
18006
18639
  try {
18007
- entries = await readdir2(runsDir);
18008
- } catch {
18009
- continue;
18640
+ runDirectories = await listBookRunDirectories(bookDir);
18641
+ } catch (error) {
18642
+ if (errorCodeOf2(error) === "ENOENT") continue;
18643
+ throw error;
18010
18644
  }
18011
- for (const entry of entries) {
18012
- if (entry === `${runId}@judge` || entry.startsWith(`${runId}@`)) {
18013
- return join11(runsDir, entry);
18645
+ for (const runDirectory of runDirectories) {
18646
+ const entry = basename4(runDirectory);
18647
+ if (onlyRole === void 0 && (entry === `${runId}@judge` || entry.startsWith(`${runId}@`)) || entry === `${runId}@${onlyRole}`) {
18648
+ matches.push(runDirectory);
18014
18649
  }
18015
18650
  }
18016
18651
  }
18017
- return void 0;
18652
+ if (matches.length === 0) return void 0;
18653
+ if (matches.length === 1) return matches[0];
18654
+ throw new Error(
18655
+ `ambiguous role run id ${runId}: ${matches.join(", ")}`
18656
+ );
18018
18657
  }
18019
18658
  function parentRunPathFromGatePointerInstruction(instruction) {
18020
18659
  if (!instruction.startsWith(GATE_DOSSIER_POINTER_PREFIX)) return void 0;
@@ -18025,7 +18664,7 @@ async function readRunParentPath(runDirectory) {
18025
18664
  let raw;
18026
18665
  try {
18027
18666
  raw = JSON.parse(
18028
- await readFile9(join11(runDirectory, "admitted-request.json"), "utf8")
18667
+ await readFile10(join13(runDirectory, "admitted-request.json"), "utf8")
18029
18668
  );
18030
18669
  } catch (error) {
18031
18670
  if (errorCodeOf2(error) === "ENOENT") return void 0;
@@ -18043,51 +18682,104 @@ async function readRunParentPath(runDirectory) {
18043
18682
  }
18044
18683
  return void 0;
18045
18684
  }
18685
+ async function runHasFormedSessionPrincipal(runDirectory) {
18686
+ const disk = await readRoleRunStateDisk(runDirectory);
18687
+ if (disk === void 0) return false;
18688
+ const sessionFile = typeof disk.principalWire.sessionFile === "string" && disk.principalWire.sessionFile.trim() !== "" ? disk.principalWire.sessionFile : join13(disk.principalWire.sessionDirectory, "session.jsonl");
18689
+ try {
18690
+ const stat2 = await lstat2(sessionFile);
18691
+ return stat2.isFile() && !stat2.isSymbolicLink();
18692
+ } catch (error) {
18693
+ if (errorCodeOf2(error) === "ENOENT") return false;
18694
+ throw error;
18695
+ }
18696
+ }
18046
18697
  async function findLatestRunIdForSeatTicket(input) {
18698
+ if (input.ticketNumber === void 0 && input.parentRunPath === void 0) {
18699
+ return void 0;
18700
+ }
18047
18701
  const ledgerHome = resolveActivationLedgerHome(input.home);
18048
- const runsDir = join11(
18049
- activationBookDirectory(ledgerHome, input.bookKey),
18050
- "runs"
18051
- );
18052
- let entries;
18702
+ const bookDir = activationBookDirectory(ledgerHome, input.bookKey);
18703
+ let runDirectories;
18053
18704
  try {
18054
- entries = await readdir2(runsDir);
18705
+ runDirectories = await listBookRunDirectories(bookDir);
18055
18706
  } catch (error) {
18056
18707
  if (errorCodeOf2(error) === "ENOENT") return void 0;
18057
18708
  throw error;
18058
18709
  }
18059
18710
  const suffix = `@${input.role}`;
18060
18711
  let best;
18061
- for (const entry of entries) {
18712
+ for (const runDirectory of runDirectories) {
18713
+ const entry = basename4(runDirectory);
18062
18714
  if (!entry.endsWith(suffix)) continue;
18063
18715
  const runId = entry.slice(0, entry.length - suffix.length);
18064
18716
  if (runId.length === 0) continue;
18065
- const runDirectory = join11(runsDir, entry);
18066
18717
  if (input.parentRunPath !== void 0) {
18067
18718
  const parentPath = await readRunParentPath(runDirectory);
18068
18719
  if (parentPath !== input.parentRunPath) continue;
18069
18720
  } else if (input.ticketNumber !== void 0) {
18070
- const ticketNumber = await readRunTicketNumber(runDirectory);
18721
+ const ticketNumber = await readBoardTicketNumber(runDirectory);
18071
18722
  if (ticketNumber !== input.ticketNumber) continue;
18072
- } else {
18073
- continue;
18074
18723
  }
18724
+ if (!await runHasFormedSessionPrincipal(runDirectory)) continue;
18075
18725
  if (best === void 0 || runId > best) best = runId;
18076
18726
  }
18077
18727
  return best;
18078
18728
  }
18079
18729
  function parsePersistedTicketIdentity(record4) {
18080
18730
  const correlationId = typeof record4.correlationId === "string" && record4.correlationId.trim() !== "" ? record4.correlationId : void 0;
18081
- const ticketNumber = typeof record4.ticketNumber === "number" && Number.isSafeInteger(record4.ticketNumber) && record4.ticketNumber >= 1 ? record4.ticketNumber : void 0;
18731
+ const ticketNumber = isSafePositiveTicketNumber(record4.ticketNumber) ? record4.ticketNumber : void 0;
18082
18732
  return {
18083
18733
  ...correlationId === void 0 ? {} : { correlationId },
18084
18734
  ...ticketNumber === void 0 ? {} : { ticketNumber }
18085
18735
  };
18086
18736
  }
18737
+ function readDurableCourtTicketNumbersPage(record4, principalTicket, pageLabel) {
18738
+ const interpreted = interpretDurableCourtTicketNumbers(record4, {
18739
+ ...principalTicket === void 0 ? {} : { principalTicket }
18740
+ });
18741
+ if (interpreted.kind === "damage") {
18742
+ return {
18743
+ kind: "damage",
18744
+ reason: `role run ${pageLabel} courtTicketNumbers is damaged: ${interpreted.reason}`
18745
+ };
18746
+ }
18747
+ if (interpreted.kind === "ok") {
18748
+ return { kind: "ok", tickets: interpreted.tickets };
18749
+ }
18750
+ return { kind: "absent" };
18751
+ }
18752
+ function mergeDurableCourtTicketNumbers(input) {
18753
+ const fromAdmitted = input.admittedRecord === void 0 ? { kind: "absent" } : readDurableCourtTicketNumbersPage(
18754
+ input.admittedRecord,
18755
+ input.principalTicket,
18756
+ "admitted-request"
18757
+ );
18758
+ const fromInvocation = input.invocationRecord === void 0 ? { kind: "absent" } : readDurableCourtTicketNumbersPage(
18759
+ input.invocationRecord,
18760
+ input.principalTicket,
18761
+ "invocation"
18762
+ );
18763
+ if (fromAdmitted.kind === "damage") return fromAdmitted;
18764
+ if (fromInvocation.kind === "damage") return fromInvocation;
18765
+ if (fromAdmitted.kind === "ok" && fromInvocation.kind === "ok") {
18766
+ if (!sameCourtTicketNumbers(fromAdmitted.tickets, fromInvocation.tickets)) {
18767
+ return {
18768
+ kind: "damage",
18769
+ reason: "role run courtTicketNumbers differs between admitted-request and invocation"
18770
+ };
18771
+ }
18772
+ return { kind: "ok", tickets: fromAdmitted.tickets };
18773
+ }
18774
+ if (fromAdmitted.kind === "ok") return { kind: "ok", tickets: fromAdmitted.tickets };
18775
+ if (fromInvocation.kind === "ok") return { kind: "ok", tickets: fromInvocation.tickets };
18776
+ return { kind: "ok" };
18777
+ }
18087
18778
  function restoredTicketFields(fields) {
18088
18779
  return {
18089
18780
  ...fields.correlationId === void 0 ? {} : { correlationId: fields.correlationId },
18090
- ...fields.ticketNumber === void 0 ? {} : { ticketNumber: fields.ticketNumber }
18781
+ ...fields.ticketNumber === void 0 ? {} : { ticketNumber: fields.ticketNumber },
18782
+ ...fields.courtTicketNumbers === void 0 ? {} : { courtTicketNumbers: fields.courtTicketNumbers }
18091
18783
  };
18092
18784
  }
18093
18785
  async function loadResumableRunRecord(home, runId, authority) {
@@ -18123,6 +18815,10 @@ async function loadResumableRunRecord(home, runId, authority) {
18123
18815
  let derived;
18124
18816
  let correlationId;
18125
18817
  let ticketNumber;
18818
+ let courtTicketNumbers;
18819
+ let courtTicketNumbersDamage;
18820
+ let admittedIdentityRecord;
18821
+ let invocationIdentityRecord;
18126
18822
  let prNumber;
18127
18823
  let repository;
18128
18824
  let repositoryDisplay;
@@ -18136,7 +18832,7 @@ async function loadResumableRunRecord(home, runId, authority) {
18136
18832
  let sourceRun;
18137
18833
  try {
18138
18834
  const raw = JSON.parse(
18139
- await readFile9(run.admittedRequestPath, "utf8")
18835
+ await readFile10(run.admittedRequestPath, "utf8")
18140
18836
  );
18141
18837
  if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) {
18142
18838
  const record4 = raw;
@@ -18236,6 +18932,7 @@ async function loadResumableRunRecord(home, runId, authority) {
18236
18932
  };
18237
18933
  }
18238
18934
  }
18935
+ admittedIdentityRecord = record4;
18239
18936
  const fromAdmitted = parsePersistedTicketIdentity(record4);
18240
18937
  correlationId = fromAdmitted.correlationId;
18241
18938
  ticketNumber = fromAdmitted.ticketNumber;
@@ -18250,10 +18947,11 @@ async function loadResumableRunRecord(home, runId, authority) {
18250
18947
  let model;
18251
18948
  try {
18252
18949
  const invocationRaw = JSON.parse(
18253
- await readFile9(join11(run.runDirectory, "invocation.json"), "utf8")
18950
+ await readFile10(join13(run.runDirectory, "invocation.json"), "utf8")
18254
18951
  );
18255
18952
  if (invocationRaw !== null && typeof invocationRaw === "object" && !Array.isArray(invocationRaw)) {
18256
18953
  const rec = invocationRaw;
18954
+ invocationIdentityRecord = rec;
18257
18955
  if (typeof rec.provider === "string" && typeof rec.model === "string") {
18258
18956
  model = {
18259
18957
  provider: rec.provider,
@@ -18268,6 +18966,9 @@ async function loadResumableRunRecord(home, runId, authority) {
18268
18966
  }
18269
18967
  }
18270
18968
  } catch (error) {
18969
+ if (error instanceof CliUsageError) {
18970
+ throw error;
18971
+ }
18271
18972
  if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) {
18272
18973
  throw new CliUsageError(
18273
18974
  `role run invocation identity is unreadable: ${runId}`,
@@ -18275,6 +18976,16 @@ async function loadResumableRunRecord(home, runId, authority) {
18275
18976
  );
18276
18977
  }
18277
18978
  }
18979
+ const mergedSet = mergeDurableCourtTicketNumbers({
18980
+ admittedRecord: admittedIdentityRecord,
18981
+ invocationRecord: invocationIdentityRecord,
18982
+ principalTicket: ticketNumber
18983
+ });
18984
+ if (mergedSet.kind === "damage") {
18985
+ courtTicketNumbersDamage = mergedSet.reason;
18986
+ } else if (mergedSet.tickets !== void 0) {
18987
+ courtTicketNumbers = mergedSet.tickets;
18988
+ }
18278
18989
  return {
18279
18990
  run,
18280
18991
  principal,
@@ -18294,6 +19005,8 @@ async function loadResumableRunRecord(home, runId, authority) {
18294
19005
  ...derived === void 0 ? {} : { derived },
18295
19006
  ...correlationId === void 0 ? {} : { correlationId },
18296
19007
  ...ticketNumber === void 0 ? {} : { ticketNumber },
19008
+ ...courtTicketNumbers === void 0 ? {} : { courtTicketNumbers },
19009
+ ...courtTicketNumbersDamage === void 0 ? {} : { courtTicketNumbersDamage },
18297
19010
  ...prNumber === void 0 ? {} : { prNumber },
18298
19011
  ...repository === void 0 ? {} : { repository },
18299
19012
  ...repositoryDisplay === void 0 ? {} : { repositoryDisplay },
@@ -18441,9 +19154,14 @@ async function loadResumableCountersignRun(home, runId, authority) {
18441
19154
  `role run ${runId} belongs to ${loaded.run.role}, not countersign`
18442
19155
  );
18443
19156
  }
19157
+ const base = resumedBaseAdmitted(loaded);
18444
19158
  const admitted = {
18445
19159
  role: "countersign",
18446
- ...resumedBaseAdmitted(loaded)
19160
+ ...base,
19161
+ ...base.courtTicketNumbers === void 0 ? {} : { courtTicketNumbers: base.courtTicketNumbers },
19162
+ ...loaded.admittedFields.courtTicketNumbersDamage === void 0 ? {} : {
19163
+ courtTicketNumbersDamage: loaded.admittedFields.courtTicketNumbersDamage
19164
+ }
18447
19165
  };
18448
19166
  return seatLoadedResult(loaded, admitted);
18449
19167
  }
@@ -18614,7 +19332,8 @@ async function loadResumableInspectorRun(home, runId, authority) {
18614
19332
  }
18615
19333
  const admitted = {
18616
19334
  role: "inspector",
18617
- ...resumedBaseAdmitted(loaded)
19335
+ ...resumedBaseAdmitted(loaded),
19336
+ ...loaded.admittedFields.sourceRunPath === void 0 ? {} : { sourceRunPath: loaded.admittedFields.sourceRunPath }
18618
19337
  };
18619
19338
  return seatLoadedResult(loaded, admitted);
18620
19339
  }
@@ -18629,11 +19348,13 @@ var init_run_lifecycle = __esm({
18629
19348
  "src/public-cli/run-lifecycle.ts"() {
18630
19349
  "use strict";
18631
19350
  init_activation_ledger_topology();
19351
+ init_role_run_placement();
18632
19352
  init_run_ticket_number();
18633
19353
  init_cli_errors();
18634
19354
  init_typed_provider_http();
18635
19355
  init_typed_provider_http();
18636
19356
  init_collector_config();
19357
+ init_diarist_contracts();
18637
19358
  init_engine_material();
18638
19359
  init_invocation();
18639
19360
  V1_RESUMABLE_PROVIDERS = ["openai-codex", "xai"];
@@ -18660,8 +19381,8 @@ __export(notary_source_run_exports, {
18660
19381
  loadNotarySourceRunLocator: () => loadNotarySourceRunLocator,
18661
19382
  resolveNotarySourceRunLocator: () => resolveNotarySourceRunLocator
18662
19383
  });
18663
- import { dirname as dirname8, isAbsolute as isAbsolute6, join as join12, resolve as resolve7, basename as basename5 } from "node:path";
18664
- import { lstat as lstat2, realpath as realpath3 } from "node:fs/promises";
19384
+ import { dirname as dirname8, isAbsolute as isAbsolute6, join as join14, resolve as resolve6, basename as basename5 } from "node:path";
19385
+ import { lstat as lstat3, realpath as realpath3 } from "node:fs/promises";
18665
19386
  function parseRunDirectoryName(name) {
18666
19387
  const match = RUN_DIR_NAME.exec(name);
18667
19388
  if (match === null) return void 0;
@@ -18679,7 +19400,7 @@ async function requireRunDirectory(candidate, display) {
18679
19400
  }
18680
19401
  let stat2;
18681
19402
  try {
18682
- stat2 = await lstat2(real);
19403
+ stat2 = await lstat3(real);
18683
19404
  } catch (error) {
18684
19405
  throw new NotarySourceRunError(
18685
19406
  `notary --source-run is not a readable run directory: ${display}`,
@@ -18706,19 +19427,20 @@ async function resolveNotarySourceRunLocator(options) {
18706
19427
  }
18707
19428
  const ledgerHome = resolveActivationLedgerHome(options.home);
18708
19429
  const bookKey = resolveBookKeyFromGit(options.projectRoot);
18709
- const bookRunsRoot = join12(activationBookDirectory(ledgerHome, bookKey), "runs");
19430
+ const bookRunsRoot = join14(activationBookDirectory(ledgerHome, bookKey), "runs");
18710
19431
  let candidate;
18711
19432
  const bare = parseRunDirectoryName(raw);
18712
19433
  if (bare !== void 0 && !raw.includes("/") && !raw.includes("\\")) {
18713
- candidate = join12(bookRunsRoot, `${bare.runId}@${bare.role}`);
19434
+ candidate = await findRunDirectoryById(options.home, bare.runId, bookKey, bare.role) ?? join14(bookRunsRoot, `${bare.runId}@${bare.role}`);
18714
19435
  } else {
18715
- candidate = isAbsolute6(raw) ? raw : resolve7(options.projectRoot, raw);
19436
+ candidate = isAbsolute6(raw) ? raw : resolve6(options.projectRoot, raw);
18716
19437
  }
18717
19438
  const real = await requireRunDirectory(candidate, raw);
18718
19439
  const identity = parseRunDirectoryName(basename5(real));
18719
- const runsRootIdentity = physicalPathIdentity(bookRunsRoot);
19440
+ const bookIdentity = physicalPathIdentity(activationBookDirectory(ledgerHome, bookKey));
18720
19441
  const parentIdentity = physicalPathIdentity(dirname8(real));
18721
- if (parentIdentity !== runsRootIdentity) {
19442
+ const subjectBookIdentity = physicalPathIdentity(dirname8(dirname8(dirname8(real))));
19443
+ if (parentIdentity !== physicalPathIdentity(bookRunsRoot) && !(basename5(dirname8(real)) === "runs" && subjectBookIdentity === bookIdentity)) {
18722
19444
  throw new NotarySourceRunError(
18723
19445
  "notary --source-run must resolve to a retained run under the project machine-ledger book"
18724
19446
  );
@@ -19429,8 +20151,8 @@ var init_option_definitions = __esm({
19429
20151
  repeatable: false,
19430
20152
  form: "option",
19431
20153
  description: {
19432
- en: "Optional project-relative .ak-roles/books/<book>/issues/<n>/runs override matching --issue.",
19433
- zh: "\u53EF\u9009\u9879\u76EE\u76F8\u5BF9 .ak-roles/books/<book>/issues/<n>/runs \u8986\u76D6\uFF0C\u4E14\u987B\u5339\u914D --issue\u3002"
20154
+ en: "Optional project-relative .ak-roles/books/<book>/<n>/runs override matching --issue.",
20155
+ zh: "\u53EF\u9009\u9879\u76EE\u76F8\u5BF9 .ak-roles/books/<book>/<n>/runs \u8986\u76D6\uFF0C\u4E14\u987B\u5339\u914D --issue\u3002"
19434
20156
  }
19435
20157
  }
19436
20158
  ];
@@ -19865,6 +20587,7 @@ __export(invocation_exports, {
19865
20587
  admitNotaryInvocation: () => admitNotaryInvocation,
19866
20588
  admitReviewerInvocation: () => admitReviewerInvocation,
19867
20589
  bindAdmittedTicketNumber: () => bindAdmittedTicketNumber,
20590
+ bindCourtTicketNumbersOnAdmitted: () => bindCourtTicketNumbersOnAdmitted,
19868
20591
  bindTicketNumberOnRunDirectory: () => bindTicketNumberOnRunDirectory,
19869
20592
  buildCoderTransportPrompt: () => buildCoderTransportPrompt,
19870
20593
  buildCollectorTransportPrompt: () => buildCollectorTransportPrompt,
@@ -19909,31 +20632,34 @@ __export(invocation_exports, {
19909
20632
  recordEffectiveInvocationModel: () => recordEffectiveInvocationModel,
19910
20633
  recordLaunchedPiIdentity: () => recordLaunchedPiIdentity,
19911
20634
  recordLaunchedRolePackageIdentity: () => recordLaunchedRolePackageIdentity,
20635
+ relocateAdmittedRunToTicket: () => relocateAdmittedRunToTicket,
19912
20636
  requireAuthorityRef: () => requireAuthorityRef,
19913
20637
  resolveDoctorCaseRunsPath: () => resolveDoctorCaseRunsPath,
19914
20638
  resolveGitHubRemoteRepository: () => resolveGitHubRemoteRepository
19915
20639
  });
19916
20640
  import { execFileSync as execFileSync3 } from "node:child_process";
19917
- import { existsSync as existsSync5 } from "node:fs";
20641
+ import { existsSync as existsSync6 } from "node:fs";
19918
20642
  import {
19919
- lstat as lstat3,
19920
- mkdir as mkdir2,
19921
- readFile as readFile10,
20643
+ lstat as lstat4,
20644
+ readFile as readFile11,
19922
20645
  realpath as realpath4,
19923
- writeFile as writeFile4
20646
+ rename,
20647
+ writeFile as writeFile5
19924
20648
  } from "node:fs/promises";
19925
- import { basename as basename6, isAbsolute as isAbsolute7, join as join13, resolve as resolve8, sep as sep3 } from "node:path";
20649
+ import { basename as basename6, dirname as dirname9, isAbsolute as isAbsolute7, join as join15, resolve as resolve7, sep as sep4 } from "node:path";
19926
20650
  function issueAdmissionPlacement(authority, request) {
19927
- const principal = authority.issue(request);
19928
- const { sessionDirectory, sessionFile } = authority.decode(principal);
19929
- const runDirectory = join13(sessionDirectory, "..");
19930
20651
  const ledgerHome = resolveActivationLedgerHome(request.home);
19931
20652
  const bookKey = resolveBookKeyFromGit(request.cwd);
20653
+ const placement = roleRunPlacement(ledgerHome, {
20654
+ bookKey,
20655
+ subject: request.subject,
20656
+ runId: request.runId,
20657
+ role: request.role
20658
+ });
20659
+ ensureRoleRunPlacement(ledgerHome, placement);
19932
20660
  return {
19933
- principal,
19934
- sessionDirectory,
19935
- sessionFile,
19936
- runDirectory,
20661
+ principal: authority.seal(placement),
20662
+ ...placement,
19937
20663
  ledgerHome,
19938
20664
  bookKey
19939
20665
  };
@@ -19945,7 +20671,7 @@ async function writeAdmittedRequestPersistence(admittedRequestPath, body, coordi
19945
20671
  sessionDirectory: coordinates.sessionDirectory,
19946
20672
  sessionFile: coordinates.sessionFile
19947
20673
  };
19948
- await writeFile4(
20674
+ await writeFile5(
19949
20675
  admittedRequestPath,
19950
20676
  `${JSON.stringify(projection, null, 2)}
19951
20677
  `,
@@ -19973,16 +20699,16 @@ async function writeRoleInvocationLedger(source, role, effectiveModel) {
19973
20699
  ...source.ticketNumber === void 0 ? {} : { ticketNumber: source.ticketNumber },
19974
20700
  ...effectiveModelLedgerFields(effectiveModel)
19975
20701
  };
19976
- await writeFile4(
19977
- join13(source.runDirectory, "invocation.json"),
20702
+ await writeFile5(
20703
+ join15(source.runDirectory, "invocation.json"),
19978
20704
  `${JSON.stringify(identity, null, 2)}
19979
20705
  `,
19980
20706
  "utf8"
19981
20707
  );
19982
20708
  }
19983
20709
  async function recordEffectiveInvocationModel(runDirectory, model, engine, host, engineModel) {
19984
- const ledgerPath = join13(runDirectory, "invocation.json");
19985
- const current = JSON.parse(await readFile10(ledgerPath, "utf8"));
20710
+ const ledgerPath = join15(runDirectory, "invocation.json");
20711
+ const current = JSON.parse(await readFile11(ledgerPath, "utf8"));
19986
20712
  const next = { ...current };
19987
20713
  if (model !== void 0) {
19988
20714
  next.provider = model.provider;
@@ -20006,7 +20732,7 @@ async function recordEffectiveInvocationModel(runDirectory, model, engine, host,
20006
20732
  if (host !== void 0) {
20007
20733
  next.host = host;
20008
20734
  }
20009
- await writeFile4(
20735
+ await writeFile5(
20010
20736
  ledgerPath,
20011
20737
  `${JSON.stringify(next, null, 2)}
20012
20738
  `,
@@ -20014,9 +20740,9 @@ async function recordEffectiveInvocationModel(runDirectory, model, engine, host,
20014
20740
  );
20015
20741
  }
20016
20742
  async function mergeInvocationIdentityPage(runDirectory, fields) {
20017
- const ledgerPath = join13(runDirectory, "invocation.json");
20018
- const current = JSON.parse(await readFile10(ledgerPath, "utf8"));
20019
- await writeFile4(
20743
+ const ledgerPath = join15(runDirectory, "invocation.json");
20744
+ const current = JSON.parse(await readFile11(ledgerPath, "utf8"));
20745
+ await writeFile5(
20020
20746
  ledgerPath,
20021
20747
  `${JSON.stringify({
20022
20748
  ...current,
@@ -20031,14 +20757,14 @@ async function persistAdmittedSourceRunPath(admitted, sourceRunPath) {
20031
20757
  throw new Error("persistAdmittedSourceRunPath requires a non-empty sourceRunPath");
20032
20758
  }
20033
20759
  const admittedPath = admitted.admittedRequestPath;
20034
- const current = JSON.parse(await readFile10(admittedPath, "utf8"));
20760
+ const current = JSON.parse(await readFile11(admittedPath, "utf8"));
20035
20761
  if (typeof current.sourceRunPath === "string") {
20036
20762
  if (current.sourceRunPath === sourceRunPath) return;
20037
20763
  throw new Error(
20038
20764
  `persistAdmittedSourceRunPath refuses to replace ${current.sourceRunPath} with ${sourceRunPath}`
20039
20765
  );
20040
20766
  }
20041
- await writeFile4(
20767
+ await writeFile5(
20042
20768
  admittedPath,
20043
20769
  `${JSON.stringify({ ...current, sourceRunPath }, null, 2)}
20044
20770
  `,
@@ -20046,35 +20772,103 @@ async function persistAdmittedSourceRunPath(admitted, sourceRunPath) {
20046
20772
  );
20047
20773
  }
20048
20774
  async function bindAdmittedTicketNumber(admitted, ticketNumber) {
20049
- if (!Number.isSafeInteger(ticketNumber) || ticketNumber < 1) {
20050
- throw new Error(`bindAdmittedTicketNumber requires a safe positive integer, got ${String(ticketNumber)}`);
20051
- }
20052
20775
  if (admitted.ticketNumber !== void 0) {
20053
20776
  if (admitted.ticketNumber === ticketNumber) return;
20054
20777
  throw new Error(
20055
20778
  `bindAdmittedTicketNumber refuses to replace existing ticket #${admitted.ticketNumber} with #${ticketNumber}`
20056
20779
  );
20057
20780
  }
20781
+ await bindTicketNumberOnRunDirectory(admitted.runDirectory, ticketNumber);
20058
20782
  admitted.ticketNumber = ticketNumber;
20059
- await mergeInvocationIdentityPage(admitted.runDirectory, { ticketNumber });
20783
+ }
20784
+ async function bindCourtTicketNumbersOnAdmitted(admitted, courtTicketNumbers) {
20785
+ if (admitted.ticketNumber === void 0) {
20786
+ throw new Error(
20787
+ "bindCourtTicketNumbersOnAdmitted requires a bound principal ticketNumber"
20788
+ );
20789
+ }
20790
+ const principal = requireSafePositiveTicketNumber(
20791
+ admitted.ticketNumber,
20792
+ "bindCourtTicketNumbersOnAdmitted principal ticketNumber"
20793
+ );
20794
+ for (const item of courtTicketNumbers) {
20795
+ if (!isSafePositiveTicketNumber(item)) {
20796
+ throw new Error(
20797
+ `bindCourtTicketNumbersOnAdmitted requires safe positive integers, got ${String(item)}`
20798
+ );
20799
+ }
20800
+ }
20801
+ const projected = projectCourtTicketNumbers(courtTicketNumbers, {
20802
+ principalTicket: principal
20803
+ });
20804
+ if (projected === null || projected.length === 0) {
20805
+ throw new Error("bindCourtTicketNumbersOnAdmitted requires a non-empty ticket set");
20806
+ }
20807
+ const frozen = Object.freeze([...projected]);
20060
20808
  const admittedPath = admitted.admittedRequestPath;
20061
- const current = JSON.parse(await readFile10(admittedPath, "utf8"));
20062
- await writeFile4(
20809
+ const current = JSON.parse(await readFile11(admittedPath, "utf8"));
20810
+ await writeFile5(
20063
20811
  admittedPath,
20064
- `${JSON.stringify({ ...current, ticketNumber }, null, 2)}
20812
+ `${JSON.stringify({ ...current, courtTicketNumbers: frozen }, null, 2)}
20065
20813
  `,
20066
20814
  "utf8"
20067
20815
  );
20816
+ await mergeInvocationIdentityPage(admitted.runDirectory, {
20817
+ courtTicketNumbers: frozen
20818
+ });
20819
+ admitted.courtTicketNumbers = frozen;
20068
20820
  }
20069
- async function bindTicketNumberOnRunDirectory(runDirectory, ticketNumber) {
20070
- if (!Number.isSafeInteger(ticketNumber) || ticketNumber < 1) {
20071
- throw new Error(
20072
- `bindTicketNumberOnRunDirectory requires a safe positive integer, got ${String(ticketNumber)}`
20821
+ async function relocateAdmittedRunToTicket(admitted, authority, heldLease) {
20822
+ if (admitted.ticketNumber === void 0 || !admitted.runDirectory.includes(`${sep4}unbound${sep4}runs${sep4}`)) return;
20823
+ const oldRunDirectory = admitted.runDirectory;
20824
+ const ledgerHome = resolveActivationLedgerHome(homeFromRunDirectory(oldRunDirectory));
20825
+ const target = roleRunPlacement(ledgerHome, {
20826
+ bookKey: admitted.bookKey,
20827
+ subject: { ticketNumber: admitted.ticketNumber },
20828
+ runId: admitted.runId,
20829
+ role: admitted.role
20830
+ });
20831
+ ensureRoleRunDirectory(ledgerHome, dirname9(target.runDirectory));
20832
+ await rename(oldRunDirectory, target.runDirectory);
20833
+ heldLease?.relocate(target.runDirectory);
20834
+ const admittedRecord = admitted;
20835
+ rewriteRunDirectoryPathFields(
20836
+ admittedRecord,
20837
+ [
20838
+ "runDirectory",
20839
+ "admittedRequestPath",
20840
+ "taskPath",
20841
+ "packetPath",
20842
+ "prerequisitesPath",
20843
+ "requestManifestPath",
20844
+ "mergerInputPath"
20845
+ ],
20846
+ oldRunDirectory,
20847
+ target.runDirectory
20848
+ );
20849
+ for (const attachment of admitted.attachments) {
20850
+ attachment.frozenPath = rewriteRunDirectoryPathValue(
20851
+ attachment.frozenPath,
20852
+ oldRunDirectory,
20853
+ target.runDirectory
20073
20854
  );
20074
20855
  }
20075
- const admittedPath = join13(runDirectory, "admitted-request.json");
20076
- const invocationPath = join13(runDirectory, "invocation.json");
20077
- const admitted = JSON.parse(await readFile10(admittedPath, "utf8"));
20856
+ const principal = authority.seal(target);
20857
+ admitted.principal = principal;
20858
+ await rewriteRoleRunDurablePages({
20859
+ pagesDirectory: target.runDirectory,
20860
+ oldRunDirectory,
20861
+ newRunDirectory: target.runDirectory
20862
+ });
20863
+ }
20864
+ async function bindTicketNumberOnRunDirectory(runDirectory, ticketNumber) {
20865
+ requireSafePositiveTicketNumber(
20866
+ ticketNumber,
20867
+ "bindTicketNumberOnRunDirectory"
20868
+ );
20869
+ const admittedPath = join15(runDirectory, "admitted-request.json");
20870
+ const invocationPath = join15(runDirectory, "invocation.json");
20871
+ const admitted = JSON.parse(await readFile11(admittedPath, "utf8"));
20078
20872
  const existing = admitted.ticketNumber;
20079
20873
  if (typeof existing === "number") {
20080
20874
  if (existing === ticketNumber) return;
@@ -20082,9 +20876,9 @@ async function bindTicketNumberOnRunDirectory(runDirectory, ticketNumber) {
20082
20876
  `bindTicketNumberOnRunDirectory refuses to replace existing ticket #${existing} with #${ticketNumber}`
20083
20877
  );
20084
20878
  }
20085
- if (existsSync5(invocationPath)) {
20879
+ if (existsSync6(invocationPath)) {
20086
20880
  const invocation = JSON.parse(
20087
- await readFile10(invocationPath, "utf8")
20881
+ await readFile11(invocationPath, "utf8")
20088
20882
  );
20089
20883
  if (typeof invocation.ticketNumber === "number" && invocation.ticketNumber !== ticketNumber) {
20090
20884
  throw new Error(
@@ -20092,7 +20886,7 @@ async function bindTicketNumberOnRunDirectory(runDirectory, ticketNumber) {
20092
20886
  );
20093
20887
  }
20094
20888
  }
20095
- await writeFile4(
20889
+ await writeFile5(
20096
20890
  admittedPath,
20097
20891
  `${JSON.stringify({ ...admitted, ticketNumber }, null, 2)}
20098
20892
  `,
@@ -20109,7 +20903,7 @@ async function recordLaunchedPiIdentity(runDirectory, identity) {
20109
20903
  async function observeLaunchedRolePackageIdentity(packageRoot2, selectedRoleEntry) {
20110
20904
  const rolePackageRoot = packageRoot2;
20111
20905
  const raw = JSON.parse(
20112
- await readFile10(join13(rolePackageRoot, "package.json"), "utf8")
20906
+ await readFile11(join15(rolePackageRoot, "package.json"), "utf8")
20113
20907
  );
20114
20908
  if (typeof raw.version !== "string" || raw.version.trim() === "") {
20115
20909
  throw new Error(
@@ -20350,10 +21144,10 @@ function parseFixerArgv(args) {
20350
21144
  };
20351
21145
  }
20352
21146
  async function freezeRegularFileAttachment(sourcePath, destinationDir, index) {
20353
- const absolute = isAbsolute7(sourcePath) ? sourcePath : resolve8(sourcePath);
21147
+ const absolute = isAbsolute7(sourcePath) ? sourcePath : resolve7(sourcePath);
20354
21148
  let st;
20355
21149
  try {
20356
- st = await lstat3(absolute);
21150
+ st = await lstat4(absolute);
20357
21151
  } catch (error) {
20358
21152
  throw new CliUsageError(
20359
21153
  `attachment is not a readable regular file: ${sourcePath}`,
@@ -20365,10 +21159,10 @@ async function freezeRegularFileAttachment(sourcePath, destinationDir, index) {
20365
21159
  `attachment must be a regular file (not a directory or symlink): ${sourcePath}`
20366
21160
  );
20367
21161
  }
20368
- const bytes = await readFile10(absolute);
21162
+ const bytes = await readFile11(absolute);
20369
21163
  const name = `${String(index).padStart(2, "0")}-${basename6(absolute)}`;
20370
- const frozenPath = join13(destinationDir, name);
20371
- await writeFile4(frozenPath, bytes);
21164
+ const frozenPath = join15(destinationDir, name);
21165
+ await writeFile5(frozenPath, bytes);
20372
21166
  return {
20373
21167
  attachment: {
20374
21168
  provenancePath: absolute,
@@ -20395,35 +21189,41 @@ async function freezeAttachments(attachmentPaths, attachmentsDirectory) {
20395
21189
  async function freezeAttachmentsIntoRun(attachmentPaths, runDirectory, summonsKey = `s-${Date.now().toString(36)}`) {
20396
21190
  if (attachmentPaths.length === 0) return [];
20397
21191
  const ledgerHome = resolveActivationLedgerHome(homeFromRunDirectory(runDirectory));
20398
- const attachmentsDirectory = join13(runDirectory, "attachments", summonsKey);
21192
+ const attachmentsDirectory = join15(runDirectory, "attachments", summonsKey);
20399
21193
  ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
20400
21194
  return freezeAttachments(attachmentPaths, attachmentsDirectory);
20401
21195
  }
20402
21196
  function ticketAdmissionFields(ticketNumber) {
20403
- return ticketNumber === void 0 ? {} : { ticketNumber };
21197
+ if (ticketNumber === void 0) return {};
21198
+ return {
21199
+ ticketNumber: requireSafePositiveTicketNumber(
21200
+ ticketNumber,
21201
+ "assertedTicketNumber"
21202
+ )
21203
+ };
20404
21204
  }
20405
21205
  async function admitStandardMaterialInvocation(role, options) {
20406
21206
  if (options.project !== void 0) {
20407
21207
  requireOptionPath("--project", options.project);
20408
21208
  }
20409
- const projectRoot = resolve8(options.project ?? options.cwd);
21209
+ const projectRoot = resolve7(options.project ?? options.cwd);
20410
21210
  const runId = (options.createRunId ?? uuidv7)();
21211
+ const ticketFields = ticketAdmissionFields(options.assertedTicketNumber);
20411
21212
  const {
20412
21213
  principal,
20413
21214
  sessionDirectory,
20414
21215
  sessionFile,
20415
21216
  runDirectory,
21217
+ attachmentsDirectory,
20416
21218
  ledgerHome,
20417
21219
  bookKey
20418
21220
  } = issueAdmissionPlacement(options.principalAuthority, {
20419
21221
  cwd: projectRoot,
20420
21222
  runId,
20421
21223
  role,
21224
+ subject: ticketFields.ticketNumber === void 0 ? { unbound: true } : { ticketNumber: ticketFields.ticketNumber },
20422
21225
  home: options.home
20423
21226
  });
20424
- const attachmentsDirectory = join13(runDirectory, "attachments");
20425
- ensureRealDirectoryTree(ledgerHome, sessionDirectory);
20426
- ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
20427
21227
  const attachments = await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
20428
21228
  const correlationFields = options.correlationId === void 0 ? {} : { correlationId: options.correlationId };
20429
21229
  const instruction = options.instruction;
@@ -20444,9 +21244,10 @@ async function admitStandardMaterialInvocation(role, options) {
20444
21244
  byteLength: a.byteLength,
20445
21245
  sha256: a.sha256,
20446
21246
  mediaKind: a.mediaKind
20447
- }))
21247
+ })),
21248
+ ...ticketFields
20448
21249
  };
20449
- const admittedRequestPath = join13(runDirectory, "admitted-request.json");
21250
+ const admittedRequestPath = join15(runDirectory, "admitted-request.json");
20450
21251
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
20451
21252
  sessionDirectory,
20452
21253
  sessionFile
@@ -20467,7 +21268,8 @@ async function admitStandardMaterialInvocation(role, options) {
20467
21268
  runDirectory,
20468
21269
  principal,
20469
21270
  admittedRequestPath,
20470
- ...correlationFields
21271
+ ...correlationFields,
21272
+ ...ticketFields
20471
21273
  };
20472
21274
  }
20473
21275
  async function admitJudgeInvocation(options) {
@@ -20509,24 +21311,23 @@ async function admitCountersignInvocation(options) {
20509
21311
  if (options.project !== void 0) {
20510
21312
  requireOptionPath("--project", options.project);
20511
21313
  }
20512
- const projectRoot = resolve8(options.project ?? options.cwd);
21314
+ const projectRoot = resolve7(options.project ?? options.cwd);
20513
21315
  const runId = (options.createRunId ?? uuidv7)();
20514
21316
  const {
20515
21317
  principal,
20516
21318
  sessionDirectory,
20517
21319
  sessionFile,
20518
21320
  runDirectory,
21321
+ attachmentsDirectory,
20519
21322
  ledgerHome,
20520
21323
  bookKey
20521
21324
  } = issueAdmissionPlacement(options.principalAuthority, {
20522
21325
  cwd: projectRoot,
20523
21326
  runId,
20524
21327
  role: "countersign",
21328
+ subject: { unbound: true },
20525
21329
  home: options.home
20526
21330
  });
20527
- const attachmentsDirectory = join13(runDirectory, "attachments");
20528
- ensureRealDirectoryTree(ledgerHome, sessionDirectory);
20529
- ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
20530
21331
  const attachments = await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
20531
21332
  const instruction = options.instruction;
20532
21333
  const instructionEmpty = instruction.trim() === "";
@@ -20548,7 +21349,7 @@ async function admitCountersignInvocation(options) {
20548
21349
  mediaKind: a.mediaKind
20549
21350
  }))
20550
21351
  };
20551
- const admittedRequestPath = join13(runDirectory, "admitted-request.json");
21352
+ const admittedRequestPath = join15(runDirectory, "admitted-request.json");
20552
21353
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
20553
21354
  sessionDirectory,
20554
21355
  sessionFile
@@ -20574,7 +21375,7 @@ function buildCountersignTransportPrompt(admitted, engineMaterial) {
20574
21375
  async function loadAdmittedJudgeRequest(runDirectory) {
20575
21376
  try {
20576
21377
  const raw = JSON.parse(
20577
- await readFile10(join13(runDirectory, "admitted-request.json"), "utf8")
21378
+ await readFile11(join15(runDirectory, "admitted-request.json"), "utf8")
20578
21379
  );
20579
21380
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return void 0;
20580
21381
  const record4 = raw;
@@ -20592,9 +21393,11 @@ async function loadAdmittedJudgeRequest(runDirectory) {
20592
21393
  }
20593
21394
  }
20594
21395
  async function ensureRunArtifactsDir(runDirectory) {
20595
- const dir = join13(runDirectory, "artifacts");
20596
- await mkdir2(dir, { recursive: true });
20597
- return dir;
21396
+ const directory = roleRunArtifactsDirectory(runDirectory);
21397
+ return ensureRoleRunDirectory(
21398
+ resolveActivationLedgerHome(homeFromRunDirectory(runDirectory)),
21399
+ directory
21400
+ );
20598
21401
  }
20599
21402
  async function admitCoderInvocation(options) {
20600
21403
  if (options.project !== void 0) {
@@ -20609,27 +21412,26 @@ async function admitCoderInvocation(options) {
20609
21412
  if (options.phase !== "plan" && options.phase !== "apply") {
20610
21413
  throw new CliUsageError("coder phase must be plan or apply");
20611
21414
  }
20612
- const projectRoot = resolve8(options.project ?? options.cwd);
21415
+ const projectRoot = resolve7(options.project ?? options.cwd);
20613
21416
  const runId = (options.createRunId ?? uuidv7)();
20614
21417
  const {
20615
21418
  principal,
20616
21419
  sessionDirectory,
20617
21420
  sessionFile,
20618
21421
  runDirectory,
21422
+ attachmentsDirectory,
20619
21423
  ledgerHome,
20620
21424
  bookKey
20621
21425
  } = issueAdmissionPlacement(options.principalAuthority, {
20622
21426
  cwd: projectRoot,
20623
21427
  runId,
20624
21428
  role: "coder",
21429
+ subject: { unbound: true },
20625
21430
  home: options.home
20626
21431
  });
20627
- const attachmentsDirectory = join13(runDirectory, "attachments");
20628
- ensureRealDirectoryTree(ledgerHome, sessionDirectory);
20629
- ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
20630
21432
  const attachments = await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
20631
- const taskPath = join13(runDirectory, "task.md");
20632
- await writeFile4(taskPath, instruction, "utf8");
21433
+ const taskPath = join15(runDirectory, "task.md");
21434
+ await writeFile5(taskPath, instruction, "utf8");
20633
21435
  const admitted = {
20634
21436
  role: "coder",
20635
21437
  phase: options.phase,
@@ -20649,7 +21451,7 @@ async function admitCoderInvocation(options) {
20649
21451
  mediaKind: a.mediaKind
20650
21452
  }))
20651
21453
  };
20652
- const admittedRequestPath = join13(runDirectory, "admitted-request.json");
21454
+ const admittedRequestPath = join15(runDirectory, "admitted-request.json");
20653
21455
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
20654
21456
  sessionDirectory,
20655
21457
  sessionFile
@@ -20697,9 +21499,9 @@ async function admitFixerInvocation(options) {
20697
21499
  let prerequisites = Object.freeze([]);
20698
21500
  let prerequisitesSource;
20699
21501
  if (options.prerequisitesPath !== void 0) {
20700
- const absolutePrereq = isAbsolute7(options.prerequisitesPath) ? options.prerequisitesPath : resolve8(options.prerequisitesPath);
21502
+ const absolutePrereq = isAbsolute7(options.prerequisitesPath) ? options.prerequisitesPath : resolve7(options.prerequisitesPath);
20701
21503
  try {
20702
- prerequisitesSource = await readFile10(absolutePrereq, "utf8");
21504
+ prerequisitesSource = await readFile11(absolutePrereq, "utf8");
20703
21505
  } catch (error) {
20704
21506
  throw new CliUsageError(
20705
21507
  `fixer prerequisites path is unreadable: ${options.prerequisitesPath}`,
@@ -20715,37 +21517,36 @@ async function admitFixerInvocation(options) {
20715
21517
  throw error;
20716
21518
  }
20717
21519
  }
20718
- const projectRoot = resolve8(options.project ?? options.cwd);
21520
+ const projectRoot = resolve7(options.project ?? options.cwd);
20719
21521
  const runId = (options.createRunId ?? uuidv7)();
20720
21522
  const {
20721
21523
  principal,
20722
21524
  sessionDirectory,
20723
21525
  sessionFile,
20724
21526
  runDirectory,
21527
+ attachmentsDirectory,
20725
21528
  ledgerHome,
20726
21529
  bookKey
20727
21530
  } = issueAdmissionPlacement(options.principalAuthority, {
20728
21531
  cwd: projectRoot,
20729
21532
  runId,
20730
21533
  role: "fixer",
21534
+ subject: { unbound: true },
20731
21535
  home: options.home
20732
21536
  });
20733
- const attachmentsDirectory = join13(runDirectory, "attachments");
20734
- ensureRealDirectoryTree(ledgerHome, sessionDirectory);
20735
- ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
20736
21537
  const attachments = await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
20737
21538
  let prerequisitesPath;
20738
21539
  if (prerequisitesSource !== void 0) {
20739
- prerequisitesPath = join13(runDirectory, "prerequisites.json");
20740
- await writeFile4(
21540
+ prerequisitesPath = join15(runDirectory, "prerequisites.json");
21541
+ await writeFile5(
20741
21542
  prerequisitesPath,
20742
21543
  `${JSON.stringify(prerequisites, null, 2)}
20743
21544
  `,
20744
21545
  "utf8"
20745
21546
  );
20746
21547
  }
20747
- const packetPath = join13(runDirectory, "fix-packet.md");
20748
- await writeFile4(packetPath, instruction, "utf8");
21548
+ const packetPath = join15(runDirectory, "fix-packet.md");
21549
+ await writeFile5(packetPath, instruction, "utf8");
20749
21550
  const admitted = {
20750
21551
  role: "fixer",
20751
21552
  phase: options.phase,
@@ -20770,7 +21571,7 @@ async function admitFixerInvocation(options) {
20770
21571
  mediaKind: a.mediaKind
20771
21572
  }))
20772
21573
  };
20773
- const admittedRequestPath = join13(runDirectory, "admitted-request.json");
21574
+ const admittedRequestPath = join15(runDirectory, "admitted-request.json");
20774
21575
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
20775
21576
  sessionDirectory,
20776
21577
  sessionFile
@@ -20940,7 +21741,7 @@ async function admitCollectorInvocation(options) {
20940
21741
  throw new CliUsageError(detail, { cause: error });
20941
21742
  }
20942
21743
  }
20943
- const projectRoot = resolve8(options.project ?? options.cwd);
21744
+ const projectRoot = resolve7(options.project ?? options.cwd);
20944
21745
  let repository;
20945
21746
  if (options.repo !== void 0) {
20946
21747
  try {
@@ -20969,17 +21770,16 @@ async function admitCollectorInvocation(options) {
20969
21770
  sessionDirectory,
20970
21771
  sessionFile,
20971
21772
  runDirectory,
21773
+ attachmentsDirectory,
20972
21774
  ledgerHome,
20973
21775
  bookKey
20974
21776
  } = issueAdmissionPlacement(options.principalAuthority, {
20975
21777
  cwd: projectRoot,
20976
21778
  runId,
20977
21779
  role: "collector",
21780
+ subject: { unbound: true },
20978
21781
  home: options.home
20979
21782
  });
20980
- const attachmentsDirectory = join13(runDirectory, "attachments");
20981
- ensureRealDirectoryTree(ledgerHome, sessionDirectory);
20982
- ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
20983
21783
  const attachments = await freezeAttachments(options.attachmentPaths ?? [], attachmentsDirectory);
20984
21784
  const instruction = options.instruction ?? "";
20985
21785
  const instructionEmpty = instruction.trim() === "";
@@ -20991,8 +21791,8 @@ async function admitCollectorInvocation(options) {
20991
21791
  const prNumber = target.kind === "bound" ? target.prNumber : void 0;
20992
21792
  let requestManifestPath;
20993
21793
  if (manifestCanonicalJson !== void 0) {
20994
- requestManifestPath = join13(runDirectory, "request-manifest.json");
20995
- await writeFile4(requestManifestPath, manifestCanonicalJson, "utf8");
21794
+ requestManifestPath = join15(runDirectory, "request-manifest.json");
21795
+ await writeFile5(requestManifestPath, manifestCanonicalJson, "utf8");
20996
21796
  }
20997
21797
  const admitted = {
20998
21798
  role: "collector",
@@ -21017,7 +21817,7 @@ async function admitCollectorInvocation(options) {
21017
21817
  mediaKind: a.mediaKind
21018
21818
  }))
21019
21819
  };
21020
- const admittedRequestPath = join13(runDirectory, "admitted-request.json");
21820
+ const admittedRequestPath = join15(runDirectory, "admitted-request.json");
21021
21821
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
21022
21822
  sessionDirectory,
21023
21823
  sessionFile
@@ -21115,9 +21915,8 @@ function parseDoctorArgv(args) {
21115
21915
  }
21116
21916
  async function resolveDoctorCaseRunsPath(options) {
21117
21917
  const ledgerHome = resolveActivationLedgerHome(options.home);
21118
- const defaultRuns = join13(
21918
+ const defaultRuns = join15(
21119
21919
  activationBookDirectory(ledgerHome, options.bookKey),
21120
- "issues",
21121
21920
  String(options.issueNumber),
21122
21921
  "runs"
21123
21922
  );
@@ -21133,7 +21932,7 @@ async function resolveDoctorCaseRunsPath(options) {
21133
21932
  "doctor --runs must be a project-relative path"
21134
21933
  );
21135
21934
  }
21136
- const resolved = resolve8(options.projectRoot, raw);
21935
+ const resolved = resolve7(options.projectRoot, raw);
21137
21936
  if (resolved !== options.projectRoot && !pathContainedIn(options.projectRoot, resolved)) {
21138
21937
  throw new CliUsageError(
21139
21938
  "doctor --runs escapes the project root"
@@ -21149,11 +21948,11 @@ async function resolveDoctorCaseRunsPath(options) {
21149
21948
  { cause: error }
21150
21949
  );
21151
21950
  }
21152
- const normalized = real.split(sep3).join("/");
21951
+ const normalized = real.split(sep4).join("/");
21153
21952
  const match = normalized.match(DOCTOR_CASE_RUNS_PATH_PATTERN);
21154
21953
  if (!match) {
21155
21954
  throw new CliUsageError(
21156
- "doctor --runs must be an .ak-roles/books/<book>/issues/<n>/runs directory"
21955
+ "doctor --runs must be an .ak-roles/books/<book>/<n>/runs directory"
21157
21956
  );
21158
21957
  }
21159
21958
  if (Number(match[1]) !== options.issueNumber) {
@@ -21172,19 +21971,21 @@ async function admitDoctorInvocation(options) {
21172
21971
  `doctor --issue must be a positive integer, got ${options.issueNumber}`
21173
21972
  );
21174
21973
  }
21175
- const projectRoot = resolve8(options.project ?? options.cwd);
21974
+ const projectRoot = resolve7(options.project ?? options.cwd);
21176
21975
  const runId = (options.createRunId ?? uuidv7)();
21177
21976
  const {
21178
21977
  principal,
21179
21978
  sessionDirectory,
21180
21979
  sessionFile,
21181
21980
  runDirectory,
21981
+ attachmentsDirectory,
21182
21982
  ledgerHome,
21183
21983
  bookKey
21184
21984
  } = issueAdmissionPlacement(options.principalAuthority, {
21185
21985
  cwd: projectRoot,
21186
21986
  runId,
21187
21987
  role: "doctor",
21988
+ subject: { unbound: true },
21188
21989
  home: options.home
21189
21990
  });
21190
21991
  let caseRunsPath;
@@ -21222,9 +22023,6 @@ async function admitDoctorInvocation(options) {
21222
22023
  { cause: error }
21223
22024
  );
21224
22025
  }
21225
- const attachmentsDirectory = join13(runDirectory, "attachments");
21226
- ensureRealDirectoryTree(ledgerHome, sessionDirectory);
21227
- ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
21228
22026
  const attachments = await freezeAttachments(options.attachmentPaths ?? [], attachmentsDirectory);
21229
22027
  const instruction = options.instruction ?? "";
21230
22028
  const instructionEmpty = instruction.trim() === "";
@@ -21248,7 +22046,7 @@ async function admitDoctorInvocation(options) {
21248
22046
  mediaKind: a.mediaKind
21249
22047
  }))
21250
22048
  };
21251
- const admittedRequestPath = join13(runDirectory, "admitted-request.json");
22049
+ const admittedRequestPath = join15(runDirectory, "admitted-request.json");
21252
22050
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
21253
22051
  sessionDirectory,
21254
22052
  sessionFile
@@ -21333,7 +22131,7 @@ async function admitNotaryInvocation(options) {
21333
22131
  if (options.project !== void 0) {
21334
22132
  requireOptionPath("--project", options.project);
21335
22133
  }
21336
- const projectRoot = resolve8(options.project ?? options.cwd);
22134
+ const projectRoot = resolve7(options.project ?? options.cwd);
21337
22135
  let sourceRun;
21338
22136
  try {
21339
22137
  sourceRun = await resolveNotarySourceRunLocator({
@@ -21347,24 +22145,24 @@ async function admitNotaryInvocation(options) {
21347
22145
  }
21348
22146
  throw error;
21349
22147
  }
22148
+ const inheritedTicketNumber = await readBoardTicketNumber(sourceRun.runDirectory);
21350
22149
  const runId = options.createRunId?.() ?? uuidv7();
21351
22150
  const {
21352
22151
  principal,
21353
22152
  sessionDirectory,
21354
22153
  sessionFile,
21355
22154
  runDirectory,
22155
+ attachmentsDirectory,
21356
22156
  ledgerHome,
21357
22157
  bookKey
21358
22158
  } = issueAdmissionPlacement(options.principalAuthority, {
21359
22159
  cwd: projectRoot,
21360
22160
  runId,
21361
22161
  role: "notary",
22162
+ subject: inheritedTicketNumber === void 0 ? { unbound: true } : { ticketNumber: inheritedTicketNumber },
21362
22163
  home: options.home
21363
22164
  });
21364
- ensureRealDirectoryTree(ledgerHome, sessionDirectory);
21365
- const ticketFields = ticketAdmissionFields(
21366
- await readRunTicketNumber(sourceRun.runDirectory)
21367
- );
22165
+ const ticketFields = ticketAdmissionFields(inheritedTicketNumber);
21368
22166
  const admitted = {
21369
22167
  role: "notary",
21370
22168
  runId,
@@ -21380,7 +22178,7 @@ async function admitNotaryInvocation(options) {
21380
22178
  ...ticketFields,
21381
22179
  ...options.correlationId === void 0 ? {} : { correlationId: options.correlationId }
21382
22180
  };
21383
- const admittedRequestPath = join13(runDirectory, "admitted-request.json");
22181
+ const admittedRequestPath = join15(runDirectory, "admitted-request.json");
21384
22182
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
21385
22183
  sessionDirectory,
21386
22184
  sessionFile
@@ -21451,22 +22249,23 @@ async function admitGleanerLeftInvocation(options) {
21451
22249
  if (options.baseRevision.trim() === "") {
21452
22250
  throw new CliUsageError("--base requires a nonempty revision");
21453
22251
  }
21454
- const projectRoot = resolve8(options.project ?? options.cwd);
22252
+ const projectRoot = resolve7(options.project ?? options.cwd);
21455
22253
  const runId = (options.createRunId ?? uuidv7)();
21456
22254
  const {
21457
22255
  principal,
21458
22256
  sessionDirectory,
21459
22257
  sessionFile,
21460
22258
  runDirectory,
22259
+ attachmentsDirectory,
21461
22260
  ledgerHome,
21462
22261
  bookKey
21463
22262
  } = issueAdmissionPlacement(options.principalAuthority, {
21464
22263
  cwd: projectRoot,
21465
22264
  runId,
21466
22265
  role: "gleaner-left",
22266
+ subject: { unbound: true },
21467
22267
  home: options.home
21468
22268
  });
21469
- ensureRealDirectoryTree(ledgerHome, sessionDirectory);
21470
22269
  const instruction = options.instruction;
21471
22270
  const instructionEmpty = instruction.trim() === "";
21472
22271
  const admitted = {
@@ -21482,7 +22281,7 @@ async function admitGleanerLeftInvocation(options) {
21482
22281
  attachments: [],
21483
22282
  ...options.correlationId === void 0 ? {} : { correlationId: options.correlationId }
21484
22283
  };
21485
- const admittedRequestPath = join13(runDirectory, "admitted-request.json");
22284
+ const admittedRequestPath = join15(runDirectory, "admitted-request.json");
21486
22285
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
21487
22286
  sessionDirectory,
21488
22287
  sessionFile
@@ -21572,24 +22371,23 @@ async function admitReviewerInvocation(options) {
21572
22371
  const authorityRefs = Object.freeze(
21573
22372
  (options.authorityRefs ?? []).map((ref) => requireAuthorityRef(ref))
21574
22373
  );
21575
- const projectRoot = resolve8(options.project ?? options.cwd);
22374
+ const projectRoot = resolve7(options.project ?? options.cwd);
21576
22375
  const runId = (options.createRunId ?? uuidv7)();
21577
22376
  const {
21578
22377
  principal,
21579
22378
  sessionDirectory,
21580
22379
  sessionFile,
21581
22380
  runDirectory,
22381
+ attachmentsDirectory,
21582
22382
  ledgerHome,
21583
22383
  bookKey
21584
22384
  } = issueAdmissionPlacement(options.principalAuthority, {
21585
22385
  cwd: projectRoot,
21586
22386
  runId,
21587
22387
  role: "reviewer",
22388
+ subject: { unbound: true },
21588
22389
  home: options.home
21589
22390
  });
21590
- const attachmentsDirectory = join13(runDirectory, "attachments");
21591
- ensureRealDirectoryTree(ledgerHome, sessionDirectory);
21592
- ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
21593
22391
  const attachments = await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
21594
22392
  const instruction = options.instruction;
21595
22393
  const instructionEmpty = instruction.trim() === "";
@@ -21612,7 +22410,7 @@ async function admitReviewerInvocation(options) {
21612
22410
  mediaKind: a.mediaKind
21613
22411
  }))
21614
22412
  };
21615
- const admittedRequestPath = join13(runDirectory, "admitted-request.json");
22413
+ const admittedRequestPath = join15(runDirectory, "admitted-request.json");
21616
22414
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
21617
22415
  sessionDirectory,
21618
22416
  sessionFile
@@ -21711,7 +22509,7 @@ async function admitMergerInvocation(options) {
21711
22509
  if (instruction.trim() === "") {
21712
22510
  throw new CliUsageError("merger requires a nonblank task instruction");
21713
22511
  }
21714
- const projectRoot = resolve8(options.project ?? options.cwd);
22512
+ const projectRoot = resolve7(options.project ?? options.cwd);
21715
22513
  const derived = await deriveMergerEnvelopeFromActiveMerge(
21716
22514
  projectRoot,
21717
22515
  options.gitState ?? createProductionMergerGitState(projectRoot)
@@ -21722,17 +22520,16 @@ async function admitMergerInvocation(options) {
21722
22520
  sessionDirectory,
21723
22521
  sessionFile,
21724
22522
  runDirectory,
22523
+ attachmentsDirectory,
21725
22524
  ledgerHome,
21726
22525
  bookKey
21727
22526
  } = issueAdmissionPlacement(options.principalAuthority, {
21728
22527
  cwd: projectRoot,
21729
22528
  runId,
21730
22529
  role: "merger",
22530
+ subject: { unbound: true },
21731
22531
  home: options.home
21732
22532
  });
21733
- const attachmentsDirectory = join13(runDirectory, "attachments");
21734
- ensureRealDirectoryTree(ledgerHome, sessionDirectory);
21735
- ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
21736
22533
  const attachments = await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
21737
22534
  const targetLabel = derived.targetObjectId === "" ? "(none observed)" : derived.targetObjectId;
21738
22535
  const sourceLabel = derived.sourceObjectId === "" ? "(none observed)" : derived.sourceObjectId;
@@ -21758,8 +22555,8 @@ async function admitMergerInvocation(options) {
21758
22555
  resolutionScope: [...derived.resolutionScope],
21759
22556
  authorizedChecks: []
21760
22557
  });
21761
- const mergerInputPath = join13(runDirectory, "merger-input.json");
21762
- await writeFile4(
22558
+ const mergerInputPath = join15(runDirectory, "merger-input.json");
22559
+ await writeFile5(
21763
22560
  mergerInputPath,
21764
22561
  `${JSON.stringify(mergerInput, null, 2)}
21765
22562
  `,
@@ -21789,7 +22586,7 @@ async function admitMergerInvocation(options) {
21789
22586
  mediaKind: a.mediaKind
21790
22587
  }))
21791
22588
  };
21792
- const admittedRequestPath = join13(runDirectory, "admitted-request.json");
22589
+ const admittedRequestPath = join15(runDirectory, "admitted-request.json");
21793
22590
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
21794
22591
  sessionDirectory,
21795
22592
  sessionFile
@@ -21843,11 +22640,11 @@ function parseAnalystCohortIssueToken(raw, flag) {
21843
22640
  `${flag} requires a comma-separated list of N or book:N`
21844
22641
  );
21845
22642
  }
21846
- const sep4 = trimmed.lastIndexOf(":");
21847
- if (sep4 > 0) {
21848
- const rhs = trimmed.slice(sep4 + 1);
22643
+ const sep5 = trimmed.lastIndexOf(":");
22644
+ if (sep5 > 0) {
22645
+ const rhs = trimmed.slice(sep5 + 1);
21849
22646
  if (ANALYST_TICKET_NUMBER_PATTERN.test(rhs)) {
21850
- const bookKey = trimmed.slice(0, sep4);
22647
+ const bookKey = trimmed.slice(0, sep5);
21851
22648
  if (bookKey.trim() === "") {
21852
22649
  throw new CliUsageError(
21853
22650
  `${flag} book:N requires a non-empty book key, got ${raw}`
@@ -22047,8 +22844,11 @@ var init_invocation = __esm({
22047
22844
  "use strict";
22048
22845
  init_activation_ledger_topology();
22049
22846
  init_activation_ledger_git();
22847
+ init_role_run_placement();
22050
22848
  init_run_ticket_number();
22849
+ init_role_run_relocation();
22051
22850
  init_doctor_evidence();
22851
+ init_diarist_contracts();
22052
22852
  init_collector_config();
22053
22853
  init_collector_target();
22054
22854
  init_github_remote();
@@ -22063,23 +22863,23 @@ var init_invocation = __esm({
22063
22863
  init_cli_errors();
22064
22864
  init_option_definitions();
22065
22865
  DOCTOR_ISSUE_NUMBER_PATTERN = /^[1-9]\d*$/;
22066
- DOCTOR_CASE_RUNS_PATH_PATTERN = /\/\.ak-roles\/books\/[^/]+\/issues\/([1-9]\d*)\/runs$/;
22866
+ DOCTOR_CASE_RUNS_PATH_PATTERN = /\/\.ak-roles\/books\/[^/]+\/(?:issues\/)?([1-9]\d*)\/runs$/;
22067
22867
  ANALYST_TICKET_NUMBER_PATTERN = /^[1-9]\d*$/;
22068
22868
  }
22069
22869
  });
22070
22870
 
22071
22871
  // src/public-cli/load-production-acp-host.ts
22072
- import { existsSync as existsSync6 } from "node:fs";
22073
- import { join as join14 } from "node:path";
22872
+ import { existsSync as existsSync7 } from "node:fs";
22873
+ import { join as join16 } from "node:path";
22074
22874
  import { pathToFileURL } from "node:url";
22075
22875
  async function loadProductionAcpHostFactory(packageRoot2, host) {
22076
22876
  const description = lookupHostDescription(host);
22077
22877
  if (description === void 0) {
22078
22878
  throw new Error(`unregistered host: ${host}`);
22079
22879
  }
22080
- const built = join14(packageRoot2, "dist/acp-host/production-host.js");
22081
- const source = join14(packageRoot2, "src/acp-host/production-host.ts");
22082
- const target = existsSync6(built) ? built : source;
22880
+ const built = join16(packageRoot2, "dist/acp-host/production-host.js");
22881
+ const source = join16(packageRoot2, "src/acp-host/production-host.ts");
22882
+ const target = existsSync7(built) ? built : source;
22083
22883
  const href = pathToFileURL(target).href;
22084
22884
  const mod = await import(href);
22085
22885
  const create = mod.createProductionAcpRoleTurnHost;
@@ -22093,17 +22893,17 @@ var init_load_production_acp_host = __esm({
22093
22893
  });
22094
22894
 
22095
22895
  // src/public-cli/load-production-headless-host.ts
22096
- import { existsSync as existsSync7 } from "node:fs";
22097
- import { join as join15 } from "node:path";
22896
+ import { existsSync as existsSync8 } from "node:fs";
22897
+ import { join as join17 } from "node:path";
22098
22898
  import { pathToFileURL as pathToFileURL2 } from "node:url";
22099
22899
  async function loadProductionHeadlessHostFactory(packageRoot2, host) {
22100
22900
  const description = lookupHeadlessHostDescription(host);
22101
22901
  if (description === void 0) {
22102
22902
  throw new Error(`unregistered headless host: ${host}`);
22103
22903
  }
22104
- const built = join15(packageRoot2, "dist/headless-host/production-host.js");
22105
- const source = join15(packageRoot2, "src/headless-host/production-host.ts");
22106
- const target = existsSync7(built) ? built : source;
22904
+ const built = join17(packageRoot2, "dist/headless-host/production-host.js");
22905
+ const source = join17(packageRoot2, "src/headless-host/production-host.ts");
22906
+ const target = existsSync8(built) ? built : source;
22107
22907
  const href = pathToFileURL2(target).href;
22108
22908
  const mod = await import(href);
22109
22909
  const create = mod.createProductionHeadlessRoleTurnHost;
@@ -22229,8 +23029,8 @@ var init_role_turn_host_resolution = __esm({
22229
23029
 
22230
23030
  // src/package-resources/method-skill.ts
22231
23031
  import { createHash as createHash4 } from "node:crypto";
22232
- import { readFile as readFile11, realpath as realpath5 } from "node:fs/promises";
22233
- import { join as join16 } from "node:path";
23032
+ import { readFile as readFile12, realpath as realpath5 } from "node:fs/promises";
23033
+ import { join as join18 } from "node:path";
22234
23034
  function gitBlobOid(bytes) {
22235
23035
  const body = typeof bytes === "string" ? Buffer.from(bytes, "utf8") : Buffer.from(bytes);
22236
23036
  const header = Buffer.from(`blob ${body.byteLength}\0`, "utf8");
@@ -22247,10 +23047,10 @@ function packagedMethodSkillRelativeDirectory(name) {
22247
23047
  return `${METHOD_SKILL_RELATIVE_ROOT}/${name}`;
22248
23048
  }
22249
23049
  function resolvePackagedMethodSkillRoot(packageRoot2, name) {
22250
- return join16(packageRoot2, packagedMethodSkillRelativeDirectory(name));
23050
+ return join18(packageRoot2, packagedMethodSkillRelativeDirectory(name));
22251
23051
  }
22252
23052
  function resolvePackagedMethodSkillPath(packageRoot2, name) {
22253
- return join16(resolvePackagedMethodSkillRoot(packageRoot2, name), "SKILL.md");
23053
+ return join18(resolvePackagedMethodSkillRoot(packageRoot2, name), "SKILL.md");
22254
23054
  }
22255
23055
  function isRecord4(value) {
22256
23056
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -22344,11 +23144,11 @@ function parseProvenance(raw, expectedName) {
22344
23144
  }
22345
23145
  async function loadPackagedMethodSkillMaterial(packageRoot2, name) {
22346
23146
  const rootDirectory = resolvePackagedMethodSkillRoot(packageRoot2, name);
22347
- const skillPathConfigured = join16(rootDirectory, "SKILL.md");
22348
- const provenancePath = join16(rootDirectory, "provenance.json");
23147
+ const skillPathConfigured = join18(rootDirectory, "SKILL.md");
23148
+ const provenancePath = join18(rootDirectory, "provenance.json");
22349
23149
  let provenanceRaw;
22350
23150
  try {
22351
- provenanceRaw = await readFile11(provenancePath, "utf8");
23151
+ provenanceRaw = await readFile12(provenancePath, "utf8");
22352
23152
  } catch (error) {
22353
23153
  throw new PackagedMethodSkillUnavailableError(name, provenancePath, error);
22354
23154
  }
@@ -22362,10 +23162,10 @@ async function loadPackagedMethodSkillMaterial(packageRoot2, name) {
22362
23162
  }
22363
23163
  const provenance = parseProvenance(provenanceJson, name);
22364
23164
  for (const [rel, expected] of Object.entries(provenance.files)) {
22365
- const absolute = join16(rootDirectory, rel);
23165
+ const absolute = join18(rootDirectory, rel);
22366
23166
  let bytes;
22367
23167
  try {
22368
- bytes = await readFile11(absolute);
23168
+ bytes = await readFile12(absolute);
22369
23169
  } catch (error) {
22370
23170
  throw new PackagedMethodSkillUnavailableError(name, absolute, error);
22371
23171
  }
@@ -22381,7 +23181,7 @@ async function loadPackagedMethodSkillMaterial(packageRoot2, name) {
22381
23181
  let raw;
22382
23182
  try {
22383
23183
  skillPath = await realpath5(skillPathConfigured);
22384
- raw = await readFile11(skillPath, "utf8");
23184
+ raw = await readFile12(skillPath, "utf8");
22385
23185
  } catch (error) {
22386
23186
  throw new PackagedMethodSkillUnavailableError(name, skillPathConfigured, error);
22387
23187
  }
@@ -22459,45 +23259,13 @@ var init_method_skill = __esm({
22459
23259
  }
22460
23260
  });
22461
23261
 
22462
- // src/auditor-dossier-tool.ts
22463
- var init_auditor_dossier_tool = __esm({
22464
- "src/auditor-dossier-tool.ts"() {
22465
- "use strict";
22466
- init_build();
22467
- }
22468
- });
22469
-
22470
- // src/gatekeeper-role.ts
22471
- var init_gatekeeper_role = __esm({
22472
- "src/gatekeeper-role.ts"() {
22473
- "use strict";
22474
- init_auditor_dossier_tool();
22475
- init_submission_errors();
22476
- init_inspector_contracts();
22477
- init_gatekeeper_output();
22478
- init_submission_errors();
22479
- }
22480
- });
22481
-
22482
- // src/compliance-transport.ts
22483
- var AUDITOR_PARENT_ATTEMPT_BINDING_ENTRY_TYPE, AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE;
22484
- var init_compliance_transport = __esm({
22485
- "src/compliance-transport.ts"() {
22486
- "use strict";
22487
- init_auditor_dossier_tool();
22488
- init_gatekeeper_role();
22489
- AUDITOR_PARENT_ATTEMPT_BINDING_ENTRY_TYPE = "ak_auditor_parent_attempt_binding";
22490
- AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE = "ak_auditor_compliance_failure";
22491
- }
22492
- });
22493
-
22494
23262
  // src/ledger-session-read.ts
22495
- import { readFile as readFile12 } from "node:fs/promises";
23263
+ import { readFile as readFile13 } from "node:fs/promises";
22496
23264
  function isRecord5(value) {
22497
23265
  return typeof value === "object" && value !== null && !Array.isArray(value);
22498
23266
  }
22499
23267
  async function readLedgerSessionJsonl(path) {
22500
- const text = await readFile12(path, "utf8");
23268
+ const text = await readFile13(path, "utf8");
22501
23269
  const lines = text.split("\n");
22502
23270
  const rows = [];
22503
23271
  for (let index = 0; index < lines.length; index += 1) {
@@ -22671,8 +23439,8 @@ var init_ledger_session_read = __esm({
22671
23439
  });
22672
23440
 
22673
23441
  // src/analyst-gate-cycles-read.ts
22674
- import { readdir as readdir3 } from "node:fs/promises";
22675
- import { join as join17 } from "node:path";
23442
+ import { readdir as readdir5 } from "node:fs/promises";
23443
+ import { join as join19 } from "node:path";
22676
23444
  function isRecord6(value) {
22677
23445
  return typeof value === "object" && value !== null && !Array.isArray(value);
22678
23446
  }
@@ -22887,10 +23655,10 @@ function pairGateRounds(volumes) {
22887
23655
  return rounds.sort((a, b) => a.officerStartedAt.localeCompare(b.officerStartedAt)).map((round, index) => ({ ...round, roundIndex: index + 1 }));
22888
23656
  }
22889
23657
  async function resolveOfficerSessionFromPointerFile(pointerPath) {
22890
- const { readFile: readFile23 } = await import("node:fs/promises");
23658
+ const { readFile: readFile25 } = await import("node:fs/promises");
22891
23659
  let raw;
22892
23660
  try {
22893
- raw = JSON.parse(await readFile23(pointerPath, "utf8"));
23661
+ raw = JSON.parse(await readFile25(pointerPath, "utf8"));
22894
23662
  } catch (error) {
22895
23663
  throw new Error(
22896
23664
  `direct officer run pointer unreadable in ${pointerPath}: ${error instanceof Error ? error.message : String(error)}`,
@@ -22913,7 +23681,7 @@ async function readAnalystGateCyclesFromAuditorRoles(auditorRolesDirectory, opti
22913
23681
  for (const directory of directories) {
22914
23682
  let names;
22915
23683
  try {
22916
- const entries = await readdir3(directory, { withFileTypes: true });
23684
+ const entries = await readdir5(directory, { withFileTypes: true });
22917
23685
  names = entries.filter(
22918
23686
  (e) => e.isFile() && (e.name.endsWith(".jsonl") || e.name.endsWith(".pointer.json"))
22919
23687
  ).map((e) => e.name).sort();
@@ -22922,7 +23690,7 @@ async function readAnalystGateCyclesFromAuditorRoles(auditorRolesDirectory, opti
22922
23690
  throw error;
22923
23691
  }
22924
23692
  for (const name of names) {
22925
- const path = join17(directory, name);
23693
+ const path = join19(directory, name);
22926
23694
  const fromPointer = name.endsWith(".pointer.json");
22927
23695
  const sessionPath = fromPointer ? await resolveOfficerSessionFromPointerFile(path) : path;
22928
23696
  if (sessionPath === void 0) continue;
@@ -22973,9 +23741,9 @@ var init_audit_escalation = __esm({
22973
23741
  });
22974
23742
 
22975
23743
  // src/run-terminal-artifacts.ts
22976
- import { readdir as readdir4, readFile as readFile13 } from "node:fs/promises";
22977
- import { basename as basename7, dirname as dirname9, join as join18 } from "node:path";
22978
- function isMissingPathError2(error) {
23744
+ import { readdir as readdir6, readFile as readFile14 } from "node:fs/promises";
23745
+ import { basename as basename7, dirname as dirname10, join as join20 } from "node:path";
23746
+ function isMissingPathError3(error) {
22979
23747
  return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
22980
23748
  }
22981
23749
  function errorText2(error) {
@@ -23005,9 +23773,9 @@ function readUsableTerminalArtifactBody(body) {
23005
23773
  async function readTerminalArtifactAtPath(path, file) {
23006
23774
  let raw;
23007
23775
  try {
23008
- raw = await readFile13(path, "utf8");
23776
+ raw = await readFile14(path, "utf8");
23009
23777
  } catch (error) {
23010
- if (isMissingPathError2(error)) return void 0;
23778
+ if (isMissingPathError3(error)) return void 0;
23011
23779
  return {
23012
23780
  status: "unreadable",
23013
23781
  file,
@@ -23042,14 +23810,14 @@ async function listUniqueErrorFallbackPaths(directories) {
23042
23810
  for (const dir of directories) {
23043
23811
  let names;
23044
23812
  try {
23045
- names = await readdir4(dir);
23813
+ names = await readdir6(dir);
23046
23814
  } catch (error) {
23047
- if (isMissingPathError2(error)) continue;
23815
+ if (isMissingPathError3(error)) continue;
23048
23816
  throw error;
23049
23817
  }
23050
23818
  for (const name of names.sort((a, b) => a.localeCompare(b))) {
23051
23819
  if (!UNIQUE_ERROR_FALLBACK_NAME.test(name)) continue;
23052
- found.push(join18(dir, name));
23820
+ found.push(join20(dir, name));
23053
23821
  }
23054
23822
  }
23055
23823
  return found;
@@ -23065,14 +23833,14 @@ function presentUniqueFallbackBoundToRun(body, expectedRunId) {
23065
23833
  return typeof body.runId === "string" && body.runId === expectedRunId;
23066
23834
  }
23067
23835
  async function readRunTerminalArtifact(runDirectory) {
23068
- const artifactsDir = join18(runDirectory, "artifacts");
23836
+ const artifactsDir = roleRunArtifactsDirectory(runDirectory);
23069
23837
  for (const file of RUN_TERMINAL_ARTIFACT_FILES) {
23070
- const path = join18(artifactsDir, file);
23838
+ const path = join20(artifactsDir, file);
23071
23839
  const read = await readTerminalArtifactAtPath(path, file);
23072
23840
  if (read !== void 0) return read;
23073
23841
  }
23074
23842
  for (const relative3 of RUN_TERMINAL_ERROR_FALLBACK_RELATIVE_PATHS) {
23075
- const path = join18(runDirectory, relative3);
23843
+ const path = join20(runDirectory, relative3);
23076
23844
  const read = await readTerminalArtifactAtPath(path, "error.json");
23077
23845
  if (read !== void 0) return read;
23078
23846
  }
@@ -23081,7 +23849,7 @@ async function readRunTerminalArtifact(runDirectory) {
23081
23849
  if (read !== void 0) return read;
23082
23850
  }
23083
23851
  const expectedRunId = runIdFromRunDirectory(runDirectory);
23084
- for (const path of await listUniqueErrorFallbackPaths([dirname9(runDirectory)])) {
23852
+ for (const path of await listUniqueErrorFallbackPaths([dirname10(runDirectory)])) {
23085
23853
  const read = await readTerminalArtifactAtPath(path, "error.json");
23086
23854
  if (read === void 0) continue;
23087
23855
  if (read.status === "present") {
@@ -23095,6 +23863,7 @@ var RUN_TERMINAL_ARTIFACT_FILES, RUN_TERMINAL_ERROR_FALLBACK_RELATIVE_PATHS, UNI
23095
23863
  var init_run_terminal_artifacts = __esm({
23096
23864
  "src/run-terminal-artifacts.ts"() {
23097
23865
  "use strict";
23866
+ init_role_run_placement();
23098
23867
  RUN_TERMINAL_ARTIFACT_FILES = [
23099
23868
  "report.json",
23100
23869
  "error.json",
@@ -23109,21 +23878,34 @@ var init_run_terminal_artifacts = __esm({
23109
23878
  });
23110
23879
 
23111
23880
  // src/submission-ledger.ts
23112
- function submissionRecordFile(cwd, runId, home) {
23113
- const ledgerHome = resolveActivationLedgerHome(home);
23881
+ import { join as join21 } from "node:path";
23882
+ async function submissionRecordFile(cwd, runId, scope) {
23883
+ const ledgerHome = resolveActivationLedgerHome(scope.home);
23884
+ let sessionParent = scope.sessionParent;
23885
+ if (sessionParent === void 0) {
23886
+ const discoveredRun = await findRunDirectoryById(scope.home, runId);
23887
+ if (discoveredRun === void 0) return void 0;
23888
+ sessionParent = join21(discoveredRun, "session", "session.jsonl");
23889
+ }
23114
23890
  return resolveSitianRecordPathInLedger({
23115
23891
  level: "event",
23116
23892
  kind: "candidate",
23117
23893
  subject: { runId },
23118
- cwd
23894
+ cwd,
23895
+ sessionParent
23119
23896
  }, ledgerHome).recordFile;
23120
23897
  }
23121
- async function readOwnedSubmissionRecords(cwd, runId, home) {
23122
- const file = submissionRecordFile(cwd, runId, home);
23898
+ async function readOwnedSubmissionRecords(cwd, runId, scope = {}) {
23899
+ const file = await submissionRecordFile(cwd, runId, scope);
23900
+ if (file === void 0) {
23901
+ return { file: void 0, owned: [] };
23902
+ }
23123
23903
  const { records } = await readSitianRecords(file);
23124
23904
  return {
23125
23905
  file,
23126
- owned: records.filter((record4) => typeof record4.subject === "object" && record4.subject !== null && record4.subject.runId === runId)
23906
+ owned: records.filter(
23907
+ (record4) => typeof record4.subject === "object" && record4.subject !== null && record4.subject.runId === runId
23908
+ )
23127
23909
  };
23128
23910
  }
23129
23911
  function resolveReadScope(homeOrScope) {
@@ -23146,8 +23928,8 @@ function recordAttemptId(record4) {
23146
23928
  }
23147
23929
  return void 0;
23148
23930
  }
23149
- async function hasFreshAttemptSubmission(cwd, runId, attemptId, home) {
23150
- const { owned } = await readOwnedSubmissionRecords(cwd, runId, home);
23931
+ async function hasFreshAttemptSubmission(cwd, runId, attemptId, homeOrScope) {
23932
+ const { owned } = await readOwnedSubmissionRecords(cwd, runId, resolveReadScope(homeOrScope));
23151
23933
  return owned.some((record4) => {
23152
23934
  if (recordAttemptId(record4) !== attemptId) return false;
23153
23935
  if (record4.kind === "sealed") return true;
@@ -23191,10 +23973,8 @@ function rowFromPayload(kind, payload, accepted, roleFallback) {
23191
23973
  ...typeof payload.toolCallId === "string" && payload.toolCallId.length > 0 ? { toolCallId: payload.toolCallId } : {}
23192
23974
  };
23193
23975
  }
23194
- async function readRecordedSubmissionRows(cwd, runId, homeOrScope) {
23195
- const scope = resolveReadScope(homeOrScope);
23196
- const { owned } = await readOwnedSubmissionRecords(cwd, runId, scope.home);
23197
- const scoped = recordsForAttempt(owned, scope.attemptId);
23976
+ function mapOwnedToSubmissionRows(owned) {
23977
+ const scoped = owned;
23198
23978
  const out = [];
23199
23979
  const indexByCall = /* @__PURE__ */ new Map();
23200
23980
  const roleByCall = /* @__PURE__ */ new Map();
@@ -23258,6 +24038,21 @@ async function readRecordedSubmissionRows(cwd, runId, homeOrScope) {
23258
24038
  }
23259
24039
  return out;
23260
24040
  }
24041
+ async function readRecordedSubmissionRows(cwd, runId, homeOrScope) {
24042
+ const scope = resolveReadScope(homeOrScope);
24043
+ const { owned } = await readOwnedSubmissionRecords(cwd, runId, scope);
24044
+ const scoped = recordsForAttempt(owned, scope.attemptId);
24045
+ return mapOwnedToSubmissionRows(scoped);
24046
+ }
24047
+ async function readAttemptScopedSubmissionRows(cwd, runId, attemptId, home) {
24048
+ if (attemptId.length === 0) return [];
24049
+ const { owned } = await readOwnedSubmissionRecords(
24050
+ cwd,
24051
+ runId,
24052
+ home === void 0 ? {} : { home }
24053
+ );
24054
+ return mapOwnedToSubmissionRows(owned.filter((record4) => recordAttemptId(record4) === attemptId));
24055
+ }
23261
24056
  async function readRecordedSubmissions(cwd, runId, homeOrScope) {
23262
24057
  return (await readRecordedSubmissionRows(cwd, runId, homeOrScope)).map((row) => row.accepted);
23263
24058
  }
@@ -23265,33 +24060,35 @@ var init_submission_ledger = __esm({
23265
24060
  "src/submission-ledger.ts"() {
23266
24061
  "use strict";
23267
24062
  init_activation_ledger_topology();
24063
+ init_host_contracts();
23268
24064
  init_audit_escalation();
23269
24065
  init_run_terminal_artifacts();
23270
24066
  init_sitian_facade();
24067
+ init_run_lifecycle();
23271
24068
  init_submission_correctable_error();
23272
24069
  init_terminating_infrastructure();
23273
24070
  }
23274
24071
  });
23275
24072
 
23276
24073
  // src/session-opening-materials.ts
23277
- import { existsSync as existsSync8 } from "node:fs";
23278
- import { readFile as readFile14 } from "node:fs/promises";
23279
- import { dirname as dirname10, join as join19 } from "node:path";
24074
+ import { existsSync as existsSync9 } from "node:fs";
24075
+ import { readFile as readFile15 } from "node:fs/promises";
24076
+ import { dirname as dirname11, join as join22 } from "node:path";
23280
24077
  import { fileURLToPath, pathToFileURL as pathToFileURL3 } from "node:url";
23281
24078
  function resolvePackageRootDir(moduleUrl = import.meta.url) {
23282
- let dir = dirname10(fileURLToPath(moduleUrl));
24079
+ let dir = dirname11(fileURLToPath(moduleUrl));
23283
24080
  for (let i = 0; i < 8; i += 1) {
23284
- if (existsSync8(join19(dir, "package.json")) && existsSync8(join19(dir, "souls"))) {
24081
+ if (existsSync9(join22(dir, "package.json")) && existsSync9(join22(dir, "souls"))) {
23285
24082
  return dir;
23286
24083
  }
23287
- const parent = dirname10(dir);
24084
+ const parent = dirname11(dir);
23288
24085
  if (parent === dir) break;
23289
24086
  dir = parent;
23290
24087
  }
23291
24088
  return fileURLToPath(new URL("..", moduleUrl));
23292
24089
  }
23293
24090
  async function readPackageMaterial(relativePath) {
23294
- return readFile14(fileURLToPath(new URL(relativePath, packageRootUrl)), "utf8");
24091
+ return readFile15(fileURLToPath(new URL(relativePath, packageRootUrl)), "utf8");
23295
24092
  }
23296
24093
  async function joinPackageMaterials(relativePaths) {
23297
24094
  const chunks = [];
@@ -23387,6 +24184,7 @@ var DOCTOR_CANDIDATE_ENTRY_TYPE;
23387
24184
  var init_dossier_resolution = __esm({
23388
24185
  "src/dossier-resolution.ts"() {
23389
24186
  "use strict";
24187
+ init_host_contracts();
23390
24188
  DOCTOR_CANDIDATE_ENTRY_TYPE = "ak_doctor_audit_candidate";
23391
24189
  }
23392
24190
  });
@@ -23532,13 +24330,13 @@ var init_reviewer_dispatch = __esm({
23532
24330
  });
23533
24331
 
23534
24332
  // src/public-cli/reviewer-dispatch-rejection.ts
23535
- import { readFile as readFile15, unlink as unlink3 } from "node:fs/promises";
23536
- import { join as join20 } from "node:path";
24333
+ import { readFile as readFile16, unlink as unlink3 } from "node:fs/promises";
24334
+ import { join as join23 } from "node:path";
23537
24335
  function isReviewerPreflightViolation(value) {
23538
24336
  return typeof value === "string" && REVIEWER_PREFLIGHT_VIOLATIONS.includes(value);
23539
24337
  }
23540
24338
  function reviewerDispatchRejectionPath(runDirectory) {
23541
- return join20(runDirectory, REVIEWER_DISPATCH_REJECTION_FILE);
24339
+ return join23(runDirectory, REVIEWER_DISPATCH_REJECTION_FILE);
23542
24340
  }
23543
24341
  async function clearReviewerDispatchRejection(runDirectory) {
23544
24342
  try {
@@ -23553,7 +24351,7 @@ async function clearReviewerDispatchRejection(runDirectory) {
23553
24351
  async function readReviewerDispatchRejection(runDirectory) {
23554
24352
  let raw;
23555
24353
  try {
23556
- raw = await readFile15(reviewerDispatchRejectionPath(runDirectory), "utf8");
24354
+ raw = await readFile16(reviewerDispatchRejectionPath(runDirectory), "utf8");
23557
24355
  } catch (error) {
23558
24356
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
23559
24357
  return void 0;
@@ -23910,14 +24708,15 @@ var init_terminal = __esm({
23910
24708
 
23911
24709
  // src/public-cli/settlement.ts
23912
24710
  import { randomUUID as randomUUID3 } from "node:crypto";
23913
- import { appendFile as appendFile2, readFile as readFile16, readdir as readdir5, writeFile as writeFile5 } from "node:fs/promises";
23914
- import { dirname as dirname11, join as join21 } from "node:path";
24711
+ import { appendFile as appendFile2, readFile as readFile17, readdir as readdir7, writeFile as writeFile6 } from "node:fs/promises";
24712
+ import { dirname as dirname12, join as join24 } from "node:path";
23915
24713
  function sealedLedgerHome(admitted) {
23916
24714
  return homeFromRunDirectory(admitted.runDirectory);
23917
24715
  }
23918
24716
  function ledgerReadScope(admitted, scope) {
23919
24717
  return {
23920
24718
  home: sealedLedgerHome(admitted),
24719
+ sessionParent: join24(admitted.runDirectory, "session", "session.jsonl"),
23921
24720
  ...scope?.courtAttemptId === void 0 || scope.courtAttemptId.length === 0 ? {} : { attemptId: scope.courtAttemptId }
23922
24721
  };
23923
24722
  }
@@ -23934,6 +24733,16 @@ function roleOutcomeFromRows(role, rows) {
23934
24733
  return { kind: "accepted", role, payloads };
23935
24734
  }
23936
24735
  async function sealedLedgerOutcome(admitted, role, scope) {
24736
+ const home = sealedLedgerHome(admitted);
24737
+ if (scope?.courtAttemptId !== void 0 && scope.courtAttemptId.length > 0) {
24738
+ const thisCourt = await readAttemptScopedSubmissionRows(
24739
+ admitted.projectRoot,
24740
+ admitted.runId,
24741
+ scope.courtAttemptId,
24742
+ home
24743
+ );
24744
+ return roleOutcomeFromRows(role, thisCourt);
24745
+ }
23937
24746
  const rows = await readRecordedSubmissionRows(
23938
24747
  admitted.projectRoot,
23939
24748
  admitted.runId,
@@ -23947,7 +24756,7 @@ async function attemptProducedFreshSubmission(admitted, scope) {
23947
24756
  admitted.projectRoot,
23948
24757
  admitted.runId,
23949
24758
  scope.courtAttemptId,
23950
- sealedLedgerHome(admitted)
24759
+ ledgerReadScope(admitted, scope)
23951
24760
  );
23952
24761
  }
23953
24762
  async function recordedSubmissionPayloads(admitted, scope) {
@@ -23960,11 +24769,15 @@ async function recordedSubmissionPayloads(admitted, scope) {
23960
24769
  function withSubmissions(terminal, submissions) {
23961
24770
  if (submissions.length === 0) return terminal;
23962
24771
  const roleOutcome = terminal.roleOutcome;
23963
- const withPayloads = roleOutcome.kind === "accepted" || roleOutcome.kind === "audit_escalation" || roleOutcome.kind === "failure" ? { ...roleOutcome, payloads: submissions } : roleOutcome;
24772
+ const withPayloads = roleOutcome.kind === "accepted" || roleOutcome.kind === "audit_escalation" ? { ...roleOutcome, payloads: (roleOutcome.payloads ?? []).length > 0 ? roleOutcome.payloads : submissions } : roleOutcome.kind === "failure" ? { ...roleOutcome, payloads: roleOutcome.payloads ?? submissions } : roleOutcome;
23964
24773
  return { ...terminal, roleOutcome: withPayloads, submissions };
23965
24774
  }
23966
24775
  async function attachRecordedSubmissions(admitted, terminal, scope) {
23967
- return withSubmissions(terminal, await recordedSubmissionPayloads(admitted, scope));
24776
+ void scope;
24777
+ return withSubmissions(
24778
+ terminal,
24779
+ await recordedSubmissionPayloads(admitted, void 0)
24780
+ );
23968
24781
  }
23969
24782
  async function settleHostEndedNoReceipt(admitted, authority) {
23970
24783
  const facts = noReceiptLifecycleFacts({
@@ -24038,10 +24851,10 @@ function presentControlledFailure(failure, io) {
24038
24851
  }
24039
24852
  async function inspectJudgeSession(sessionFile) {
24040
24853
  try {
24041
- await readFile16(sessionFile, "utf8");
24854
+ await readFile17(sessionFile, "utf8");
24042
24855
  return { state: "present" };
24043
24856
  } catch (error) {
24044
- if (isMissingPathError3(error)) return { state: "missing" };
24857
+ if (isMissingPathError4(error)) return { state: "missing" };
24045
24858
  return {
24046
24859
  state: "unreadable",
24047
24860
  diagnostic: error instanceof Error ? error.message || error.name : String(error)
@@ -24241,7 +25054,7 @@ function explicitInternalKnownFailureClassificationInput(failure) {
24241
25054
  ...failure.details === void 0 ? {} : { knownDetails: failure.details }
24242
25055
  };
24243
25056
  }
24244
- function isMissingPathError3(error) {
25057
+ function isMissingPathError4(error) {
24245
25058
  return error instanceof Error && "code" in error && error.code === "ENOENT";
24246
25059
  }
24247
25060
  function sessionReadFailure(error, fallbackMessage) {
@@ -24270,7 +25083,7 @@ function sessionReadFailure(error, fallbackMessage) {
24270
25083
  return failed;
24271
25084
  }
24272
25085
  async function readBoundSessionEntries(sessionFile) {
24273
- const text = await readFile16(sessionFile, "utf8");
25086
+ const text = await readFile17(sessionFile, "utf8");
24274
25087
  const entries = [];
24275
25088
  for (const line2 of text.trim().split("\n").filter(Boolean)) {
24276
25089
  try {
@@ -24331,7 +25144,7 @@ async function readSitianRetainedAuditorProviderStop(sessionFile) {
24331
25144
  kind: "auditor",
24332
25145
  sessionParent: sessionFile,
24333
25146
  // Path is driven by sessionParent when under ledger home; cwd is a fallback only.
24334
- cwd: dirname11(sessionFile)
25147
+ cwd: dirname12(sessionFile)
24335
25148
  });
24336
25149
  const { records } = await readSitianRecords(recordFile);
24337
25150
  for (let i = records.length - 1; i >= 0; i -= 1) {
@@ -24357,18 +25170,18 @@ async function readSessionProviderStop(sessionFile) {
24357
25170
  }
24358
25171
  }
24359
25172
  async function readBoundEvidenceChildKnownFailure(sessionFile) {
24360
- const childDirectory = join21(dirname11(sessionFile), "evidence-children");
25173
+ const childDirectory = join24(dirname12(sessionFile), "evidence-children");
24361
25174
  let names;
24362
25175
  try {
24363
- names = await readdir5(childDirectory);
25176
+ names = await readdir7(childDirectory);
24364
25177
  } catch (error) {
24365
- if (isMissingPathError3(error)) return void 0;
25178
+ if (isMissingPathError4(error)) return void 0;
24366
25179
  throw sessionReadFailure(error, "failed to read bound evidence-child session directory");
24367
25180
  }
24368
25181
  for (const file of names.filter((name) => name.endsWith(".jsonl")).sort().reverse()) {
24369
25182
  let entries;
24370
25183
  try {
24371
- entries = await readBoundSessionEntries(join21(childDirectory, file));
25184
+ entries = await readBoundSessionEntries(join24(childDirectory, file));
24372
25185
  } catch (error) {
24373
25186
  throw sessionReadFailure(error, "failed to read discovered evidence-child session");
24374
25187
  }
@@ -24392,7 +25205,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
24392
25205
  try {
24393
25206
  parentEntries = await readBoundSessionEntries(sessionFile);
24394
25207
  } catch (error) {
24395
- if (isMissingPathError3(error)) return void 0;
25208
+ if (isMissingPathError4(error)) return void 0;
24396
25209
  throw sessionReadFailure(error, "failed to read parent session for auditor binding");
24397
25210
  }
24398
25211
  const parentId = parentEntries.find((entry) => entry.type === "session")?.id;
@@ -24423,22 +25236,22 @@ async function loadBoundAuditorVolumes(sessionFile) {
24423
25236
  latestParentUserIndex = i;
24424
25237
  break;
24425
25238
  }
24426
- const childDirectories = [join21(dirname11(sessionFile), "auditor-roles")];
25239
+ const childDirectories = [join24(dirname12(sessionFile), "auditor-roles")];
24427
25240
  const valid = [];
24428
25241
  let sawAnyDirectory = false;
24429
25242
  for (const childDirectory of childDirectories) {
24430
25243
  let names;
24431
25244
  try {
24432
- names = await readdir5(childDirectory);
25245
+ names = await readdir7(childDirectory);
24433
25246
  sawAnyDirectory = true;
24434
25247
  } catch (error) {
24435
- if (isMissingPathError3(error)) continue;
25248
+ if (isMissingPathError4(error)) continue;
24436
25249
  throw sessionReadFailure(error, "failed to read bound auditor session directory");
24437
25250
  }
24438
25251
  for (const file of names.filter((name) => name.endsWith(".jsonl")).sort().reverse()) {
24439
25252
  let entries;
24440
25253
  try {
24441
- entries = await readBoundSessionEntries(join21(childDirectory, file));
25254
+ entries = await readBoundSessionEntries(join24(childDirectory, file));
24442
25255
  } catch (error) {
24443
25256
  throw sessionReadFailure(error, "failed to read discovered auditor session");
24444
25257
  }
@@ -24596,7 +25409,7 @@ async function resolveAuditedRunnerFailureResolution(input) {
24596
25409
  );
24597
25410
  if (terminatingFailure !== void 0) return resolutionOf(terminatingFailure);
24598
25411
  } catch (error) {
24599
- if (!isMissingPathError3(error)) {
25412
+ if (!isMissingPathError4(error)) {
24600
25413
  const failure = sessionReadFailure(error, "failed to recover typed terminating-tool failure");
24601
25414
  return resolutionOf({
24602
25415
  cause: "session",
@@ -24943,8 +25756,8 @@ function projectTerminalGateFact(rounds) {
24943
25756
  };
24944
25757
  }
24945
25758
  async function extractGateFactFromSessionDirectory(sessionDirectory, options = {}) {
24946
- const directories = [join21(sessionDirectory, "auditor-roles")];
24947
- const parentSessionFile = options.parentSessionFile ?? join21(sessionDirectory, "session.jsonl");
25759
+ const directories = [join24(sessionDirectory, "auditor-roles")];
25760
+ const parentSessionFile = options.parentSessionFile ?? join24(sessionDirectory, "session.jsonl");
24948
25761
  const rounds = await readAnalystGateCyclesFromAuditorRoles(directories, {
24949
25762
  parentSessionFile
24950
25763
  });
@@ -25025,7 +25838,7 @@ async function extractNavigatorFactFromAdmittedSession(sessionFile) {
25025
25838
  const entries = await readBoundSessionEntries(sessionFile);
25026
25839
  return extractNavigatorFact(entries);
25027
25840
  } catch (error) {
25028
- if (isMissingPathError3(error)) {
25841
+ if (isMissingPathError4(error)) {
25029
25842
  return {
25030
25843
  disposition: "unavailable",
25031
25844
  source: "unknown",
@@ -25042,9 +25855,9 @@ async function extractNavigatorFactFromAdmittedSession(sessionFile) {
25042
25855
  async function publishJudgeArtifacts(admitted, roleOutcome, coordinates) {
25043
25856
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
25044
25857
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
25045
- const reportPath = join21(artifactsDir, "report.json");
25046
- const evidencePath = join21(artifactsDir, "evidence.json");
25047
- await writeFile5(
25858
+ const reportPath = join24(artifactsDir, "report.json");
25859
+ const evidencePath = join24(artifactsDir, "evidence.json");
25860
+ await writeFile6(
25048
25861
  reportPath,
25049
25862
  `${JSON.stringify(
25050
25863
  {
@@ -25058,7 +25871,7 @@ async function publishJudgeArtifacts(admitted, roleOutcome, coordinates) {
25058
25871
  `,
25059
25872
  "utf8"
25060
25873
  );
25061
- await writeFile5(
25874
+ await writeFile6(
25062
25875
  evidencePath,
25063
25876
  `${JSON.stringify(
25064
25877
  {
@@ -25087,9 +25900,9 @@ async function publishJudgeArtifacts(admitted, roleOutcome, coordinates) {
25087
25900
  async function publishCoderArtifacts(admitted, roleOutcome, coordinates, options = {}) {
25088
25901
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
25089
25902
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
25090
- const reportPath = join21(artifactsDir, "report.json");
25091
- const evidencePath = join21(artifactsDir, "evidence.json");
25092
- await writeFile5(
25903
+ const reportPath = join24(artifactsDir, "report.json");
25904
+ const evidencePath = join24(artifactsDir, "evidence.json");
25905
+ await writeFile6(
25093
25906
  reportPath,
25094
25907
  `${JSON.stringify(
25095
25908
  {
@@ -25104,7 +25917,7 @@ async function publishCoderArtifacts(admitted, roleOutcome, coordinates, options
25104
25917
  `,
25105
25918
  "utf8"
25106
25919
  );
25107
- await writeFile5(
25920
+ await writeFile6(
25108
25921
  evidencePath,
25109
25922
  `${JSON.stringify(
25110
25923
  {
@@ -25138,7 +25951,7 @@ async function readLawfulSettlementEntries(sessionFile) {
25138
25951
  try {
25139
25952
  return await readBoundSessionEntries(sessionFile);
25140
25953
  } catch (error) {
25141
- if (isMissingPathError3(error)) return void 0;
25954
+ if (isMissingPathError4(error)) return void 0;
25142
25955
  throw error instanceof Error && error.knownCause === "session" ? error : sessionReadFailure(error, "session unreadable");
25143
25956
  }
25144
25957
  }
@@ -25225,9 +26038,9 @@ function extractFixerMethodInvocations(entries, options) {
25225
26038
  async function publishFixerArtifacts(admitted, roleOutcome, coordinates, options) {
25226
26039
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
25227
26040
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
25228
- const reportPath = join21(artifactsDir, "report.json");
25229
- const evidencePath = join21(artifactsDir, "evidence.json");
25230
- await writeFile5(
26041
+ const reportPath = join24(artifactsDir, "report.json");
26042
+ const evidencePath = join24(artifactsDir, "evidence.json");
26043
+ await writeFile6(
25231
26044
  reportPath,
25232
26045
  `${JSON.stringify(
25233
26046
  {
@@ -25242,7 +26055,7 @@ async function publishFixerArtifacts(admitted, roleOutcome, coordinates, options
25242
26055
  `,
25243
26056
  "utf8"
25244
26057
  );
25245
- await writeFile5(
26058
+ await writeFile6(
25246
26059
  evidencePath,
25247
26060
  `${JSON.stringify(
25248
26061
  {
@@ -25313,9 +26126,9 @@ async function settleLawfulFixerTerminalResult(admitted, authority, options, sco
25313
26126
  async function publishCollectorArtifacts(admitted, roleOutcome, coordinates) {
25314
26127
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
25315
26128
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
25316
- const reportPath = join21(artifactsDir, "report.json");
25317
- const evidencePath = join21(artifactsDir, "evidence.json");
25318
- await writeFile5(
26129
+ const reportPath = join24(artifactsDir, "report.json");
26130
+ const evidencePath = join24(artifactsDir, "evidence.json");
26131
+ await writeFile6(
25319
26132
  reportPath,
25320
26133
  `${JSON.stringify(
25321
26134
  {
@@ -25329,7 +26142,7 @@ async function publishCollectorArtifacts(admitted, roleOutcome, coordinates) {
25329
26142
  `,
25330
26143
  "utf8"
25331
26144
  );
25332
- await writeFile5(
26145
+ await writeFile6(
25333
26146
  evidencePath,
25334
26147
  `${JSON.stringify(
25335
26148
  {
@@ -25431,9 +26244,9 @@ function extractDoctorCandidateAuditNoReceiptFact(entries) {
25431
26244
  async function publishDoctorArtifacts(admitted, roleOutcome, coordinates, options = {}) {
25432
26245
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
25433
26246
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
25434
- const reportPath = join21(artifactsDir, "report.json");
25435
- const evidencePath = join21(artifactsDir, "evidence.json");
25436
- await writeFile5(
26247
+ const reportPath = join24(artifactsDir, "report.json");
26248
+ const evidencePath = join24(artifactsDir, "evidence.json");
26249
+ await writeFile6(
25437
26250
  reportPath,
25438
26251
  `${JSON.stringify(
25439
26252
  {
@@ -25449,7 +26262,7 @@ async function publishDoctorArtifacts(admitted, roleOutcome, coordinates, option
25449
26262
  `,
25450
26263
  "utf8"
25451
26264
  );
25452
- await writeFile5(
26265
+ await writeFile6(
25453
26266
  evidencePath,
25454
26267
  `${JSON.stringify(
25455
26268
  {
@@ -25687,9 +26500,9 @@ function extractReviewerMethodInvocations(entries, options) {
25687
26500
  async function publishReviewerArtifacts(admitted, roleOutcome, coordinates, options) {
25688
26501
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
25689
26502
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
25690
- const reportPath = join21(artifactsDir, "report.json");
25691
- const evidencePath = join21(artifactsDir, "evidence.json");
25692
- await writeFile5(
26503
+ const reportPath = join24(artifactsDir, "report.json");
26504
+ const evidencePath = join24(artifactsDir, "evidence.json");
26505
+ await writeFile6(
25693
26506
  reportPath,
25694
26507
  `${JSON.stringify(
25695
26508
  {
@@ -25703,7 +26516,7 @@ async function publishReviewerArtifacts(admitted, roleOutcome, coordinates, opti
25703
26516
  `,
25704
26517
  "utf8"
25705
26518
  );
25706
- await writeFile5(
26519
+ await writeFile6(
25707
26520
  evidencePath,
25708
26521
  `${JSON.stringify(
25709
26522
  {
@@ -25792,9 +26605,9 @@ function extractMergerMethodInvocations(entries, options) {
25792
26605
  async function publishMergerArtifacts(admitted, roleOutcome, coordinates, options) {
25793
26606
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
25794
26607
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
25795
- const reportPath = join21(artifactsDir, "report.json");
25796
- const evidencePath = join21(artifactsDir, "evidence.json");
25797
- await writeFile5(
26608
+ const reportPath = join24(artifactsDir, "report.json");
26609
+ const evidencePath = join24(artifactsDir, "evidence.json");
26610
+ await writeFile6(
25798
26611
  reportPath,
25799
26612
  `${JSON.stringify(
25800
26613
  {
@@ -25808,7 +26621,7 @@ async function publishMergerArtifacts(admitted, roleOutcome, coordinates, option
25808
26621
  `,
25809
26622
  "utf8"
25810
26623
  );
25811
- await writeFile5(
26624
+ await writeFile6(
25812
26625
  evidencePath,
25813
26626
  `${JSON.stringify(
25814
26627
  {
@@ -25912,13 +26725,13 @@ function publicationAttemptFromError(path, error) {
25912
26725
  }
25913
26726
  function uniqueFailureFallbackDirs(runDirectory, baseDir) {
25914
26727
  const dirs = [];
25915
- for (const dir of [baseDir, runDirectory, dirname11(runDirectory)]) {
26728
+ for (const dir of [baseDir, runDirectory, dirname12(runDirectory)]) {
25916
26729
  if (!dirs.includes(dir)) dirs.push(dir);
25917
26730
  }
25918
26731
  return dirs;
25919
26732
  }
25920
26733
  async function resolveFailureArtifactsBase(runDirectory) {
25921
- const artifactsDir = join21(runDirectory, "artifacts");
26734
+ const artifactsDir = roleRunArtifactsDirectory(runDirectory);
25922
26735
  try {
25923
26736
  await ensureRunArtifactsDir(runDirectory);
25924
26737
  return { baseDir: artifactsDir };
@@ -25934,13 +26747,13 @@ async function writeFailureJsonRetainingCause(preferredCandidates, uniqueFallbac
25934
26747
  const candidates = [
25935
26748
  ...preferredCandidates,
25936
26749
  // One unique name per fallback dir — collisions on fixed names cannot exhaust this.
25937
- ...uniqueFallbackDirs.map((dir) => join21(dir, `${stem}.${randomUUID3()}.json`))
26750
+ ...uniqueFallbackDirs.map((dir) => join24(dir, `${stem}.${randomUUID3()}.json`))
25938
26751
  ];
25939
26752
  for (let i = 0; i < candidates.length; i += 1) {
25940
26753
  const path = candidates[i];
25941
26754
  const payload = issues.length === 0 ? basePayload : { ...basePayload, publicationIssues: issues };
25942
26755
  try {
25943
- await writeFile5(
26756
+ await writeFile6(
25944
26757
  path,
25945
26758
  `${JSON.stringify(payload, null, 2)}
25946
26759
  `,
@@ -25979,26 +26792,26 @@ async function publishFailureArtifacts(admitted, failure, authority) {
25979
26792
  } catch (error) {
25980
26793
  priorIssues.push(publicationAttemptFromError(sessionFile, error));
25981
26794
  }
25982
- const underArtifacts = baseDir === join21(admitted.runDirectory, "artifacts");
26795
+ const underArtifacts = baseDir === roleRunArtifactsDirectory(admitted.runDirectory);
25983
26796
  const uniqueFallbackDirs = uniqueFailureFallbackDirs(
25984
26797
  admitted.runDirectory,
25985
26798
  baseDir
25986
26799
  );
25987
26800
  const errorCandidates = underArtifacts ? [
25988
- join21(baseDir, "error.json"),
25989
- join21(baseDir, "error.settlement.json"),
25990
- join21(admitted.runDirectory, "error.settlement.json")
26801
+ join24(baseDir, "error.json"),
26802
+ join24(baseDir, "error.settlement.json"),
26803
+ join24(admitted.runDirectory, "error.settlement.json")
25991
26804
  ] : [
25992
- join21(baseDir, "error.settlement.json"),
25993
- join21(baseDir, "error.json")
26805
+ join24(baseDir, "error.settlement.json"),
26806
+ join24(baseDir, "error.json")
25994
26807
  ];
25995
26808
  const evidenceCandidates = underArtifacts ? [
25996
- join21(baseDir, "evidence.json"),
25997
- join21(baseDir, "evidence.settlement.json"),
25998
- join21(admitted.runDirectory, "evidence.settlement.json")
26809
+ join24(baseDir, "evidence.json"),
26810
+ join24(baseDir, "evidence.settlement.json"),
26811
+ join24(admitted.runDirectory, "evidence.settlement.json")
25999
26812
  ] : [
26000
- join21(baseDir, "evidence.settlement.json"),
26001
- join21(baseDir, "evidence.json")
26813
+ join24(baseDir, "evidence.settlement.json"),
26814
+ join24(baseDir, "evidence.json")
26002
26815
  ];
26003
26816
  const errorPayloadBase = {
26004
26817
  kind: "error",
@@ -26193,6 +27006,7 @@ var init_settlement = __esm({
26193
27006
  init_method_skill();
26194
27007
  init_navigator_invocation_identity();
26195
27008
  init_receipt_delivery_policy();
27009
+ init_role_run_placement();
26196
27010
  init_invocation();
26197
27011
  init_terminal();
26198
27012
  COLLECTOR_INFRASTRUCTURE_TOOLS = /* @__PURE__ */ new Set([
@@ -26248,17 +27062,17 @@ var init_turn_request = __esm({
26248
27062
  });
26249
27063
 
26250
27064
  // src/session-identity.ts
26251
- import { mkdir as mkdir4, readFile as readFile17, rename, writeFile as writeFile6 } from "node:fs/promises";
26252
- import { dirname as dirname12, join as join22 } from "node:path";
27065
+ import { mkdir as mkdir3, readFile as readFile18, rename as rename2, writeFile as writeFile7 } from "node:fs/promises";
27066
+ import { dirname as dirname13, join as join25 } from "node:path";
26253
27067
  function createSessionIdentityAuthority(authority, sessionBindingFile) {
26254
- const bindingPath = (principal) => join22(authority.decode(principal).sessionDirectory, sessionBindingFile);
27068
+ const bindingPath = (principal) => join25(authority.decode(principal).sessionDirectory, sessionBindingFile);
26255
27069
  return {
26256
27070
  resolveSessionFile(principal) {
26257
27071
  return authority.decode(principal).sessionFile;
26258
27072
  },
26259
27073
  async load(principal) {
26260
27074
  try {
26261
- const value = JSON.parse(await readFile17(bindingPath(principal), "utf8"));
27075
+ const value = JSON.parse(await readFile18(bindingPath(principal), "utf8"));
26262
27076
  if (typeof value !== "object" || value === null || typeof value.sessionId !== "string") {
26263
27077
  throw new Error("durable session binding is invalid");
26264
27078
  }
@@ -26270,11 +27084,11 @@ function createSessionIdentityAuthority(authority, sessionBindingFile) {
26270
27084
  },
26271
27085
  async bind(principal, sessionId) {
26272
27086
  const target = bindingPath(principal);
26273
- await mkdir4(dirname12(target), { recursive: true });
27087
+ await mkdir3(dirname13(target), { recursive: true });
26274
27088
  const temporary = `${target}.${process.pid}.tmp`;
26275
- await writeFile6(temporary, `${JSON.stringify({ sessionId })}
27089
+ await writeFile7(temporary, `${JSON.stringify({ sessionId })}
26276
27090
  `, { encoding: "utf8", mode: 384 });
26277
- await rename(temporary, target);
27091
+ await rename2(temporary, target);
26278
27092
  }
26279
27093
  };
26280
27094
  }
@@ -26307,9 +27121,9 @@ var init_ticket_provenance_contracts = __esm({
26307
27121
  });
26308
27122
 
26309
27123
  // src/ticket-provenance.ts
26310
- import { join as join23 } from "node:path";
27124
+ import { join as join26 } from "node:path";
26311
27125
  function ticketProvenanceSubject(ticketNumber) {
26312
- if (!Number.isSafeInteger(ticketNumber) || ticketNumber < 1) {
27126
+ if (!isSafePositiveTicketNumber(ticketNumber)) {
26313
27127
  throw new Error(`ticket-provenance subject requires a positive ticket number, got ${String(ticketNumber)}`);
26314
27128
  }
26315
27129
  return String(ticketNumber);
@@ -26325,18 +27139,22 @@ function resolveTicketProvenanceVolume(ticketNumber, cwd, home) {
26325
27139
  return {
26326
27140
  recordFile: path.recordFile,
26327
27141
  volumeDir: path.sessionDir,
26328
- humanViewFile: join23(path.sessionDir, TICKET_PROVENANCE_HUMAN_VIEW)
27142
+ humanViewFile: join26(path.sessionDir, TICKET_PROVENANCE_HUMAN_VIEW)
26329
27143
  };
26330
27144
  }
26331
27145
  var init_ticket_provenance = __esm({
26332
27146
  "src/ticket-provenance.ts"() {
26333
27147
  "use strict";
26334
27148
  init_sitian_facade();
27149
+ init_run_ticket_number();
26335
27150
  init_ticket_provenance_contracts();
26336
27151
  }
26337
27152
  });
26338
27153
 
26339
27154
  // src/public-cli/case-dossier-delivery.ts
27155
+ import { mkdtemp, readFile as readFile19, rm, writeFile as writeFile8 } from "node:fs/promises";
27156
+ import { tmpdir } from "node:os";
27157
+ import { join as join27 } from "node:path";
26340
27158
  function describeDossierFile(path) {
26341
27159
  return path;
26342
27160
  }
@@ -26355,19 +27173,43 @@ async function projectCaseDossierPointerSection(input) {
26355
27173
  `\u8BB0\u5F55\u5377\u5B97\uFF1A${describeDossierFile(volume.recordFile)}`
26356
27174
  ].join("\n");
26357
27175
  }
26358
- var CASE_DOSSIER_SECTION_HEADING;
27176
+ async function deliverCaseDossierAsAttachment(input) {
27177
+ const section = await projectCaseDossierPointerSection({
27178
+ ticketNumber: input.ticketNumber,
27179
+ projectRoot: input.projectRoot,
27180
+ home: input.home
27181
+ });
27182
+ if (section === void 0) return void 0;
27183
+ const stagingDir = await mkdtemp(join27(tmpdir(), "ak-case-dossier-"));
27184
+ try {
27185
+ const stagingPath = join27(stagingDir, CASE_DOSSIER_ATTACH_FILE);
27186
+ await writeFile8(stagingPath, `${section}
27187
+ `, "utf8");
27188
+ return await freezeAttachmentsIntoRun(
27189
+ [stagingPath],
27190
+ input.runDirectory,
27191
+ CASE_DOSSIER_ATTACH_KEY
27192
+ );
27193
+ } finally {
27194
+ await rm(stagingDir, { recursive: true, force: true });
27195
+ }
27196
+ }
27197
+ var CASE_DOSSIER_SECTION_HEADING, CASE_DOSSIER_ATTACH_KEY, CASE_DOSSIER_ATTACH_FILE;
26359
27198
  var init_case_dossier_delivery = __esm({
26360
27199
  "src/public-cli/case-dossier-delivery.ts"() {
26361
27200
  "use strict";
26362
27201
  init_ticket_provenance();
27202
+ init_invocation();
26363
27203
  CASE_DOSSIER_SECTION_HEADING = "## \u672C\u7968\u8D77\u5C45\u5F55\uFF08\u7CFB\u7EDF\u968F\u6848\u63D0\u4F9B\uFF09";
27204
+ CASE_DOSSIER_ATTACH_KEY = "case-dossier";
27205
+ CASE_DOSSIER_ATTACH_FILE = "case-dossier-pointer.md";
26364
27206
  }
26365
27207
  });
26366
27208
 
26367
27209
  // src/host-transition-prior-native.ts
26368
- import { access as access3, readdir as readdir6 } from "node:fs/promises";
26369
- import { dirname as dirname13, join as join24 } from "node:path";
26370
- function isEnoent2(error) {
27210
+ import { access as access3, readdir as readdir8 } from "node:fs/promises";
27211
+ import { dirname as dirname14, join as join28 } from "node:path";
27212
+ function isEnoent3(error) {
26371
27213
  return typeof error === "object" && error !== null && error.code === "ENOENT";
26372
27214
  }
26373
27215
  async function listPiNativeRecordPaths(sessionFile) {
@@ -26375,28 +27217,28 @@ async function listPiNativeRecordPaths(sessionFile) {
26375
27217
  await access3(sessionFile);
26376
27218
  return [sessionFile];
26377
27219
  } catch (error) {
26378
- if (isEnoent2(error)) return [];
27220
+ if (isEnoent3(error)) return [];
26379
27221
  throw error;
26380
27222
  }
26381
27223
  }
26382
27224
  async function listSitianRecordPaths(sessionParent) {
26383
- const sessionRoot = dirname13(sessionParent);
27225
+ const sessionRoot = dirname14(sessionParent);
26384
27226
  let entries;
26385
27227
  try {
26386
- entries = await readdir6(sessionRoot, { withFileTypes: true });
27228
+ entries = await readdir8(sessionRoot, { withFileTypes: true });
26387
27229
  } catch (error) {
26388
- if (isEnoent2(error)) return [];
27230
+ if (isEnoent3(error)) return [];
26389
27231
  throw error;
26390
27232
  }
26391
27233
  const recordPaths = [];
26392
27234
  for (const entry of entries) {
26393
27235
  if (!entry.isDirectory()) continue;
26394
- const recordFile = join24(sessionRoot, entry.name, "records.jsonl");
27236
+ const recordFile = join28(sessionRoot, entry.name, "records.jsonl");
26395
27237
  try {
26396
27238
  await access3(recordFile);
26397
27239
  recordPaths.push(recordFile);
26398
27240
  } catch (error) {
26399
- if (!isEnoent2(error)) throw error;
27241
+ if (!isEnoent3(error)) throw error;
26400
27242
  }
26401
27243
  }
26402
27244
  recordPaths.sort();
@@ -26460,8 +27302,8 @@ var init_public_run_credentials = __esm({
26460
27302
  // src/public-cli/auto-resume.ts
26461
27303
  import { constants as fsConstants2 } from "node:fs";
26462
27304
  import { randomUUID as randomUUID4 } from "node:crypto";
26463
- import { lstat as lstat5, mkdir as mkdir5, open as open2 } from "node:fs/promises";
26464
- import { join as join25 } from "node:path";
27305
+ import { lstat as lstat6, mkdir as mkdir4, open as open2 } from "node:fs/promises";
27306
+ import { join as join29 } from "node:path";
26465
27307
  async function persistReturnedRunState(admitted, authority, options) {
26466
27308
  if (options?.lawful === true) {
26467
27309
  await markRunTerminal(admitted.runDirectory);
@@ -26496,24 +27338,21 @@ async function finalizeExceptionRunBestEffort(runDirectory, io) {
26496
27338
  );
26497
27339
  }
26498
27340
  }
26499
- function runArtifactsDirectory(runDirectory) {
26500
- return join25(runDirectory, "artifacts");
26501
- }
26502
27341
  async function ensureRealArtifactsDirectory(runDirectory) {
26503
- const runStat = await lstat5(runDirectory);
27342
+ const runStat = await lstat6(runDirectory);
26504
27343
  if (runStat.isSymbolicLink() || !runStat.isDirectory()) {
26505
27344
  throw new Error("run artifact retention: run directory is not a real directory");
26506
27345
  }
26507
- const artifactsDir = runArtifactsDirectory(runDirectory);
27346
+ const artifactsDir = roleRunArtifactsDirectory(runDirectory);
26508
27347
  try {
26509
- const existing = await lstat5(artifactsDir);
27348
+ const existing = await lstat6(artifactsDir);
26510
27349
  if (existing.isSymbolicLink() || !existing.isDirectory()) {
26511
27350
  throw new Error("run artifact retention: artifacts path is not a real directory");
26512
27351
  }
26513
27352
  } catch (error) {
26514
- if (!isMissingPathError4(error)) throw error;
26515
- await mkdir5(artifactsDir, { recursive: true });
26516
- const created = await lstat5(artifactsDir);
27353
+ if (!isMissingPathError5(error)) throw error;
27354
+ await mkdir4(artifactsDir, { recursive: true });
27355
+ const created = await lstat6(artifactsDir);
26517
27356
  if (created.isSymbolicLink() || !created.isDirectory()) {
26518
27357
  throw new Error("run artifact retention: artifacts directory is not a real directory");
26519
27358
  }
@@ -26543,7 +27382,7 @@ function serializeThrownValue(value, depth = 0, seen = /* @__PURE__ */ new WeakS
26543
27382
  }
26544
27383
  return value;
26545
27384
  }
26546
- function isMissingPathError4(error) {
27385
+ function isMissingPathError5(error) {
26547
27386
  return error instanceof Error && "code" in error && error.code === "ENOENT";
26548
27387
  }
26549
27388
  function transferNestedValue(value, depth, seen) {
@@ -26579,7 +27418,7 @@ function jsonSafeReplacer() {
26579
27418
  };
26580
27419
  }
26581
27420
  async function writeHardenedArtifactFile(artifactsDir, namePrefix, payload) {
26582
- const filePath = join25(artifactsDir, `${namePrefix}-${randomUUID4()}.json`);
27421
+ const filePath = join29(artifactsDir, `${namePrefix}-${randomUUID4()}.json`);
26583
27422
  const body = `${JSON.stringify(payload, jsonSafeReplacer(), 2)}
26584
27423
  `;
26585
27424
  const noFollowFlag = typeof fsConstants2.O_NOFOLLOW === "number" ? fsConstants2.O_NOFOLLOW : 0;
@@ -26828,6 +27667,7 @@ var dummyIo, TurnDispatchedFailure, DISPATCH_ERROR_RETENTION_ENTRY_TYPE;
26828
27667
  var init_auto_resume = __esm({
26829
27668
  "src/public-cli/auto-resume.ts"() {
26830
27669
  "use strict";
27670
+ init_role_run_placement();
26831
27671
  init_run_lifecycle();
26832
27672
  init_config2();
26833
27673
  init_terminal();
@@ -26850,8 +27690,8 @@ var init_auto_resume = __esm({
26850
27690
 
26851
27691
  // src/public-cli/post-admission.ts
26852
27692
  import { randomUUID as randomUUID5 } from "node:crypto";
26853
- import { readFile as readFile18, writeFile as writeFile7 } from "node:fs/promises";
26854
- import { isAbsolute as isAbsolute8, join as join26, resolve as resolve9 } from "node:path";
27693
+ import { readFile as readFile20, writeFile as writeFile9 } from "node:fs/promises";
27694
+ import { isAbsolute as isAbsolute8, join as join30, resolve as resolve8 } from "node:path";
26855
27695
  function describeCaughtError(error) {
26856
27696
  if (error instanceof Error) {
26857
27697
  const code = error.code;
@@ -26865,15 +27705,18 @@ function appendContinuationSection(continuation, section) {
26865
27705
  ${section}`;
26866
27706
  return continuation.kind === "initial" ? { kind: "initial", prompt } : { kind: "resume", prompt };
26867
27707
  }
27708
+ function isStationChildOfficerDialogue(role, env) {
27709
+ return env.stationChild === true && isOfficerReviewSeat(role);
27710
+ }
26868
27711
  function withOnceSuccessfulBeforeDispatch(adapters) {
26869
27712
  const hook = adapters.beforeDispatch;
26870
27713
  if (hook === void 0) return adapters;
26871
27714
  let succeeded = false;
26872
27715
  return {
26873
27716
  ...adapters,
26874
- beforeDispatch: async (admitted) => {
27717
+ beforeDispatch: async (admitted, lease) => {
26875
27718
  if (succeeded) return;
26876
- await hook(admitted);
27719
+ await hook(admitted, lease);
26877
27720
  succeeded = true;
26878
27721
  }
26879
27722
  };
@@ -26892,8 +27735,8 @@ async function recordBestEffortPostDispatchDiagnostic(admitted, env, diagnostic,
26892
27735
  } catch (appendError) {
26893
27736
  try {
26894
27737
  const artifactsDir = await ensureRealArtifactsDirectory(admitted.runDirectory);
26895
- await writeFile7(
26896
- join26(artifactsDir, `post-admission-diagnostic-${randomUUID5()}.json`),
27738
+ await writeFile9(
27739
+ join30(artifactsDir, `post-admission-diagnostic-${randomUUID5()}.json`),
26897
27740
  `${JSON.stringify({ version: 1, ...payload }, null, 2)}
26898
27741
  `,
26899
27742
  { encoding: "utf8", flag: "wx" }
@@ -26909,7 +27752,7 @@ async function recordBestEffortPostDispatchDiagnostic(admitted, env, diagnostic,
26909
27752
  }
26910
27753
  async function readInvocationHost(runDirectory) {
26911
27754
  try {
26912
- const raw = JSON.parse(await readFile18(join26(runDirectory, "invocation.json"), "utf8"));
27755
+ const raw = JSON.parse(await readFile20(join30(runDirectory, "invocation.json"), "utf8"));
26913
27756
  return typeof raw.host === "string" && raw.host.trim() !== "" ? raw.host : void 0;
26914
27757
  } catch (error) {
26915
27758
  if (error.code === "ENOENT") return void 0;
@@ -27027,6 +27870,44 @@ async function dispatchPostAdmissionTurn(input) {
27027
27870
  const persistRunState = input.persistRunState !== false;
27028
27871
  const deferredPersist = persistRunState ? {} : { needsPersist: true };
27029
27872
  const shouldPresent = adapters.shouldPresentSettled ?? ((terminal) => isLawfulTypedTerminalOutcome(terminal.roleOutcome));
27873
+ let afterDispatchApplied = false;
27874
+ const finishAfterTurn = async (result2) => {
27875
+ if (adapters.afterDispatch === void 0 || afterDispatchApplied) return result2;
27876
+ afterDispatchApplied = true;
27877
+ try {
27878
+ await adapters.afterDispatch(admitted, lease);
27879
+ return result2;
27880
+ } catch (error) {
27881
+ const primaryFailure = result2.terminal !== void 0 && !isLawfulTypedTerminalOutcome(result2.terminal.roleOutcome);
27882
+ if (primaryFailure) {
27883
+ await recordBestEffortPostDispatchDiagnostic(
27884
+ admitted,
27885
+ env,
27886
+ `afterDispatch failed beside primary terminal (best-effort continue): ${describeErrorIdentity(error)}`,
27887
+ io
27888
+ );
27889
+ return result2;
27890
+ }
27891
+ return {
27892
+ ...await presentControlledFailure2(
27893
+ admitted,
27894
+ {
27895
+ timedOut: false,
27896
+ code: null,
27897
+ stderr: "",
27898
+ thrown: error
27899
+ },
27900
+ adapters,
27901
+ env.principalAuthority,
27902
+ io,
27903
+ persistRunState
27904
+ ),
27905
+ ...result2.turnDispatched === true ? { turnDispatched: true } : {},
27906
+ ...result2.skipAutoResume === true ? { skipAutoResume: true } : {},
27907
+ ...deferredPersist
27908
+ };
27909
+ }
27910
+ };
27030
27911
  try {
27031
27912
  const missingCredential = missingCredentialPreDispatchFailure(
27032
27913
  env.model,
@@ -27078,7 +27959,7 @@ async function dispatchPostAdmissionTurn(input) {
27078
27959
  await clearReviewerDispatchRejection(admitted.runDirectory);
27079
27960
  if (adapters.beforeDispatch !== void 0) {
27080
27961
  try {
27081
- await adapters.beforeDispatch(admitted);
27962
+ await adapters.beforeDispatch(admitted, lease);
27082
27963
  } catch (error) {
27083
27964
  const settled2 = await presentControlledFailure2(
27084
27965
  admitted,
@@ -27106,19 +27987,28 @@ async function dispatchPostAdmissionTurn(input) {
27106
27987
  if (hostTransition !== void 0) {
27107
27988
  turnRequest = { ...turnRequest, hostTransition };
27108
27989
  }
27109
- const dossierSection = await projectCaseDossierPointerSection({
27110
- ticketNumber: admitted.ticketNumber,
27111
- projectRoot: admitted.projectRoot,
27112
- home: env.home
27113
- });
27114
- if (dossierSection !== void 0) {
27115
- turnRequest = {
27116
- ...turnRequest,
27117
- continuation: appendContinuationSection(
27118
- turnRequest.continuation,
27119
- dossierSection
27120
- )
27121
- };
27990
+ if (isStationChildOfficerDialogue(admitted.role, env)) {
27991
+ await deliverCaseDossierAsAttachment({
27992
+ ticketNumber: admitted.ticketNumber,
27993
+ projectRoot: admitted.projectRoot,
27994
+ home: env.home,
27995
+ runDirectory: admitted.runDirectory
27996
+ });
27997
+ } else {
27998
+ const dossierSection = await projectCaseDossierPointerSection({
27999
+ ticketNumber: admitted.ticketNumber,
28000
+ projectRoot: admitted.projectRoot,
28001
+ home: env.home
28002
+ });
28003
+ if (dossierSection !== void 0) {
28004
+ turnRequest = {
28005
+ ...turnRequest,
28006
+ continuation: appendContinuationSection(
28007
+ turnRequest.continuation,
28008
+ dossierSection
28009
+ )
28010
+ };
28011
+ }
27122
28012
  }
27123
28013
  await markRunRunning(
27124
28014
  admitted.runDirectory,
@@ -27144,12 +28034,12 @@ async function dispatchPostAdmissionTurn(input) {
27144
28034
  io,
27145
28035
  persistRunState
27146
28036
  );
27147
- return { ...settled2, turnDispatched: true, ...deferredPersist };
28037
+ return await finishAfterTurn({ ...settled2, turnDispatched: true, ...deferredPersist });
27148
28038
  }
27149
28039
  let stderrLogWriteFailure;
27150
28040
  try {
27151
- await writeFile7(
27152
- join26(admitted.runDirectory, "stderr.log"),
28041
+ await writeFile9(
28042
+ join30(admitted.runDirectory, "stderr.log"),
27153
28043
  result2.stderr,
27154
28044
  "utf8"
27155
28045
  );
@@ -27223,7 +28113,7 @@ async function dispatchPostAdmissionTurn(input) {
27223
28113
  io,
27224
28114
  persistRunState
27225
28115
  );
27226
- return { ...settledFailure, turnDispatched: true, ...deferredPersist };
28116
+ return await finishAfterTurn({ ...settledFailure, turnDispatched: true, ...deferredPersist });
27227
28117
  }
27228
28118
  if (settledOutcome !== void 0) {
27229
28119
  if (persistRunState) {
@@ -27244,10 +28134,10 @@ async function dispatchPostAdmissionTurn(input) {
27244
28134
  io,
27245
28135
  persistRunState
27246
28136
  );
27247
- return { ...failed, turnDispatched: true, ...deferredPersist };
28137
+ return await finishAfterTurn({ ...failed, turnDispatched: true, ...deferredPersist });
27248
28138
  }
27249
28139
  }
27250
- return { ...settledOutcome, ...deferredPersist };
28140
+ return await finishAfterTurn({ ...settledOutcome, ...deferredPersist });
27251
28141
  }
27252
28142
  if (hostSignalFailed) {
27253
28143
  const resolutionInput = controlledFailureInputFromResolution(resolution);
@@ -27274,7 +28164,7 @@ async function dispatchPostAdmissionTurn(input) {
27274
28164
  io,
27275
28165
  persistRunState
27276
28166
  );
27277
- return { ...failed, turnDispatched: true, ...deferredPersist };
28167
+ return await finishAfterTurn({ ...failed, turnDispatched: true, ...deferredPersist });
27278
28168
  }
27279
28169
  if (stderrLogWriteFailure !== void 0) {
27280
28170
  const failed = await settleAfterTurnStarted(
@@ -27290,7 +28180,7 @@ async function dispatchPostAdmissionTurn(input) {
27290
28180
  io,
27291
28181
  persistRunState
27292
28182
  );
27293
- return { ...failed, turnDispatched: true, ...deferredPersist };
28183
+ return await finishAfterTurn({ ...failed, turnDispatched: true, ...deferredPersist });
27294
28184
  }
27295
28185
  const noReceipt = await attachRecordedSubmissions(
27296
28186
  admitted,
@@ -27315,16 +28205,16 @@ async function dispatchPostAdmissionTurn(input) {
27315
28205
  io,
27316
28206
  persistRunState
27317
28207
  );
27318
- return { ...failed, turnDispatched: true, ...deferredPersist };
28208
+ return await finishAfterTurn({ ...failed, turnDispatched: true, ...deferredPersist });
27319
28209
  }
27320
28210
  }
27321
- return {
28211
+ return await finishAfterTurn({
27322
28212
  exitCode: exitCodeForTerminalOutcome(noReceipt.roleOutcome),
27323
28213
  admitted,
27324
28214
  terminal: noReceipt,
27325
28215
  turnDispatched: true,
27326
28216
  ...deferredPersist
27327
- };
28217
+ });
27328
28218
  } finally {
27329
28219
  try {
27330
28220
  await lease.release();
@@ -27338,25 +28228,17 @@ async function dispatchPostAdmissionTurn(input) {
27338
28228
  }
27339
28229
  }
27340
28230
  function resumeTurnRequestProjectionOptions(admitted, request, env, summonsPrepared) {
27341
- const officerSourcePath = request.summons?.sourceRunPath;
27342
- const withReread = (body) => {
27343
- if (officerSourcePath === void 0 || admitted.role !== "notary" && admitted.role !== "inspector" && admitted.role !== "auditor") {
27344
- return body;
27345
- }
27346
- if (body.startsWith("\u8BF7\u91CD\u8BFB")) return body;
27347
- return `\u8BF7\u91CD\u8BFB
27348
- ${body}`;
27349
- };
28231
+ const officerDialogue = isStationChildOfficerDialogue(admitted.role, env);
27350
28232
  let prompt;
27351
28233
  if (request.message !== void 0) {
27352
28234
  if (summonsPrepared !== void 0) {
27353
- prompt = withReread(buildInstructionTransportPrompt({
28235
+ prompt = officerDialogue ? request.message : buildInstructionTransportPrompt({
27354
28236
  instruction: request.message,
27355
28237
  instructionEmpty: false,
27356
28238
  attachments: summonsPrepared.attachments
27357
- }));
28239
+ });
27358
28240
  } else if (request.summons !== void 0) {
27359
- prompt = withReread(request.message);
28241
+ prompt = request.message;
27360
28242
  } else {
27361
28243
  prompt = buildResumeContinuationPrompt({
27362
28244
  packageRoot: env.packageRoot,
@@ -27365,17 +28247,9 @@ ${body}`;
27365
28247
  });
27366
28248
  }
27367
28249
  } else if (summonsPrepared !== void 0) {
27368
- prompt = withReread(buildInstructionTransportPrompt(summonsPrepared));
28250
+ prompt = officerDialogue ? summonsPrepared.instructionEmpty ? "" : summonsPrepared.instruction : buildInstructionTransportPrompt(summonsPrepared);
27369
28251
  } else if (request.summons !== void 0) {
27370
- const path = request.summons.sourceRunPath;
27371
- if (path !== void 0 && (admitted.role === "notary" || admitted.role === "inspector" || admitted.role === "auditor")) {
27372
- prompt = `\u8BF7\u91CD\u8BFB
27373
- ${GATE_DOSSIER_POINTER_PREFIX}${path}`;
27374
- } else if (admitted.role === "notary" || admitted.role === "inspector" || admitted.role === "auditor") {
27375
- prompt = "\u8BF7\u91CD\u8BFB";
27376
- } else {
27377
- prompt = "";
27378
- }
28252
+ prompt = "";
27379
28253
  } else {
27380
28254
  prompt = buildResumeContinuationPrompt({
27381
28255
  packageRoot: env.packageRoot,
@@ -27411,8 +28285,8 @@ async function dispatchAfterWriterLease(input) {
27411
28285
  }
27412
28286
  }
27413
28287
  function isAlreadyFrozenSummonsAttachment(runDirectory, attachmentPath) {
27414
- const absolute = isAbsolute8(attachmentPath) ? attachmentPath : resolve9(attachmentPath);
27415
- return pathContainedIn(join26(runDirectory, "attachments"), absolute);
28288
+ const absolute = isAbsolute8(attachmentPath) ? attachmentPath : resolve8(attachmentPath);
28289
+ return pathContainedIn(join30(runDirectory, "attachments"), absolute);
27416
28290
  }
27417
28291
  async function prepareSummonsResumeMaterials(runDirectory, summons) {
27418
28292
  if (summons === void 0) return void 0;
@@ -27708,6 +28582,7 @@ var init_post_admission = __esm({
27708
28582
  init_activation_ledger_topology();
27709
28583
  init_engine_material();
27710
28584
  init_session_identity();
28585
+ init_host_contracts();
27711
28586
  init_case_dossier_delivery();
27712
28587
  init_host_transition_prior_native();
27713
28588
  init_public_run_credentials();
@@ -28060,7 +28935,7 @@ async function runPublicInstructionSeat(argv, env, io, role, parseArgv2) {
28060
28935
  home: env.home
28061
28936
  });
28062
28937
  auditorSourceRun = resolved.runDirectory;
28063
- auditorSourceTicket = await readRunTicketNumber(resolved.runDirectory);
28938
+ auditorSourceTicket = await readBoardTicketNumber(resolved.runDirectory);
28064
28939
  } catch (error) {
28065
28940
  presentStructuralRejection(
28066
28941
  new CliUsageError(error instanceof Error ? error.message : String(error)),
@@ -28069,7 +28944,7 @@ async function runPublicInstructionSeat(argv, env, io, role, parseArgv2) {
28069
28944
  return { exitCode: 2 };
28070
28945
  }
28071
28946
  }
28072
- const resumeInstruction = env.reviewReask;
28947
+ const resumeInstruction = env.reviewReask ?? env.gateReviewInstruction;
28073
28948
  const summons = {
28074
28949
  ...resumeInstruction === void 0 ? {
28075
28950
  instruction: parsed.instruction,
@@ -28108,7 +28983,8 @@ async function runPublicInstructionSeat(argv, env, io, role, parseArgv2) {
28108
28983
  ...parsed.project === void 0 ? {} : { project: parsed.project },
28109
28984
  ...env.createRunId === void 0 ? {} : { createRunId: env.createRunId },
28110
28985
  ...env.model === void 0 ? {} : { model: env.model },
28111
- ...env.correlationId === void 0 ? {} : { correlationId: env.correlationId }
28986
+ ...env.correlationId === void 0 ? {} : { correlationId: env.correlationId },
28987
+ ...auditorSourceTicket === void 0 ? {} : { assertedTicketNumber: auditorSourceTicket }
28112
28988
  });
28113
28989
  } catch (error) {
28114
28990
  if (error instanceof CliUsageError) {
@@ -28135,7 +29011,8 @@ async function runPublicInstructionSeat(argv, env, io, role, parseArgv2) {
28135
29011
  ...env.correlationId === void 0 || env.correlationId.trim() === "" ? {} : { correlationId: env.correlationId },
28136
29012
  continuation: {
28137
29013
  kind: "initial",
28138
- prompt: buildInstructionTransportPrompt(
29014
+ // #879: gate first mint uses parent payload as content when present.
29015
+ prompt: env.reviewReask ?? env.gateReviewInstruction ?? buildInstructionTransportPrompt(
28139
29016
  admitted,
28140
29017
  engineSessionMaterialFromOptions({
28141
29018
  ...pickEngineAxis(env),
@@ -28149,13 +29026,7 @@ async function runPublicInstructionSeat(argv, env, io, role, parseArgv2) {
28149
29026
  env,
28150
29027
  io,
28151
29028
  request: turnRequest,
28152
- adapters: instructionSeatAdapters({
28153
- beforeDispatch: async (admittedSeat) => {
28154
- if (auditorSourceTicket !== void 0) {
28155
- await bindAdmittedTicketNumber(admittedSeat, auditorSourceTicket);
28156
- }
28157
- }
28158
- }),
29029
+ adapters: instructionSeatAdapters(),
28159
29030
  ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
28160
29031
  });
28161
29032
  }
@@ -28340,7 +29211,7 @@ async function runPublicNotary(argv, env, io, parseNotaryArgv2) {
28340
29211
  throw error;
28341
29212
  }
28342
29213
  {
28343
- const resumeInstruction = env.reviewReask;
29214
+ const resumeInstruction = env.reviewReask ?? env.gateReviewInstruction;
28344
29215
  const summons = {
28345
29216
  sourceRunPath: source.runDirectory,
28346
29217
  sourceRun: source,
@@ -28395,7 +29266,9 @@ async function runPublicNotary(argv, env, io, parseNotaryArgv2) {
28395
29266
  ...env.correlationId === void 0 || env.correlationId.trim() === "" ? {} : { correlationId: env.correlationId },
28396
29267
  continuation: {
28397
29268
  kind: "initial",
28398
- prompt: buildNotaryTransportPrompt(admitted, engineMaterial)
29269
+ // #879: gate path first mint carries parent payload as dialogue content;
29270
+ // external zero-prompt kickoff unchanged when no body/reask.
29271
+ prompt: env.reviewReask ?? env.gateReviewInstruction ?? buildNotaryTransportPrompt(admitted, engineMaterial)
28399
29272
  }
28400
29273
  });
28401
29274
  return await runPostAdmissionOneShot({
@@ -28483,12 +29356,20 @@ __export(inspector_run_exports, {
28483
29356
  runPublicInspector: () => runPublicInspector,
28484
29357
  runPublicInspectorResume: () => runPublicInspectorResume
28485
29358
  });
29359
+ function inspectorParentRunPath(admitted) {
29360
+ if (typeof admitted.sourceRunPath === "string" && admitted.sourceRunPath.trim() !== "") {
29361
+ return admitted.sourceRunPath;
29362
+ }
29363
+ return parentRunPathFromGatePointerInstruction(admitted.instruction);
29364
+ }
28486
29365
  function buildInspectorTurnRequest(admitted, options) {
29366
+ const sourceRun = inspectorParentRunPath(admitted);
28487
29367
  return projectRoleTurnRequest(
28488
29368
  admitted,
28489
29369
  {
28490
29370
  activation: {
28491
- role: "inspector"
29371
+ role: "inspector",
29372
+ ...sourceRun === void 0 ? {} : { sourceRun }
28492
29373
  }
28493
29374
  },
28494
29375
  options
@@ -28508,7 +29389,7 @@ async function runPublicInspector(argv, env, io, parseInspectorArgv2) {
28508
29389
  const projectRoot = parsed.project ?? env.cwd;
28509
29390
  const parentRunPath = parentRunPathFromGatePointerInstruction(parsed.instruction);
28510
29391
  if (parentRunPath !== void 0) {
28511
- const resumeInstruction = env.reviewReask;
29392
+ const resumeInstruction = env.reviewReask ?? env.gateReviewInstruction;
28512
29393
  const summons = {
28513
29394
  sourceRunPath: parentRunPath,
28514
29395
  ...resumeInstruction === void 0 ? {
@@ -28553,6 +29434,10 @@ async function runPublicInspector(argv, env, io, parseInspectorArgv2) {
28553
29434
  throw error;
28554
29435
  }
28555
29436
  await markRunAdmitted(admitted, env.principalAuthority);
29437
+ if (parentRunPath !== void 0) {
29438
+ await persistAdmittedSourceRunPath(admitted, parentRunPath);
29439
+ admitted = { ...admitted, sourceRunPath: parentRunPath };
29440
+ }
28556
29441
  const engineMaterial = engineSessionMaterialFromOptions({
28557
29442
  ...pickEngineAxis(env),
28558
29443
  packageRoot: env.packageRoot
@@ -28567,7 +29452,8 @@ async function runPublicInspector(argv, env, io, parseInspectorArgv2) {
28567
29452
  ...env.correlationId === void 0 || env.correlationId.trim() === "" ? {} : { correlationId: env.correlationId },
28568
29453
  continuation: {
28569
29454
  kind: "initial",
28570
- prompt: buildInspectorTransportPrompt(admitted, engineMaterial)
29455
+ // #879: gate first mint uses parent payload as content; binding stays typed activation.
29456
+ prompt: env.reviewReask ?? env.gateReviewInstruction ?? buildInspectorTransportPrompt(admitted, engineMaterial)
28571
29457
  }
28572
29458
  });
28573
29459
  return await runPostAdmissionOneShot({
@@ -28864,10 +29750,26 @@ function buildDiaristTurnRequest(admitted, options) {
28864
29750
  options
28865
29751
  );
28866
29752
  }
28867
- function diaristAdapters() {
29753
+ async function bindAndRelocateDiaristIfBoardBound(admitted, authority, lease) {
29754
+ const boardTicket = await readBoardTicketNumber(admitted.runDirectory);
29755
+ if (boardTicket === void 0) return;
29756
+ if (admitted.ticketNumber === void 0) {
29757
+ await bindAdmittedTicketNumber(admitted, boardTicket);
29758
+ }
29759
+ await relocateAdmittedRunToTicket(admitted, authority, lease);
29760
+ }
29761
+ function diaristAdapters(env) {
28868
29762
  return {
28869
29763
  trySettle: (admitted, authority, scope) => trySettleDiaristTerminalResult(admitted, authority, scope),
28870
- shouldPresentSettled: () => true
29764
+ shouldPresentSettled: () => true,
29765
+ // Resume interrupted state: board ticket already on pages, run still under unbound/.
29766
+ beforeDispatch: async (admitted, lease) => {
29767
+ await bindAndRelocateDiaristIfBoardBound(admitted, env.principalAuthority, lease);
29768
+ },
29769
+ // First post-turn assert: accept hook wrote board pages; relocate before lease release.
29770
+ afterDispatch: async (admitted, lease) => {
29771
+ await bindAndRelocateDiaristIfBoardBound(admitted, env.principalAuthority, lease);
29772
+ }
28871
29773
  };
28872
29774
  }
28873
29775
  async function runPublicDiarist(argv, env, io, parseDiaristArgv2) {
@@ -28915,7 +29817,8 @@ async function runPublicDiarist(argv, env, io, parseDiaristArgv2) {
28915
29817
  ...parsed.project === void 0 ? {} : { project: parsed.project },
28916
29818
  ...env.createRunId === void 0 ? {} : { createRunId: env.createRunId },
28917
29819
  ...env.model === void 0 ? {} : { model: env.model },
28918
- ...env.correlationId === void 0 ? {} : { correlationId: env.correlationId }
29820
+ ...env.correlationId === void 0 ? {} : { correlationId: env.correlationId },
29821
+ ...handoffTicket === void 0 ? {} : { assertedTicketNumber: handoffTicket }
28919
29822
  });
28920
29823
  } catch (error) {
28921
29824
  if (error instanceof CliUsageError) {
@@ -28925,9 +29828,6 @@ async function runPublicDiarist(argv, env, io, parseDiaristArgv2) {
28925
29828
  throw error;
28926
29829
  }
28927
29830
  await markRunAdmitted(admitted, env.principalAuthority);
28928
- if (typeof handoffTicket === "number" && Number.isSafeInteger(handoffTicket) && handoffTicket >= 1) {
28929
- await bindAdmittedTicketNumber(admitted, handoffTicket);
28930
- }
28931
29831
  const turnProjection = {
28932
29832
  packageRoot: env.packageRoot,
28933
29833
  home: env.home,
@@ -28953,19 +29853,8 @@ async function runPublicDiarist(argv, env, io, parseDiaristArgv2) {
28953
29853
  env,
28954
29854
  io,
28955
29855
  request: turnRequest,
28956
- adapters: diaristAdapters(),
29856
+ adapters: diaristAdapters(env),
28957
29857
  ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
28958
- }).then(async (result2) => {
28959
- if (admitted.ticketNumber === void 0 && result2.admitted !== void 0) {
28960
- const fromPages = await readRunTicketNumber(admitted.runDirectory);
28961
- if (fromPages !== void 0) {
28962
- await bindAdmittedTicketNumber(admitted, fromPages);
28963
- if (result2.admitted.ticketNumber === void 0) {
28964
- result2.admitted.ticketNumber = fromPages;
28965
- }
28966
- }
28967
- }
28968
- return result2;
28969
29858
  });
28970
29859
  }
28971
29860
  async function runPublicDiaristResume(request, env, io) {
@@ -28989,7 +29878,7 @@ async function runPublicDiaristResume(request, env, io) {
28989
29878
  )
28990
29879
  );
28991
29880
  },
28992
- adapters: diaristAdapters(),
29881
+ adapters: diaristAdapters(env),
28993
29882
  ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
28994
29883
  });
28995
29884
  }
@@ -29016,8 +29905,8 @@ __export(public_role_summons_exports, {
29016
29905
  summonGateOfficer: () => summonGateOfficer,
29017
29906
  summonPublicRole: () => summonPublicRole
29018
29907
  });
29019
- import { existsSync as existsSync9 } from "node:fs";
29020
- import { join as join27 } from "node:path";
29908
+ import { existsSync as existsSync10 } from "node:fs";
29909
+ import { join as join31 } from "node:path";
29021
29910
  function createCapturingIo() {
29022
29911
  const chunks = [];
29023
29912
  return {
@@ -29040,7 +29929,7 @@ function parentDir(path) {
29040
29929
  function walkPackageRoot(start) {
29041
29930
  let dir = start;
29042
29931
  for (let i = 0; i < 12; i += 1) {
29043
- if (existsSync9(join27(dir, "package.json")) && existsSync9(join27(dir, "souls"))) {
29932
+ if (existsSync10(join31(dir, "package.json")) && existsSync10(join31(dir, "souls"))) {
29044
29933
  return dir;
29045
29934
  }
29046
29935
  const parent = parentDir(dir);
@@ -29134,7 +30023,7 @@ async function createSummonEnv(options) {
29134
30023
  async function summonPublicRole(options) {
29135
30024
  const packageRoot2 = resolveSummonsPackageRoot(options.packageRoot);
29136
30025
  const home = await resolveSummonHome(options);
29137
- const agentDir = options.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? join27(home, ".pi", "agent");
30026
+ const agentDir = options.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? join31(home, ".pi", "agent");
29138
30027
  const {
29139
30028
  loadCredentialProviders: loadCredentialProviders2,
29140
30029
  loadPublicCliConfig: loadPublicCliConfig2,
@@ -29175,6 +30064,8 @@ async function summonPublicRole(options) {
29175
30064
  ...options.signal === void 0 ? {} : { signal: options.signal },
29176
30065
  // #753: reask rides the existing notary same-ticket resume summons.instruction.
29177
30066
  ...options.reviewReask === void 0 ? {} : { reviewReask: options.reviewReask },
30067
+ // #879: verbatim submission body on officer dialogue content channel.
30068
+ ...options.gateReviewInstruction === void 0 ? {} : { gateReviewInstruction: options.gateReviewInstruction },
29178
30069
  ...options.boundTicketNumber === void 0 ? {} : { boundTicketNumber: options.boundTicketNumber },
29179
30070
  // createRunId is the only remaining env overlay — host is seat-selected above.
29180
30071
  ...options.createRunId === void 0 ? {} : { createRunId: options.createRunId }
@@ -29282,6 +30173,11 @@ async function summonGateOfficer(options) {
29282
30173
  const { homeFromRunDirectory: homeFromRunDirectory3 } = await Promise.resolve().then(() => (init_activation_ledger_topology(), activation_ledger_topology_exports));
29283
30174
  home = homeFromRunDirectory3(options.sourceRunDirectory);
29284
30175
  }
30176
+ let gateReviewInstruction;
30177
+ if (options.reask === void 0 && options.submission !== void 0) {
30178
+ const { readableGateItem: readableGateItem2 } = await Promise.resolve().then(() => (init_readable_gate_item(), readable_gate_item_exports));
30179
+ gateReviewInstruction = readableGateItem2(options.submission);
30180
+ }
29285
30181
  const common = {
29286
30182
  cwd: options.cwd,
29287
30183
  ...home === void 0 ? {} : { home },
@@ -29289,6 +30185,7 @@ async function summonGateOfficer(options) {
29289
30185
  ...options.io === void 0 ? {} : { io: options.io },
29290
30186
  ...options.signal === void 0 ? {} : { signal: options.signal },
29291
30187
  ...options.reask === void 0 ? {} : { reviewReask: options.reask },
30188
+ ...gateReviewInstruction === void 0 ? {} : { gateReviewInstruction },
29292
30189
  ...options.roleTurnHost === void 0 ? {} : { roleTurnHost: options.roleTurnHost },
29293
30190
  ...options.hostAdapters === void 0 ? {} : { hostAdapters: options.hostAdapters },
29294
30191
  ...options.createRunId === void 0 ? {} : { createRunId: options.createRunId }
@@ -29342,6 +30239,30 @@ function buildCountersignTurnRequest(admitted, options) {
29342
30239
  options
29343
30240
  );
29344
30241
  }
30242
+ function courtTicketNumbersFromOutcome(roleOutcome, principalTicket) {
30243
+ if (roleOutcome === void 0) return void 0;
30244
+ const payloads = roleOutcome.kind === "accepted" || roleOutcome.kind === "audit_escalation" || roleOutcome.kind === "failure" ? roleOutcome.payloads ?? [] : [];
30245
+ let latest;
30246
+ for (const payload of payloads) {
30247
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
30248
+ continue;
30249
+ }
30250
+ const record4 = payload;
30251
+ if (!Object.hasOwn(record4, "courtTicketNumbers")) continue;
30252
+ const raw = record4.courtTicketNumbers;
30253
+ if (!Array.isArray(raw)) continue;
30254
+ const members = projectCourtTicketNumbers(raw);
30255
+ if (members === null) continue;
30256
+ if (members.length === 0) {
30257
+ if (raw.length === 0) {
30258
+ latest = projectCourtTicketNumbers([], { principalTicket }) ?? void 0;
30259
+ }
30260
+ continue;
30261
+ }
30262
+ latest = projectCourtTicketNumbers(raw, { principalTicket }) ?? void 0;
30263
+ }
30264
+ return latest;
30265
+ }
29345
30266
  function courtDiaristEscalated(roleOutcome) {
29346
30267
  if (roleOutcome === void 0) return false;
29347
30268
  if (roleOutcome.kind === "audit_escalation") return true;
@@ -29392,9 +30313,14 @@ async function invokeCourtDiarist(input, env, io) {
29392
30313
  };
29393
30314
  }
29394
30315
  const asserted = result2.admitted?.ticketNumber;
29395
- if (typeof asserted === "number" && Number.isSafeInteger(asserted) && asserted >= 1) {
30316
+ if (isSafePositiveTicketNumber(asserted)) {
30317
+ const courtTicketNumbers = courtTicketNumbersFromOutcome(roleOutcome, asserted);
29396
30318
  return {
29397
- identity: { kind: "ticket", ticketNumber: asserted }
30319
+ identity: {
30320
+ kind: "ticket",
30321
+ ticketNumber: asserted,
30322
+ ...courtTicketNumbers === void 0 ? {} : { courtTicketNumbers }
30323
+ }
29398
30324
  };
29399
30325
  }
29400
30326
  return {
@@ -29407,24 +30333,37 @@ async function runCountersignCourtDiaristStation(admitted, env, io) {
29407
30333
  return;
29408
30334
  }
29409
30335
  if (admitted.ticketNumber === void 0) return;
29410
- const outcome = await invokeCourtDiarist(
29411
- {
29412
- instruction: `\u6574\u7406 #${admitted.ticketNumber} \u7684\u672C\u6848\u4F9D\u636E\u3002`,
29413
- projectRoot: admitted.projectRoot,
29414
- failureLabel: `ticket #${admitted.ticketNumber}`,
29415
- // Refresh holds a typed key — hand it off so identity is bound before turn.
29416
- boundTicketNumber: admitted.ticketNumber
29417
- },
29418
- env,
29419
- io
29420
- );
29421
- if (outcome.identity.kind === "escalate") {
29422
- throw new StationChildExhaustedError(
29423
- "court diarist station escalated (cannot identify court target)"
29424
- );
30336
+ let refreshTickets;
30337
+ if (admitted.courtTicketNumbers !== void 0) {
30338
+ if (admitted.courtTicketNumbers.length === 0 || !admitted.courtTicketNumbers.includes(admitted.ticketNumber)) {
30339
+ throw new StationChildExhaustedError(
30340
+ `court diarist station: courtTicketNumbers is damaged (empty or missing principal #${admitted.ticketNumber})`
30341
+ );
30342
+ }
30343
+ refreshTickets = admitted.courtTicketNumbers;
30344
+ } else {
30345
+ refreshTickets = [admitted.ticketNumber];
29425
30346
  }
29426
- if (outcome.failedWithoutEscalate !== void 0) {
29427
- throw new StationChildExhaustedError(outcome.failedWithoutEscalate.diagnostic);
30347
+ for (const ticketNumber of refreshTickets) {
30348
+ const outcome = await invokeCourtDiarist(
30349
+ {
30350
+ instruction: `\u6574\u7406 #${ticketNumber} \u7684\u672C\u6848\u4F9D\u636E\u3002`,
30351
+ projectRoot: admitted.projectRoot,
30352
+ failureLabel: `ticket #${ticketNumber}`,
30353
+ // Refresh holds a typed key — hand it off so identity is bound before turn.
30354
+ boundTicketNumber: ticketNumber
30355
+ },
30356
+ env,
30357
+ io
30358
+ );
30359
+ if (outcome.identity.kind === "escalate") {
30360
+ throw new StationChildExhaustedError(
30361
+ "court diarist station escalated (cannot identify court target)"
30362
+ );
30363
+ }
30364
+ if (outcome.failedWithoutEscalate !== void 0) {
30365
+ throw new StationChildExhaustedError(outcome.failedWithoutEscalate.diagnostic);
30366
+ }
29428
30367
  }
29429
30368
  }
29430
30369
  async function runPublicCountersign(argv, env, io, parseCountersignArgv2) {
@@ -29460,6 +30399,7 @@ async function runPublicCountersign(argv, env, io, parseCountersignArgv2) {
29460
30399
  }
29461
30400
  await markRunAdmitted(admitted, env.principalAuthority);
29462
30401
  let typedTicket;
30402
+ let typedCourtTicketNumbers;
29463
30403
  let identityDiaristRan = false;
29464
30404
  if (env.runCourtDiaristStation === void 0) {
29465
30405
  const outcome = await invokeCourtDiarist(
@@ -29503,7 +30443,9 @@ async function runPublicCountersign(argv, env, io, parseCountersignArgv2) {
29503
30443
  );
29504
30444
  }
29505
30445
  if (outcome.identity.kind === "ticket") {
29506
- typedTicket = outcome.identity.ticketNumber;
30446
+ const assertedTicket = outcome.identity.ticketNumber;
30447
+ typedTicket = assertedTicket;
30448
+ typedCourtTicketNumbers = outcome.identity.courtTicketNumbers;
29507
30449
  const summons = {
29508
30450
  instruction: parsed.instruction,
29509
30451
  instructionEmpty: parsed.instruction.trim() === "",
@@ -29517,13 +30459,18 @@ async function runPublicCountersign(argv, env, io, parseCountersignArgv2) {
29517
30459
  freshSummons: env.freshSummons,
29518
30460
  summons,
29519
30461
  resume: async (runId, materials) => {
30462
+ await bindAdmittedTicketNumber(admitted, assertedTicket);
30463
+ await relocateAdmittedRunToTicket(admitted, env.principalAuthority);
29520
30464
  await markRunTerminal(admitted.runDirectory);
29521
30465
  return await runPublicCountersignResume(
29522
30466
  {
29523
30467
  runId,
29524
30468
  ...materials === void 0 ? {} : { summons: materials }
29525
30469
  },
29526
- env,
30470
+ {
30471
+ ...env,
30472
+ ...typedCourtTicketNumbers === void 0 ? {} : { pendingCourtTicketNumbers: typedCourtTicketNumbers }
30473
+ },
29527
30474
  io
29528
30475
  );
29529
30476
  }
@@ -29533,6 +30480,29 @@ async function runPublicCountersign(argv, env, io, parseCountersignArgv2) {
29533
30480
  }
29534
30481
  }
29535
30482
  }
30483
+ if (identityDiaristRan && typedTicket !== void 0) {
30484
+ try {
30485
+ await bindAdmittedTicketNumber(admitted, typedTicket);
30486
+ await relocateAdmittedRunToTicket(admitted, env.principalAuthority);
30487
+ await bindCourtTicketNumbersOnAdmitted(
30488
+ admitted,
30489
+ typedCourtTicketNumbers ?? [typedTicket]
30490
+ );
30491
+ } catch (error) {
30492
+ return await presentControlledFailure2(
30493
+ admitted,
30494
+ {
30495
+ timedOut: false,
30496
+ code: null,
30497
+ stderr: "",
30498
+ thrown: error
30499
+ },
30500
+ countersignAdapters(),
30501
+ env.principalAuthority,
30502
+ io
30503
+ );
30504
+ }
30505
+ }
29536
30506
  const turnProjection = {
29537
30507
  packageRoot: env.packageRoot,
29538
30508
  home: env.home,
@@ -29553,19 +30523,23 @@ async function runPublicCountersign(argv, env, io, parseCountersignArgv2) {
29553
30523
  }
29554
30524
  };
29555
30525
  const turnRequest = buildCountersignTurnRequest(admitted, turnProjection);
29556
- return await runPostAdmissionOneShot({
30526
+ const result2 = await runPostAdmissionOneShot({
29557
30527
  admitted,
29558
30528
  env,
29559
30529
  io,
29560
30530
  request: turnRequest,
29561
30531
  adapters: countersignAdapters({
29562
- beforeDispatch: async (admittedSeat) => {
30532
+ beforeDispatch: async (admittedSeat, lease) => {
29563
30533
  if (!identityDiaristRan) {
29564
30534
  await runCountersignCourtDiaristStation(admittedSeat, env, io);
29565
30535
  } else if (typedTicket !== void 0) {
29566
- await bindAdmittedTicketNumber(admittedSeat, typedTicket);
29567
30536
  await runCountersignCourtDiaristStation(admittedSeat, env, io);
29568
30537
  }
30538
+ await relocateAdmittedRunToTicket(
30539
+ admittedSeat,
30540
+ env.principalAuthority,
30541
+ lease
30542
+ );
29569
30543
  Object.assign(
29570
30544
  turnRequest,
29571
30545
  buildCountersignTurnRequest(admittedSeat, turnProjection)
@@ -29574,6 +30548,8 @@ async function runPublicCountersign(argv, env, io, parseCountersignArgv2) {
29574
30548
  }),
29575
30549
  ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
29576
30550
  });
30551
+ await relocateAdmittedRunToTicket(admitted, env.principalAuthority);
30552
+ return result2;
29577
30553
  }
29578
30554
  function countersignAdapters(options) {
29579
30555
  return {
@@ -29610,6 +30586,15 @@ async function runPublicCountersignResume(request, env, io) {
29610
30586
  },
29611
30587
  adapters: countersignAdapters({
29612
30588
  beforeDispatch: async (admitted) => {
30589
+ if (admitted.courtTicketNumbersDamage !== void 0) {
30590
+ throw new StationChildExhaustedError(admitted.courtTicketNumbersDamage);
30591
+ }
30592
+ if (env.pendingCourtTicketNumbers !== void 0) {
30593
+ await bindCourtTicketNumbersOnAdmitted(
30594
+ admitted,
30595
+ env.pendingCourtTicketNumbers
30596
+ );
30597
+ }
29613
30598
  await runCountersignCourtDiaristStation(admitted, env, io);
29614
30599
  }
29615
30600
  }),
@@ -29621,6 +30606,8 @@ var init_countersign_run = __esm({
29621
30606
  "use strict";
29622
30607
  init_engine_material();
29623
30608
  init_cli_errors();
30609
+ init_diarist_contracts();
30610
+ init_run_ticket_number();
29624
30611
  init_invocation();
29625
30612
  init_post_admission();
29626
30613
  init_run_lifecycle();
@@ -30276,16 +31263,16 @@ var init_analyst_book_key = __esm({
30276
31263
 
30277
31264
  // src/atomic-write.ts
30278
31265
  import { randomUUID as randomUUID6 } from "node:crypto";
30279
- import { rename as rename2, rm, writeFile as writeFile8 } from "node:fs/promises";
30280
- import { dirname as dirname14, join as join28 } from "node:path";
31266
+ import { rename as rename3, rm as rm2, writeFile as writeFile10 } from "node:fs/promises";
31267
+ import { dirname as dirname15, join as join32 } from "node:path";
30281
31268
  async function writeFileAtomically(destination, contents) {
30282
- const parent = dirname14(destination);
30283
- const temporary = join28(parent, `.atomic-write-${randomUUID6()}.tmp`);
31269
+ const parent = dirname15(destination);
31270
+ const temporary = join32(parent, `.atomic-write-${randomUUID6()}.tmp`);
30284
31271
  try {
30285
- await writeFile8(temporary, contents);
30286
- await rename2(temporary, destination);
31272
+ await writeFile10(temporary, contents);
31273
+ await rename3(temporary, destination);
30287
31274
  } catch (error) {
30288
- await rm(temporary, { force: true }).catch(() => void 0);
31275
+ await rm2(temporary, { force: true }).catch(() => void 0);
30289
31276
  throw error;
30290
31277
  }
30291
31278
  }
@@ -30296,17 +31283,17 @@ var init_atomic_write = __esm({
30296
31283
  });
30297
31284
 
30298
31285
  // src/analyst-index.ts
30299
- import { open as open3, readFile as readFile19, unlink as unlink4 } from "node:fs/promises";
30300
- import { dirname as dirname15, join as join29 } from "node:path";
31286
+ import { open as open3, readFile as readFile21, unlink as unlink4 } from "node:fs/promises";
31287
+ import { dirname as dirname16, join as join33 } from "node:path";
30301
31288
  function sleep(ms) {
30302
- return new Promise((resolve11) => {
30303
- setTimeout(resolve11, ms);
31289
+ return new Promise((resolve10) => {
31290
+ setTimeout(resolve10, ms);
30304
31291
  });
30305
31292
  }
30306
31293
  async function withAnalystLibraryIndexLock(ledgerHome, fn) {
30307
31294
  const indexPath = analystLibraryIndexPath(ledgerHome);
30308
- ensureRealDirectoryTree(ledgerHome, dirname15(indexPath));
30309
- const lockPath = join29(dirname15(indexPath), LIBRARY_INDEX_LOCK_NAME);
31295
+ ensureRealDirectoryTree(ledgerHome, dirname16(indexPath));
31296
+ const lockPath = join33(dirname16(indexPath), LIBRARY_INDEX_LOCK_NAME);
30310
31297
  assertLedgerFileInsideHome(lockPath, ledgerHome);
30311
31298
  const startedAt = Date.now();
30312
31299
  while (true) {
@@ -30333,7 +31320,7 @@ async function withAnalystLibraryIndexLock(ledgerHome, fn) {
30333
31320
  }
30334
31321
  }
30335
31322
  function analystLibraryIndexPath(ledgerHome) {
30336
- return join29(ledgerHome, "analyst", "library-index.json");
31323
+ return join33(ledgerHome, "analyst", "library-index.json");
30337
31324
  }
30338
31325
  function rowFromIssueMetricsPage(page) {
30339
31326
  return {
@@ -30424,7 +31411,7 @@ async function readAnalystLibraryIndexPage(ledgerHome) {
30424
31411
  const path = analystLibraryIndexPath(ledgerHome);
30425
31412
  let raw;
30426
31413
  try {
30427
- raw = await readFile19(path, "utf8");
31414
+ raw = await readFile21(path, "utf8");
30428
31415
  } catch (error) {
30429
31416
  if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
30430
31417
  return void 0;
@@ -30442,7 +31429,7 @@ async function readAnalystLibraryIndexPage(ledgerHome) {
30442
31429
  }
30443
31430
  async function writeAnalystLibraryIndexPage(ledgerHome, page) {
30444
31431
  const path = analystLibraryIndexPath(ledgerHome);
30445
- ensureRealDirectoryTree(ledgerHome, dirname15(path));
31432
+ ensureRealDirectoryTree(ledgerHome, dirname16(path));
30446
31433
  assertLedgerFileInsideHome(path, ledgerHome);
30447
31434
  await writeFileAtomically(path, `${JSON.stringify(page, null, 2)}
30448
31435
  `);
@@ -30628,9 +31615,9 @@ var init_analyst_cohort = __esm({
30628
31615
  });
30629
31616
 
30630
31617
  // src/analyst-ledger.ts
30631
- import { readdir as readdir7, readFile as readFile20 } from "node:fs/promises";
30632
- import { join as join30 } from "node:path";
30633
- function isMissingPathError5(error) {
31618
+ import { readdir as readdir9, readFile as readFile22 } from "node:fs/promises";
31619
+ import { basename as basename8, join as join34 } from "node:path";
31620
+ function isMissingPathError6(error) {
30634
31621
  return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
30635
31622
  }
30636
31623
  function errorText3(error) {
@@ -30642,7 +31629,7 @@ function isRecord10(value) {
30642
31629
  async function readExistingRunLifecycleState(runDirectory) {
30643
31630
  try {
30644
31631
  const raw = JSON.parse(
30645
- await readFile20(join30(runDirectory, "run-state.json"), "utf8")
31632
+ await readFile22(join34(runDirectory, "run-state.json"), "utf8")
30646
31633
  );
30647
31634
  if (!isRecord10(raw) || typeof raw.state !== "string") return void 0;
30648
31635
  return raw.state;
@@ -30664,19 +31651,19 @@ function tryResolveBookKeyFromProjectRoot(projectRoot) {
30664
31651
  }
30665
31652
  async function listLedgerBookNames(booksRoot) {
30666
31653
  try {
30667
- const entries = await readdir7(booksRoot, { withFileTypes: true });
31654
+ const entries = await readdir9(booksRoot, { withFileTypes: true });
30668
31655
  return entries.filter((e) => e.isDirectory()).map((e) => e.name).sort();
30669
31656
  } catch (error) {
30670
- if (isMissingPathError5(error)) return [];
31657
+ if (isMissingPathError6(error)) return [];
30671
31658
  throw error;
30672
31659
  }
30673
31660
  }
30674
31661
  async function readInvocationScopeFields(runDirectory) {
30675
31662
  let raw;
30676
31663
  try {
30677
- raw = await readFile20(join30(runDirectory, "invocation.json"), "utf8");
31664
+ raw = await readFile22(join34(runDirectory, "invocation.json"), "utf8");
30678
31665
  } catch (error) {
30679
- if (isMissingPathError5(error)) return void 0;
31666
+ if (isMissingPathError6(error)) return void 0;
30680
31667
  throw error;
30681
31668
  }
30682
31669
  const parsed = JSON.parse(raw);
@@ -30685,8 +31672,9 @@ async function readInvocationScopeFields(runDirectory) {
30685
31672
  return void 0;
30686
31673
  }
30687
31674
  const projectRoot = parsed.projectRoot;
30688
- if (typeof parsed.ticketNumber === "number" && Number.isInteger(parsed.ticketNumber) && parsed.ticketNumber >= 1) {
30689
- return { projectRoot, ticketNumber: parsed.ticketNumber };
31675
+ const ticketNumber = await readRunTicketNumber(runDirectory);
31676
+ if (ticketNumber !== void 0) {
31677
+ return { projectRoot, ticketNumber };
30690
31678
  }
30691
31679
  return { projectRoot };
30692
31680
  }
@@ -30706,15 +31694,15 @@ function decideIssueScope(input) {
30706
31694
  }
30707
31695
  async function resolveSessionFile(runDirectory) {
30708
31696
  try {
30709
- const raw = await readFile20(join30(runDirectory, "invocation.json"), "utf8");
31697
+ const raw = await readFile22(join34(runDirectory, "invocation.json"), "utf8");
30710
31698
  const parsed = JSON.parse(raw);
30711
31699
  if (isRecord10(parsed) && typeof parsed.sessionFile === "string" && parsed.sessionFile.trim() !== "") {
30712
31700
  return parsed.sessionFile;
30713
31701
  }
30714
31702
  } catch (error) {
30715
- if (!isMissingPathError5(error)) throw error;
31703
+ if (!isMissingPathError6(error)) throw error;
30716
31704
  }
30717
- return join30(runDirectory, "session", "session.jsonl");
31705
+ return join34(runDirectory, "session", "session.jsonl");
30718
31706
  }
30719
31707
  function attributeSessionRowsForRun(input) {
30720
31708
  if (pathContainedIn(input.runDirectory, input.sessionFile)) {
@@ -30886,9 +31874,9 @@ async function classifyScopedRun(input) {
30886
31874
  }
30887
31875
  let gateCycles;
30888
31876
  try {
30889
- const parentSessionFile = join30(input.runDirectory, "session", "session.jsonl");
31877
+ const parentSessionFile = join34(input.runDirectory, "session", "session.jsonl");
30890
31878
  gateCycles = await readAnalystGateCyclesFromAuditorRoles(
30891
- join30(input.runDirectory, "session", "auditor-roles"),
31879
+ join34(input.runDirectory, "session", "auditor-roles"),
30892
31880
  { parentSessionFile }
30893
31881
  );
30894
31882
  } catch (error) {
@@ -30921,7 +31909,7 @@ async function classifyScopedRun(input) {
30921
31909
  async function scanAnalystIssueRuns(input) {
30922
31910
  const ledgerHome = resolveActivationLedgerHome(input.home);
30923
31911
  const scopeTicketNumber = input.ticketNumber;
30924
- const booksRoot = join30(ledgerHome, "books");
31912
+ const booksRoot = join34(ledgerHome, "books");
30925
31913
  let wholeBook = false;
30926
31914
  let scopeRootIdentity;
30927
31915
  let bookNames;
@@ -30953,19 +31941,18 @@ async function scanAnalystIssueRuns(input) {
30953
31941
  const unreadable = [];
30954
31942
  const scopeConflicts = [];
30955
31943
  for (const book of bookNames) {
30956
- const runsDir = join30(booksRoot, book, "runs");
30957
- let runNames;
31944
+ const bookDir = join34(booksRoot, book);
31945
+ let runDirectories;
30958
31946
  try {
30959
- const entries = await readdir7(runsDir, { withFileTypes: true });
30960
- runNames = entries.filter((e) => e.isDirectory()).map((e) => e.name).sort();
31947
+ runDirectories = await listBookRunDirectories(bookDir);
30961
31948
  } catch (error) {
30962
- if (isMissingPathError5(error)) continue;
31949
+ if (isMissingPathError6(error)) continue;
30963
31950
  throw error;
30964
31951
  }
30965
- for (const runName of runNames) {
31952
+ for (const runDirectory of runDirectories) {
31953
+ const runName = basename8(runDirectory);
30966
31954
  const parsed = parseRunDirectoryName2(runName);
30967
31955
  if (parsed === void 0) continue;
30968
- const runDirectory = join30(runsDir, runName);
30969
31956
  let scopeFields;
30970
31957
  try {
30971
31958
  scopeFields = await readInvocationScopeFields(runDirectory);
@@ -31005,6 +31992,8 @@ var init_analyst_ledger = __esm({
31005
31992
  "use strict";
31006
31993
  init_activation_ledger_git();
31007
31994
  init_activation_ledger_topology();
31995
+ init_role_run_placement();
31996
+ init_run_ticket_number();
31008
31997
  init_ledger_session_read();
31009
31998
  init_run_terminal_artifacts();
31010
31999
  init_analyst_gate_cycles_read();
@@ -31819,7 +32808,7 @@ var init_analyst_metric_family = __esm({
31819
32808
 
31820
32809
  // src/analyst-page.ts
31821
32810
  import { createHash as createHash5 } from "node:crypto";
31822
- import { dirname as dirname16, join as join31 } from "node:path";
32811
+ import { dirname as dirname17, join as join35 } from "node:path";
31823
32812
  function analystIssuePageKey(address) {
31824
32813
  const parts = ["book", address.bookKey];
31825
32814
  if (address.issueNumber !== void 0) {
@@ -31830,7 +32819,7 @@ function analystIssuePageKey(address) {
31830
32819
  return createHash5("sha256").update(parts.join("\0")).digest("hex").slice(0, 32);
31831
32820
  }
31832
32821
  function analystIssuePagePath(ledgerHome, address) {
31833
- return join31(ledgerHome, "analyst", "issues", `${analystIssuePageKey(address)}.json`);
32822
+ return join35(ledgerHome, "analyst", "issues", `${analystIssuePageKey(address)}.json`);
31834
32823
  }
31835
32824
  function analystIssuePageAddressFromPage(page) {
31836
32825
  return {
@@ -31949,7 +32938,7 @@ async function buildAnalystIssueMetricsPage(input) {
31949
32938
  }
31950
32939
  async function writeAnalystIssueMetricsPage(ledgerHome, page) {
31951
32940
  const path = analystIssuePagePath(ledgerHome, analystIssuePageAddressFromPage(page));
31952
- ensureRealDirectoryTree(ledgerHome, dirname16(path));
32941
+ ensureRealDirectoryTree(ledgerHome, dirname17(path));
31953
32942
  assertLedgerFileInsideHome(path, ledgerHome);
31954
32943
  await writeFileAtomically(path, `${JSON.stringify(page, null, 2)}
31955
32944
  `);
@@ -31966,8 +32955,8 @@ var init_analyst_page = __esm({
31966
32955
  });
31967
32956
 
31968
32957
  // src/analyst-entry.ts
31969
- import { readFile as readFile21 } from "node:fs/promises";
31970
- function isMissingPathError6(error) {
32958
+ import { readFile as readFile23 } from "node:fs/promises";
32959
+ function isMissingPathError7(error) {
31971
32960
  return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
31972
32961
  }
31973
32962
  function cachedPageMatchesRequestedScope(page, input) {
@@ -31996,13 +32985,13 @@ async function readOrComputeAnalystIssuePage(input, options) {
31996
32985
  ...issueNumber === void 0 && input.bookKey === void 0 ? { scopeRootIdentity: projectRoot } : {}
31997
32986
  });
31998
32987
  try {
31999
- const raw = await readFile21(pagePath, "utf8");
32988
+ const raw = await readFile23(pagePath, "utf8");
32000
32989
  const page = JSON.parse(raw);
32001
32990
  if (cachedPageMatchesRequestedScope(page, { bookKey, ...input })) {
32002
32991
  return { mode: "issue", page, pagePath };
32003
32992
  }
32004
32993
  } catch (error) {
32005
- if (!isMissingPathError6(error)) {
32994
+ if (!isMissingPathError7(error)) {
32006
32995
  throw new AnalystIssueComputeError({
32007
32996
  bookKey,
32008
32997
  projectRoot,
@@ -32091,10 +33080,10 @@ async function runAnalystModelGroupsMode(input, home) {
32091
33080
  scopeRootIdentity: projectRoot
32092
33081
  });
32093
33082
  try {
32094
- const raw = await readFile21(pagePath, "utf8");
33083
+ const raw = await readFile23(pagePath, "utf8");
32095
33084
  JSON.parse(raw);
32096
33085
  } catch (error) {
32097
- if (!isMissingPathError6(error)) {
33086
+ if (!isMissingPathError7(error)) {
32098
33087
  throw new AnalystIssueComputeError({ bookKey, projectRoot, cause: error });
32099
33088
  }
32100
33089
  try {
@@ -32190,8 +33179,8 @@ var init_analyst_entry = __esm({
32190
33179
  });
32191
33180
 
32192
33181
  // src/public-cli/analyst-run.ts
32193
- import { readFile as readFile22 } from "node:fs/promises";
32194
- import { isAbsolute as isAbsolute10, resolve as resolve10 } from "node:path";
33182
+ import { readFile as readFile24 } from "node:fs/promises";
33183
+ import { isAbsolute as isAbsolute10, resolve as resolve9 } from "node:path";
32195
33184
  function resolveAnalystIssueBookKeyFromCwd(cwd = process.cwd()) {
32196
33185
  try {
32197
33186
  return resolveBookKeyFromGit(cwd);
@@ -32240,10 +33229,10 @@ async function buildAnalystSweepModeInputFromAttachmentPaths(attachmentPaths) {
32240
33229
  );
32241
33230
  }
32242
33231
  const sourcePath = attachmentPaths[0];
32243
- const absolute = isAbsolute10(sourcePath) ? sourcePath : resolve10(sourcePath);
33232
+ const absolute = isAbsolute10(sourcePath) ? sourcePath : resolve9(sourcePath);
32244
33233
  let bytes;
32245
33234
  try {
32246
- bytes = await readFile22(absolute);
33235
+ bytes = await readFile24(absolute);
32247
33236
  } catch (error) {
32248
33237
  throw new CliUsageError(
32249
33238
  `analyst sweep attachment is not a readable regular file: ${sourcePath}`,
@@ -32363,7 +33352,7 @@ __export(cli_exports, {
32363
33352
  runAkRole: () => runAkRole
32364
33353
  });
32365
33354
  import { realpath as realpath6 } from "node:fs/promises";
32366
- import { join as join32 } from "node:path";
33355
+ import { join as join36 } from "node:path";
32367
33356
  function takePublicGlobalFlag(argv, index, options) {
32368
33357
  const tokens = argv.slice(index);
32369
33358
  const taken = options.takeDashed(tokens);
@@ -32460,7 +33449,7 @@ function resolveHome(env) {
32460
33449
  return env.home ?? packageMachineHome();
32461
33450
  }
32462
33451
  function resolveAgentDir(env, home) {
32463
- return env.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? join32(home, ".pi", "agent");
33452
+ return env.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? join36(home, ".pi", "agent");
32464
33453
  }
32465
33454
  function parseThinking(value) {
32466
33455
  return value;
@@ -33474,8 +34463,8 @@ var init_cli = __esm({
33474
34463
  });
33475
34464
 
33476
34465
  // src/public-cli/main.ts
33477
- import { existsSync as existsSync10 } from "node:fs";
33478
- import { dirname as dirname17, join as join33 } from "node:path";
34466
+ import { existsSync as existsSync11 } from "node:fs";
34467
+ import { dirname as dirname18, join as join37 } from "node:path";
33479
34468
  import { fileURLToPath as fileURLToPath2 } from "node:url";
33480
34469
 
33481
34470
  // src/public-cli/host-pi-runtime.ts
@@ -33562,10 +34551,10 @@ function linkPackage(packageRoot2, name, targetDir) {
33562
34551
  }
33563
34552
 
33564
34553
  // src/public-cli/main.ts
33565
- var here = dirname17(fileURLToPath2(import.meta.url));
34554
+ var here = dirname18(fileURLToPath2(import.meta.url));
33566
34555
  function resolvePackageRoot(binDir) {
33567
- const canonical = join33(binDir, "..", "..");
33568
- if (existsSync10(join33(canonical, "package.json"))) {
34556
+ const canonical = join37(binDir, "..", "..");
34557
+ if (existsSync11(join37(canonical, "package.json"))) {
33569
34558
  return canonical;
33570
34559
  }
33571
34560
  return binDir;