@akagilnc/pi-workflow-roles 0.1.4295 → 0.1.4363

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 (48) hide show
  1. package/dist/acp-host/production-host.js +623 -550
  2. package/dist/doctor-contracts.js +2 -2
  3. package/dist/headless-host/production-host.js +635 -562
  4. package/dist/merger-contracts.js +2 -2
  5. package/dist/migrate-book-topology.js +13 -8
  6. package/dist/notary-contracts.js +2 -2
  7. package/dist/package-contracts/auditor-output.js +2 -2
  8. package/dist/package-contracts/fixer-output.js +2 -2
  9. package/dist/package-contracts/gatekeeper-output.js +2 -2
  10. package/dist/package-contracts/navigator-output.js +2 -2
  11. package/dist/package-contracts/terminating-infrastructure.js +7 -2
  12. package/dist/public-cli/case-dossier-delivery.js +45 -28
  13. package/dist/public-cli/main.js +300 -331
  14. package/dist/public-cli/post-admission.js +41 -41
  15. package/dist/public-cli/settlement.js +3 -53
  16. package/dist/session-dialogue.js +61 -63
  17. package/dist/sitian-appender.js +21 -4
  18. package/dist/sitian-facade.js +0 -1
  19. package/dist/ticket-provenance-contracts.js +5 -4
  20. package/dist/ticket-provenance.js +295 -79
  21. package/package.json +1 -1
  22. package/src/collector-tool-schemas.ts +2 -2
  23. package/src/countersign-role.ts +2 -2
  24. package/src/diarist-role.ts +2 -2
  25. package/src/doctor-contracts.ts +2 -2
  26. package/src/gleaner-left-role.ts +2 -2
  27. package/src/inspector-role.ts +2 -2
  28. package/src/judge-role.ts +2 -2
  29. package/src/merger-contracts.ts +2 -2
  30. package/src/notary-contracts.ts +2 -2
  31. package/src/package-contracts/auditor-output.ts +2 -2
  32. package/src/package-contracts/fixer-output.ts +2 -2
  33. package/src/package-contracts/gatekeeper-output.ts +2 -2
  34. package/src/package-contracts/navigator-output.ts +2 -2
  35. package/src/package-contracts/terminating-infrastructure.ts +13 -3
  36. package/src/public-cli/case-dossier-delivery.ts +48 -29
  37. package/src/public-cli/post-admission.ts +42 -50
  38. package/src/public-cli/settlement.ts +3 -53
  39. package/src/reviewer-role.ts +2 -2
  40. package/src/session-dialogue.ts +68 -65
  41. package/src/sitian-appender.ts +36 -3
  42. package/src/sitian-facade.ts +1 -3
  43. package/src/ticket-provenance-contracts.ts +11 -7
  44. package/src/ticket-provenance.ts +332 -93
  45. package/src/worker-role.ts +2 -2
  46. package/dist/atomic-write.js +0 -23
  47. package/dist/sitian-volume.js +0 -67
  48. package/src/sitian-volume.ts +0 -91
@@ -1246,10 +1246,15 @@ var init_open_tool_schema = __esm({
1246
1246
 
1247
1247
  // src/package-contracts/terminating-infrastructure.ts
1248
1248
  import { Type as Type3 } from "typebox";
1249
- function withInfrastructureFailureDeclaration(schema) {
1249
+ function withTerminatingOutputDeclarations(schema) {
1250
1250
  const baseProperties = schema.properties;
1251
1251
  const properties = {
1252
1252
  ...baseProperties ?? {},
1253
+ ...baseProperties?.ticketNumber === void 0 ? {
1254
+ ticketNumber: Type3.Unknown({
1255
+ description: "\u53EF\u9009\u672C\u7968\u53F7\uFF1A\u5C1A\u672A\u7ED1\u5B9A\u65F6\u7531\u89D2\u8272\u5728\u65E2\u6709\u56DE\u6267\u4E2D\u7533\u62A5\uFF1B\u673A\u68B0\u5C42\u53EA\u8BB0\u5F55\u5408\u6CD5\u6B63\u6574\u6570\uFF0C\u4E0D\u4ECE\u6563\u6587\u63A8\u5BFC\u3001\u4E0D\u9A8C\u771F\u3002\u7F3A\u5931\u6216\u9519\u5F62\u4E0D\u62D2\u6536\u3002"
1256
+ })
1257
+ } : {},
1253
1258
  [INFRASTRUCTURE_FAILURE_DECLARATION_KEY]: infrastructureFailureDeclarationSchema.properties[INFRASTRUCTURE_FAILURE_DECLARATION_KEY]
1254
1259
  };
1255
1260
  const object = Type3.Object(properties, { additionalProperties: true });
@@ -1343,7 +1348,7 @@ var init_gatekeeper_output = __esm({
1343
1348
  })
1344
1349
  })
1345
1350
  );
1346
- gatekeeperOutputSchema = withInfrastructureFailureDeclaration(
1351
+ gatekeeperOutputSchema = withTerminatingOutputDeclarations(
1347
1352
  gatekeeperDecisionSchema
1348
1353
  );
1349
1354
  }
@@ -1552,7 +1557,7 @@ var init_navigator_output = __esm({
1552
1557
  init_terminating_infrastructure();
1553
1558
  NAVIGATOR_OUTPUT_TOOL_NAME = "ak_navigator_output";
1554
1559
  NAVIGATOR_ACCEPTED_TEXT = "\u6E38\u5955\u4F7F\u5EFA\u8BAE\u5DF2\u53D7\u7406";
1555
- navigatorOutputSchema = withInfrastructureFailureDeclaration(
1560
+ navigatorOutputSchema = withTerminatingOutputDeclarations(
1556
1561
  openToolObject(
1557
1562
  Type5.Object({
1558
1563
  status: Type5.Unknown({
@@ -1650,7 +1655,7 @@ var init_fixer_output = __esm({
1650
1655
  Type6.Object({ status: Type6.Unknown({ description: FIXER_STATUS_DESCRIPTION }), report: Type6.String({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" }), classResults: Type6.Array(classResultSchema, { description: "\u5404\u7C7B\u62D2\u7EDD\u7ED3\u7B97" }) }),
1651
1656
  Type6.Object({ status: Type6.Unknown({ description: FIXER_STATUS_DESCRIPTION }), report: Type6.String({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" }), classResults: Type6.Array(classResultSchema, { description: "\u5404\u7C7B\u5B8C\u6210\u6216\u62D2\u7EDD\u7ED3\u7B97" }), testEvidence: Type6.Optional(testEvidenceSchema) })
1652
1657
  ]);
1653
- fixerOutputSchema = withInfrastructureFailureDeclaration(
1658
+ fixerOutputSchema = withTerminatingOutputDeclarations(
1654
1659
  openToolObjectFromUnion(fixerOutputVariants)
1655
1660
  );
1656
1661
  }
@@ -1816,7 +1821,7 @@ var init_doctor_contracts = __esm({
1816
1821
  missingEvidence: Type8.Array(Type8.Object({ need: nonblank, targetKeys: evidenceIds }, { additionalProperties: true }), { description: "\u5982\u5B9E\u8BC1\u8BCD\u6240\u9700\u800C\u5C1A\u7F3A\u7684\u8BC1\u636E" })
1817
1822
  }, { additionalProperties: false, description: "\u8BC1\u636E\u4E0D\u8DB3\u4EE5\u652F\u6491\u5982\u5B9E\u6848\u8BC1\u8BCD" })
1818
1823
  ]);
1819
- doctorSubmissionSchema = withInfrastructureFailureDeclaration(
1824
+ doctorSubmissionSchema = withTerminatingOutputDeclarations(
1820
1825
  openToolObjectFromUnion(doctorSubmissionVariants)
1821
1826
  );
1822
1827
  doctorEvidenceReadSchema = Type8.Object({ evidenceId: Type8.String({ minLength: 1, description: "\u5F85\u8BFB\u7559\u5B58\u8BC1\u636E\u6807\u8BC6" }), offset: Type8.Optional(Type8.Integer({ minimum: 0, description: "\u8D77\u59CB\u5B57\u8282\u504F\u79FB\uFF08\u4ECE 0 \u8BA1\uFF09" })), limit: Type8.Optional(Type8.Integer({ minimum: 1, description: "\u8FD4\u56DE\u5B57\u8282\u6570\uFF08\u65E0\u4E0A\u9650\uFF09" })) }, { additionalProperties: true });
@@ -1934,7 +1939,7 @@ var init_merger_contracts = __esm({
1934
1939
  Type9.Object({ status: Type9.Unknown({ description: MERGER_STATUS_DESCRIPTION }), attemptId: Type9.String({ description: "\u5DF2\u53D7\u7406\u5408\u5E76 attempt \u8EAB\u4EFD" }), report: Type9.String({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" }), mergeCommitId: Type9.String({ description: "\u5B8C\u6210\u5408\u5E76 commit object ID" }) }, { additionalProperties: false }),
1935
1940
  Type9.Object({ status: Type9.Unknown({ description: MERGER_STATUS_DESCRIPTION }), attemptId: Type9.String({ description: "\u5DF2\u53D7\u7406\u5408\u5E76 attempt \u8EAB\u4EFD" }), diagnosis: Type9.String({ description: "\u5408\u5E76\u65E0\u6CD5\u6216\u4E0D\u5E94\u7531\u672C\u5E2D\u5B8C\u6210\u7684\u539F\u56E0\uFF08\u542B\u65E0\u8FDB\u884C\u4E2D\u5408\u5E76\u3001\u65E0\u6D3B\u53EF\u5E72\u3001\u9700\u65B0\u7684\u4EA7\u54C1/\u6743\u529B\u51B3\u5B9A\uFF09" }), report: Type9.String({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" }) }, { additionalProperties: false })
1936
1941
  ]);
1937
- mergerOutputSchema = withInfrastructureFailureDeclaration(openToolObjectFromUnion(mergerOutputVariants));
1942
+ mergerOutputSchema = withTerminatingOutputDeclarations(openToolObjectFromUnion(mergerOutputVariants));
1938
1943
  MERGER_OUTPUT_TOOL_NAME = "ak_merger_output";
1939
1944
  MERGER_ACCEPTED_TEXT = "\u5408\u5E76\u56DE\u6267\u5DF2\u63A5\u53D7";
1940
1945
  record = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
@@ -1975,7 +1980,7 @@ var init_notary_contracts = __esm({
1975
1980
  }
1976
1981
  };
1977
1982
  NOTARY_FIXED_KICKOFF = "\u7B26\u5B9D\u90CE\u6848\u5377\u5DF2\u53D7\u7406\uFF1B\u6765\u6E90 run \u5B9A\u4F4D\u89C1\u4F1A\u8BDD\u6750\u6599\u3002";
1978
- notaryOutputSchema = withInfrastructureFailureDeclaration(
1983
+ notaryOutputSchema = withTerminatingOutputDeclarations(
1979
1984
  openToolObject(
1980
1985
  Type10.Object({
1981
1986
  status: Type10.Unknown({
@@ -2030,7 +2035,7 @@ var init_auditor_output = __esm({
2030
2035
  init_terminating_infrastructure();
2031
2036
  AUDITOR_OUTPUT_TOOL_NAME = "ak_auditor_output";
2032
2037
  AUDITOR_ACCEPTED_TEXT = "\u5BA1\u5211\u9662\u56DE\u6267\u5DF2\u63A5\u53D7";
2033
- auditorOutputSchema = withInfrastructureFailureDeclaration(
2038
+ auditorOutputSchema = withTerminatingOutputDeclarations(
2034
2039
  openToolObject(
2035
2040
  Type11.Object({
2036
2041
  status: Type11.Unknown({
@@ -2704,25 +2709,40 @@ function resolveSitianVolumeCategory(kind) {
2704
2709
  }
2705
2710
  return kind;
2706
2711
  }
2712
+ function ticketProvenanceUnderBookPaths(ledgerHome, bookKey, ticketId) {
2713
+ const sessionDir = join10(activationBookDirectory(ledgerHome, bookKey), ticketId);
2714
+ return { sessionDir, recordFile: join10(sessionDir, SITIAN_RECORDS_LEAF) };
2715
+ }
2707
2716
  function resolveSitianRecordPathInLedger(input, ledgerHome) {
2708
2717
  const category = resolveSitianVolumeCategory(input.kind);
2709
2718
  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;
2710
2719
  let sessionDir;
2720
+ let recordFile;
2711
2721
  if (ticketNumber !== void 0) {
2712
- const bookDir = activationBookDirectory(
2722
+ const paths = ticketProvenanceUnderBookPaths(
2713
2723
  ledgerHome,
2714
- resolveBookKeyFromGit(input.cwd ?? process.cwd())
2724
+ resolveBookKeyFromGit(input.cwd ?? process.cwd()),
2725
+ ticketNumber
2715
2726
  );
2716
- sessionDir = join10(bookDir, ticketNumber);
2727
+ sessionDir = paths.sessionDir;
2728
+ recordFile = paths.recordFile;
2717
2729
  } else {
2718
2730
  if (input.sessionParent === void 0 || input.sessionParent.length === 0 || !physicallyContainedIn(ledgerHome, input.sessionParent)) {
2719
2731
  throw new Error("Sitian record ownership requires a parent session inside the ledger home");
2720
2732
  }
2721
2733
  sessionDir = join10(dirname5(input.sessionParent), category);
2734
+ recordFile = join10(sessionDir, SITIAN_RECORDS_LEAF);
2722
2735
  }
2723
- const recordFile = join10(sessionDir, "records.jsonl");
2724
2736
  return { sessionDir, recordFile, ledgerHome };
2725
2737
  }
2738
+ function projectTicketRecordsPathShape() {
2739
+ const { recordFile } = ticketProvenanceUnderBookPaths(
2740
+ join10("~", ".ak-roles"),
2741
+ "<\u7C3F>",
2742
+ "<\u7968\u53F7>"
2743
+ );
2744
+ return recordFile.replace(/\\/g, "/");
2745
+ }
2726
2746
  function resolveSitianRecordPath(input) {
2727
2747
  const ledgerHome = input.home !== void 0 && input.home.length > 0 ? resolveActivationLedgerHome(input.home) : resolveActivationLedgerHomeForPath(input.sessionParent);
2728
2748
  return resolveSitianRecordPathInLedger(input, ledgerHome);
@@ -2759,7 +2779,7 @@ function appendSitianRecord(input) {
2759
2779
  );
2760
2780
  }
2761
2781
  }
2762
- var S4_SUBMISSION_LEDGER_KINDS;
2782
+ var S4_SUBMISSION_LEDGER_KINDS, SITIAN_RECORDS_LEAF;
2763
2783
  var init_sitian_appender = __esm({
2764
2784
  "src/sitian-appender.ts"() {
2765
2785
  "use strict";
@@ -2773,6 +2793,7 @@ var init_sitian_appender = __esm({
2773
2793
  "sealed",
2774
2794
  "post-seal-anomaly"
2775
2795
  ]);
2796
+ SITIAN_RECORDS_LEAF = "records.jsonl";
2776
2797
  }
2777
2798
  });
2778
2799
 
@@ -2823,85 +2844,6 @@ var init_sitian_reader = __esm({
2823
2844
  }
2824
2845
  });
2825
2846
 
2826
- // src/atomic-write.ts
2827
- import { randomUUID as randomUUID2 } from "node:crypto";
2828
- import { rename, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
2829
- import { dirname as dirname6, join as join11 } from "node:path";
2830
- async function writeFileAtomically(destination, contents) {
2831
- const parent = dirname6(destination);
2832
- const temporary = join11(parent, `.atomic-write-${randomUUID2()}.tmp`);
2833
- try {
2834
- await writeFile2(temporary, contents);
2835
- await rename(temporary, destination);
2836
- } catch (error) {
2837
- await rm2(temporary, { force: true }).catch(() => void 0);
2838
- throw error;
2839
- }
2840
- }
2841
- var init_atomic_write = __esm({
2842
- "src/atomic-write.ts"() {
2843
- "use strict";
2844
- }
2845
- });
2846
-
2847
- // src/sitian-volume.ts
2848
- import { appendFileSync as appendFileSync2 } from "node:fs";
2849
- import { readFile as readFile3 } from "node:fs/promises";
2850
- function resolveSitianVolume(input) {
2851
- const path = resolveSitianRecordPath(input);
2852
- return { recordFile: path.recordFile, volumeDir: path.sessionDir };
2853
- }
2854
- function ensureSitianVolume(input) {
2855
- try {
2856
- const { sessionDir, recordFile, ledgerHome } = resolveSitianRecordPath(input);
2857
- ensureRealDirectoryTree(ledgerHome, sessionDir);
2858
- appendFileSync2(recordFile, "", "utf8");
2859
- return { recordFile, volumeDir: sessionDir };
2860
- } catch (error) {
2861
- if (error instanceof SitianInfrastructureError) throw error;
2862
- throw new SitianInfrastructureError(
2863
- `Sitian volume ensure failure: ${errorText(error)}`,
2864
- { cause: error }
2865
- );
2866
- }
2867
- }
2868
- async function readSitianVolumeText(input) {
2869
- const { recordFile } = resolveSitianVolume(input);
2870
- try {
2871
- return { recordFile, text: await readFile3(recordFile, "utf8") };
2872
- } catch (error) {
2873
- if (error.code === "ENOENT") {
2874
- return { recordFile, text: void 0 };
2875
- }
2876
- throw new SitianInfrastructureError(
2877
- `Sitian volume read failure: ${errorText(error)}`,
2878
- { cause: error }
2879
- );
2880
- }
2881
- }
2882
- async function rewriteSitianVolume(input) {
2883
- try {
2884
- const volume = ensureSitianVolume(input);
2885
- await writeFileAtomically(volume.recordFile, input.body);
2886
- return volume;
2887
- } catch (error) {
2888
- if (error instanceof SitianInfrastructureError) throw error;
2889
- throw new SitianInfrastructureError(
2890
- `Sitian volume rewrite failure: ${errorText(error)}`,
2891
- { cause: error }
2892
- );
2893
- }
2894
- }
2895
- var init_sitian_volume = __esm({
2896
- "src/sitian-volume.ts"() {
2897
- "use strict";
2898
- init_activation_ledger_topology();
2899
- init_atomic_write();
2900
- init_sitian_appender();
2901
- init_sitian_contracts();
2902
- }
2903
- });
2904
-
2905
2847
  // src/sitian-facade.ts
2906
2848
  function sitianReport(input) {
2907
2849
  return appendSitianRecord(input);
@@ -2913,7 +2855,6 @@ var init_sitian_facade = __esm({
2913
2855
  init_sitian_contracts();
2914
2856
  init_sitian_appender();
2915
2857
  init_sitian_reader();
2916
- init_sitian_volume();
2917
2858
  }
2918
2859
  });
2919
2860
 
@@ -2931,13 +2872,13 @@ __export(role_turn_host_exports, {
2931
2872
  });
2932
2873
  import { execFile, spawn as spawn2 } from "node:child_process";
2933
2874
  import { constants } from "node:fs";
2934
- import { access, appendFile, readFile as readFile4, realpath } from "node:fs/promises";
2935
- import { basename as basename3, delimiter, dirname as dirname7, isAbsolute as isAbsolute3, join as join12, resolve as resolve5 } from "node:path";
2875
+ import { access, appendFile, readFile as readFile3, realpath } from "node:fs/promises";
2876
+ import { basename as basename3, delimiter, dirname as dirname6, isAbsolute as isAbsolute3, join as join11, resolve as resolve5 } from "node:path";
2936
2877
  import { platform } from "node:process";
2937
2878
  import { promisify } from "node:util";
2938
- import { randomUUID as randomUUID3 } from "node:crypto";
2879
+ import { randomUUID as randomUUID2 } from "node:crypto";
2939
2880
  function resolveInternalRoleEntrypoint(packageRoot) {
2940
- return join12(packageRoot, INTERNAL_ROLE_ENTRYPOINT_RELATIVE);
2881
+ return join11(packageRoot, INTERNAL_ROLE_ENTRYPOINT_RELATIVE);
2941
2882
  }
2942
2883
  function buildExplicitInternalActivationArgs(selectedRoleEntry, extraArgs = []) {
2943
2884
  return ["--no-extensions", "-e", selectedRoleEntry, ...extraArgs];
@@ -2973,7 +2914,7 @@ function buildMethodArgs(methods) {
2973
2914
  function applyPiNativeSkillInvocation(methods, prompt) {
2974
2915
  const skills = methods.filter((method) => method.kind === "skill");
2975
2916
  if (skills.length !== 1) return prompt;
2976
- const name = basename3(dirname7(skills[0].path));
2917
+ const name = basename3(dirname6(skills[0].path));
2977
2918
  if (name.length === 0) return prompt;
2978
2919
  const token = `/skill:${name}`;
2979
2920
  const trimmed = prompt.trimStart();
@@ -3214,7 +3155,7 @@ ${paths.join("\n")}`
3214
3155
  }
3215
3156
  async function appendPiSessionCustomEntry(authority, principal, customType, data) {
3216
3157
  const { sessionFile } = authority.decode(principal);
3217
- const text = await readFile4(sessionFile, "utf8");
3158
+ const text = await readFile3(sessionFile, "utf8");
3218
3159
  let parentId = null;
3219
3160
  for (const line2 of text.trim().split("\n").filter(Boolean)) {
3220
3161
  const entry = JSON.parse(line2);
@@ -3225,7 +3166,7 @@ async function appendPiSessionCustomEntry(authority, principal, customType, data
3225
3166
  type: "custom",
3226
3167
  customType,
3227
3168
  data,
3228
- id: randomUUID3(),
3169
+ id: randomUUID2(),
3229
3170
  parentId,
3230
3171
  timestamp: timestamp2
3231
3172
  })}
@@ -3386,7 +3327,7 @@ __export(session_assistant_usage_exports, {
3386
3327
  sessionFileFromPublicSummon: () => sessionFileFromPublicSummon,
3387
3328
  usageFromPublicSummon: () => usageFromPublicSummon
3388
3329
  });
3389
- import { join as join13 } from "node:path";
3330
+ import { join as join12 } from "node:path";
3390
3331
  async function readAssistantUsageFromSessionFile(sessionFile) {
3391
3332
  const { readFile: readFile25 } = await import("node:fs/promises");
3392
3333
  let text;
@@ -3456,7 +3397,7 @@ async function readAssistantUsageFromSessionFile(sessionFile) {
3456
3397
  }
3457
3398
  function sessionFileFromPublicSummon(summoned) {
3458
3399
  if (typeof summoned.runDirectory === "string" && summoned.runDirectory.trim() !== "") {
3459
- return join13(summoned.runDirectory, "session", "session.jsonl");
3400
+ return join12(summoned.runDirectory, "session", "session.jsonl");
3460
3401
  }
3461
3402
  const fromArtifacts = summoned.terminal?.artifacts?.map((a) => a.path).find((p) => typeof p === "string" && p.endsWith("session.jsonl"));
3462
3403
  if (fromArtifacts !== void 0) return fromArtifacts;
@@ -3465,7 +3406,7 @@ function sessionFileFromPublicSummon(summoned) {
3465
3406
  const facts = outcome.decisiveFacts;
3466
3407
  const pointer = facts?.runPointer;
3467
3408
  if (typeof pointer === "string" && pointer.trim() !== "") {
3468
- return join13(pointer, "session", "session.jsonl");
3409
+ return join12(pointer, "session", "session.jsonl");
3469
3410
  }
3470
3411
  return void 0;
3471
3412
  }
@@ -3572,8 +3513,8 @@ async function runComplianceAudit(options) {
3572
3513
  const subject = options.subject;
3573
3514
  const summon = options.summonAuditor ?? (async (auditSubject, sourceRunDirectory, auditSignal, reask2) => {
3574
3515
  const { summonPublicRole: summonPublicRole2 } = await Promise.resolve().then(() => (init_public_role_summons(), public_role_summons_exports));
3575
- const { homeFromRunDirectory: homeFromRunDirectory3 } = await Promise.resolve().then(() => (init_activation_ledger_topology(), activation_ledger_topology_exports));
3576
- const home = homeFromRunDirectory3(sourceRunDirectory);
3516
+ const { homeFromRunDirectory: homeFromRunDirectory2 } = await Promise.resolve().then(() => (init_activation_ledger_topology(), activation_ledger_topology_exports));
3517
+ const home = homeFromRunDirectory2(sourceRunDirectory);
3577
3518
  return await summonPublicRole2({
3578
3519
  role: "auditor",
3579
3520
  argv: [
@@ -3620,8 +3561,8 @@ var init_compliance_transport = __esm({
3620
3561
 
3621
3562
  // src/role-run-relocation.ts
3622
3563
  import { existsSync as existsSync5 } from "node:fs";
3623
- import { readdir as readdir2, readFile as readFile5, writeFile as writeFile3 } from "node:fs/promises";
3624
- import { join as join14, sep as sep2 } from "node:path";
3564
+ import { readdir as readdir2, readFile as readFile4, writeFile as writeFile2 } from "node:fs/promises";
3565
+ import { join as join13, sep as sep2 } from "node:path";
3625
3566
  function isEnoent2(error) {
3626
3567
  return error instanceof Error && "code" in error && error.code === "ENOENT";
3627
3568
  }
@@ -3710,15 +3651,15 @@ function rewriteSummonsMaterials(value, rewrites) {
3710
3651
  }
3711
3652
  async function rewriteJsonObjectFile(path, fields, rewrites) {
3712
3653
  if (!existsSync5(path)) return;
3713
- const page = JSON.parse(await readFile5(path, "utf8"));
3654
+ const page = JSON.parse(await readFile4(path, "utf8"));
3714
3655
  if (!isPlainObject(page)) return;
3715
3656
  rewriteRunDirectoryPathFieldsAgainstRewrites(page, fields, rewrites);
3716
- await writeFile3(path, `${JSON.stringify(page, null, 2)}
3657
+ await writeFile2(path, `${JSON.stringify(page, null, 2)}
3717
3658
  `, "utf8");
3718
3659
  }
3719
3660
  async function rewriteOfficerPointerFile(path, rewrites) {
3720
3661
  if (!existsSync5(path)) return;
3721
- const page = JSON.parse(await readFile5(path, "utf8"));
3662
+ const page = JSON.parse(await readFile4(path, "utf8"));
3722
3663
  if (!isPlainObject(page)) return;
3723
3664
  if (page.kind !== "direct-officer-run-pointer") return;
3724
3665
  rewriteRunDirectoryPathFieldsAgainstRewrites(
@@ -3726,12 +3667,12 @@ async function rewriteOfficerPointerFile(path, rewrites) {
3726
3667
  OFFICER_POINTER_FIELDS,
3727
3668
  rewrites
3728
3669
  );
3729
- await writeFile3(path, `${JSON.stringify(page)}
3670
+ await writeFile2(path, `${JSON.stringify(page)}
3730
3671
  `, "utf8");
3731
3672
  }
3732
3673
  async function rewriteSitianRecordsJsonl(path, rewrites) {
3733
3674
  if (!existsSync5(path)) return;
3734
- const raw = await readFile5(path, "utf8");
3675
+ const raw = await readFile4(path, "utf8");
3735
3676
  if (raw.length === 0) return;
3736
3677
  const endsWithNewline = raw.endsWith("\n");
3737
3678
  const lines = raw.split("\n");
@@ -3773,7 +3714,7 @@ async function rewriteSitianRecordsJsonl(path, rewrites) {
3773
3714
  }
3774
3715
  if (!changed) return;
3775
3716
  const body = out.join("\n");
3776
- await writeFile3(
3717
+ await writeFile2(
3777
3718
  path,
3778
3719
  endsWithNewline && !body.endsWith("\n") ? `${body}
3779
3720
  ` : body,
@@ -3782,7 +3723,7 @@ async function rewriteSitianRecordsJsonl(path, rewrites) {
3782
3723
  }
3783
3724
  async function rewriteSessionTranscriptBindings(path, rewrites) {
3784
3725
  if (!existsSync5(path)) return;
3785
- const raw = await readFile5(path, "utf8");
3726
+ const raw = await readFile4(path, "utf8");
3786
3727
  if (raw.length === 0) return;
3787
3728
  const endsWithNewline = raw.endsWith("\n");
3788
3729
  const lines = raw.split("\n");
@@ -3833,7 +3774,7 @@ async function rewriteSessionTranscriptBindings(path, rewrites) {
3833
3774
  }
3834
3775
  if (!changed) return;
3835
3776
  const body = out.join("\n");
3836
- await writeFile3(
3777
+ await writeFile2(
3837
3778
  path,
3838
3779
  endsWithNewline && !body.endsWith("\n") ? `${body}
3839
3780
  ` : body,
@@ -3841,7 +3782,7 @@ async function rewriteSessionTranscriptBindings(path, rewrites) {
3841
3782
  );
3842
3783
  }
3843
3784
  async function rewriteNestedMachinePathPages(pagesDirectory, rewrites) {
3844
- const sessionRoot = join14(pagesDirectory, "session");
3785
+ const sessionRoot = join13(pagesDirectory, "session");
3845
3786
  async function walk(directory) {
3846
3787
  let entries;
3847
3788
  try {
@@ -3851,7 +3792,7 @@ async function rewriteNestedMachinePathPages(pagesDirectory, rewrites) {
3851
3792
  throw error;
3852
3793
  }
3853
3794
  for (const entry of entries) {
3854
- const path = join14(directory, entry.name);
3795
+ const path = join13(directory, entry.name);
3855
3796
  if (entry.isDirectory()) {
3856
3797
  await walk(path);
3857
3798
  continue;
@@ -3873,9 +3814,9 @@ async function rewriteNestedMachinePathPages(pagesDirectory, rewrites) {
3873
3814
  async function rewriteRoleRunDurablePages(input) {
3874
3815
  const { pagesDirectory } = input;
3875
3816
  const rewrites = collectRewrites(input);
3876
- const admittedPath = join14(pagesDirectory, "admitted-request.json");
3817
+ const admittedPath = join13(pagesDirectory, "admitted-request.json");
3877
3818
  if (existsSync5(admittedPath)) {
3878
- const page = JSON.parse(await readFile5(admittedPath, "utf8"));
3819
+ const page = JSON.parse(await readFile4(admittedPath, "utf8"));
3879
3820
  rewriteRunDirectoryPathFieldsAgainstRewrites(
3880
3821
  page,
3881
3822
  ADMITTED_PAGE_FIELDS,
@@ -3900,27 +3841,27 @@ async function rewriteRoleRunDurablePages(input) {
3900
3841
  rewrites
3901
3842
  );
3902
3843
  }
3903
- await writeFile3(admittedPath, `${JSON.stringify(page, null, 2)}
3844
+ await writeFile2(admittedPath, `${JSON.stringify(page, null, 2)}
3904
3845
  `, "utf8");
3905
3846
  }
3906
- const invocationPath = join14(pagesDirectory, "invocation.json");
3847
+ const invocationPath = join13(pagesDirectory, "invocation.json");
3907
3848
  if (existsSync5(invocationPath)) {
3908
- const page = JSON.parse(await readFile5(invocationPath, "utf8"));
3849
+ const page = JSON.parse(await readFile4(invocationPath, "utf8"));
3909
3850
  rewriteRunDirectoryPathFieldsAgainstRewrites(
3910
3851
  page,
3911
3852
  INVOCATION_PAGE_FIELDS,
3912
3853
  rewrites
3913
3854
  );
3914
- await writeFile3(
3855
+ await writeFile2(
3915
3856
  invocationPath,
3916
3857
  `${JSON.stringify(page, null, 2)}
3917
3858
  `,
3918
3859
  "utf8"
3919
3860
  );
3920
3861
  }
3921
- const statePath = join14(pagesDirectory, "run-state.json");
3862
+ const statePath = join13(pagesDirectory, "run-state.json");
3922
3863
  if (existsSync5(statePath)) {
3923
- const page = JSON.parse(await readFile5(statePath, "utf8"));
3864
+ const page = JSON.parse(await readFile4(statePath, "utf8"));
3924
3865
  rewriteRunDirectoryPathFieldsAgainstRewrites(
3925
3866
  page,
3926
3867
  RUN_STATE_PAGE_FIELDS,
@@ -3936,7 +3877,7 @@ async function rewriteRoleRunDurablePages(input) {
3936
3877
  if (isPlainObject(page.currentCourt)) {
3937
3878
  rewriteSummonsMaterials(page.currentCourt.summons, rewrites);
3938
3879
  }
3939
- await writeFile3(statePath, `${JSON.stringify(page, null, 2)}
3880
+ await writeFile2(statePath, `${JSON.stringify(page, null, 2)}
3940
3881
  `, "utf8");
3941
3882
  }
3942
3883
  await rewriteNestedMachinePathPages(pagesDirectory, rewrites);
@@ -4104,8 +4045,8 @@ var init_terminating_tools = __esm({
4104
4045
  });
4105
4046
 
4106
4047
  // src/doctor-evidence.ts
4107
- import { readdir as readdir3, readFile as readFile6, realpath as realpath2, stat } from "node:fs/promises";
4108
- import { dirname as dirname8, relative as relative2, resolve as resolve6, sep as sep3 } from "node:path";
4048
+ import { readdir as readdir3, readFile as readFile5, realpath as realpath2, stat } from "node:fs/promises";
4049
+ import { dirname as dirname7, relative as relative2, resolve as resolve6, sep as sep3 } from "node:path";
4109
4050
  function record2(value) {
4110
4051
  return typeof value === "object" && value !== null && !Array.isArray(value);
4111
4052
  }
@@ -4144,7 +4085,7 @@ async function stableRunsIdentity(root) {
4144
4085
  } catch (error) {
4145
4086
  if (!isMissingPathError2(error)) throw error;
4146
4087
  }
4147
- const parent = dirname8(cursor);
4088
+ const parent = dirname7(cursor);
4148
4089
  if (parent === cursor) return root;
4149
4090
  cursor = parent;
4150
4091
  }
@@ -4220,7 +4161,7 @@ async function loadDoctorCase(runsPath) {
4220
4161
  const turns = { count: 0, sources: [] }, calls = { count: 0, sources: [] }, tokens = { count: 0, sources: [] };
4221
4162
  for (const path of await discoverCaseFiles(root)) {
4222
4163
  const id = relative2(root, path).split(sep3).join("/");
4223
- const bytes = await readFile6(path);
4164
+ const bytes = await readFile5(path);
4224
4165
  const content = bytes.toString("utf8");
4225
4166
  const kind = id.endsWith(".jsonl") ? "session" : "stderr";
4226
4167
  evidence.push({ id, kind, byteLength: bytes.byteLength, contentLength: content.length, sha256: sha256Hex(bytes), content });
@@ -4250,7 +4191,7 @@ var init_doctor_evidence = __esm({
4250
4191
 
4251
4192
  // src/collector-config.ts
4252
4193
  import { createHash as createHash4 } from "node:crypto";
4253
- import { readFile as readFile7 } from "node:fs/promises";
4194
+ import { readFile as readFile6 } from "node:fs/promises";
4254
4195
  function fail3(message, cause) {
4255
4196
  throw new Error(message, cause === void 0 ? void 0 : { cause });
4256
4197
  }
@@ -4293,7 +4234,7 @@ function emptyCollectorManifest() {
4293
4234
  async function loadCollectorManifest(path) {
4294
4235
  let bytes;
4295
4236
  try {
4296
- bytes = await readFile7(path);
4237
+ bytes = await readFile6(path);
4297
4238
  } catch (error) {
4298
4239
  fail3(`Collector request manifest is unreadable at ${path}`, error);
4299
4240
  }
@@ -5133,7 +5074,7 @@ var init_git_object_id = __esm({
5133
5074
 
5134
5075
  // src/merger-git-state.ts
5135
5076
  import { execFile as execFile2 } from "node:child_process";
5136
- import { access as access2, readFile as readFile8 } from "node:fs/promises";
5077
+ import { access as access2, readFile as readFile7 } from "node:fs/promises";
5137
5078
  import { constants as fsConstants } from "node:fs";
5138
5079
  import { isAbsolute as isAbsolute4, resolve as resolve7 } from "node:path";
5139
5080
  import { promisify as promisify2 } from "node:util";
@@ -5203,7 +5144,7 @@ function createProductionMergerGitState(repositoryRoot = process.cwd()) {
5203
5144
  const mergeHeadPath = isAbsolute4(mergeHeadReported) ? mergeHeadReported : resolve7(repositoryRoot, mergeHeadReported);
5204
5145
  let sourceObjectId = "";
5205
5146
  if (await pathExists(mergeHeadPath)) {
5206
- const raw = exactUtf8(await readFile8(mergeHeadPath), "Git MERGE_HEAD");
5147
+ const raw = exactUtf8(await readFile7(mergeHeadPath), "Git MERGE_HEAD");
5207
5148
  const mergeHeads = raw.trim().split(/\r?\n/).map((row) => row.trim()).filter(Boolean);
5208
5149
  if (mergeHeads.length === 0) throw new Error("Git MERGE_HEAD is empty");
5209
5150
  if (mergeHeads.length !== 1) throw new Error("Assigned repository does not have one ordinary in-progress merge");
@@ -5255,10 +5196,10 @@ var init_uuidv7 = __esm({
5255
5196
  });
5256
5197
 
5257
5198
  // src/typed-provider-http.ts
5258
- import { readFile as readFile9, unlink, writeFile as writeFile4 } from "node:fs/promises";
5259
- import { join as join15 } from "node:path";
5199
+ import { readFile as readFile8, unlink, writeFile as writeFile3 } from "node:fs/promises";
5200
+ import { join as join14 } from "node:path";
5260
5201
  function typedProviderHttpPath(runDirectory) {
5261
- return join15(runDirectory, TYPED_HTTP_FILE);
5202
+ return join14(runDirectory, TYPED_HTTP_FILE);
5262
5203
  }
5263
5204
  async function clearTypedProviderHttpObservation(runDirectory) {
5264
5205
  try {
@@ -5279,7 +5220,7 @@ async function recordTypedProviderHttpStatus(runDirectory, observation) {
5279
5220
  httpStatus: observation.httpStatus,
5280
5221
  provider: observation.provider
5281
5222
  };
5282
- await writeFile4(
5223
+ await writeFile3(
5283
5224
  typedProviderHttpPath(runDirectory),
5284
5225
  `${JSON.stringify(body)}
5285
5226
  `,
@@ -5289,7 +5230,7 @@ async function recordTypedProviderHttpStatus(runDirectory, observation) {
5289
5230
  async function readLatestTypedProviderHttpObservation(runDirectory) {
5290
5231
  let text;
5291
5232
  try {
5292
- text = await readFile9(typedProviderHttpPath(runDirectory), "utf8");
5233
+ text = await readFile8(typedProviderHttpPath(runDirectory), "utf8");
5293
5234
  } catch (error) {
5294
5235
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
5295
5236
  return void 0;
@@ -5318,8 +5259,8 @@ var init_typed_provider_http = __esm({
5318
5259
  });
5319
5260
 
5320
5261
  // src/public-cli/run-lifecycle.ts
5321
- import { chmod, lstat as lstat2, open, readdir as readdir4, readFile as readFile10, unlink as unlink2, writeFile as writeFile5 } from "node:fs/promises";
5322
- import { basename as basename4, join as join16 } from "node:path";
5262
+ import { chmod, lstat as lstat2, open, readdir as readdir4, readFile as readFile9, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
5263
+ import { basename as basename4, join as join15 } from "node:path";
5323
5264
  function selectResumeContinuationPrompt(message, engineMaterial) {
5324
5265
  const lines = message !== void 0 ? [message] : [];
5325
5266
  return appendEngineSessionMaterial(lines, engineMaterial).join("\n");
@@ -5348,8 +5289,8 @@ function renderResumeCommand(runId) {
5348
5289
  }
5349
5290
  async function writeRoleRunState(runDirectory, record4) {
5350
5291
  const payload = { ...record4, runDirectory };
5351
- await writeFile5(
5352
- join16(runDirectory, RUN_STATE_FILE),
5292
+ await writeFile4(
5293
+ join15(runDirectory, RUN_STATE_FILE),
5353
5294
  `${JSON.stringify(payload, null, 2)}
5354
5295
  `,
5355
5296
  "utf8"
@@ -5399,7 +5340,7 @@ function parseCurrentCourtState(raw) {
5399
5340
  async function readRoleRunStateDisk(runDirectory) {
5400
5341
  let raw;
5401
5342
  try {
5402
- raw = JSON.parse(await readFile10(join16(runDirectory, RUN_STATE_FILE), "utf8"));
5343
+ raw = JSON.parse(await readFile9(join15(runDirectory, RUN_STATE_FILE), "utf8"));
5403
5344
  } catch (error) {
5404
5345
  if (errorCodeOf2(error) === "ENOENT") return void 0;
5405
5346
  throw error;
@@ -5466,8 +5407,8 @@ async function writeRoleRunStateDisk(runDirectory, disk) {
5466
5407
  ...disk.resumable === void 0 ? {} : { resumable: disk.resumable },
5467
5408
  ...disk.currentCourt === void 0 ? {} : { currentCourt: disk.currentCourt }
5468
5409
  };
5469
- await writeFile5(
5470
- join16(runDirectory, RUN_STATE_FILE),
5410
+ await writeFile4(
5411
+ join15(runDirectory, RUN_STATE_FILE),
5471
5412
  `${JSON.stringify(payload, null, 2)}
5472
5413
  `,
5473
5414
  "utf8"
@@ -5634,7 +5575,7 @@ function isProcessAlive(pid) {
5634
5575
  async function autopsyWriterLock(lockPath) {
5635
5576
  let content;
5636
5577
  try {
5637
- content = await readFile10(lockPath, "utf8");
5578
+ content = await readFile9(lockPath, "utf8");
5638
5579
  } catch (error) {
5639
5580
  if (errorCodeOf2(error) === "ENOENT") return { verdict: "absent" };
5640
5581
  return { verdict: "unknown", reason: "unreadable", readFailure: error };
@@ -5693,7 +5634,7 @@ async function createWriterLease(lockPath, runDirectory, reportCleanupFailure) {
5693
5634
  },
5694
5635
  relocate(nextRunDirectory) {
5695
5636
  currentRunDirectory = nextRunDirectory;
5696
- currentLockPath = join16(nextRunDirectory, WRITER_LOCK_FILE);
5637
+ currentLockPath = join15(nextRunDirectory, WRITER_LOCK_FILE);
5697
5638
  },
5698
5639
  async release() {
5699
5640
  if (released) return;
@@ -5732,10 +5673,10 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
5732
5673
  };
5733
5674
  const reportReadFailure = (error) => {
5734
5675
  reportDiagnostic(
5735
- `writer lease lock read failed (holder liveness unverifiable; lock left in place) at ${join16(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
5676
+ `writer lease lock read failed (holder liveness unverifiable; lock left in place) at ${join15(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
5736
5677
  );
5737
5678
  };
5738
- const lockPath = join16(runDirectory, WRITER_LOCK_FILE);
5679
+ const lockPath = join15(runDirectory, WRITER_LOCK_FILE);
5739
5680
  let lastAutopsy = { verdict: "absent" };
5740
5681
  let lastReclaimFailure;
5741
5682
  for (let reclaimsLeft = WRITER_LEASE_RECLAIM_ROUNDS; ; reclaimsLeft -= 1) {
@@ -5790,7 +5731,7 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
5790
5731
  async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole) {
5791
5732
  if (runId.trim() === "") return void 0;
5792
5733
  const ledgerHome = resolveActivationLedgerHome(home);
5793
- const booksRoot = join16(ledgerHome, "books");
5734
+ const booksRoot = join15(ledgerHome, "books");
5794
5735
  let bookKeys;
5795
5736
  try {
5796
5737
  bookKeys = await readdir4(booksRoot);
@@ -5831,7 +5772,7 @@ async function readRunParentPath(runDirectory) {
5831
5772
  let raw;
5832
5773
  try {
5833
5774
  raw = JSON.parse(
5834
- await readFile10(join16(runDirectory, "admitted-request.json"), "utf8")
5775
+ await readFile9(join15(runDirectory, "admitted-request.json"), "utf8")
5835
5776
  );
5836
5777
  } catch (error) {
5837
5778
  if (errorCodeOf2(error) === "ENOENT") return void 0;
@@ -5852,7 +5793,7 @@ async function readRunParentPath(runDirectory) {
5852
5793
  async function runHasFormedSessionPrincipal(runDirectory) {
5853
5794
  const disk = await readRoleRunStateDisk(runDirectory);
5854
5795
  if (disk === void 0) return false;
5855
- const sessionFile = typeof disk.principalWire.sessionFile === "string" && disk.principalWire.sessionFile.trim() !== "" ? disk.principalWire.sessionFile : join16(disk.principalWire.sessionDirectory, "session.jsonl");
5796
+ const sessionFile = typeof disk.principalWire.sessionFile === "string" && disk.principalWire.sessionFile.trim() !== "" ? disk.principalWire.sessionFile : join15(disk.principalWire.sessionDirectory, "session.jsonl");
5856
5797
  try {
5857
5798
  const stat2 = await lstat2(sessionFile);
5858
5799
  return stat2.isFile() && !stat2.isSymbolicLink();
@@ -5999,7 +5940,7 @@ async function loadResumableRunRecord(home, runId, authority) {
5999
5940
  let sourceRun;
6000
5941
  try {
6001
5942
  const raw = JSON.parse(
6002
- await readFile10(run.admittedRequestPath, "utf8")
5943
+ await readFile9(run.admittedRequestPath, "utf8")
6003
5944
  );
6004
5945
  if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) {
6005
5946
  const record4 = raw;
@@ -6114,7 +6055,7 @@ async function loadResumableRunRecord(home, runId, authority) {
6114
6055
  let model;
6115
6056
  try {
6116
6057
  const invocationRaw = JSON.parse(
6117
- await readFile10(join16(run.runDirectory, "invocation.json"), "utf8")
6058
+ await readFile9(join15(run.runDirectory, "invocation.json"), "utf8")
6118
6059
  );
6119
6060
  if (invocationRaw !== null && typeof invocationRaw === "object" && !Array.isArray(invocationRaw)) {
6120
6061
  const rec = invocationRaw;
@@ -6345,7 +6286,7 @@ __export(notary_source_run_exports, {
6345
6286
  loadNotarySourceRunLocator: () => loadNotarySourceRunLocator,
6346
6287
  resolveNotarySourceRunLocator: () => resolveNotarySourceRunLocator
6347
6288
  });
6348
- import { dirname as dirname9, isAbsolute as isAbsolute6, join as join17, resolve as resolve8, basename as basename5 } from "node:path";
6289
+ import { dirname as dirname8, isAbsolute as isAbsolute6, join as join16, resolve as resolve8, basename as basename5 } from "node:path";
6349
6290
  import { lstat as lstat3, realpath as realpath3 } from "node:fs/promises";
6350
6291
  function parseRunDirectoryName(name) {
6351
6292
  const match = RUN_DIR_NAME.exec(name);
@@ -6391,20 +6332,20 @@ async function resolveNotarySourceRunLocator(options) {
6391
6332
  }
6392
6333
  const ledgerHome = resolveActivationLedgerHome(options.home);
6393
6334
  const bookKey = resolveBookKeyFromGit(options.projectRoot);
6394
- const bookRunsRoot = join17(activationBookDirectory(ledgerHome, bookKey), "runs");
6335
+ const bookRunsRoot = join16(activationBookDirectory(ledgerHome, bookKey), "runs");
6395
6336
  let candidate;
6396
6337
  const bare = parseRunDirectoryName(raw);
6397
6338
  if (bare !== void 0 && !raw.includes("/") && !raw.includes("\\")) {
6398
- candidate = await findRunDirectoryById(options.home, bare.runId, bookKey, bare.role) ?? join17(bookRunsRoot, `${bare.runId}@${bare.role}`);
6339
+ candidate = await findRunDirectoryById(options.home, bare.runId, bookKey, bare.role) ?? join16(bookRunsRoot, `${bare.runId}@${bare.role}`);
6399
6340
  } else {
6400
6341
  candidate = isAbsolute6(raw) ? raw : resolve8(options.projectRoot, raw);
6401
6342
  }
6402
6343
  const real = await requireRunDirectory(candidate, raw);
6403
6344
  const identity = parseRunDirectoryName(basename5(real));
6404
6345
  const bookIdentity = physicalPathIdentity(activationBookDirectory(ledgerHome, bookKey));
6405
- const parentIdentity = physicalPathIdentity(dirname9(real));
6406
- const subjectBookIdentity = physicalPathIdentity(dirname9(dirname9(dirname9(real))));
6407
- if (parentIdentity !== physicalPathIdentity(bookRunsRoot) && !(basename5(dirname9(real)) === "runs" && subjectBookIdentity === bookIdentity)) {
6346
+ const parentIdentity = physicalPathIdentity(dirname8(real));
6347
+ const subjectBookIdentity = physicalPathIdentity(dirname8(dirname8(dirname8(real))));
6348
+ if (parentIdentity !== physicalPathIdentity(bookRunsRoot) && !(basename5(dirname8(real)) === "runs" && subjectBookIdentity === bookIdentity)) {
6408
6349
  throw new NotarySourceRunError(
6409
6350
  "notary --source-run must resolve to a retained run under the project machine-ledger book"
6410
6351
  );
@@ -7545,12 +7486,12 @@ import { execFileSync as execFileSync3 } from "node:child_process";
7545
7486
  import { existsSync as existsSync6 } from "node:fs";
7546
7487
  import {
7547
7488
  lstat as lstat4,
7548
- readFile as readFile11,
7489
+ readFile as readFile10,
7549
7490
  realpath as realpath4,
7550
- rename as rename2,
7551
- writeFile as writeFile6
7491
+ rename,
7492
+ writeFile as writeFile5
7552
7493
  } from "node:fs/promises";
7553
- import { basename as basename6, dirname as dirname10, isAbsolute as isAbsolute7, join as join18, resolve as resolve9, sep as sep4 } from "node:path";
7494
+ import { basename as basename6, dirname as dirname9, isAbsolute as isAbsolute7, join as join17, resolve as resolve9, sep as sep4 } from "node:path";
7554
7495
  function issueAdmissionPlacement(authority, request) {
7555
7496
  const ledgerHome = resolveActivationLedgerHome(request.home);
7556
7497
  const bookKey = resolveBookKeyFromGit(request.cwd);
@@ -7575,7 +7516,7 @@ async function writeAdmittedRequestPersistence(admittedRequestPath, body, coordi
7575
7516
  sessionDirectory: coordinates.sessionDirectory,
7576
7517
  sessionFile: coordinates.sessionFile
7577
7518
  };
7578
- await writeFile6(
7519
+ await writeFile5(
7579
7520
  admittedRequestPath,
7580
7521
  `${JSON.stringify(projection, null, 2)}
7581
7522
  `,
@@ -7603,16 +7544,16 @@ async function writeRoleInvocationLedger(source, role, effectiveModel) {
7603
7544
  ...source.ticketNumber === void 0 ? {} : { ticketNumber: source.ticketNumber },
7604
7545
  ...effectiveModelLedgerFields(effectiveModel)
7605
7546
  };
7606
- await writeFile6(
7607
- join18(source.runDirectory, "invocation.json"),
7547
+ await writeFile5(
7548
+ join17(source.runDirectory, "invocation.json"),
7608
7549
  `${JSON.stringify(identity, null, 2)}
7609
7550
  `,
7610
7551
  "utf8"
7611
7552
  );
7612
7553
  }
7613
7554
  async function recordEffectiveInvocationModel(runDirectory, model, engine, host, engineModel) {
7614
- const ledgerPath = join18(runDirectory, "invocation.json");
7615
- const current = JSON.parse(await readFile11(ledgerPath, "utf8"));
7555
+ const ledgerPath = join17(runDirectory, "invocation.json");
7556
+ const current = JSON.parse(await readFile10(ledgerPath, "utf8"));
7616
7557
  const next = { ...current };
7617
7558
  if (model !== void 0) {
7618
7559
  next.provider = model.provider;
@@ -7636,7 +7577,7 @@ async function recordEffectiveInvocationModel(runDirectory, model, engine, host,
7636
7577
  if (host !== void 0) {
7637
7578
  next.host = host;
7638
7579
  }
7639
- await writeFile6(
7580
+ await writeFile5(
7640
7581
  ledgerPath,
7641
7582
  `${JSON.stringify(next, null, 2)}
7642
7583
  `,
@@ -7644,9 +7585,9 @@ async function recordEffectiveInvocationModel(runDirectory, model, engine, host,
7644
7585
  );
7645
7586
  }
7646
7587
  async function mergeInvocationIdentityPage(runDirectory, fields) {
7647
- const ledgerPath = join18(runDirectory, "invocation.json");
7648
- const current = JSON.parse(await readFile11(ledgerPath, "utf8"));
7649
- await writeFile6(
7588
+ const ledgerPath = join17(runDirectory, "invocation.json");
7589
+ const current = JSON.parse(await readFile10(ledgerPath, "utf8"));
7590
+ await writeFile5(
7650
7591
  ledgerPath,
7651
7592
  `${JSON.stringify({
7652
7593
  ...current,
@@ -7661,14 +7602,14 @@ async function persistAdmittedSourceRunPath(admitted, sourceRunPath) {
7661
7602
  throw new Error("persistAdmittedSourceRunPath requires a non-empty sourceRunPath");
7662
7603
  }
7663
7604
  const admittedPath = admitted.admittedRequestPath;
7664
- const current = JSON.parse(await readFile11(admittedPath, "utf8"));
7605
+ const current = JSON.parse(await readFile10(admittedPath, "utf8"));
7665
7606
  if (typeof current.sourceRunPath === "string") {
7666
7607
  if (current.sourceRunPath === sourceRunPath) return;
7667
7608
  throw new Error(
7668
7609
  `persistAdmittedSourceRunPath refuses to replace ${current.sourceRunPath} with ${sourceRunPath}`
7669
7610
  );
7670
7611
  }
7671
- await writeFile6(
7612
+ await writeFile5(
7672
7613
  admittedPath,
7673
7614
  `${JSON.stringify({ ...current, sourceRunPath }, null, 2)}
7674
7615
  `,
@@ -7710,8 +7651,8 @@ async function bindCourtTicketNumbersOnAdmitted(admitted, courtTicketNumbers) {
7710
7651
  }
7711
7652
  const frozen = Object.freeze([...projected]);
7712
7653
  const admittedPath = admitted.admittedRequestPath;
7713
- const current = JSON.parse(await readFile11(admittedPath, "utf8"));
7714
- await writeFile6(
7654
+ const current = JSON.parse(await readFile10(admittedPath, "utf8"));
7655
+ await writeFile5(
7715
7656
  admittedPath,
7716
7657
  `${JSON.stringify({ ...current, courtTicketNumbers: frozen }, null, 2)}
7717
7658
  `,
@@ -7732,8 +7673,8 @@ async function relocateAdmittedRunToTicket(admitted, authority, heldLease) {
7732
7673
  runId: admitted.runId,
7733
7674
  role: admitted.role
7734
7675
  });
7735
- ensureRoleRunDirectory(ledgerHome, dirname10(target.runDirectory));
7736
- await rename2(oldRunDirectory, target.runDirectory);
7676
+ ensureRoleRunDirectory(ledgerHome, dirname9(target.runDirectory));
7677
+ await rename(oldRunDirectory, target.runDirectory);
7737
7678
  heldLease?.relocate(target.runDirectory);
7738
7679
  const admittedRecord = admitted;
7739
7680
  rewriteRunDirectoryPathFields(
@@ -7770,9 +7711,9 @@ async function bindTicketNumberOnRunDirectory(runDirectory, ticketNumber) {
7770
7711
  ticketNumber,
7771
7712
  "bindTicketNumberOnRunDirectory"
7772
7713
  );
7773
- const admittedPath = join18(runDirectory, "admitted-request.json");
7774
- const invocationPath = join18(runDirectory, "invocation.json");
7775
- const admitted = JSON.parse(await readFile11(admittedPath, "utf8"));
7714
+ const admittedPath = join17(runDirectory, "admitted-request.json");
7715
+ const invocationPath = join17(runDirectory, "invocation.json");
7716
+ const admitted = JSON.parse(await readFile10(admittedPath, "utf8"));
7776
7717
  const existing = admitted.ticketNumber;
7777
7718
  if (typeof existing === "number") {
7778
7719
  if (existing === ticketNumber) return;
@@ -7782,7 +7723,7 @@ async function bindTicketNumberOnRunDirectory(runDirectory, ticketNumber) {
7782
7723
  }
7783
7724
  if (existsSync6(invocationPath)) {
7784
7725
  const invocation = JSON.parse(
7785
- await readFile11(invocationPath, "utf8")
7726
+ await readFile10(invocationPath, "utf8")
7786
7727
  );
7787
7728
  if (typeof invocation.ticketNumber === "number" && invocation.ticketNumber !== ticketNumber) {
7788
7729
  throw new Error(
@@ -7790,7 +7731,7 @@ async function bindTicketNumberOnRunDirectory(runDirectory, ticketNumber) {
7790
7731
  );
7791
7732
  }
7792
7733
  }
7793
- await writeFile6(
7734
+ await writeFile5(
7794
7735
  admittedPath,
7795
7736
  `${JSON.stringify({ ...admitted, ticketNumber }, null, 2)}
7796
7737
  `,
@@ -7807,7 +7748,7 @@ async function recordLaunchedPiIdentity(runDirectory, identity) {
7807
7748
  async function observeLaunchedRolePackageIdentity(packageRoot, selectedRoleEntry) {
7808
7749
  const rolePackageRoot = packageRoot;
7809
7750
  const raw = JSON.parse(
7810
- await readFile11(join18(rolePackageRoot, "package.json"), "utf8")
7751
+ await readFile10(join17(rolePackageRoot, "package.json"), "utf8")
7811
7752
  );
7812
7753
  if (typeof raw.version !== "string" || raw.version.trim() === "") {
7813
7754
  throw new Error(
@@ -8063,10 +8004,10 @@ async function freezeRegularFileAttachment(sourcePath, destinationDir, index) {
8063
8004
  `attachment must be a regular file (not a directory or symlink): ${sourcePath}`
8064
8005
  );
8065
8006
  }
8066
- const bytes = await readFile11(absolute);
8007
+ const bytes = await readFile10(absolute);
8067
8008
  const name = `${String(index).padStart(2, "0")}-${basename6(absolute)}`;
8068
- const frozenPath = join18(destinationDir, name);
8069
- await writeFile6(frozenPath, bytes);
8009
+ const frozenPath = join17(destinationDir, name);
8010
+ await writeFile5(frozenPath, bytes);
8070
8011
  return {
8071
8012
  attachment: {
8072
8013
  provenancePath: absolute,
@@ -8093,7 +8034,7 @@ async function freezeAttachments(attachmentPaths, attachmentsDirectory) {
8093
8034
  async function freezeAttachmentsIntoRun(attachmentPaths, runDirectory, summonsKey = `s-${Date.now().toString(36)}`) {
8094
8035
  if (attachmentPaths.length === 0) return [];
8095
8036
  const ledgerHome = resolveActivationLedgerHome(homeFromRunDirectory(runDirectory));
8096
- const attachmentsDirectory = join18(runDirectory, "attachments", summonsKey);
8037
+ const attachmentsDirectory = join17(runDirectory, "attachments", summonsKey);
8097
8038
  ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
8098
8039
  return freezeAttachments(attachmentPaths, attachmentsDirectory);
8099
8040
  }
@@ -8151,7 +8092,7 @@ async function admitStandardMaterialInvocation(role, options) {
8151
8092
  })),
8152
8093
  ...ticketFields
8153
8094
  };
8154
- const admittedRequestPath = join18(runDirectory, "admitted-request.json");
8095
+ const admittedRequestPath = join17(runDirectory, "admitted-request.json");
8155
8096
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
8156
8097
  sessionDirectory,
8157
8098
  sessionFile
@@ -8253,7 +8194,7 @@ async function admitCountersignInvocation(options) {
8253
8194
  mediaKind: a.mediaKind
8254
8195
  }))
8255
8196
  };
8256
- const admittedRequestPath = join18(runDirectory, "admitted-request.json");
8197
+ const admittedRequestPath = join17(runDirectory, "admitted-request.json");
8257
8198
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
8258
8199
  sessionDirectory,
8259
8200
  sessionFile
@@ -8279,7 +8220,7 @@ function buildCountersignTransportPrompt(admitted, engineMaterial) {
8279
8220
  async function loadAdmittedJudgeRequest(runDirectory) {
8280
8221
  try {
8281
8222
  const raw = JSON.parse(
8282
- await readFile11(join18(runDirectory, "admitted-request.json"), "utf8")
8223
+ await readFile10(join17(runDirectory, "admitted-request.json"), "utf8")
8283
8224
  );
8284
8225
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return void 0;
8285
8226
  const record4 = raw;
@@ -8334,8 +8275,8 @@ async function admitCoderInvocation(options) {
8334
8275
  home: options.home
8335
8276
  });
8336
8277
  const attachments = await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
8337
- const taskPath = join18(runDirectory, "task.md");
8338
- await writeFile6(taskPath, instruction, "utf8");
8278
+ const taskPath = join17(runDirectory, "task.md");
8279
+ await writeFile5(taskPath, instruction, "utf8");
8339
8280
  const admitted = {
8340
8281
  role: "coder",
8341
8282
  phase: options.phase,
@@ -8355,7 +8296,7 @@ async function admitCoderInvocation(options) {
8355
8296
  mediaKind: a.mediaKind
8356
8297
  }))
8357
8298
  };
8358
- const admittedRequestPath = join18(runDirectory, "admitted-request.json");
8299
+ const admittedRequestPath = join17(runDirectory, "admitted-request.json");
8359
8300
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
8360
8301
  sessionDirectory,
8361
8302
  sessionFile
@@ -8405,7 +8346,7 @@ async function admitFixerInvocation(options) {
8405
8346
  if (options.prerequisitesPath !== void 0) {
8406
8347
  const absolutePrereq = isAbsolute7(options.prerequisitesPath) ? options.prerequisitesPath : resolve9(options.prerequisitesPath);
8407
8348
  try {
8408
- prerequisitesSource = await readFile11(absolutePrereq, "utf8");
8349
+ prerequisitesSource = await readFile10(absolutePrereq, "utf8");
8409
8350
  } catch (error) {
8410
8351
  throw new CliUsageError(
8411
8352
  `fixer prerequisites path is unreadable: ${options.prerequisitesPath}`,
@@ -8441,16 +8382,16 @@ async function admitFixerInvocation(options) {
8441
8382
  const attachments = await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
8442
8383
  let prerequisitesPath;
8443
8384
  if (prerequisitesSource !== void 0) {
8444
- prerequisitesPath = join18(runDirectory, "prerequisites.json");
8445
- await writeFile6(
8385
+ prerequisitesPath = join17(runDirectory, "prerequisites.json");
8386
+ await writeFile5(
8446
8387
  prerequisitesPath,
8447
8388
  `${JSON.stringify(prerequisites, null, 2)}
8448
8389
  `,
8449
8390
  "utf8"
8450
8391
  );
8451
8392
  }
8452
- const packetPath = join18(runDirectory, "fix-packet.md");
8453
- await writeFile6(packetPath, instruction, "utf8");
8393
+ const packetPath = join17(runDirectory, "fix-packet.md");
8394
+ await writeFile5(packetPath, instruction, "utf8");
8454
8395
  const admitted = {
8455
8396
  role: "fixer",
8456
8397
  phase: options.phase,
@@ -8475,7 +8416,7 @@ async function admitFixerInvocation(options) {
8475
8416
  mediaKind: a.mediaKind
8476
8417
  }))
8477
8418
  };
8478
- const admittedRequestPath = join18(runDirectory, "admitted-request.json");
8419
+ const admittedRequestPath = join17(runDirectory, "admitted-request.json");
8479
8420
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
8480
8421
  sessionDirectory,
8481
8422
  sessionFile
@@ -8695,8 +8636,8 @@ async function admitCollectorInvocation(options) {
8695
8636
  const prNumber = target.kind === "bound" ? target.prNumber : void 0;
8696
8637
  let requestManifestPath;
8697
8638
  if (manifestCanonicalJson !== void 0) {
8698
- requestManifestPath = join18(runDirectory, "request-manifest.json");
8699
- await writeFile6(requestManifestPath, manifestCanonicalJson, "utf8");
8639
+ requestManifestPath = join17(runDirectory, "request-manifest.json");
8640
+ await writeFile5(requestManifestPath, manifestCanonicalJson, "utf8");
8700
8641
  }
8701
8642
  const admitted = {
8702
8643
  role: "collector",
@@ -8721,7 +8662,7 @@ async function admitCollectorInvocation(options) {
8721
8662
  mediaKind: a.mediaKind
8722
8663
  }))
8723
8664
  };
8724
- const admittedRequestPath = join18(runDirectory, "admitted-request.json");
8665
+ const admittedRequestPath = join17(runDirectory, "admitted-request.json");
8725
8666
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
8726
8667
  sessionDirectory,
8727
8668
  sessionFile
@@ -8819,7 +8760,7 @@ function parseDoctorArgv(args) {
8819
8760
  }
8820
8761
  async function resolveDoctorCaseRunsPath(options) {
8821
8762
  const ledgerHome = resolveActivationLedgerHome(options.home);
8822
- const defaultRuns = join18(
8763
+ const defaultRuns = join17(
8823
8764
  activationBookDirectory(ledgerHome, options.bookKey),
8824
8765
  String(options.issueNumber),
8825
8766
  "runs"
@@ -8950,7 +8891,7 @@ async function admitDoctorInvocation(options) {
8950
8891
  mediaKind: a.mediaKind
8951
8892
  }))
8952
8893
  };
8953
- const admittedRequestPath = join18(runDirectory, "admitted-request.json");
8894
+ const admittedRequestPath = join17(runDirectory, "admitted-request.json");
8954
8895
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
8955
8896
  sessionDirectory,
8956
8897
  sessionFile
@@ -9082,7 +9023,7 @@ async function admitNotaryInvocation(options) {
9082
9023
  ...ticketFields,
9083
9024
  ...options.correlationId === void 0 ? {} : { correlationId: options.correlationId }
9084
9025
  };
9085
- const admittedRequestPath = join18(runDirectory, "admitted-request.json");
9026
+ const admittedRequestPath = join17(runDirectory, "admitted-request.json");
9086
9027
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
9087
9028
  sessionDirectory,
9088
9029
  sessionFile
@@ -9185,7 +9126,7 @@ async function admitGleanerLeftInvocation(options) {
9185
9126
  attachments: [],
9186
9127
  ...options.correlationId === void 0 ? {} : { correlationId: options.correlationId }
9187
9128
  };
9188
- const admittedRequestPath = join18(runDirectory, "admitted-request.json");
9129
+ const admittedRequestPath = join17(runDirectory, "admitted-request.json");
9189
9130
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
9190
9131
  sessionDirectory,
9191
9132
  sessionFile
@@ -9314,7 +9255,7 @@ async function admitReviewerInvocation(options) {
9314
9255
  mediaKind: a.mediaKind
9315
9256
  }))
9316
9257
  };
9317
- const admittedRequestPath = join18(runDirectory, "admitted-request.json");
9258
+ const admittedRequestPath = join17(runDirectory, "admitted-request.json");
9318
9259
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
9319
9260
  sessionDirectory,
9320
9261
  sessionFile
@@ -9459,8 +9400,8 @@ async function admitMergerInvocation(options) {
9459
9400
  resolutionScope: [...derived.resolutionScope],
9460
9401
  authorizedChecks: []
9461
9402
  });
9462
- const mergerInputPath = join18(runDirectory, "merger-input.json");
9463
- await writeFile6(
9403
+ const mergerInputPath = join17(runDirectory, "merger-input.json");
9404
+ await writeFile5(
9464
9405
  mergerInputPath,
9465
9406
  `${JSON.stringify(mergerInput, null, 2)}
9466
9407
  `,
@@ -9490,7 +9431,7 @@ async function admitMergerInvocation(options) {
9490
9431
  mediaKind: a.mediaKind
9491
9432
  }))
9492
9433
  };
9493
- const admittedRequestPath = join18(runDirectory, "admitted-request.json");
9434
+ const admittedRequestPath = join17(runDirectory, "admitted-request.json");
9494
9435
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
9495
9436
  sessionDirectory,
9496
9437
  sessionFile
@@ -9774,15 +9715,15 @@ var init_invocation = __esm({
9774
9715
 
9775
9716
  // src/public-cli/load-production-acp-host.ts
9776
9717
  import { existsSync as existsSync7 } from "node:fs";
9777
- import { join as join19 } from "node:path";
9718
+ import { join as join18 } from "node:path";
9778
9719
  import { pathToFileURL } from "node:url";
9779
9720
  async function loadProductionAcpHostFactory(packageRoot, host) {
9780
9721
  const description = lookupHostDescription(host);
9781
9722
  if (description === void 0) {
9782
9723
  throw new Error(`unregistered host: ${host}`);
9783
9724
  }
9784
- const built = join19(packageRoot, "dist/acp-host/production-host.js");
9785
- const source = join19(packageRoot, "src/acp-host/production-host.ts");
9725
+ const built = join18(packageRoot, "dist/acp-host/production-host.js");
9726
+ const source = join18(packageRoot, "src/acp-host/production-host.ts");
9786
9727
  const target = existsSync7(built) ? built : source;
9787
9728
  const href = pathToFileURL(target).href;
9788
9729
  const mod = await import(href);
@@ -9798,15 +9739,15 @@ var init_load_production_acp_host = __esm({
9798
9739
 
9799
9740
  // src/public-cli/load-production-headless-host.ts
9800
9741
  import { existsSync as existsSync8 } from "node:fs";
9801
- import { join as join20 } from "node:path";
9742
+ import { join as join19 } from "node:path";
9802
9743
  import { pathToFileURL as pathToFileURL2 } from "node:url";
9803
9744
  async function loadProductionHeadlessHostFactory(packageRoot, host) {
9804
9745
  const description = lookupHeadlessHostDescription(host);
9805
9746
  if (description === void 0) {
9806
9747
  throw new Error(`unregistered headless host: ${host}`);
9807
9748
  }
9808
- const built = join20(packageRoot, "dist/headless-host/production-host.js");
9809
- const source = join20(packageRoot, "src/headless-host/production-host.ts");
9749
+ const built = join19(packageRoot, "dist/headless-host/production-host.js");
9750
+ const source = join19(packageRoot, "src/headless-host/production-host.ts");
9810
9751
  const target = existsSync8(built) ? built : source;
9811
9752
  const href = pathToFileURL2(target).href;
9812
9753
  const mod = await import(href);
@@ -10055,8 +9996,8 @@ __export(config_exports, {
10055
9996
  setPersistentSeatHost: () => setPersistentSeatHost,
10056
9997
  validatePublicCliConfigAxes: () => validatePublicCliConfigAxes
10057
9998
  });
10058
- import { mkdir, readFile as readFile12, writeFile as writeFile7 } from "node:fs/promises";
10059
- import { dirname as dirname11, join as join21 } from "node:path";
9999
+ import { mkdir, readFile as readFile11, writeFile as writeFile6 } from "node:fs/promises";
10000
+ import { dirname as dirname10, join as join20 } from "node:path";
10060
10001
  function isGateOfficerSeat(value) {
10061
10002
  return GATE_OFFICER_SEATS.includes(value);
10062
10003
  }
@@ -10064,12 +10005,12 @@ function publicCliConfigPath(home) {
10064
10005
  if (typeof home !== "string" || home.trim() === "") {
10065
10006
  throw new Error("home must be explicitly provided");
10066
10007
  }
10067
- return join21(home, ".ak-roles", "public-cli.json");
10008
+ return join20(home, ".ak-roles", "public-cli.json");
10068
10009
  }
10069
10010
  async function loadPublicCliConfig(home) {
10070
10011
  const path = publicCliConfigPath(home);
10071
10012
  try {
10072
- const raw = await readFile12(path, "utf8");
10013
+ const raw = await readFile11(path, "utf8");
10073
10014
  return parsePublicCliConfig(JSON.parse(raw));
10074
10015
  } catch (error) {
10075
10016
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -10080,9 +10021,9 @@ async function loadPublicCliConfig(home) {
10080
10021
  }
10081
10022
  async function savePublicCliConfig(config, home) {
10082
10023
  const path = publicCliConfigPath(home);
10083
- await mkdir(dirname11(path), { recursive: true });
10024
+ await mkdir(dirname10(path), { recursive: true });
10084
10025
  const normalized = parsePublicCliConfig(config);
10085
- await writeFile7(
10026
+ await writeFile6(
10086
10027
  path,
10087
10028
  `${JSON.stringify(serializePublicCliConfig(normalized), null, 2)}
10088
10029
  `,
@@ -10527,7 +10468,7 @@ function credentialProvidersFromAuthData(data) {
10527
10468
  }
10528
10469
  async function loadCredentialProviders(agentDir) {
10529
10470
  try {
10530
- const raw = await readFile12(join21(agentDir, "auth.json"), "utf8");
10471
+ const raw = await readFile11(join20(agentDir, "auth.json"), "utf8");
10531
10472
  return credentialProvidersFromAuthData(JSON.parse(raw));
10532
10473
  } catch (error) {
10533
10474
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -10566,15 +10507,15 @@ __export(host_providers_exports, {
10566
10507
  renderHostProvidersTable: () => renderHostProvidersTable
10567
10508
  });
10568
10509
  import { readFileSync as readFileSync3 } from "node:fs";
10569
- import { join as join22 } from "node:path";
10510
+ import { join as join21 } from "node:path";
10570
10511
  function hostProvidersPath(home) {
10571
10512
  if (typeof home !== "string" || home.trim() === "") {
10572
10513
  throw new Error("home must be explicitly provided");
10573
10514
  }
10574
- return join22(home, ".ak-roles", "host-providers.json");
10515
+ return join21(home, ".ak-roles", "host-providers.json");
10575
10516
  }
10576
10517
  function hermesProviderModelsCachePath(home) {
10577
- return join22(home, ".hermes", "provider_models_cache.json");
10518
+ return join21(home, ".hermes", "provider_models_cache.json");
10578
10519
  }
10579
10520
  function parseHostProvidersTable(value) {
10580
10521
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -10729,12 +10670,12 @@ var init_host_providers = __esm({
10729
10670
  });
10730
10671
 
10731
10672
  // src/ledger-session-read.ts
10732
- import { readFile as readFile13 } from "node:fs/promises";
10673
+ import { readFile as readFile12 } from "node:fs/promises";
10733
10674
  function isRecord5(value) {
10734
10675
  return typeof value === "object" && value !== null && !Array.isArray(value);
10735
10676
  }
10736
10677
  async function readLedgerSessionJsonlLines(path) {
10737
- const text = await readFile13(path, "utf8");
10678
+ const text = await readFile12(path, "utf8");
10738
10679
  const lines = text.split("\n");
10739
10680
  const out = [];
10740
10681
  for (let index = 0; index < lines.length; index += 1) {
@@ -10833,7 +10774,7 @@ var init_ledger_session_read = __esm({
10833
10774
 
10834
10775
  // src/analyst-gate-cycles-read.ts
10835
10776
  import { readdir as readdir5 } from "node:fs/promises";
10836
- import { join as join23 } from "node:path";
10777
+ import { join as join22 } from "node:path";
10837
10778
  function isRecord6(value) {
10838
10779
  return typeof value === "object" && value !== null && !Array.isArray(value);
10839
10780
  }
@@ -11083,7 +11024,7 @@ async function readAnalystGateCyclesFromAuditorRoles(auditorRolesDirectory, opti
11083
11024
  throw error;
11084
11025
  }
11085
11026
  for (const name of names) {
11086
- const path = join23(directory, name);
11027
+ const path = join22(directory, name);
11087
11028
  const fromPointer = name.endsWith(".pointer.json");
11088
11029
  const sessionPath = fromPointer ? await resolveOfficerSessionFromPointerFile(path) : path;
11089
11030
  if (sessionPath === void 0) continue;
@@ -11222,7 +11163,7 @@ var init_audit_escalation = __esm({
11222
11163
  });
11223
11164
 
11224
11165
  // src/run-terminal-artifacts.ts
11225
- import { basename as basename7, dirname as dirname12, join as join24 } from "node:path";
11166
+ import { basename as basename7, dirname as dirname11, join as join23 } from "node:path";
11226
11167
  function runIdFromRunDirectory(runDirectory) {
11227
11168
  const name = basename7(runDirectory);
11228
11169
  const at = name.lastIndexOf("@");
@@ -11237,7 +11178,7 @@ var init_run_terminal_artifacts = __esm({
11237
11178
  });
11238
11179
 
11239
11180
  // src/submission-ledger.ts
11240
- import { join as join25 } from "node:path";
11181
+ import { join as join24 } from "node:path";
11241
11182
  function runIdentity(context) {
11242
11183
  const directory = runDirectoryFromHostContext(context);
11243
11184
  if (directory !== void 0) {
@@ -11259,7 +11200,7 @@ async function submissionRecordFile(cwd, runId, scope) {
11259
11200
  if (sessionParent === void 0) {
11260
11201
  const discoveredRun = await findRunDirectoryById(scope.home, runId);
11261
11202
  if (discoveredRun === void 0) return void 0;
11262
- sessionParent = join25(discoveredRun, "session", "session.jsonl");
11203
+ sessionParent = join24(discoveredRun, "session", "session.jsonl");
11263
11204
  }
11264
11205
  return resolveSitianRecordPathInLedger({
11265
11206
  level: "event",
@@ -11464,13 +11405,13 @@ function createSubmissionLedgerHost(host, outputTools, failInfrastructure2 = (er
11464
11405
  const sessionParentFromContext = (context) => {
11465
11406
  const runDirectory = runDirectoryFromHostContext(context);
11466
11407
  if (runDirectory !== void 0) {
11467
- return join25(runDirectory, "session", "session.jsonl");
11408
+ return join24(runDirectory, "session", "session.jsonl");
11468
11409
  }
11469
11410
  const sessionFile = context.sessionManager.getSessionFile?.();
11470
11411
  if (typeof sessionFile === "string" && sessionFile.length > 0) return sessionFile;
11471
11412
  const sessionDir = context.sessionManager.getSessionDir?.();
11472
11413
  if (typeof sessionDir === "string" && sessionDir.length > 0) {
11473
- return join25(sessionDir, "session.jsonl");
11414
+ return join24(sessionDir, "session.jsonl");
11474
11415
  }
11475
11416
  return void 0;
11476
11417
  };
@@ -11632,23 +11573,23 @@ var init_submission_ledger = __esm({
11632
11573
 
11633
11574
  // src/session-opening-materials.ts
11634
11575
  import { existsSync as existsSync9 } from "node:fs";
11635
- import { readFile as readFile14 } from "node:fs/promises";
11636
- import { dirname as dirname13, join as join26 } from "node:path";
11576
+ import { readFile as readFile13 } from "node:fs/promises";
11577
+ import { dirname as dirname12, join as join25 } from "node:path";
11637
11578
  import { fileURLToPath, pathToFileURL as pathToFileURL3 } from "node:url";
11638
11579
  function resolvePackageRootDir(moduleUrl = import.meta.url) {
11639
- let dir = dirname13(fileURLToPath(moduleUrl));
11580
+ let dir = dirname12(fileURLToPath(moduleUrl));
11640
11581
  for (let i = 0; i < 8; i += 1) {
11641
- if (existsSync9(join26(dir, "package.json")) && existsSync9(join26(dir, "souls"))) {
11582
+ if (existsSync9(join25(dir, "package.json")) && existsSync9(join25(dir, "souls"))) {
11642
11583
  return dir;
11643
11584
  }
11644
- const parent = dirname13(dir);
11585
+ const parent = dirname12(dir);
11645
11586
  if (parent === dir) break;
11646
11587
  dir = parent;
11647
11588
  }
11648
11589
  return fileURLToPath(new URL("..", moduleUrl));
11649
11590
  }
11650
11591
  async function readPackageMaterial(relativePath) {
11651
- return readFile14(fileURLToPath(new URL(relativePath, packageRootUrl)), "utf8");
11592
+ return readFile13(fileURLToPath(new URL(relativePath, packageRootUrl)), "utf8");
11652
11593
  }
11653
11594
  async function joinPackageMaterials(relativePaths) {
11654
11595
  const chunks = [];
@@ -12232,13 +12173,13 @@ var init_reviewer_dispatch = __esm({
12232
12173
  });
12233
12174
 
12234
12175
  // src/public-cli/reviewer-dispatch-rejection.ts
12235
- import { readFile as readFile15, unlink as unlink3 } from "node:fs/promises";
12236
- import { join as join27 } from "node:path";
12176
+ import { readFile as readFile14, unlink as unlink3 } from "node:fs/promises";
12177
+ import { join as join26 } from "node:path";
12237
12178
  function isReviewerPreflightViolation(value) {
12238
12179
  return typeof value === "string" && REVIEWER_PREFLIGHT_VIOLATIONS.includes(value);
12239
12180
  }
12240
12181
  function reviewerDispatchRejectionPath(runDirectory) {
12241
- return join27(runDirectory, REVIEWER_DISPATCH_REJECTION_FILE);
12182
+ return join26(runDirectory, REVIEWER_DISPATCH_REJECTION_FILE);
12242
12183
  }
12243
12184
  async function clearReviewerDispatchRejection(runDirectory) {
12244
12185
  try {
@@ -12253,7 +12194,7 @@ async function clearReviewerDispatchRejection(runDirectory) {
12253
12194
  async function readReviewerDispatchRejection(runDirectory) {
12254
12195
  let raw;
12255
12196
  try {
12256
- raw = await readFile15(reviewerDispatchRejectionPath(runDirectory), "utf8");
12197
+ raw = await readFile14(reviewerDispatchRejectionPath(runDirectory), "utf8");
12257
12198
  } catch (error) {
12258
12199
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
12259
12200
  return void 0;
@@ -13447,9 +13388,9 @@ var init_collector_ledger = __esm({
13447
13388
  });
13448
13389
 
13449
13390
  // src/engine-detour-usage.ts
13450
- import { randomUUID as randomUUID4 } from "node:crypto";
13391
+ import { randomUUID as randomUUID3 } from "node:crypto";
13451
13392
  import { readFileSync as readFileSync4 } from "node:fs";
13452
- import { dirname as dirname14, join as join28 } from "node:path";
13393
+ import { dirname as dirname13, join as join27 } from "node:path";
13453
13394
  function engineDetourStdoutByteLength(stdout) {
13454
13395
  return Buffer.byteLength(stdout, "utf8");
13455
13396
  }
@@ -13585,7 +13526,7 @@ function projectEngineDetourToolUsageForPublicTerminal(usage, options) {
13585
13526
  function readInvocationRecord(runDirectory) {
13586
13527
  try {
13587
13528
  const raw = JSON.parse(
13588
- readFileSync4(join28(runDirectory, "invocation.json"), "utf8")
13529
+ readFileSync4(join27(runDirectory, "invocation.json"), "utf8")
13589
13530
  );
13590
13531
  return isRecord8(raw) ? raw : void 0;
13591
13532
  } catch (error) {
@@ -13615,15 +13556,15 @@ function withEngineDetourToolUsageFact(outcome, usage) {
13615
13556
  };
13616
13557
  }
13617
13558
  function runDirectoryFromSessionDirectory(sessionDirectory) {
13618
- return dirname14(sessionDirectory);
13559
+ return dirname13(sessionDirectory);
13619
13560
  }
13620
13561
  function sessionFileFromSessionDirectory(sessionDirectory) {
13621
- return join28(sessionDirectory, "session.jsonl");
13562
+ return join27(sessionDirectory, "session.jsonl");
13622
13563
  }
13623
13564
  function mintEngineDetourInvocationScope(input) {
13624
13565
  const engine = input.effectiveEngine?.trim();
13625
13566
  if (engine === void 0 || engine.length === 0) return void 0;
13626
- return randomUUID4();
13567
+ return randomUUID3();
13627
13568
  }
13628
13569
  function withEngineDetourInvocationScope(request, invocationScopeId) {
13629
13570
  if (invocationScopeId === void 0 || invocationScopeId.length === 0) {
@@ -13648,8 +13589,8 @@ var init_engine_detour_usage = __esm({
13648
13589
 
13649
13590
  // src/package-resources/method-skill.ts
13650
13591
  import { createHash as createHash7 } from "node:crypto";
13651
- import { readFile as readFile16, realpath as realpath6 } from "node:fs/promises";
13652
- import { join as join29 } from "node:path";
13592
+ import { readFile as readFile15, realpath as realpath6 } from "node:fs/promises";
13593
+ import { join as join28 } from "node:path";
13653
13594
  function gitBlobOid(bytes) {
13654
13595
  const body = typeof bytes === "string" ? Buffer.from(bytes, "utf8") : Buffer.from(bytes);
13655
13596
  const header = Buffer.from(`blob ${body.byteLength}\0`, "utf8");
@@ -13666,10 +13607,10 @@ function packagedMethodSkillRelativeDirectory(name) {
13666
13607
  return `${METHOD_SKILL_RELATIVE_ROOT}/${name}`;
13667
13608
  }
13668
13609
  function resolvePackagedMethodSkillRoot(packageRoot, name) {
13669
- return join29(packageRoot, packagedMethodSkillRelativeDirectory(name));
13610
+ return join28(packageRoot, packagedMethodSkillRelativeDirectory(name));
13670
13611
  }
13671
13612
  function resolvePackagedMethodSkillPath(packageRoot, name) {
13672
- return join29(resolvePackagedMethodSkillRoot(packageRoot, name), "SKILL.md");
13613
+ return join28(resolvePackagedMethodSkillRoot(packageRoot, name), "SKILL.md");
13673
13614
  }
13674
13615
  function isRecord9(value) {
13675
13616
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -13763,11 +13704,11 @@ function parseProvenance(raw, expectedName) {
13763
13704
  }
13764
13705
  async function loadPackagedMethodSkillMaterial(packageRoot, name) {
13765
13706
  const rootDirectory = resolvePackagedMethodSkillRoot(packageRoot, name);
13766
- const skillPathConfigured = join29(rootDirectory, "SKILL.md");
13767
- const provenancePath = join29(rootDirectory, "provenance.json");
13707
+ const skillPathConfigured = join28(rootDirectory, "SKILL.md");
13708
+ const provenancePath = join28(rootDirectory, "provenance.json");
13768
13709
  let provenanceRaw;
13769
13710
  try {
13770
- provenanceRaw = await readFile16(provenancePath, "utf8");
13711
+ provenanceRaw = await readFile15(provenancePath, "utf8");
13771
13712
  } catch (error) {
13772
13713
  throw new PackagedMethodSkillUnavailableError(name, provenancePath, error);
13773
13714
  }
@@ -13781,10 +13722,10 @@ async function loadPackagedMethodSkillMaterial(packageRoot, name) {
13781
13722
  }
13782
13723
  const provenance = parseProvenance(provenanceJson, name);
13783
13724
  for (const [rel, expected] of Object.entries(provenance.files)) {
13784
- const absolute = join29(rootDirectory, rel);
13725
+ const absolute = join28(rootDirectory, rel);
13785
13726
  let bytes;
13786
13727
  try {
13787
- bytes = await readFile16(absolute);
13728
+ bytes = await readFile15(absolute);
13788
13729
  } catch (error) {
13789
13730
  throw new PackagedMethodSkillUnavailableError(name, absolute, error);
13790
13731
  }
@@ -13800,7 +13741,7 @@ async function loadPackagedMethodSkillMaterial(packageRoot, name) {
13800
13741
  let raw;
13801
13742
  try {
13802
13743
  skillPath = await realpath6(skillPathConfigured);
13803
- raw = await readFile16(skillPath, "utf8");
13744
+ raw = await readFile15(skillPath, "utf8");
13804
13745
  } catch (error) {
13805
13746
  throw new PackagedMethodSkillUnavailableError(name, skillPathConfigured, error);
13806
13747
  }
@@ -14349,7 +14290,6 @@ __export(settlement_exports, {
14349
14290
  publishMergerArtifacts: () => publishMergerArtifacts,
14350
14291
  publishReviewerArtifacts: () => publishReviewerArtifacts,
14351
14292
  raceNavigatorGrace: () => raceNavigatorGrace,
14352
- readBoundAuditorKnownFailure: () => readBoundAuditorKnownFailure,
14353
14293
  readBoundEvidenceChildKnownFailure: () => readBoundEvidenceChildKnownFailure,
14354
14294
  readCollectorInfrastructureFailure: () => readCollectorInfrastructureFailure,
14355
14295
  readEngineDetourInfrastructureFailure: () => readEngineDetourInfrastructureFailure,
@@ -14389,16 +14329,16 @@ __export(settlement_exports, {
14389
14329
  trySettleReviewerTerminalResult: () => trySettleReviewerTerminalResult,
14390
14330
  withSubmissions: () => withSubmissions
14391
14331
  });
14392
- import { randomUUID as randomUUID5 } from "node:crypto";
14393
- import { appendFile as appendFile2, readFile as readFile17, readdir as readdir6, writeFile as writeFile8 } from "node:fs/promises";
14394
- import { dirname as dirname15, join as join30 } from "node:path";
14332
+ import { randomUUID as randomUUID4 } from "node:crypto";
14333
+ import { appendFile as appendFile2, readFile as readFile16, readdir as readdir6, writeFile as writeFile7 } from "node:fs/promises";
14334
+ import { dirname as dirname14, join as join29 } from "node:path";
14395
14335
  function sealedLedgerHome(admitted) {
14396
14336
  return homeFromRunDirectory(admitted.runDirectory);
14397
14337
  }
14398
14338
  function ledgerReadScope(admitted, scope) {
14399
14339
  return {
14400
14340
  home: sealedLedgerHome(admitted),
14401
- sessionParent: join30(admitted.runDirectory, "session", "session.jsonl"),
14341
+ sessionParent: join29(admitted.runDirectory, "session", "session.jsonl"),
14402
14342
  ...scope?.courtAttemptId === void 0 || scope.courtAttemptId.length === 0 ? {} : { attemptId: scope.courtAttemptId }
14403
14343
  };
14404
14344
  }
@@ -14534,7 +14474,7 @@ function presentControlledFailure(failure2, io) {
14534
14474
  }
14535
14475
  async function inspectJudgeSession(sessionFile) {
14536
14476
  try {
14537
- await readFile17(sessionFile, "utf8");
14477
+ await readFile16(sessionFile, "utf8");
14538
14478
  return { state: "present" };
14539
14479
  } catch (error) {
14540
14480
  if (isMissingPathError3(error)) return { state: "missing" };
@@ -14766,7 +14706,7 @@ function sessionReadFailure(error, fallbackMessage) {
14766
14706
  return failed;
14767
14707
  }
14768
14708
  async function readBoundSessionEntries(sessionFile) {
14769
- const text = await readFile17(sessionFile, "utf8");
14709
+ const text = await readFile16(sessionFile, "utf8");
14770
14710
  const entries = [];
14771
14711
  for (const line2 of text.trim().split("\n").filter(Boolean)) {
14772
14712
  try {
@@ -14827,7 +14767,7 @@ async function readSitianRetainedAuditorProviderStop(sessionFile) {
14827
14767
  kind: "auditor",
14828
14768
  sessionParent: sessionFile,
14829
14769
  // Path is driven by sessionParent when under ledger home; cwd is a fallback only.
14830
- cwd: dirname15(sessionFile)
14770
+ cwd: dirname14(sessionFile)
14831
14771
  });
14832
14772
  const { records } = await readSitianRecords(recordFile);
14833
14773
  for (let i = records.length - 1; i >= 0; i -= 1) {
@@ -14853,7 +14793,7 @@ async function readSessionProviderStop(sessionFile) {
14853
14793
  }
14854
14794
  }
14855
14795
  async function readBoundEvidenceChildKnownFailure(sessionFile) {
14856
- const childDirectory = join30(dirname15(sessionFile), "evidence-children");
14796
+ const childDirectory = join29(dirname14(sessionFile), "evidence-children");
14857
14797
  let names;
14858
14798
  try {
14859
14799
  names = await readdir6(childDirectory);
@@ -14864,7 +14804,7 @@ async function readBoundEvidenceChildKnownFailure(sessionFile) {
14864
14804
  for (const file of names.filter((name) => name.endsWith(".jsonl")).sort().reverse()) {
14865
14805
  let entries;
14866
14806
  try {
14867
- entries = await readBoundSessionEntries(join30(childDirectory, file));
14807
+ entries = await readBoundSessionEntries(join29(childDirectory, file));
14868
14808
  } catch (error) {
14869
14809
  throw sessionReadFailure(error, "failed to read discovered evidence-child session");
14870
14810
  }
@@ -14893,33 +14833,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
14893
14833
  }
14894
14834
  const parentId = parentEntries.find((entry) => entry.type === "session")?.id;
14895
14835
  if (parentId === void 0) return void 0;
14896
- const isResumeEnvelopeBytes = (value) => {
14897
- if (typeof value !== "string") return false;
14898
- if (value.length === 0) return true;
14899
- const nl = value.indexOf("\n");
14900
- const firstLine = nl === -1 ? value : value.slice(0, nl);
14901
- const body = firstLine === "" && nl !== -1 ? value.slice(nl + 1) : value;
14902
- return body.startsWith("\u672C\u6B21\u914D\u7F6E\u7684\u52B3\u52A1\u5F15\u64CE\u53CA\u5176\u624B\u518C\uFF1A") || body.startsWith("- engine:");
14903
- };
14904
- const isResumeEnvelope = (msg) => {
14905
- if (!isRecord11(msg) || msg.role !== "user") return false;
14906
- const text = typeof msg.text === "string" ? msg.text : typeof msg.content === "string" ? msg.content : void 0;
14907
- if (isResumeEnvelopeBytes(text)) return true;
14908
- const content = msg.content;
14909
- if (Array.isArray(content)) {
14910
- return content.some((p) => isRecord11(p) && (isResumeEnvelopeBytes(p.text) || isResumeEnvelopeBytes(p.content)));
14911
- }
14912
- return false;
14913
- };
14914
- let latestParentUserIndex = -1;
14915
- for (let i = parentEntries.length - 1; i >= 0; i -= 1) {
14916
- const entry = parentEntries[i];
14917
- if (entry?.type !== "message" || entry.message?.role !== "user") continue;
14918
- if (isResumeEnvelope(entry.message)) continue;
14919
- latestParentUserIndex = i;
14920
- break;
14921
- }
14922
- const childDirectories = [join30(dirname15(sessionFile), "auditor-roles")];
14836
+ const childDirectories = [join29(dirname14(sessionFile), "auditor-roles")];
14923
14837
  const valid = [];
14924
14838
  let sawAnyDirectory = false;
14925
14839
  for (const childDirectory of childDirectories) {
@@ -14934,7 +14848,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
14934
14848
  for (const file of names.filter((name) => name.endsWith(".jsonl")).sort().reverse()) {
14935
14849
  let entries;
14936
14850
  try {
14937
- entries = await readBoundSessionEntries(join30(childDirectory, file));
14851
+ entries = await readBoundSessionEntries(join29(childDirectory, file));
14938
14852
  } catch (error) {
14939
14853
  throw sessionReadFailure(error, "failed to read discovered auditor session");
14940
14854
  }
@@ -14955,12 +14869,9 @@ async function loadBoundAuditorVolumes(sessionFile) {
14955
14869
  for (const { entry: bindingEntry, start, end } of bindingPasses) {
14956
14870
  const bindingParent = bindingEntry !== void 0 && isRecord11(bindingEntry.data) && isRecord11(bindingEntry.data.parent) ? bindingEntry.data.parent : void 0;
14957
14871
  const attemptEntryId = typeof bindingParent?.attemptEntryId === "string" ? bindingParent.attemptEntryId : void 0;
14958
- const attemptEntryIndex = attemptEntryId === void 0 ? -1 : parentEntries.findIndex((entry) => entry.id === attemptEntryId);
14959
14872
  const boundSessionFile = typeof bindingParent?.sessionFile === "string" ? bindingParent.sessionFile : typeof header.parentSession === "string" ? header.parentSession : void 0;
14960
14873
  if (boundSessionFile !== sessionFile) continue;
14961
- if (bindingParent !== void 0 && (bindingParent.sessionId !== parentId || attemptEntryIndex < latestParentUserIndex)) {
14962
- continue;
14963
- }
14874
+ if (bindingParent !== void 0 && bindingParent.sessionId !== parentId) continue;
14964
14875
  if (bindingParent === void 0 && header.parentSession !== sessionFile) continue;
14965
14876
  valid.push({
14966
14877
  entries: entries.slice(start, end),
@@ -15015,11 +14926,6 @@ function providerStopFallbackFromAuditorVolumes(volumes) {
15015
14926
  }
15016
14927
  return void 0;
15017
14928
  }
15018
- async function readBoundAuditorKnownFailure(sessionFile) {
15019
- const volumes = await loadBoundAuditorVolumes(sessionFile);
15020
- if (volumes === void 0) return void 0;
15021
- return complianceFailureFromAuditorVolumes(volumes) ?? providerStopFallbackFromAuditorVolumes(volumes);
15022
- }
15023
14929
  async function readBoundAuditorComplianceFailure(sessionFile) {
15024
14930
  const volumes = await loadBoundAuditorVolumes(sessionFile);
15025
14931
  if (volumes === void 0) return void 0;
@@ -15353,7 +15259,7 @@ async function appendRunAttemptHistory(source, outcome) {
15353
15259
  type: "custom",
15354
15260
  customType: ATTEMPT_HISTORY_ENTRY_TYPE,
15355
15261
  data: attemptData,
15356
- id: randomUUID5(),
15262
+ id: randomUUID4(),
15357
15263
  parentId,
15358
15264
  timestamp: timestamp2
15359
15265
  })}
@@ -15459,8 +15365,8 @@ function projectTerminalGateFact(rounds) {
15459
15365
  };
15460
15366
  }
15461
15367
  async function extractGateFactFromSessionDirectory(sessionDirectory, options = {}) {
15462
- const directories = [join30(sessionDirectory, "auditor-roles")];
15463
- const parentSessionFile = options.parentSessionFile ?? join30(sessionDirectory, "session.jsonl");
15368
+ const directories = [join29(sessionDirectory, "auditor-roles")];
15369
+ const parentSessionFile = options.parentSessionFile ?? join29(sessionDirectory, "session.jsonl");
15464
15370
  const rounds = await readAnalystGateCyclesFromAuditorRoles(directories, {
15465
15371
  parentSessionFile
15466
15372
  });
@@ -15590,9 +15496,9 @@ async function extractNavigatorFactFromAdmittedSession(sessionFile) {
15590
15496
  async function publishJudgeArtifacts(admitted, roleOutcome, coordinates) {
15591
15497
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
15592
15498
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
15593
- const reportPath = join30(artifactsDir, "report.json");
15594
- const evidencePath = join30(artifactsDir, "evidence.json");
15595
- await writeFile8(
15499
+ const reportPath = join29(artifactsDir, "report.json");
15500
+ const evidencePath = join29(artifactsDir, "evidence.json");
15501
+ await writeFile7(
15596
15502
  reportPath,
15597
15503
  `${JSON.stringify(
15598
15504
  {
@@ -15606,7 +15512,7 @@ async function publishJudgeArtifacts(admitted, roleOutcome, coordinates) {
15606
15512
  `,
15607
15513
  "utf8"
15608
15514
  );
15609
- await writeFile8(
15515
+ await writeFile7(
15610
15516
  evidencePath,
15611
15517
  `${JSON.stringify(
15612
15518
  {
@@ -15635,9 +15541,9 @@ async function publishJudgeArtifacts(admitted, roleOutcome, coordinates) {
15635
15541
  async function publishCoderArtifacts(admitted, roleOutcome, coordinates, options = {}) {
15636
15542
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
15637
15543
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
15638
- const reportPath = join30(artifactsDir, "report.json");
15639
- const evidencePath = join30(artifactsDir, "evidence.json");
15640
- await writeFile8(
15544
+ const reportPath = join29(artifactsDir, "report.json");
15545
+ const evidencePath = join29(artifactsDir, "evidence.json");
15546
+ await writeFile7(
15641
15547
  reportPath,
15642
15548
  `${JSON.stringify(
15643
15549
  {
@@ -15652,7 +15558,7 @@ async function publishCoderArtifacts(admitted, roleOutcome, coordinates, options
15652
15558
  `,
15653
15559
  "utf8"
15654
15560
  );
15655
- await writeFile8(
15561
+ await writeFile7(
15656
15562
  evidencePath,
15657
15563
  `${JSON.stringify(
15658
15564
  {
@@ -15793,9 +15699,9 @@ function extractFixerMethodInvocations(entries, options) {
15793
15699
  async function publishFixerArtifacts(admitted, roleOutcome, coordinates, options) {
15794
15700
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
15795
15701
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
15796
- const reportPath = join30(artifactsDir, "report.json");
15797
- const evidencePath = join30(artifactsDir, "evidence.json");
15798
- await writeFile8(
15702
+ const reportPath = join29(artifactsDir, "report.json");
15703
+ const evidencePath = join29(artifactsDir, "evidence.json");
15704
+ await writeFile7(
15799
15705
  reportPath,
15800
15706
  `${JSON.stringify(
15801
15707
  {
@@ -15810,7 +15716,7 @@ async function publishFixerArtifacts(admitted, roleOutcome, coordinates, options
15810
15716
  `,
15811
15717
  "utf8"
15812
15718
  );
15813
- await writeFile8(
15719
+ await writeFile7(
15814
15720
  evidencePath,
15815
15721
  `${JSON.stringify(
15816
15722
  {
@@ -15891,9 +15797,9 @@ async function settleFixerTerminalResult(admitted, authority, options, scope) {
15891
15797
  async function publishCollectorArtifacts(admitted, roleOutcome, coordinates) {
15892
15798
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
15893
15799
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
15894
- const reportPath = join30(artifactsDir, "report.json");
15895
- const evidencePath = join30(artifactsDir, "evidence.json");
15896
- await writeFile8(
15800
+ const reportPath = join29(artifactsDir, "report.json");
15801
+ const evidencePath = join29(artifactsDir, "evidence.json");
15802
+ await writeFile7(
15897
15803
  reportPath,
15898
15804
  `${JSON.stringify(
15899
15805
  {
@@ -15907,7 +15813,7 @@ async function publishCollectorArtifacts(admitted, roleOutcome, coordinates) {
15907
15813
  `,
15908
15814
  "utf8"
15909
15815
  );
15910
- await writeFile8(
15816
+ await writeFile7(
15911
15817
  evidencePath,
15912
15818
  `${JSON.stringify(
15913
15819
  {
@@ -16024,9 +15930,9 @@ function extractDoctorCandidateAuditNoReceiptFact(entries) {
16024
15930
  async function publishDoctorArtifacts(admitted, roleOutcome, coordinates, options = {}) {
16025
15931
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
16026
15932
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
16027
- const reportPath = join30(artifactsDir, "report.json");
16028
- const evidencePath = join30(artifactsDir, "evidence.json");
16029
- await writeFile8(
15933
+ const reportPath = join29(artifactsDir, "report.json");
15934
+ const evidencePath = join29(artifactsDir, "evidence.json");
15935
+ await writeFile7(
16030
15936
  reportPath,
16031
15937
  `${JSON.stringify(
16032
15938
  {
@@ -16042,7 +15948,7 @@ async function publishDoctorArtifacts(admitted, roleOutcome, coordinates, option
16042
15948
  `,
16043
15949
  "utf8"
16044
15950
  );
16045
- await writeFile8(
15951
+ await writeFile7(
16046
15952
  evidencePath,
16047
15953
  `${JSON.stringify(
16048
15954
  {
@@ -16320,9 +16226,9 @@ function extractReviewerMethodInvocations(entries, options) {
16320
16226
  async function publishReviewerArtifacts(admitted, roleOutcome, coordinates, options) {
16321
16227
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
16322
16228
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
16323
- const reportPath = join30(artifactsDir, "report.json");
16324
- const evidencePath = join30(artifactsDir, "evidence.json");
16325
- await writeFile8(
16229
+ const reportPath = join29(artifactsDir, "report.json");
16230
+ const evidencePath = join29(artifactsDir, "evidence.json");
16231
+ await writeFile7(
16326
16232
  reportPath,
16327
16233
  `${JSON.stringify(
16328
16234
  {
@@ -16336,7 +16242,7 @@ async function publishReviewerArtifacts(admitted, roleOutcome, coordinates, opti
16336
16242
  `,
16337
16243
  "utf8"
16338
16244
  );
16339
- await writeFile8(
16245
+ await writeFile7(
16340
16246
  evidencePath,
16341
16247
  `${JSON.stringify(
16342
16248
  {
@@ -16435,9 +16341,9 @@ function extractMergerMethodInvocations(entries, options) {
16435
16341
  async function publishMergerArtifacts(admitted, roleOutcome, coordinates, options) {
16436
16342
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
16437
16343
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
16438
- const reportPath = join30(artifactsDir, "report.json");
16439
- const evidencePath = join30(artifactsDir, "evidence.json");
16440
- await writeFile8(
16344
+ const reportPath = join29(artifactsDir, "report.json");
16345
+ const evidencePath = join29(artifactsDir, "evidence.json");
16346
+ await writeFile7(
16441
16347
  reportPath,
16442
16348
  `${JSON.stringify(
16443
16349
  {
@@ -16451,7 +16357,7 @@ async function publishMergerArtifacts(admitted, roleOutcome, coordinates, option
16451
16357
  `,
16452
16358
  "utf8"
16453
16359
  );
16454
- await writeFile8(
16360
+ await writeFile7(
16455
16361
  evidencePath,
16456
16362
  `${JSON.stringify(
16457
16363
  {
@@ -16570,7 +16476,7 @@ function publicationAttemptFromError(path, error) {
16570
16476
  }
16571
16477
  function uniqueFailureFallbackDirs(runDirectory, baseDir) {
16572
16478
  const dirs = [];
16573
- for (const dir of [baseDir, runDirectory, dirname15(runDirectory)]) {
16479
+ for (const dir of [baseDir, runDirectory, dirname14(runDirectory)]) {
16574
16480
  if (!dirs.includes(dir)) dirs.push(dir);
16575
16481
  }
16576
16482
  return dirs;
@@ -16592,13 +16498,13 @@ async function writeFailureJsonRetainingCause(preferredCandidates, uniqueFallbac
16592
16498
  const candidates = [
16593
16499
  ...preferredCandidates,
16594
16500
  // One unique name per fallback dir — collisions on fixed names cannot exhaust this.
16595
- ...uniqueFallbackDirs.map((dir) => join30(dir, `${stem}.${randomUUID5()}.json`))
16501
+ ...uniqueFallbackDirs.map((dir) => join29(dir, `${stem}.${randomUUID4()}.json`))
16596
16502
  ];
16597
16503
  for (let i = 0; i < candidates.length; i += 1) {
16598
16504
  const path = candidates[i];
16599
16505
  const payload = issues.length === 0 ? basePayload : { ...basePayload, publicationIssues: issues };
16600
16506
  try {
16601
- await writeFile8(
16507
+ await writeFile7(
16602
16508
  path,
16603
16509
  `${JSON.stringify(payload, null, 2)}
16604
16510
  `,
@@ -16643,20 +16549,20 @@ async function publishFailureArtifacts(admitted, failure2, authority) {
16643
16549
  baseDir
16644
16550
  );
16645
16551
  const errorCandidates = underArtifacts ? [
16646
- join30(baseDir, "error.json"),
16647
- join30(baseDir, "error.settlement.json"),
16648
- join30(admitted.runDirectory, "error.settlement.json")
16552
+ join29(baseDir, "error.json"),
16553
+ join29(baseDir, "error.settlement.json"),
16554
+ join29(admitted.runDirectory, "error.settlement.json")
16649
16555
  ] : [
16650
- join30(baseDir, "error.settlement.json"),
16651
- join30(baseDir, "error.json")
16556
+ join29(baseDir, "error.settlement.json"),
16557
+ join29(baseDir, "error.json")
16652
16558
  ];
16653
16559
  const evidenceCandidates = underArtifacts ? [
16654
- join30(baseDir, "evidence.json"),
16655
- join30(baseDir, "evidence.settlement.json"),
16656
- join30(admitted.runDirectory, "evidence.settlement.json")
16560
+ join29(baseDir, "evidence.json"),
16561
+ join29(baseDir, "evidence.settlement.json"),
16562
+ join29(admitted.runDirectory, "evidence.settlement.json")
16657
16563
  ] : [
16658
- join30(baseDir, "evidence.settlement.json"),
16659
- join30(baseDir, "evidence.json")
16564
+ join29(baseDir, "evidence.settlement.json"),
16565
+ join29(baseDir, "evidence.json")
16660
16566
  ];
16661
16567
  const errorPayloadBase = {
16662
16568
  kind: "error",
@@ -16944,17 +16850,17 @@ var init_seat_ticket_binding = __esm({
16944
16850
  });
16945
16851
 
16946
16852
  // src/session-identity.ts
16947
- import { mkdir as mkdir3, readFile as readFile18, rename as rename3, writeFile as writeFile9 } from "node:fs/promises";
16948
- import { dirname as dirname16, join as join31 } from "node:path";
16853
+ import { mkdir as mkdir3, readFile as readFile17, rename as rename2, writeFile as writeFile8 } from "node:fs/promises";
16854
+ import { dirname as dirname15, join as join30 } from "node:path";
16949
16855
  function createSessionIdentityAuthority(authority, sessionBindingFile) {
16950
- const bindingPath = (principal) => join31(authority.decode(principal).sessionDirectory, sessionBindingFile);
16856
+ const bindingPath = (principal) => join30(authority.decode(principal).sessionDirectory, sessionBindingFile);
16951
16857
  return {
16952
16858
  resolveSessionFile(principal) {
16953
16859
  return authority.decode(principal).sessionFile;
16954
16860
  },
16955
16861
  async load(principal) {
16956
16862
  try {
16957
- const value = JSON.parse(await readFile18(bindingPath(principal), "utf8"));
16863
+ const value = JSON.parse(await readFile17(bindingPath(principal), "utf8"));
16958
16864
  if (typeof value !== "object" || value === null || typeof value.sessionId !== "string") {
16959
16865
  throw new Error("durable session binding is invalid");
16960
16866
  }
@@ -16966,11 +16872,11 @@ function createSessionIdentityAuthority(authority, sessionBindingFile) {
16966
16872
  },
16967
16873
  async bind(principal, sessionId) {
16968
16874
  const target = bindingPath(principal);
16969
- await mkdir3(dirname16(target), { recursive: true });
16875
+ await mkdir3(dirname15(target), { recursive: true });
16970
16876
  const temporary = `${target}.${process.pid}.tmp`;
16971
- await writeFile9(temporary, `${JSON.stringify({ sessionId })}
16877
+ await writeFile8(temporary, `${JSON.stringify({ sessionId })}
16972
16878
  `, { encoding: "utf8", mode: 384 });
16973
- await rename3(temporary, target);
16879
+ await rename2(temporary, target);
16974
16880
  }
16975
16881
  };
16976
16882
  }
@@ -17058,6 +16964,23 @@ function fromQueueEvent(row) {
17058
16964
  const id = nativeEventId(row);
17059
16965
  return [{ speaker: "owner", text: content, ...id === void 0 ? {} : { id } }];
17060
16966
  }
16967
+ function hasFixedOpenTagPrefix(content, tag) {
16968
+ if (!content.startsWith(tag)) return false;
16969
+ const next = content.charAt(tag.length);
16970
+ return next === "" || next === ">" || next === " " || next === " " || next === "\n" || next === "\r";
16971
+ }
16972
+ function isFixedNonOwnerEnqueueShape(content) {
16973
+ return hasFixedOpenTagPrefix(content, TASK_NOTIFICATION_OPEN_TAG);
16974
+ }
16975
+ function materializationOriginKind(row) {
16976
+ if (!isRecord12(row.origin)) return void 0;
16977
+ const kind = row.origin.kind;
16978
+ return typeof kind === "string" && kind !== "" ? kind : void 0;
16979
+ }
16980
+ function isNonOwnerOriginKind(kind) {
16981
+ if (kind === void 0) return false;
16982
+ return kind !== "human";
16983
+ }
17061
16984
  function fromMessageEvent(row) {
17062
16985
  const message = messageBody(row);
17063
16986
  if (message === void 0) return [];
@@ -17074,78 +16997,45 @@ function fromMessageEvent(row) {
17074
16997
  const id = nativeEventId(row);
17075
16998
  return [{ speaker, text, ...id === void 0 ? {} : { id } }];
17076
16999
  }
17077
- function isOwnerDialogueMessage(row) {
17078
- if (row.type === "response_item" || row.type === "event_msg") return false;
17079
- return fromMessageEvent(row).some((event) => event.speaker === "owner");
17080
- }
17081
- function isRunnerMessage(row) {
17082
- const message = messageBody(row);
17083
- return message !== void 0 && message.role === "assistant";
17084
- }
17085
- function ownerMessagesMaterializingQueue(rows) {
17086
- const skip = /* @__PURE__ */ new Set();
17087
- const retainedByEnqueue = [];
17088
- let pendingSkips = 0;
17089
- for (let index = 0; index < rows.length; index += 1) {
17090
- const row = rows[index];
17091
- if (row === void 0) continue;
17092
- if (row.type === "queue-operation") {
17093
- if (row.operation === "enqueue") {
17094
- retainedByEnqueue.push(fromQueueEvent(row).length > 0);
17095
- continue;
17096
- }
17097
- if (row.operation === "dequeue" || row.operation === "remove") {
17098
- const retained = retainedByEnqueue.shift();
17099
- if (row.operation === "dequeue" && retained === true) {
17100
- pendingSkips += 1;
17101
- }
17102
- continue;
17103
- }
17104
- }
17105
- if (isRunnerMessage(row)) {
17106
- pendingSkips = 0;
17107
- continue;
17108
- }
17109
- if (pendingSkips > 0 && isOwnerDialogueMessage(row)) {
17110
- skip.add(index);
17111
- pendingSkips -= 1;
17112
- }
17113
- }
17114
- return skip;
17115
- }
17116
17000
  function adaptSessionDialogue(rows) {
17117
- const skipOwner = ownerMessagesMaterializingQueue(rows);
17118
- return rows.map((row, index) => {
17001
+ return rows.map((row) => {
17119
17002
  if (row === void 0) return [];
17003
+ const originKind = materializationOriginKind(row);
17004
+ if (isNonOwnerOriginKind(originKind)) return [];
17005
+ if (row.type === "queue-operation" && row.operation === "enqueue" && typeof row.content === "string" && isFixedNonOwnerEnqueueShape(row.content)) {
17006
+ return [];
17007
+ }
17120
17008
  const queued = fromQueueEvent(row);
17121
17009
  if (queued.length > 0) return queued;
17122
- if (skipOwner.has(index)) return [];
17123
17010
  return fromMessageEvent(row);
17124
17011
  });
17125
17012
  }
17126
- var SPEAKER_TEXT_PART_TYPES;
17013
+ var SPEAKER_TEXT_PART_TYPES, TASK_NOTIFICATION_OPEN_TAG;
17127
17014
  var init_session_dialogue = __esm({
17128
17015
  "src/session-dialogue.ts"() {
17129
17016
  "use strict";
17130
17017
  SPEAKER_TEXT_PART_TYPES = /* @__PURE__ */ new Set(["text", "input_text", "output_text"]);
17018
+ TASK_NOTIFICATION_OPEN_TAG = "<task-notification";
17131
17019
  }
17132
17020
  });
17133
17021
 
17134
17022
  // src/ticket-provenance.ts
17135
- import { basename as basename8, dirname as dirname17, join as join32, resolve as resolve12 } from "node:path";
17023
+ import { createHash as createHash8 } from "node:crypto";
17024
+ import { readFile as readFile18 } from "node:fs/promises";
17025
+ import { basename as basename8, dirname as dirname16, join as join31, resolve as resolve12 } from "node:path";
17136
17026
  function dialogueSessionSourceRoots(home) {
17137
17027
  const machineHome = typeof home === "string" && home.trim() !== "" ? home : packageMachineHome();
17138
17028
  return [
17139
- join32(machineHome, ".claude", "projects"),
17140
- join32(machineHome, ".codex", "sessions"),
17141
- join32(machineHome, ".pi", "agent", "sessions")
17029
+ join31(machineHome, ".claude", "projects"),
17030
+ join31(machineHome, ".codex", "sessions"),
17031
+ join31(machineHome, ".pi", "agent", "sessions")
17142
17032
  ];
17143
17033
  }
17144
17034
  function isLedgerRoleSessionFile(absolute, home) {
17145
17035
  const machineHome = typeof home === "string" && home.trim() !== "" ? home : packageMachineHome();
17146
17036
  const ledgerHome = resolveActivationLedgerHome(machineHome);
17147
17037
  if (!physicallyContainedIn(ledgerHome, absolute)) return false;
17148
- return basename8(absolute) === "session.jsonl" && basename8(dirname17(absolute)) === "session";
17038
+ return basename8(absolute) === "session.jsonl" && basename8(dirname16(absolute)) === "session";
17149
17039
  }
17150
17040
  function assertDialogueSessionSourcePath(path, home) {
17151
17041
  const absolute = resolve12(path);
@@ -17175,18 +17065,46 @@ function ticketProvenanceRecordInput(ticketNumber, cwd, home) {
17175
17065
  };
17176
17066
  }
17177
17067
  function resolveTicketProvenanceVolume(ticketNumber, cwd, home) {
17178
- return resolveSitianVolume(ticketProvenanceRecordInput(ticketNumber, cwd, home));
17179
- }
17180
- async function readTicketProvenance(ticketNumber, cwd, home) {
17181
- const { recordFile, text } = await readSitianVolumeText(
17068
+ const path = resolveSitianRecordPath(
17182
17069
  ticketProvenanceRecordInput(ticketNumber, cwd, home)
17183
17070
  );
17184
- if (text === void 0) {
17185
- return { header: void 0, lines: [], recordFile };
17071
+ return { recordFile: path.recordFile, volumeDir: path.sessionDir };
17072
+ }
17073
+ function projectTicketProvenanceCommit(value) {
17074
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
17075
+ const record4 = value;
17076
+ if (record4.kind !== TICKET_PROVENANCE_KIND || typeof record4.timestamp !== "string") {
17077
+ return void 0;
17078
+ }
17079
+ const payload = record4.payload;
17080
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return void 0;
17081
+ const body = payload;
17082
+ if (body.type !== "ticket-provenance-append") return void 0;
17083
+ const sessions = projectTicketProvenanceSessions(body.sessions);
17084
+ if (sessions === void 0 || !Array.isArray(body.lines)) return void 0;
17085
+ const lines = [];
17086
+ for (const raw of body.lines) {
17087
+ const line2 = projectTicketProvenanceLine(raw);
17088
+ if (line2 === void 0) return void 0;
17089
+ lines.push(line2);
17090
+ }
17091
+ return { timestamp: record4.timestamp, sessions, lines };
17092
+ }
17093
+ async function readTicketProvenance(ticketNumber, cwd, home) {
17094
+ const { recordFile } = resolveTicketProvenanceVolume(ticketNumber, cwd, home);
17095
+ let text;
17096
+ try {
17097
+ text = await readFile18(recordFile, "utf8");
17098
+ } catch (error) {
17099
+ if (error.code === "ENOENT") {
17100
+ return { header: void 0, lines: [], unprojectedRaw: [], recordFile };
17101
+ }
17102
+ throw error;
17186
17103
  }
17187
17104
  const physical = text.split("\n");
17188
17105
  let header;
17189
17106
  const lines = [];
17107
+ const unprojectedRaw = [];
17190
17108
  let sawFirst = false;
17191
17109
  for (let index = 0; index < physical.length; index += 1) {
17192
17110
  const raw = physical[index];
@@ -17195,6 +17113,7 @@ async function readTicketProvenance(ticketNumber, cwd, home) {
17195
17113
  try {
17196
17114
  parsed = JSON.parse(raw);
17197
17115
  } catch {
17116
+ unprojectedRaw.push(raw);
17198
17117
  continue;
17199
17118
  }
17200
17119
  if (!sawFirst) {
@@ -17203,9 +17122,35 @@ async function readTicketProvenance(ticketNumber, cwd, home) {
17203
17122
  if (header !== void 0) continue;
17204
17123
  }
17205
17124
  const line2 = projectTicketProvenanceLine(parsed);
17206
- if (line2 !== void 0) lines.push(line2);
17125
+ if (line2 !== void 0) {
17126
+ lines.push(line2);
17127
+ continue;
17128
+ }
17129
+ const commit = projectTicketProvenanceCommit(parsed);
17130
+ if (commit !== void 0) {
17131
+ const merged = mergeSessionBounds(header?.sessions, commit.sessions);
17132
+ const remapped = commit.lines.map((entry) => ({
17133
+ ...entry,
17134
+ s: merged.incomingIndexes[entry.s] ?? entry.s
17135
+ }));
17136
+ const now = commit.timestamp;
17137
+ header = {
17138
+ repo: header?.repo ?? resolveBookKeyFromGit(cwd),
17139
+ ticket: ticketNumber,
17140
+ createdAt: header?.createdAt ?? now,
17141
+ updatedAt: now,
17142
+ sessions: merged.sessions
17143
+ };
17144
+ const carried = lines.map((entry) => ({
17145
+ ...entry,
17146
+ s: merged.priorIndexes[entry.s] ?? entry.s
17147
+ }));
17148
+ lines.splice(0, lines.length, ...mergeFreshIntoCarried(carried, remapped));
17149
+ continue;
17150
+ }
17151
+ unprojectedRaw.push(raw);
17207
17152
  }
17208
- return { header, lines, recordFile };
17153
+ return { header, lines, unprojectedRaw, recordFile };
17209
17154
  }
17210
17155
  function resolveBoundIndex(bound, sessionLines) {
17211
17156
  if (typeof bound.id === "string" && bound.id !== "") {
@@ -17227,6 +17172,104 @@ function resolveBoundIndex(bound, sessionLines) {
17227
17172
  function amendmentKey(s, line2) {
17228
17173
  return `${s}:${line2}`;
17229
17174
  }
17175
+ function rangeDeclarationKey(range) {
17176
+ return JSON.stringify({
17177
+ from: range.from,
17178
+ to: range.to
17179
+ });
17180
+ }
17181
+ function mergeSessionBounds(prior, incoming) {
17182
+ const merged = [];
17183
+ const indexByIdentity = /* @__PURE__ */ new Map();
17184
+ const absorb = (sessions) => {
17185
+ const indexes = [];
17186
+ for (const session of sessions) {
17187
+ const identity = physicalPathIdentity(session.path);
17188
+ let targetIndex = indexByIdentity.get(identity);
17189
+ if (targetIndex === void 0) {
17190
+ targetIndex = merged.length;
17191
+ indexByIdentity.set(identity, targetIndex);
17192
+ merged.push({ path: session.path, ranges: [] });
17193
+ }
17194
+ indexes.push(targetIndex);
17195
+ const target = merged[targetIndex];
17196
+ const seen = new Set(target.ranges.map(rangeDeclarationKey));
17197
+ for (const range of session.ranges) {
17198
+ const key = rangeDeclarationKey(range);
17199
+ if (seen.has(key)) continue;
17200
+ seen.add(key);
17201
+ target.ranges.push({ from: { ...range.from }, to: { ...range.to } });
17202
+ }
17203
+ }
17204
+ return indexes;
17205
+ };
17206
+ const priorIndexes = absorb(prior ?? []);
17207
+ const incomingIndexes = absorb(incoming);
17208
+ return { sessions: merged, priorIndexes, incomingIndexes };
17209
+ }
17210
+ function undeclaredSessionRanges(prior, merged) {
17211
+ const priorKeys = /* @__PURE__ */ new Map();
17212
+ for (const session of prior ?? []) {
17213
+ const identity = physicalPathIdentity(session.path);
17214
+ let keys = priorKeys.get(identity);
17215
+ if (keys === void 0) {
17216
+ keys = /* @__PURE__ */ new Set();
17217
+ priorKeys.set(identity, keys);
17218
+ }
17219
+ for (const range of session.ranges) keys.add(rangeDeclarationKey(range));
17220
+ }
17221
+ const out = [];
17222
+ for (let s = 0; s < merged.length; s += 1) {
17223
+ const session = merged[s];
17224
+ const declared = priorKeys.get(physicalPathIdentity(session.path)) ?? /* @__PURE__ */ new Set();
17225
+ const fresh = session.ranges.filter(
17226
+ (range) => !declared.has(rangeDeclarationKey(range))
17227
+ );
17228
+ if (fresh.length === 0) continue;
17229
+ out.push({
17230
+ s,
17231
+ session: {
17232
+ path: session.path,
17233
+ ranges: fresh.map((range) => ({
17234
+ from: { ...range.from },
17235
+ to: { ...range.to }
17236
+ }))
17237
+ }
17238
+ });
17239
+ }
17240
+ return out;
17241
+ }
17242
+ function compareLinePosition(left, right) {
17243
+ if (left.s !== right.s) return left.s - right.s;
17244
+ const leftLine = left.line ?? Number.MAX_SAFE_INTEGER;
17245
+ const rightLine = right.line ?? Number.MAX_SAFE_INTEGER;
17246
+ return leftLine - rightLine;
17247
+ }
17248
+ function mergeFreshIntoCarried(carried, fresh) {
17249
+ const seenIds = /* @__PURE__ */ new Set();
17250
+ const seenPositions = /* @__PURE__ */ new Set();
17251
+ const out = [];
17252
+ for (const line2 of carried) {
17253
+ if (line2.id !== void 0) seenIds.add(line2.id);
17254
+ if (line2.line !== void 0)
17255
+ seenPositions.add(amendmentKey(line2.s, line2.line));
17256
+ out.push(line2);
17257
+ }
17258
+ for (const line2 of fresh) {
17259
+ if (line2.id !== void 0) {
17260
+ if (seenIds.has(line2.id)) continue;
17261
+ seenIds.add(line2.id);
17262
+ }
17263
+ if (line2.line !== void 0) {
17264
+ const position = amendmentKey(line2.s, line2.line);
17265
+ if (seenPositions.has(position)) continue;
17266
+ seenPositions.add(position);
17267
+ }
17268
+ out.push(line2);
17269
+ }
17270
+ out.sort(compareLinePosition);
17271
+ return out;
17272
+ }
17230
17273
  function normalizeResolvedRanges(ranges, sessionLines, sessionPath) {
17231
17274
  const resolved = [];
17232
17275
  for (const range of ranges) {
@@ -17321,84 +17364,101 @@ async function projectSessionRanges(input) {
17321
17364
  return { lines, unparsable };
17322
17365
  }
17323
17366
  async function reprojectTicketProvenance(input) {
17324
- const recordInput = ticketProvenanceRecordInput(
17325
- input.ticketNumber,
17326
- input.cwd,
17327
- input.home
17328
- );
17329
17367
  const prior = await readTicketProvenance(input.ticketNumber, input.cwd, input.home);
17330
- const priorRaw = await readSitianVolumeText(recordInput);
17331
- const priorNonEmpty = priorRaw.text !== void 0 && priorRaw.text.trim() !== "";
17332
- const amendments = input.amendments ?? [];
17333
- let sessions = input.sessions;
17334
- if (sessions.length === 0) {
17335
- if (amendments.length > 0) {
17336
- const priorSessions = prior.header?.sessions;
17337
- if (priorSessions === void 0 || priorSessions.length === 0) {
17338
- throw new TicketProvenanceInputError(
17339
- "amendments require sessions bounds (none submitted and no prior header sessions)"
17340
- );
17341
- }
17342
- sessions = priorSessions;
17343
- } else if (priorNonEmpty) {
17344
- const now2 = (/* @__PURE__ */ new Date()).toISOString();
17345
- const header2 = prior.header ?? {
17368
+ if (input.sessions.length === 0) {
17369
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
17370
+ return {
17371
+ recordFile: prior.recordFile,
17372
+ header: prior.header ?? {
17346
17373
  repo: resolveBookKeyFromGit(input.cwd),
17347
17374
  ticket: input.ticketNumber,
17348
17375
  createdAt: now2,
17349
17376
  updatedAt: now2,
17350
17377
  sessions: []
17351
- };
17352
- return {
17353
- recordFile: prior.recordFile,
17354
- header: header2,
17355
- lines: prior.lines,
17356
- unparsable: []
17357
- };
17358
- }
17378
+ },
17379
+ lines: prior.lines,
17380
+ unparsable: []
17381
+ };
17382
+ }
17383
+ const merged = mergeSessionBounds(prior.header?.sessions, input.sessions);
17384
+ const deltas = undeclaredSessionRanges(prior.header?.sessions, merged.sessions);
17385
+ if (deltas.length === 0) {
17386
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
17387
+ return {
17388
+ recordFile: prior.recordFile,
17389
+ header: prior.header ?? {
17390
+ repo: resolveBookKeyFromGit(input.cwd),
17391
+ ticket: input.ticketNumber,
17392
+ createdAt: now2,
17393
+ updatedAt: now2,
17394
+ sessions: merged.sessions
17395
+ },
17396
+ lines: prior.lines,
17397
+ unparsable: []
17398
+ };
17359
17399
  }
17360
17400
  const amendmentsByKey = /* @__PURE__ */ new Map();
17361
- for (const amendment of amendments) {
17362
- amendmentsByKey.set(amendmentKey(amendment.s, amendment.line), amendment);
17401
+ for (const amendment of input.amendments ?? []) {
17402
+ const cumulativeIndex = merged.incomingIndexes[amendment.s];
17403
+ if (cumulativeIndex === void 0) continue;
17404
+ amendmentsByKey.set(amendmentKey(cumulativeIndex, amendment.line), {
17405
+ ...amendment,
17406
+ s: cumulativeIndex
17407
+ });
17363
17408
  }
17364
- const lines = [];
17409
+ const seenIds = new Set(
17410
+ prior.lines.flatMap((line2) => line2.id === void 0 ? [] : [line2.id])
17411
+ );
17412
+ const fresh = [];
17365
17413
  const unparsable = [];
17366
- const seenIds = /* @__PURE__ */ new Set();
17367
- for (let s = 0; s < sessions.length; s += 1) {
17414
+ for (const delta of deltas) {
17368
17415
  const projected = await projectSessionRanges({
17369
- s,
17370
- session: sessions[s],
17416
+ s: delta.s,
17417
+ session: delta.session,
17371
17418
  amendmentsByKey,
17372
17419
  seenIds,
17373
17420
  ...input.home === void 0 ? {} : { home: input.home }
17374
17421
  });
17375
- lines.push(...projected.lines);
17422
+ fresh.push(...projected.lines);
17376
17423
  unparsable.push(...projected.unparsable);
17377
17424
  }
17425
+ const lines = mergeFreshIntoCarried(prior.lines, fresh);
17378
17426
  const now = (/* @__PURE__ */ new Date()).toISOString();
17379
17427
  const header = {
17380
- repo: resolveBookKeyFromGit(input.cwd),
17428
+ repo: prior.header?.repo ?? resolveBookKeyFromGit(input.cwd),
17381
17429
  ticket: input.ticketNumber,
17382
17430
  createdAt: prior.header?.createdAt ?? now,
17383
17431
  updatedAt: now,
17384
- sessions
17432
+ sessions: merged.sessions
17385
17433
  };
17386
17434
  if (unparsable.length > 0) {
17387
- return {
17388
- recordFile: prior.recordFile,
17389
- header,
17390
- lines,
17391
- unparsable
17392
- };
17435
+ return { recordFile: prior.recordFile, header, lines, unparsable };
17393
17436
  }
17394
- const body = `${[JSON.stringify(header), ...lines.map((line2) => JSON.stringify(line2))].join("\n")}
17395
- `;
17396
- const volume = await rewriteSitianVolume({ ...recordInput, body });
17437
+ const identityMaterial = JSON.stringify({
17438
+ ticket: input.ticketNumber,
17439
+ deltas: deltas.map(({ s, session }) => ({
17440
+ s,
17441
+ path: physicalPathIdentity(session.path),
17442
+ ranges: session.ranges
17443
+ })),
17444
+ lines: fresh
17445
+ });
17446
+ const identity = `ticket-provenance:${createHash8("sha256").update(identityMaterial).digest("hex")}`;
17447
+ const pointer = appendSitianRecord({
17448
+ ...ticketProvenanceRecordInput(input.ticketNumber, input.cwd, input.home),
17449
+ identity,
17450
+ payload: {
17451
+ type: "ticket-provenance-append",
17452
+ sessions: merged.sessions,
17453
+ lines: fresh
17454
+ }
17455
+ });
17456
+ const folded = await readTicketProvenance(input.ticketNumber, input.cwd, input.home);
17397
17457
  return {
17398
- recordFile: volume.recordFile,
17399
- header,
17400
- lines,
17401
- unparsable
17458
+ recordFile: pointer.recordFile,
17459
+ header: folded.header ?? header,
17460
+ lines: folded.lines,
17461
+ unparsable: []
17402
17462
  };
17403
17463
  }
17404
17464
  var TicketProvenanceInputError;
@@ -17432,14 +17492,17 @@ __export(case_dossier_delivery_exports, {
17432
17492
  loadCaseDossierReadingMaterial: () => loadCaseDossierReadingMaterial,
17433
17493
  projectCaseDossierPointerSection: () => projectCaseDossierPointerSection
17434
17494
  });
17435
- import { mkdtemp as mkdtemp2, readFile as readFile19, rm as rm3, writeFile as writeFile10 } from "node:fs/promises";
17495
+ import { mkdtemp as mkdtemp2, readFile as readFile19, rm as rm2, writeFile as writeFile9 } from "node:fs/promises";
17436
17496
  import { tmpdir as tmpdir2 } from "node:os";
17437
- import { join as join33 } from "node:path";
17438
- function describeDossierFile(path) {
17439
- return path;
17440
- }
17497
+ import { join as join32 } from "node:path";
17441
17498
  async function projectCaseDossierPointerSection(input) {
17442
- if (input.ticketNumber === void 0) return void 0;
17499
+ if (input.ticketNumber === void 0) {
17500
+ return [
17501
+ UNBOUND_DOSSIER_PATH_HEADING,
17502
+ "",
17503
+ `\u8BB0\u5F55\u5377\u5B97\uFF1A${projectTicketRecordsPathShape()}`
17504
+ ].join("\n");
17505
+ }
17443
17506
  const volume = resolveTicketProvenanceVolume(
17444
17507
  input.ticketNumber,
17445
17508
  input.projectRoot,
@@ -17449,7 +17512,7 @@ async function projectCaseDossierPointerSection(input) {
17449
17512
  CASE_DOSSIER_SECTION_HEADING,
17450
17513
  "",
17451
17514
  `\u7968\u53F7\uFF1A#${input.ticketNumber}`,
17452
- `\u8BB0\u5F55\u5377\u5B97\uFF1A${describeDossierFile(volume.recordFile)}`
17515
+ `\u8BB0\u5F55\u5377\u5B97\uFF1A${volume.recordFile}`
17453
17516
  ].join("\n");
17454
17517
  }
17455
17518
  async function deliverCaseDossierAsAttachment(input) {
@@ -17458,11 +17521,10 @@ async function deliverCaseDossierAsAttachment(input) {
17458
17521
  projectRoot: input.projectRoot,
17459
17522
  home: input.home
17460
17523
  });
17461
- if (section === void 0) return void 0;
17462
- const stagingDir = await mkdtemp2(join33(tmpdir2(), "ak-case-dossier-"));
17524
+ const stagingDir = await mkdtemp2(join32(tmpdir2(), "ak-case-dossier-"));
17463
17525
  try {
17464
- const stagingPath = join33(stagingDir, CASE_DOSSIER_ATTACH_FILE);
17465
- await writeFile10(stagingPath, `${section}
17526
+ const stagingPath = join32(stagingDir, CASE_DOSSIER_ATTACH_FILE);
17527
+ await writeFile9(stagingPath, `${section}
17466
17528
  `, "utf8");
17467
17529
  return await freezeAttachmentsIntoRun(
17468
17530
  [stagingPath],
@@ -17470,11 +17532,11 @@ async function deliverCaseDossierAsAttachment(input) {
17470
17532
  CASE_DOSSIER_ATTACH_KEY
17471
17533
  );
17472
17534
  } finally {
17473
- await rm3(stagingDir, { recursive: true, force: true });
17535
+ await rm2(stagingDir, { recursive: true, force: true });
17474
17536
  }
17475
17537
  }
17476
17538
  async function loadCaseDossierReadingMaterial(runDirectory) {
17477
- const frozenPath = join33(
17539
+ const frozenPath = join32(
17478
17540
  runDirectory,
17479
17541
  "attachments",
17480
17542
  CASE_DOSSIER_ATTACH_KEY,
@@ -17490,13 +17552,15 @@ async function loadCaseDossierReadingMaterial(runDirectory) {
17490
17552
  if (section.trim() === "") return void 0;
17491
17553
  return { kind: "case-dossier-pointer", frozenPath, section };
17492
17554
  }
17493
- var CASE_DOSSIER_SECTION_HEADING, CASE_DOSSIER_ATTACH_KEY, CASE_DOSSIER_ATTACH_FILE;
17555
+ var CASE_DOSSIER_SECTION_HEADING, UNBOUND_DOSSIER_PATH_HEADING, CASE_DOSSIER_ATTACH_KEY, CASE_DOSSIER_ATTACH_FILE;
17494
17556
  var init_case_dossier_delivery = __esm({
17495
17557
  "src/public-cli/case-dossier-delivery.ts"() {
17496
17558
  "use strict";
17559
+ init_sitian_facade();
17497
17560
  init_ticket_provenance();
17498
17561
  init_invocation();
17499
17562
  CASE_DOSSIER_SECTION_HEADING = "## \u672C\u7968\u8D77\u5C45\u5F55\uFF08\u7CFB\u7EDF\u968F\u6848\u63D0\u4F9B\uFF09";
17563
+ UNBOUND_DOSSIER_PATH_HEADING = "## \u8D77\u5C45\u5F55\u8DEF\u5F84\uFF08\u7CFB\u7EDF\u968F\u6848\u63D0\u4F9B\uFF09";
17500
17564
  CASE_DOSSIER_ATTACH_KEY = "case-dossier";
17501
17565
  CASE_DOSSIER_ATTACH_FILE = "case-dossier-pointer.md";
17502
17566
  }
@@ -17504,7 +17568,7 @@ var init_case_dossier_delivery = __esm({
17504
17568
 
17505
17569
  // src/host-transition-prior-native.ts
17506
17570
  import { access as access4, readdir as readdir7 } from "node:fs/promises";
17507
- import { dirname as dirname18, join as join34 } from "node:path";
17571
+ import { dirname as dirname17, join as join33 } from "node:path";
17508
17572
  function isEnoent3(error) {
17509
17573
  return typeof error === "object" && error !== null && error.code === "ENOENT";
17510
17574
  }
@@ -17518,7 +17582,7 @@ async function listPiNativeRecordPaths(sessionFile) {
17518
17582
  }
17519
17583
  }
17520
17584
  async function listSitianRecordPaths(sessionParent) {
17521
- const sessionRoot = dirname18(sessionParent);
17585
+ const sessionRoot = dirname17(sessionParent);
17522
17586
  let entries;
17523
17587
  try {
17524
17588
  entries = await readdir7(sessionRoot, { withFileTypes: true });
@@ -17529,7 +17593,7 @@ async function listSitianRecordPaths(sessionParent) {
17529
17593
  const recordPaths = [];
17530
17594
  for (const entry of entries) {
17531
17595
  if (!entry.isDirectory()) continue;
17532
- const recordFile = join34(sessionRoot, entry.name, "records.jsonl");
17596
+ const recordFile = join33(sessionRoot, entry.name, "records.jsonl");
17533
17597
  try {
17534
17598
  await access4(recordFile);
17535
17599
  recordPaths.push(recordFile);
@@ -17597,9 +17661,9 @@ var init_public_run_credentials = __esm({
17597
17661
 
17598
17662
  // src/public-cli/auto-resume.ts
17599
17663
  import { constants as fsConstants2 } from "node:fs";
17600
- import { randomUUID as randomUUID6 } from "node:crypto";
17664
+ import { randomUUID as randomUUID5 } from "node:crypto";
17601
17665
  import { lstat as lstat6, mkdir as mkdir4, open as open2 } from "node:fs/promises";
17602
- import { join as join35 } from "node:path";
17666
+ import { join as join34 } from "node:path";
17603
17667
  async function persistReturnedRunState(admitted, authority, options) {
17604
17668
  if (options?.lawful === true) {
17605
17669
  await markRunTerminal(admitted.runDirectory);
@@ -17714,7 +17778,7 @@ function jsonSafeReplacer() {
17714
17778
  };
17715
17779
  }
17716
17780
  async function writeHardenedArtifactFile(artifactsDir, namePrefix, payload) {
17717
- const filePath = join35(artifactsDir, `${namePrefix}-${randomUUID6()}.json`);
17781
+ const filePath = join34(artifactsDir, `${namePrefix}-${randomUUID5()}.json`);
17718
17782
  const body = `${JSON.stringify(payload, jsonSafeReplacer(), 2)}
17719
17783
  `;
17720
17784
  const noFollowFlag = typeof fsConstants2.O_NOFOLLOW === "number" ? fsConstants2.O_NOFOLLOW : 0;
@@ -17985,9 +18049,9 @@ var init_auto_resume = __esm({
17985
18049
  });
17986
18050
 
17987
18051
  // src/public-cli/post-admission.ts
17988
- import { randomUUID as randomUUID7 } from "node:crypto";
17989
- import { writeFile as writeFile11 } from "node:fs/promises";
17990
- import { isAbsolute as isAbsolute8, join as join36, resolve as resolve13 } from "node:path";
18052
+ import { randomUUID as randomUUID6 } from "node:crypto";
18053
+ import { writeFile as writeFile10 } from "node:fs/promises";
18054
+ import { isAbsolute as isAbsolute8, join as join35, resolve as resolve13 } from "node:path";
17991
18055
  function describeCaughtError(error) {
17992
18056
  if (error instanceof Error) {
17993
18057
  const code = error.code;
@@ -17995,12 +18059,6 @@ function describeCaughtError(error) {
17995
18059
  }
17996
18060
  return { message: String(error) };
17997
18061
  }
17998
- function appendContinuationSection(continuation, section) {
17999
- const prompt = `${continuation.prompt}
18000
-
18001
- ${section}`;
18002
- return continuation.kind === "initial" ? { kind: "initial", prompt } : { kind: "resume", prompt };
18003
- }
18004
18062
  function isStationChildOfficerDialogue(role, env) {
18005
18063
  return env.stationChild === true && isOfficerReviewSeat(role);
18006
18064
  }
@@ -18031,8 +18089,8 @@ async function recordBestEffortPostDispatchDiagnostic(admitted, env, diagnostic,
18031
18089
  } catch (appendError) {
18032
18090
  try {
18033
18091
  const artifactsDir = await ensureRealArtifactsDirectory(admitted.runDirectory);
18034
- await writeFile11(
18035
- join36(artifactsDir, `post-admission-diagnostic-${randomUUID7()}.json`),
18092
+ await writeFile10(
18093
+ join35(artifactsDir, `post-admission-diagnostic-${randomUUID6()}.json`),
18036
18094
  `${JSON.stringify({ version: 1, ...payload }, null, 2)}
18037
18095
  `,
18038
18096
  { encoding: "utf8", flag: "wx" }
@@ -18138,10 +18196,24 @@ async function dispatchPostAdmissionTurn(input) {
18138
18196
  const shouldPresent = adapters.shouldPresentSettled ?? ((terminal) => isLawfulTypedTerminalOutcome(terminal.roleOutcome));
18139
18197
  let afterDispatchApplied = false;
18140
18198
  const finishAfterTurn = async (result) => {
18141
- if (adapters.afterDispatch === void 0 || afterDispatchApplied) return result;
18199
+ if (afterDispatchApplied) return result;
18142
18200
  afterDispatchApplied = true;
18143
18201
  try {
18144
- await adapters.afterDispatch(admitted, lease);
18202
+ if (admitted.ticketNumber === void 0) {
18203
+ const rows = await readRecordedSubmissionRows(
18204
+ admitted.projectRoot,
18205
+ admitted.runId,
18206
+ { home: homeFromRunDirectory(admitted.runDirectory), sessionParent: join35(admitted.runDirectory, "session", "session.jsonl") }
18207
+ );
18208
+ const asserted = rows.filter((row) => row.kind === "accepted" && row.role === admitted.role).map((row) => row.accepted).find((payload) => {
18209
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) return false;
18210
+ const value = payload.ticketNumber;
18211
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
18212
+ });
18213
+ const ticketNumber = asserted === void 0 ? void 0 : asserted.ticketNumber;
18214
+ if (ticketNumber !== void 0) await bindAdmittedTicketNumber(admitted, ticketNumber);
18215
+ }
18216
+ if (adapters.afterDispatch !== void 0) await adapters.afterDispatch(admitted, lease);
18145
18217
  return result;
18146
18218
  } catch (error) {
18147
18219
  const primaryFailure = result.terminal !== void 0 && !isLawfulTypedTerminalOutcome(result.terminal.roleOutcome);
@@ -18256,29 +18328,12 @@ async function dispatchPostAdmissionTurn(input) {
18256
18328
  if (typeof liveHost === "string" && liveHost.trim() !== "") {
18257
18329
  turnRequest = { ...turnRequest, host: liveHost.trim() };
18258
18330
  }
18259
- if (isStationChildOfficerDialogue(admitted.role, env)) {
18260
- await deliverCaseDossierAsAttachment({
18261
- ticketNumber: admitted.ticketNumber,
18262
- projectRoot: admitted.projectRoot,
18263
- home: env.home,
18264
- runDirectory: admitted.runDirectory
18265
- });
18266
- } else {
18267
- const dossierSection = await projectCaseDossierPointerSection({
18268
- ticketNumber: admitted.ticketNumber,
18269
- projectRoot: admitted.projectRoot,
18270
- home: env.home
18271
- });
18272
- if (dossierSection !== void 0) {
18273
- turnRequest = {
18274
- ...turnRequest,
18275
- continuation: appendContinuationSection(
18276
- turnRequest.continuation,
18277
- dossierSection
18278
- )
18279
- };
18280
- }
18281
- }
18331
+ await deliverCaseDossierAsAttachment({
18332
+ ticketNumber: admitted.ticketNumber,
18333
+ projectRoot: admitted.projectRoot,
18334
+ home: env.home,
18335
+ runDirectory: admitted.runDirectory
18336
+ });
18282
18337
  await markRunRunning(
18283
18338
  admitted.runDirectory,
18284
18339
  env.model,
@@ -18307,8 +18362,8 @@ async function dispatchPostAdmissionTurn(input) {
18307
18362
  }
18308
18363
  let stderrLogWriteFailure;
18309
18364
  try {
18310
- await writeFile11(
18311
- join36(admitted.runDirectory, "stderr.log"),
18365
+ await writeFile10(
18366
+ join35(admitted.runDirectory, "stderr.log"),
18312
18367
  result.stderr,
18313
18368
  "utf8"
18314
18369
  );
@@ -18540,7 +18595,7 @@ function resumeTurnRequestProjectionOptions(admitted, request, env, summonsPrepa
18540
18595
  kind: "resume",
18541
18596
  prompt
18542
18597
  },
18543
- ...request.message === void 0 ? {} : { courtAttemptId: randomUUID7() },
18598
+ ...request.message === void 0 ? {} : { courtAttemptId: randomUUID6() },
18544
18599
  ...env.stationChild === void 0 ? {} : { stationChild: env.stationChild }
18545
18600
  };
18546
18601
  }
@@ -18558,7 +18613,7 @@ async function dispatchAfterWriterLease(input) {
18558
18613
  }
18559
18614
  function isAlreadyFrozenSummonsAttachment(runDirectory, attachmentPath) {
18560
18615
  const absolute = isAbsolute8(attachmentPath) ? attachmentPath : resolve13(attachmentPath);
18561
- return pathContainedIn(join36(runDirectory, "attachments"), absolute);
18616
+ return pathContainedIn(join35(runDirectory, "attachments"), absolute);
18562
18617
  }
18563
18618
  async function prepareSummonsResumeMaterials(runDirectory, summons) {
18564
18619
  if (summons === void 0) return void 0;
@@ -18637,7 +18692,7 @@ async function runPostAdmissionSeatResume(input) {
18637
18692
  }
18638
18693
  let turnRequest = await input.buildTurnRequest(admittedForBuild, request);
18639
18694
  if (openCourtAttemptId !== void 0 || request.summons !== void 0 || request.message !== void 0) {
18640
- const courtAttemptId = openCourtAttemptId ?? (turnRequest.courtAttemptId !== void 0 && turnRequest.courtAttemptId.length > 0 ? turnRequest.courtAttemptId : randomUUID7());
18695
+ const courtAttemptId = openCourtAttemptId ?? (turnRequest.courtAttemptId !== void 0 && turnRequest.courtAttemptId.length > 0 ? turnRequest.courtAttemptId : randomUUID6());
18641
18696
  turnRequest = { ...turnRequest, courtAttemptId };
18642
18697
  if (openCourtAttemptId === void 0) {
18643
18698
  const court = {
@@ -18866,6 +18921,7 @@ var init_post_admission = __esm({
18866
18921
  init_run_lifecycle();
18867
18922
  init_cli_errors();
18868
18923
  init_invocation();
18924
+ init_submission_ledger();
18869
18925
  init_activation_ledger_topology();
18870
18926
  init_engine_material();
18871
18927
  init_session_identity();
@@ -19925,7 +19981,7 @@ __export(public_role_summons_exports, {
19925
19981
  summonPublicRole: () => summonPublicRole
19926
19982
  });
19927
19983
  import { existsSync as existsSync11 } from "node:fs";
19928
- import { join as join37 } from "node:path";
19984
+ import { join as join36 } from "node:path";
19929
19985
  function createCapturingIo() {
19930
19986
  const chunks = [];
19931
19987
  return {
@@ -19948,7 +20004,7 @@ function parentDir(path) {
19948
20004
  function walkPackageRoot(start) {
19949
20005
  let dir = start;
19950
20006
  for (let i = 0; i < 12; i += 1) {
19951
- if (existsSync11(join37(dir, "package.json")) && existsSync11(join37(dir, "souls"))) {
20007
+ if (existsSync11(join36(dir, "package.json")) && existsSync11(join36(dir, "souls"))) {
19952
20008
  return dir;
19953
20009
  }
19954
20010
  const parent = parentDir(dir);
@@ -20059,7 +20115,7 @@ async function createSummonEnv(options, afterHost) {
20059
20115
  async function summonPublicRole(options) {
20060
20116
  const packageRoot = resolveSummonsPackageRoot(options.packageRoot);
20061
20117
  const home = await resolveSummonHome(options);
20062
- const agentDir = options.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? join37(home, ".pi", "agent");
20118
+ const agentDir = options.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? join36(home, ".pi", "agent");
20063
20119
  const {
20064
20120
  loadCredentialProviders: loadCredentialProviders2,
20065
20121
  loadPublicCliConfig: loadPublicCliConfig2,
@@ -20214,8 +20270,8 @@ async function summonPublicRole(options) {
20214
20270
  async function summonGateOfficer(options) {
20215
20271
  let home = options.home;
20216
20272
  if (home === void 0) {
20217
- const { homeFromRunDirectory: homeFromRunDirectory3 } = await Promise.resolve().then(() => (init_activation_ledger_topology(), activation_ledger_topology_exports));
20218
- home = homeFromRunDirectory3(options.sourceRunDirectory);
20273
+ const { homeFromRunDirectory: homeFromRunDirectory2 } = await Promise.resolve().then(() => (init_activation_ledger_topology(), activation_ledger_topology_exports));
20274
+ home = homeFromRunDirectory2(options.sourceRunDirectory);
20219
20275
  }
20220
20276
  let gateReviewInstruction;
20221
20277
  if (options.reask === void 0 && options.submission !== void 0) {
@@ -20575,7 +20631,7 @@ import {
20575
20631
  openSync as openSync2,
20576
20632
  writeSync
20577
20633
  } from "node:fs";
20578
- import { dirname as dirname19, isAbsolute as isAbsolute10, resolve as resolve15 } from "node:path";
20634
+ import { dirname as dirname18, isAbsolute as isAbsolute10, resolve as resolve15 } from "node:path";
20579
20635
 
20580
20636
  // src/activation-ledger-session.ts
20581
20637
  init_activation_ledger_topology();
@@ -20724,7 +20780,7 @@ function appendActivationLedgerLine(ledgerPath, line2, options) {
20724
20780
  }
20725
20781
  const resolvedLedger = resolve15(ledgerPath);
20726
20782
  const resolvedHome = resolve15(options.ledgerHome);
20727
- const parent = dirname19(resolvedLedger);
20783
+ const parent = dirname18(resolvedLedger);
20728
20784
  ensureRealDirectoryTree(resolvedHome, parent);
20729
20785
  assertLedgerFileInsideHome(resolvedLedger, resolvedHome);
20730
20786
  if (typeof constants2.O_NOFOLLOW !== "number") {
@@ -21088,11 +21144,28 @@ init_collector_evidence();
21088
21144
  init_collector_github();
21089
21145
 
21090
21146
  // src/collector-handbook.ts
21091
- init_atomic_write();
21092
- init_activation_ledger_topology();
21093
21147
  import { readFile as readFile20 } from "node:fs/promises";
21094
21148
  import { join as join38, sep as sep5 } from "node:path";
21095
21149
 
21150
+ // src/atomic-write.ts
21151
+ import { randomUUID as randomUUID7 } from "node:crypto";
21152
+ import { rename as rename3, rm as rm3, writeFile as writeFile11 } from "node:fs/promises";
21153
+ import { dirname as dirname19, join as join37 } from "node:path";
21154
+ async function writeFileAtomically(destination, contents) {
21155
+ const parent = dirname19(destination);
21156
+ const temporary = join37(parent, `.atomic-write-${randomUUID7()}.tmp`);
21157
+ try {
21158
+ await writeFile11(temporary, contents);
21159
+ await rename3(temporary, destination);
21160
+ } catch (error) {
21161
+ await rm3(temporary, { force: true }).catch(() => void 0);
21162
+ throw error;
21163
+ }
21164
+ }
21165
+
21166
+ // src/collector-handbook.ts
21167
+ init_activation_ledger_topology();
21168
+
21096
21169
  // src/collector-tool-schemas.ts
21097
21170
  init_open_tool_schema();
21098
21171
  init_terminating_infrastructure();
@@ -21177,7 +21250,7 @@ var collectorOutputBaseSchema = openToolObject(
21177
21250
  })
21178
21251
  })
21179
21252
  );
21180
- var collectorOutputArgsSchema = withInfrastructureFailureDeclaration(
21253
+ var collectorOutputArgsSchema = withTerminatingOutputDeclarations(
21181
21254
  collectorOutputBaseSchema
21182
21255
  );
21183
21256
 
@@ -22024,7 +22097,7 @@ init_terminating_infrastructure();
22024
22097
  init_countersign_contracts();
22025
22098
  init_countersign_contracts();
22026
22099
  import { Type as Type16 } from "typebox";
22027
- var countersignVerdictSchema = withInfrastructureFailureDeclaration(
22100
+ var countersignVerdictSchema = withTerminatingOutputDeclarations(
22028
22101
  Type16.Object(
22029
22102
  {
22030
22103
  countersignStatus: Type16.Unknown({ description: "converged | continue | escalate\u3002\u975E\u4E09\u6001\u65F6\u8BF7\u91CD\u8BFB\u540E\u91CD\u4EA4\uFF0C\u52FF\u6539\u6807\u3002" }),
@@ -22067,7 +22140,7 @@ init_terminating_infrastructure();
22067
22140
  init_gleaner_left_contracts();
22068
22141
  init_gleaner_left_contracts();
22069
22142
  import { Type as Type17 } from "typebox";
22070
- var gleanerLeftOutputSchema = withInfrastructureFailureDeclaration(
22143
+ var gleanerLeftOutputSchema = withTerminatingOutputDeclarations(
22071
22144
  openToolObject(
22072
22145
  Type17.Object({
22073
22146
  status: Type17.Unknown({
@@ -22102,7 +22175,7 @@ init_open_tool_schema();
22102
22175
  init_terminating_infrastructure();
22103
22176
  init_inspector_contracts();
22104
22177
  import { Type as Type18 } from "typebox";
22105
- var inspectorOutputSchema = withInfrastructureFailureDeclaration(
22178
+ var inspectorOutputSchema = withTerminatingOutputDeclarations(
22106
22179
  openToolObject(
22107
22180
  Type18.Object({
22108
22181
  status: Type18.Unknown({
@@ -22134,7 +22207,7 @@ init_terminating_infrastructure();
22134
22207
  init_diarist_contracts();
22135
22208
  init_diarist_contracts();
22136
22209
  import { Type as Type19 } from "typebox";
22137
- var diaristOutputSchema = withInfrastructureFailureDeclaration(
22210
+ var diaristOutputSchema = withTerminatingOutputDeclarations(
22138
22211
  openToolObject(
22139
22212
  Type19.Object({
22140
22213
  status: Type19.Unknown({
@@ -22294,7 +22367,7 @@ init_gatekeeper_output();
22294
22367
  init_navigator_output();
22295
22368
 
22296
22369
  // src/navigator-attendance.ts
22297
- import { createHash as createHash8 } from "node:crypto";
22370
+ import { createHash as createHash9 } from "node:crypto";
22298
22371
  init_navigator_invocation_identity();
22299
22372
  init_packaged_role_registry();
22300
22373
  init_activation_ledger_topology();
@@ -22747,7 +22820,7 @@ function navigatorSubjectKey(subjectRoot, subject, provenance = "role_input") {
22747
22820
  if (provenance === "placeholder") return subjectRoot;
22748
22821
  const normalized = subject.trim().replace(/\s+/g, " ");
22749
22822
  if (normalized === "") return subjectRoot;
22750
- return `${subjectRoot}#${createHash8("sha256").update(normalized).digest("hex").slice(0, 32)}`;
22823
+ return `${subjectRoot}#${createHash9("sha256").update(normalized).digest("hex").slice(0, 32)}`;
22751
22824
  }
22752
22825
  function navigatorSubjectKeyForInput(subjectRoot, reference, cwd = process.cwd()) {
22753
22826
  if (issueRoot(subjectRoot) !== void 0 || !subjectRoot.includes("/.ak/work/")) return subjectRoot;
@@ -23273,7 +23346,7 @@ init_judge_output();
23273
23346
  import { Type as Type22 } from "typebox";
23274
23347
  var JUDGE_QUEUE_STATUSES = /* @__PURE__ */ new Set(["converged", "continue", "escalate"]);
23275
23348
  var JUDGE_STATUS_REASK = "judgeStatus \u4E0D\u662F converged\u3001continue\u3001escalate \u4E09\u6001\u4E4B\u4E00\u3002\u8BF7\u91CD\u65B0\u4EA4\u5377\uFF0Cstatus \u5199\u660E\u5176\u4E00\u3002";
23276
- var judgeVerdictSchema = withInfrastructureFailureDeclaration(
23349
+ var judgeVerdictSchema = withTerminatingOutputDeclarations(
23277
23350
  Type22.Object(
23278
23351
  {
23279
23352
  judgeStatus: Type22.Unknown({ description: "converged | continue | escalate \u2014 \u5F62\u72B6\u6307\u5F15\uFF0C\u975E schema \u95F8" }),
@@ -23400,7 +23473,7 @@ var reviewerOutputVariants = Type23.Union([
23400
23473
  amendments: Type23.Optional(reviewerAmendmentsSchema)
23401
23474
  }, { additionalProperties: false })
23402
23475
  ]);
23403
- var reviewerOutputSchema = withInfrastructureFailureDeclaration(
23476
+ var reviewerOutputSchema = withTerminatingOutputDeclarations(
23404
23477
  openToolObjectFromUnion(reviewerOutputVariants)
23405
23478
  );
23406
23479
  function createReviewerRoleRuntime(pi, dependencies, _hostActions) {
@@ -23737,7 +23810,7 @@ var coderOutputVariants = Type24.Union([
23737
23810
  }))
23738
23811
  }, { additionalProperties: false })
23739
23812
  ]);
23740
- var coderOutputSchema = withInfrastructureFailureDeclaration(
23813
+ var coderOutputSchema = withTerminatingOutputDeclarations(
23741
23814
  openToolObjectFromUnion(coderOutputVariants)
23742
23815
  );
23743
23816
  var FIXER_FLAG_DEFINITIONS = {