@akagilnc/pi-workflow-roles 0.1.4204 → 0.1.4228

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.
@@ -62,7 +62,7 @@ async function spawnEngineDetourOnce(input) {
62
62
  }
63
63
  const command = input.argv[0];
64
64
  const args = input.argv.slice(1);
65
- return await new Promise((resolve20, reject) => {
65
+ return await new Promise((resolve21, reject) => {
66
66
  let settled = false;
67
67
  const signal = input.signal;
68
68
  const child = spawn(command, args, {
@@ -92,7 +92,7 @@ async function spawnEngineDetourOnce(input) {
92
92
  if (signal !== void 0) {
93
93
  signal.removeEventListener("abort", onAbort);
94
94
  }
95
- resolve20(result);
95
+ resolve21(result);
96
96
  };
97
97
  const onAbort = () => {
98
98
  fail4(signal !== void 0 ? abortReasonError(signal) : new Error("aborted"));
@@ -2051,6 +2051,114 @@ var init_auditor_output = __esm({
2051
2051
  }
2052
2052
  });
2053
2053
 
2054
+ // src/ticket-provenance-contracts.ts
2055
+ function isRecord(value) {
2056
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2057
+ }
2058
+ function positiveInteger(value) {
2059
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 1) return value;
2060
+ if (typeof value === "string" && /^[1-9][0-9]*$/.test(value)) {
2061
+ const parsed = Number(value);
2062
+ if (Number.isSafeInteger(parsed)) return parsed;
2063
+ }
2064
+ return void 0;
2065
+ }
2066
+ function nonNegativeInteger(value) {
2067
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) return value;
2068
+ if (typeof value === "string" && /^(0|[1-9][0-9]*)$/.test(value)) {
2069
+ const parsed = Number(value);
2070
+ if (Number.isSafeInteger(parsed)) return parsed;
2071
+ }
2072
+ return void 0;
2073
+ }
2074
+ function projectSpeaker(value) {
2075
+ return value === "owner" || value === "runner" ? value : void 0;
2076
+ }
2077
+ function projectBound(value) {
2078
+ if (!isRecord(value)) return void 0;
2079
+ const id = typeof value.id === "string" && value.id !== "" ? value.id : void 0;
2080
+ const line2 = positiveInteger(value.line);
2081
+ if (id === void 0 && line2 === void 0) return void 0;
2082
+ return { ...id === void 0 ? {} : { id }, ...line2 === void 0 ? {} : { line: line2 } };
2083
+ }
2084
+ function projectTicketProvenanceSessions(value) {
2085
+ if (!Array.isArray(value)) return void 0;
2086
+ if (value.length === 0) return [];
2087
+ const sessions = [];
2088
+ for (const raw of value) {
2089
+ if (!isRecord(raw)) return void 0;
2090
+ const path = raw.path;
2091
+ if (typeof path !== "string" || path.trim() === "") return void 0;
2092
+ if (!Array.isArray(raw.ranges) || raw.ranges.length === 0) return void 0;
2093
+ const ranges = [];
2094
+ for (const rawRange of raw.ranges) {
2095
+ if (!isRecord(rawRange)) return void 0;
2096
+ const from = projectBound(rawRange.from);
2097
+ const to = projectBound(rawRange.to);
2098
+ if (from === void 0 || to === void 0) return void 0;
2099
+ ranges.push({ from, to });
2100
+ }
2101
+ sessions.push({ path, ranges });
2102
+ }
2103
+ return sessions;
2104
+ }
2105
+ function projectTicketProvenanceAmendments(value) {
2106
+ if (!Array.isArray(value)) return [];
2107
+ const out = [];
2108
+ for (const raw of value) {
2109
+ if (!isRecord(raw)) continue;
2110
+ const s = nonNegativeInteger(raw.s);
2111
+ const line2 = positiveInteger(raw.line);
2112
+ const speaker = projectSpeaker(raw.speaker);
2113
+ const text = raw.text;
2114
+ if (s === void 0 || line2 === void 0 || speaker === void 0) continue;
2115
+ if (typeof text !== "string") continue;
2116
+ out.push({ s, line: line2, speaker, text });
2117
+ }
2118
+ return out;
2119
+ }
2120
+ function projectTicketProvenanceHeader(value) {
2121
+ if (!isRecord(value)) return void 0;
2122
+ const ticket = positiveInteger(value.ticket);
2123
+ if (ticket === void 0) return void 0;
2124
+ if (typeof value.repo !== "string") return void 0;
2125
+ if (typeof value.createdAt !== "string" || typeof value.updatedAt !== "string") {
2126
+ return void 0;
2127
+ }
2128
+ const sessions = projectTicketProvenanceSessions(value.sessions);
2129
+ if (sessions === void 0) return void 0;
2130
+ return {
2131
+ repo: value.repo,
2132
+ ticket,
2133
+ createdAt: value.createdAt,
2134
+ updatedAt: value.updatedAt,
2135
+ sessions
2136
+ };
2137
+ }
2138
+ function projectTicketProvenanceLine(value) {
2139
+ if (!isRecord(value)) return void 0;
2140
+ const speaker = projectSpeaker(value.speaker);
2141
+ const s = nonNegativeInteger(value.s);
2142
+ if (speaker === void 0 || s === void 0) return void 0;
2143
+ if (typeof value.text !== "string") return void 0;
2144
+ const line2 = positiveInteger(value.line);
2145
+ const id = typeof value.id === "string" && value.id !== "" ? value.id : void 0;
2146
+ return {
2147
+ speaker,
2148
+ s,
2149
+ ...line2 === void 0 ? {} : { line: line2 },
2150
+ ...id === void 0 ? {} : { id },
2151
+ text: value.text
2152
+ };
2153
+ }
2154
+ var TICKET_PROVENANCE_KIND;
2155
+ var init_ticket_provenance_contracts = __esm({
2156
+ "src/ticket-provenance-contracts.ts"() {
2157
+ "use strict";
2158
+ TICKET_PROVENANCE_KIND = "ticket-provenance";
2159
+ }
2160
+ });
2161
+
2054
2162
  // src/diarist-contracts.ts
2055
2163
  function projectCourtTicketNumbers(raw, options) {
2056
2164
  if (!Array.isArray(raw)) return null;
@@ -2125,14 +2233,21 @@ function sameCourtTicketNumbers(left, right) {
2125
2233
  }
2126
2234
  return true;
2127
2235
  }
2128
- function projectDiaristEntries(value) {
2129
- const rows = value?.entries;
2130
- return Array.isArray(rows) ? [...rows] : [];
2236
+ function projectDiaristSessions(value) {
2237
+ const raw = value?.sessions;
2238
+ if (raw === void 0) return [];
2239
+ return projectTicketProvenanceSessions(raw);
2240
+ }
2241
+ function projectDiaristAmendments(value) {
2242
+ const raw = value?.amendments;
2243
+ if (raw === void 0) return [];
2244
+ return projectTicketProvenanceAmendments(raw);
2131
2245
  }
2132
2246
  var DIARIST_OUTPUT_TOOL_NAME, DIARIST_ACCEPTED_TEXT;
2133
2247
  var init_diarist_contracts = __esm({
2134
2248
  "src/diarist-contracts.ts"() {
2135
2249
  "use strict";
2250
+ init_ticket_provenance_contracts();
2136
2251
  init_run_ticket_number();
2137
2252
  DIARIST_OUTPUT_TOOL_NAME = "ak_diarist_output";
2138
2253
  DIARIST_ACCEPTED_TEXT = "\u8D77\u5C45\u90CE\u56DE\u6267\u5DF2\u63A5\u53D7";
@@ -2463,7 +2578,7 @@ import {
2463
2578
  writeFileSync as writeFileSync2
2464
2579
  } from "node:fs";
2465
2580
  import { dirname as dirname5, join as join10 } from "node:path";
2466
- function isRecord(value) {
2581
+ function isRecord2(value) {
2467
2582
  return typeof value === "object" && value !== null && !Array.isArray(value);
2468
2583
  }
2469
2584
  function errorCodeOf(error) {
@@ -2491,7 +2606,7 @@ function findIdentityPointer(recordFile, identity, kind, level) {
2491
2606
  if (!trimmed) continue;
2492
2607
  try {
2493
2608
  const parsed = JSON.parse(trimmed);
2494
- if (isRecord(parsed) && parsed.identity === identity) {
2609
+ if (isRecord2(parsed) && parsed.identity === identity) {
2495
2610
  return { identity, recordFile, kind, level };
2496
2611
  }
2497
2612
  } catch {
@@ -2664,7 +2779,7 @@ var init_sitian_appender = __esm({
2664
2779
  // src/sitian-reader.ts
2665
2780
  import { existsSync as existsSync4 } from "node:fs";
2666
2781
  import { readFile as readFile2 } from "node:fs/promises";
2667
- function isRecord2(value) {
2782
+ function isRecord3(value) {
2668
2783
  return typeof value === "object" && value !== null && !Array.isArray(value);
2669
2784
  }
2670
2785
  async function readSitianRecords(recordFile) {
@@ -2680,7 +2795,7 @@ async function readSitianRecords(recordFile) {
2680
2795
  if (!line2.trim()) continue;
2681
2796
  try {
2682
2797
  const parsed = JSON.parse(line2);
2683
- if (isRecord2(parsed)) {
2798
+ if (isRecord3(parsed)) {
2684
2799
  records.push(parsed);
2685
2800
  } else {
2686
2801
  const typeDesc = parsed === null ? "null" : Array.isArray(parsed) ? "array" : typeof parsed;
@@ -2708,6 +2823,85 @@ var init_sitian_reader = __esm({
2708
2823
  }
2709
2824
  });
2710
2825
 
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
+
2711
2905
  // src/sitian-facade.ts
2712
2906
  function sitianReport(input) {
2713
2907
  return appendSitianRecord(input);
@@ -2719,6 +2913,7 @@ var init_sitian_facade = __esm({
2719
2913
  init_sitian_contracts();
2720
2914
  init_sitian_appender();
2721
2915
  init_sitian_reader();
2916
+ init_sitian_volume();
2722
2917
  }
2723
2918
  });
2724
2919
 
@@ -2736,13 +2931,13 @@ __export(role_turn_host_exports, {
2736
2931
  });
2737
2932
  import { execFile, spawn as spawn2 } from "node:child_process";
2738
2933
  import { constants } from "node:fs";
2739
- import { access, appendFile, readFile as readFile3, realpath } from "node:fs/promises";
2740
- import { basename as basename3, delimiter, dirname as dirname6, isAbsolute as isAbsolute3, join as join11, resolve as resolve5 } from "node:path";
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";
2741
2936
  import { platform } from "node:process";
2742
2937
  import { promisify } from "node:util";
2743
- import { randomUUID as randomUUID2 } from "node:crypto";
2938
+ import { randomUUID as randomUUID3 } from "node:crypto";
2744
2939
  function resolveInternalRoleEntrypoint(packageRoot) {
2745
- return join11(packageRoot, INTERNAL_ROLE_ENTRYPOINT_RELATIVE);
2940
+ return join12(packageRoot, INTERNAL_ROLE_ENTRYPOINT_RELATIVE);
2746
2941
  }
2747
2942
  function buildExplicitInternalActivationArgs(selectedRoleEntry, extraArgs = []) {
2748
2943
  return ["--no-extensions", "-e", selectedRoleEntry, ...extraArgs];
@@ -2778,7 +2973,7 @@ function buildMethodArgs(methods) {
2778
2973
  function applyPiNativeSkillInvocation(methods, prompt) {
2779
2974
  const skills = methods.filter((method) => method.kind === "skill");
2780
2975
  if (skills.length !== 1) return prompt;
2781
- const name = basename3(dirname6(skills[0].path));
2976
+ const name = basename3(dirname7(skills[0].path));
2782
2977
  if (name.length === 0) return prompt;
2783
2978
  const token = `/skill:${name}`;
2784
2979
  const trimmed = prompt.trimStart();
@@ -3015,7 +3210,7 @@ ${paths.join("\n")}`
3015
3210
  }
3016
3211
  async function appendPiSessionCustomEntry(authority, principal, customType, data) {
3017
3212
  const { sessionFile } = authority.decode(principal);
3018
- const text = await readFile3(sessionFile, "utf8");
3213
+ const text = await readFile4(sessionFile, "utf8");
3019
3214
  let parentId = null;
3020
3215
  for (const line2 of text.trim().split("\n").filter(Boolean)) {
3021
3216
  const entry = JSON.parse(line2);
@@ -3026,7 +3221,7 @@ async function appendPiSessionCustomEntry(authority, principal, customType, data
3026
3221
  type: "custom",
3027
3222
  customType,
3028
3223
  data,
3029
- id: randomUUID2(),
3224
+ id: randomUUID3(),
3030
3225
  parentId,
3031
3226
  timestamp: timestamp2
3032
3227
  })}
@@ -3187,12 +3382,12 @@ __export(session_assistant_usage_exports, {
3187
3382
  sessionFileFromPublicSummon: () => sessionFileFromPublicSummon,
3188
3383
  usageFromPublicSummon: () => usageFromPublicSummon
3189
3384
  });
3190
- import { join as join12 } from "node:path";
3385
+ import { join as join13 } from "node:path";
3191
3386
  async function readAssistantUsageFromSessionFile(sessionFile) {
3192
- const { readFile: readFile25 } = await import("node:fs/promises");
3387
+ const { readFile: readFile26 } = await import("node:fs/promises");
3193
3388
  let text;
3194
3389
  try {
3195
- text = await readFile25(sessionFile, "utf8");
3390
+ text = await readFile26(sessionFile, "utf8");
3196
3391
  } catch (error) {
3197
3392
  if (error?.code === "ENOENT") return void 0;
3198
3393
  throw error;
@@ -3257,7 +3452,7 @@ async function readAssistantUsageFromSessionFile(sessionFile) {
3257
3452
  }
3258
3453
  function sessionFileFromPublicSummon(summoned) {
3259
3454
  if (typeof summoned.runDirectory === "string" && summoned.runDirectory.trim() !== "") {
3260
- return join12(summoned.runDirectory, "session", "session.jsonl");
3455
+ return join13(summoned.runDirectory, "session", "session.jsonl");
3261
3456
  }
3262
3457
  const fromArtifacts = summoned.terminal?.artifacts?.map((a) => a.path).find((p) => typeof p === "string" && p.endsWith("session.jsonl"));
3263
3458
  if (fromArtifacts !== void 0) return fromArtifacts;
@@ -3266,7 +3461,7 @@ function sessionFileFromPublicSummon(summoned) {
3266
3461
  const facts = outcome.decisiveFacts;
3267
3462
  const pointer = facts?.runPointer;
3268
3463
  if (typeof pointer === "string" && pointer.trim() !== "") {
3269
- return join12(pointer, "session", "session.jsonl");
3464
+ return join13(pointer, "session", "session.jsonl");
3270
3465
  }
3271
3466
  return void 0;
3272
3467
  }
@@ -3421,8 +3616,8 @@ var init_compliance_transport = __esm({
3421
3616
 
3422
3617
  // src/role-run-relocation.ts
3423
3618
  import { existsSync as existsSync5 } from "node:fs";
3424
- import { readdir as readdir2, readFile as readFile4, writeFile as writeFile2 } from "node:fs/promises";
3425
- import { join as join13, sep as sep2 } from "node:path";
3619
+ import { readdir as readdir2, readFile as readFile5, writeFile as writeFile3 } from "node:fs/promises";
3620
+ import { join as join14, sep as sep2 } from "node:path";
3426
3621
  function isEnoent2(error) {
3427
3622
  return error instanceof Error && "code" in error && error.code === "ENOENT";
3428
3623
  }
@@ -3511,15 +3706,15 @@ function rewriteSummonsMaterials(value, rewrites) {
3511
3706
  }
3512
3707
  async function rewriteJsonObjectFile(path, fields, rewrites) {
3513
3708
  if (!existsSync5(path)) return;
3514
- const page = JSON.parse(await readFile4(path, "utf8"));
3709
+ const page = JSON.parse(await readFile5(path, "utf8"));
3515
3710
  if (!isPlainObject(page)) return;
3516
3711
  rewriteRunDirectoryPathFieldsAgainstRewrites(page, fields, rewrites);
3517
- await writeFile2(path, `${JSON.stringify(page, null, 2)}
3712
+ await writeFile3(path, `${JSON.stringify(page, null, 2)}
3518
3713
  `, "utf8");
3519
3714
  }
3520
3715
  async function rewriteOfficerPointerFile(path, rewrites) {
3521
3716
  if (!existsSync5(path)) return;
3522
- const page = JSON.parse(await readFile4(path, "utf8"));
3717
+ const page = JSON.parse(await readFile5(path, "utf8"));
3523
3718
  if (!isPlainObject(page)) return;
3524
3719
  if (page.kind !== "direct-officer-run-pointer") return;
3525
3720
  rewriteRunDirectoryPathFieldsAgainstRewrites(
@@ -3527,12 +3722,12 @@ async function rewriteOfficerPointerFile(path, rewrites) {
3527
3722
  OFFICER_POINTER_FIELDS,
3528
3723
  rewrites
3529
3724
  );
3530
- await writeFile2(path, `${JSON.stringify(page)}
3725
+ await writeFile3(path, `${JSON.stringify(page)}
3531
3726
  `, "utf8");
3532
3727
  }
3533
3728
  async function rewriteSitianRecordsJsonl(path, rewrites) {
3534
3729
  if (!existsSync5(path)) return;
3535
- const raw = await readFile4(path, "utf8");
3730
+ const raw = await readFile5(path, "utf8");
3536
3731
  if (raw.length === 0) return;
3537
3732
  const endsWithNewline = raw.endsWith("\n");
3538
3733
  const lines = raw.split("\n");
@@ -3574,7 +3769,7 @@ async function rewriteSitianRecordsJsonl(path, rewrites) {
3574
3769
  }
3575
3770
  if (!changed) return;
3576
3771
  const body = out.join("\n");
3577
- await writeFile2(
3772
+ await writeFile3(
3578
3773
  path,
3579
3774
  endsWithNewline && !body.endsWith("\n") ? `${body}
3580
3775
  ` : body,
@@ -3583,7 +3778,7 @@ async function rewriteSitianRecordsJsonl(path, rewrites) {
3583
3778
  }
3584
3779
  async function rewriteSessionTranscriptBindings(path, rewrites) {
3585
3780
  if (!existsSync5(path)) return;
3586
- const raw = await readFile4(path, "utf8");
3781
+ const raw = await readFile5(path, "utf8");
3587
3782
  if (raw.length === 0) return;
3588
3783
  const endsWithNewline = raw.endsWith("\n");
3589
3784
  const lines = raw.split("\n");
@@ -3634,7 +3829,7 @@ async function rewriteSessionTranscriptBindings(path, rewrites) {
3634
3829
  }
3635
3830
  if (!changed) return;
3636
3831
  const body = out.join("\n");
3637
- await writeFile2(
3832
+ await writeFile3(
3638
3833
  path,
3639
3834
  endsWithNewline && !body.endsWith("\n") ? `${body}
3640
3835
  ` : body,
@@ -3642,7 +3837,7 @@ async function rewriteSessionTranscriptBindings(path, rewrites) {
3642
3837
  );
3643
3838
  }
3644
3839
  async function rewriteNestedMachinePathPages(pagesDirectory, rewrites) {
3645
- const sessionRoot = join13(pagesDirectory, "session");
3840
+ const sessionRoot = join14(pagesDirectory, "session");
3646
3841
  async function walk(directory) {
3647
3842
  let entries;
3648
3843
  try {
@@ -3652,7 +3847,7 @@ async function rewriteNestedMachinePathPages(pagesDirectory, rewrites) {
3652
3847
  throw error;
3653
3848
  }
3654
3849
  for (const entry of entries) {
3655
- const path = join13(directory, entry.name);
3850
+ const path = join14(directory, entry.name);
3656
3851
  if (entry.isDirectory()) {
3657
3852
  await walk(path);
3658
3853
  continue;
@@ -3674,9 +3869,9 @@ async function rewriteNestedMachinePathPages(pagesDirectory, rewrites) {
3674
3869
  async function rewriteRoleRunDurablePages(input) {
3675
3870
  const { pagesDirectory } = input;
3676
3871
  const rewrites = collectRewrites(input);
3677
- const admittedPath = join13(pagesDirectory, "admitted-request.json");
3872
+ const admittedPath = join14(pagesDirectory, "admitted-request.json");
3678
3873
  if (existsSync5(admittedPath)) {
3679
- const page = JSON.parse(await readFile4(admittedPath, "utf8"));
3874
+ const page = JSON.parse(await readFile5(admittedPath, "utf8"));
3680
3875
  rewriteRunDirectoryPathFieldsAgainstRewrites(
3681
3876
  page,
3682
3877
  ADMITTED_PAGE_FIELDS,
@@ -3701,27 +3896,27 @@ async function rewriteRoleRunDurablePages(input) {
3701
3896
  rewrites
3702
3897
  );
3703
3898
  }
3704
- await writeFile2(admittedPath, `${JSON.stringify(page, null, 2)}
3899
+ await writeFile3(admittedPath, `${JSON.stringify(page, null, 2)}
3705
3900
  `, "utf8");
3706
3901
  }
3707
- const invocationPath = join13(pagesDirectory, "invocation.json");
3902
+ const invocationPath = join14(pagesDirectory, "invocation.json");
3708
3903
  if (existsSync5(invocationPath)) {
3709
- const page = JSON.parse(await readFile4(invocationPath, "utf8"));
3904
+ const page = JSON.parse(await readFile5(invocationPath, "utf8"));
3710
3905
  rewriteRunDirectoryPathFieldsAgainstRewrites(
3711
3906
  page,
3712
3907
  INVOCATION_PAGE_FIELDS,
3713
3908
  rewrites
3714
3909
  );
3715
- await writeFile2(
3910
+ await writeFile3(
3716
3911
  invocationPath,
3717
3912
  `${JSON.stringify(page, null, 2)}
3718
3913
  `,
3719
3914
  "utf8"
3720
3915
  );
3721
3916
  }
3722
- const statePath = join13(pagesDirectory, "run-state.json");
3917
+ const statePath = join14(pagesDirectory, "run-state.json");
3723
3918
  if (existsSync5(statePath)) {
3724
- const page = JSON.parse(await readFile4(statePath, "utf8"));
3919
+ const page = JSON.parse(await readFile5(statePath, "utf8"));
3725
3920
  rewriteRunDirectoryPathFieldsAgainstRewrites(
3726
3921
  page,
3727
3922
  RUN_STATE_PAGE_FIELDS,
@@ -3737,7 +3932,7 @@ async function rewriteRoleRunDurablePages(input) {
3737
3932
  if (isPlainObject(page.currentCourt)) {
3738
3933
  rewriteSummonsMaterials(page.currentCourt.summons, rewrites);
3739
3934
  }
3740
- await writeFile2(statePath, `${JSON.stringify(page, null, 2)}
3935
+ await writeFile3(statePath, `${JSON.stringify(page, null, 2)}
3741
3936
  `, "utf8");
3742
3937
  }
3743
3938
  await rewriteNestedMachinePathPages(pagesDirectory, rewrites);
@@ -3905,8 +4100,8 @@ var init_terminating_tools = __esm({
3905
4100
  });
3906
4101
 
3907
4102
  // src/doctor-evidence.ts
3908
- import { readdir as readdir3, readFile as readFile5, realpath as realpath2, stat } from "node:fs/promises";
3909
- import { dirname as dirname7, relative as relative2, resolve as resolve6, sep as sep3 } from "node:path";
4103
+ import { readdir as readdir3, readFile as readFile6, realpath as realpath2, stat } from "node:fs/promises";
4104
+ import { dirname as dirname8, relative as relative2, resolve as resolve6, sep as sep3 } from "node:path";
3910
4105
  function record2(value) {
3911
4106
  return typeof value === "object" && value !== null && !Array.isArray(value);
3912
4107
  }
@@ -3945,7 +4140,7 @@ async function stableRunsIdentity(root) {
3945
4140
  } catch (error) {
3946
4141
  if (!isMissingPathError2(error)) throw error;
3947
4142
  }
3948
- const parent = dirname7(cursor);
4143
+ const parent = dirname8(cursor);
3949
4144
  if (parent === cursor) return root;
3950
4145
  cursor = parent;
3951
4146
  }
@@ -4021,7 +4216,7 @@ async function loadDoctorCase(runsPath) {
4021
4216
  const turns = { count: 0, sources: [] }, calls = { count: 0, sources: [] }, tokens = { count: 0, sources: [] };
4022
4217
  for (const path of await discoverCaseFiles(root)) {
4023
4218
  const id = relative2(root, path).split(sep3).join("/");
4024
- const bytes = await readFile5(path);
4219
+ const bytes = await readFile6(path);
4025
4220
  const content = bytes.toString("utf8");
4026
4221
  const kind = id.endsWith(".jsonl") ? "session" : "stderr";
4027
4222
  evidence.push({ id, kind, byteLength: bytes.byteLength, contentLength: content.length, sha256: sha256Hex(bytes), content });
@@ -4051,7 +4246,7 @@ var init_doctor_evidence = __esm({
4051
4246
 
4052
4247
  // src/collector-config.ts
4053
4248
  import { createHash as createHash4 } from "node:crypto";
4054
- import { readFile as readFile6 } from "node:fs/promises";
4249
+ import { readFile as readFile7 } from "node:fs/promises";
4055
4250
  function fail3(message, cause) {
4056
4251
  throw new Error(message, cause === void 0 ? void 0 : { cause });
4057
4252
  }
@@ -4094,7 +4289,7 @@ function emptyCollectorManifest() {
4094
4289
  async function loadCollectorManifest(path) {
4095
4290
  let bytes;
4096
4291
  try {
4097
- bytes = await readFile6(path);
4292
+ bytes = await readFile7(path);
4098
4293
  } catch (error) {
4099
4294
  fail3(`Collector request manifest is unreadable at ${path}`, error);
4100
4295
  }
@@ -4130,7 +4325,7 @@ var init_collector_config = __esm({
4130
4325
  // src/collector-github.ts
4131
4326
  import { spawn as spawn3 } from "node:child_process";
4132
4327
  import { createHash as createHash5 } from "node:crypto";
4133
- function isRecord3(value) {
4328
+ function isRecord4(value) {
4134
4329
  return typeof value === "object" && value !== null && !Array.isArray(value);
4135
4330
  }
4136
4331
  function requireString(value, label) {
@@ -4169,7 +4364,7 @@ function parsePullRequestNumberList(raw, label) {
4169
4364
  }
4170
4365
  const numbers = [];
4171
4366
  for (const item of raw) {
4172
- if (!isRecord3(item)) {
4367
+ if (!isRecord4(item)) {
4173
4368
  throw new Error(`GitHub ${label} payload contains a non-object pull request entry`);
4174
4369
  }
4175
4370
  try {
@@ -4237,7 +4432,7 @@ async function listPullRequestNumbersByTicket(runner, input) {
4237
4432
  });
4238
4433
  }
4239
4434
  const issueRaw = parseJson(issueResponse.bodyText, issuePath);
4240
- if (!isRecord3(issueRaw)) {
4435
+ if (!isRecord4(issueRaw)) {
4241
4436
  throw new Error(`GitHub ${issuePath} payload is not an object`);
4242
4437
  }
4243
4438
  if (Object.hasOwn(issueRaw, "pull_request")) {
@@ -4296,7 +4491,7 @@ async function listPullRequestNumbersByTicket(runner, input) {
4296
4491
  } catch (error) {
4297
4492
  throw new Error("GitHub GraphQL issue\u2192PR returned malformed JSON", { cause: error });
4298
4493
  }
4299
- if (!isRecord3(payload)) {
4494
+ if (!isRecord4(payload)) {
4300
4495
  throw new Error("GitHub GraphQL issue\u2192PR payload is not an object");
4301
4496
  }
4302
4497
  if (payload.errors !== void 0) {
@@ -4305,30 +4500,30 @@ async function listPullRequestNumbersByTicket(runner, input) {
4305
4500
  });
4306
4501
  }
4307
4502
  const data = payload.data;
4308
- if (!isRecord3(data)) return [];
4503
+ if (!isRecord4(data)) return [];
4309
4504
  const repository = data["repository"];
4310
- if (!isRecord3(repository)) return [];
4505
+ if (!isRecord4(repository)) return [];
4311
4506
  const issue = repository["issue"];
4312
- if (!isRecord3(issue)) return [];
4507
+ if (!isRecord4(issue)) return [];
4313
4508
  const numbers = [];
4314
4509
  const closedBy = issue["closedByPullRequestsReferences"];
4315
- if (isRecord3(closedBy) && Array.isArray(closedBy["nodes"])) {
4510
+ if (isRecord4(closedBy) && Array.isArray(closedBy["nodes"])) {
4316
4511
  for (const node of closedBy["nodes"]) {
4317
- if (isRecord3(node) && typeof node["number"] === "number") {
4512
+ if (isRecord4(node) && typeof node["number"] === "number") {
4318
4513
  numbers.push(parseCollectorPrNumber(node["number"]));
4319
4514
  }
4320
4515
  }
4321
4516
  }
4322
4517
  const timeline = issue["timelineItems"];
4323
- if (isRecord3(timeline) && Array.isArray(timeline["nodes"])) {
4518
+ if (isRecord4(timeline) && Array.isArray(timeline["nodes"])) {
4324
4519
  for (const node of timeline["nodes"]) {
4325
- if (!isRecord3(node)) continue;
4520
+ if (!isRecord4(node)) continue;
4326
4521
  const source = node["source"];
4327
- if (isRecord3(source) && typeof source["number"] === "number") {
4522
+ if (isRecord4(source) && typeof source["number"] === "number") {
4328
4523
  numbers.push(parseCollectorPrNumber(source["number"]));
4329
4524
  }
4330
4525
  const subject = node["subject"];
4331
- if (isRecord3(subject) && typeof subject["number"] === "number") {
4526
+ if (isRecord4(subject) && typeof subject["number"] === "number") {
4332
4527
  numbers.push(parseCollectorPrNumber(subject["number"]));
4333
4528
  }
4334
4529
  }
@@ -4343,25 +4538,25 @@ function commentFailureCause(error) {
4343
4538
  };
4344
4539
  }
4345
4540
  function requireUserLogin(raw) {
4346
- if (!isRecord3(raw) || typeof raw["login"] !== "string") {
4541
+ if (!isRecord4(raw) || typeof raw["login"] !== "string") {
4347
4542
  throw new Error("GitHub payload missing user.login");
4348
4543
  }
4349
4544
  return raw["login"];
4350
4545
  }
4351
4546
  function optionalUserLogin(raw) {
4352
4547
  if (raw === null) return null;
4353
- if (!isRecord3(raw) || typeof raw["login"] !== "string") {
4548
+ if (!isRecord4(raw) || typeof raw["login"] !== "string") {
4354
4549
  throw new Error("GitHub payload missing user.login");
4355
4550
  }
4356
4551
  return raw["login"];
4357
4552
  }
4358
4553
  function machineIdentity(raw) {
4359
4554
  const user = raw["user"];
4360
- if (!isRecord3(user) || typeof user["type"] !== "string" || typeof user["id"] !== "number") {
4555
+ if (!isRecord4(user) || typeof user["type"] !== "string" || typeof user["id"] !== "number") {
4361
4556
  return null;
4362
4557
  }
4363
4558
  const app = raw["performed_via_github_app"];
4364
- const appId = isRecord3(app) && typeof app["id"] === "number" ? app["id"] : void 0;
4559
+ const appId = isRecord4(app) && typeof app["id"] === "number" ? app["id"] : void 0;
4365
4560
  return {
4366
4561
  userType: user["type"],
4367
4562
  userId: user["id"],
@@ -4369,9 +4564,9 @@ function machineIdentity(raw) {
4369
4564
  };
4370
4565
  }
4371
4566
  function normalizePullRequest(raw) {
4372
- if (!isRecord3(raw)) throw new Error("GitHub pull request payload must be an object");
4567
+ if (!isRecord4(raw)) throw new Error("GitHub pull request payload must be an object");
4373
4568
  const head = raw["head"];
4374
- if (!isRecord3(head) || typeof head["sha"] !== "string" || head["sha"].length === 0) {
4569
+ if (!isRecord4(head) || typeof head["sha"] !== "string" || head["sha"].length === 0) {
4375
4570
  throw new Error("GitHub pull request payload missing head.sha");
4376
4571
  }
4377
4572
  const number = requireNumber(raw["number"], "number");
@@ -4390,7 +4585,7 @@ function normalizePullRequest(raw) {
4390
4585
  };
4391
4586
  }
4392
4587
  function normalizePullRequestReaction(raw) {
4393
- if (!isRecord3(raw)) throw new Error("GitHub reaction payload must be an object");
4588
+ if (!isRecord4(raw)) throw new Error("GitHub reaction payload must be an object");
4394
4589
  return {
4395
4590
  id: requireNumber(raw["id"], "reaction.id"),
4396
4591
  userLogin: optionalUserLogin(raw["user"]),
@@ -4401,7 +4596,7 @@ function normalizePullRequestReaction(raw) {
4401
4596
  };
4402
4597
  }
4403
4598
  function normalizeReview(raw) {
4404
- if (!isRecord3(raw)) throw new Error("GitHub review payload must be an object");
4599
+ if (!isRecord4(raw)) throw new Error("GitHub review payload must be an object");
4405
4600
  return {
4406
4601
  id: requireNumber(raw["id"], "review.id"),
4407
4602
  ...typeof raw["node_id"] === "string" ? { nodeId: raw["node_id"] } : {},
@@ -4416,7 +4611,7 @@ function normalizeReview(raw) {
4416
4611
  };
4417
4612
  }
4418
4613
  function normalizeIssueComment(raw) {
4419
- if (!isRecord3(raw)) throw new Error("GitHub issue comment payload must be an object");
4614
+ if (!isRecord4(raw)) throw new Error("GitHub issue comment payload must be an object");
4420
4615
  return {
4421
4616
  id: requireNumber(raw["id"], "comment.id"),
4422
4617
  userLogin: optionalUserLogin(raw["user"]),
@@ -4429,7 +4624,7 @@ function normalizeIssueComment(raw) {
4429
4624
  };
4430
4625
  }
4431
4626
  function normalizeReviewComment(raw) {
4432
- if (!isRecord3(raw)) throw new Error("GitHub review comment payload must be an object");
4627
+ if (!isRecord4(raw)) throw new Error("GitHub review comment payload must be an object");
4433
4628
  return {
4434
4629
  id: requireNumber(raw["id"], "review_comment.id"),
4435
4630
  pullRequestReviewId: typeof raw["pull_request_review_id"] === "number" ? raw["pull_request_review_id"] : null,
@@ -4453,7 +4648,7 @@ function normalizeReviewComment(raw) {
4453
4648
  function createGhApiRunner(options = {}) {
4454
4649
  const spawnImpl = options.spawnImpl ?? spawn3;
4455
4650
  return async (args, runOptions = {}) => {
4456
- return await new Promise((resolve20, reject) => {
4651
+ return await new Promise((resolve21, reject) => {
4457
4652
  const signal = runOptions.signal;
4458
4653
  if (signal?.aborted) {
4459
4654
  reject(signal.reason ?? new Error("aborted"));
@@ -4526,11 +4721,11 @@ function createGhApiRunner(options = {}) {
4526
4721
  const value = line2.slice(idx + 1).trim();
4527
4722
  headers[name] = value;
4528
4723
  }
4529
- resolve20({ status, headers, bodyText });
4724
+ resolve21({ status, headers, bodyText });
4530
4725
  return;
4531
4726
  }
4532
4727
  if (code === 0) {
4533
- resolve20({ status: 200, headers: {}, bodyText: stdout });
4728
+ resolve21({ status: 200, headers: {}, bodyText: stdout });
4534
4729
  return;
4535
4730
  }
4536
4731
  const failure2 = new Error(
@@ -4688,11 +4883,11 @@ function createGhCollectorGitHubTransport(runner = createGhApiRunner()) {
4688
4883
  if (input.signal?.aborted) {
4689
4884
  throw error;
4690
4885
  }
4691
- if (isRecord3(error) && error["ambiguousGhFailure"] === true) {
4886
+ if (isRecord4(error) && error["ambiguousGhFailure"] === true) {
4692
4887
  const cause = commentFailureCause(error);
4693
4888
  return { kind: "ambiguous_loss", diagnostics: cause.message, cause };
4694
4889
  }
4695
- if (isRecord3(error) && error["name"] === "AbortError") {
4890
+ if (isRecord4(error) && error["name"] === "AbortError") {
4696
4891
  throw error;
4697
4892
  }
4698
4893
  throw error;
@@ -4930,7 +5125,7 @@ var init_git_object_id = __esm({
4930
5125
 
4931
5126
  // src/merger-git-state.ts
4932
5127
  import { execFile as execFile2 } from "node:child_process";
4933
- import { access as access2, readFile as readFile7 } from "node:fs/promises";
5128
+ import { access as access2, readFile as readFile8 } from "node:fs/promises";
4934
5129
  import { constants as fsConstants } from "node:fs";
4935
5130
  import { isAbsolute as isAbsolute4, resolve as resolve7 } from "node:path";
4936
5131
  import { promisify as promisify2 } from "node:util";
@@ -5000,7 +5195,7 @@ function createProductionMergerGitState(repositoryRoot = process.cwd()) {
5000
5195
  const mergeHeadPath = isAbsolute4(mergeHeadReported) ? mergeHeadReported : resolve7(repositoryRoot, mergeHeadReported);
5001
5196
  let sourceObjectId = "";
5002
5197
  if (await pathExists(mergeHeadPath)) {
5003
- const raw = exactUtf8(await readFile7(mergeHeadPath), "Git MERGE_HEAD");
5198
+ const raw = exactUtf8(await readFile8(mergeHeadPath), "Git MERGE_HEAD");
5004
5199
  const mergeHeads = raw.trim().split(/\r?\n/).map((row) => row.trim()).filter(Boolean);
5005
5200
  if (mergeHeads.length === 0) throw new Error("Git MERGE_HEAD is empty");
5006
5201
  if (mergeHeads.length !== 1) throw new Error("Assigned repository does not have one ordinary in-progress merge");
@@ -5052,10 +5247,10 @@ var init_uuidv7 = __esm({
5052
5247
  });
5053
5248
 
5054
5249
  // src/typed-provider-http.ts
5055
- import { readFile as readFile8, unlink, writeFile as writeFile3 } from "node:fs/promises";
5056
- import { join as join14 } from "node:path";
5250
+ import { readFile as readFile9, unlink, writeFile as writeFile4 } from "node:fs/promises";
5251
+ import { join as join15 } from "node:path";
5057
5252
  function typedProviderHttpPath(runDirectory) {
5058
- return join14(runDirectory, TYPED_HTTP_FILE);
5253
+ return join15(runDirectory, TYPED_HTTP_FILE);
5059
5254
  }
5060
5255
  async function clearTypedProviderHttpObservation(runDirectory) {
5061
5256
  try {
@@ -5076,7 +5271,7 @@ async function recordTypedProviderHttpStatus(runDirectory, observation) {
5076
5271
  httpStatus: observation.httpStatus,
5077
5272
  provider: observation.provider
5078
5273
  };
5079
- await writeFile3(
5274
+ await writeFile4(
5080
5275
  typedProviderHttpPath(runDirectory),
5081
5276
  `${JSON.stringify(body)}
5082
5277
  `,
@@ -5086,7 +5281,7 @@ async function recordTypedProviderHttpStatus(runDirectory, observation) {
5086
5281
  async function readLatestTypedProviderHttpObservation(runDirectory) {
5087
5282
  let text;
5088
5283
  try {
5089
- text = await readFile8(typedProviderHttpPath(runDirectory), "utf8");
5284
+ text = await readFile9(typedProviderHttpPath(runDirectory), "utf8");
5090
5285
  } catch (error) {
5091
5286
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
5092
5287
  return void 0;
@@ -5115,8 +5310,8 @@ var init_typed_provider_http = __esm({
5115
5310
  });
5116
5311
 
5117
5312
  // src/public-cli/run-lifecycle.ts
5118
- import { chmod, lstat as lstat2, open, readdir as readdir4, readFile as readFile9, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
5119
- import { basename as basename4, join as join15 } from "node:path";
5313
+ import { chmod, lstat as lstat2, open, readdir as readdir4, readFile as readFile10, unlink as unlink2, writeFile as writeFile5 } from "node:fs/promises";
5314
+ import { basename as basename4, join as join16 } from "node:path";
5120
5315
  function selectResumeContinuationPrompt(message, engineMaterial) {
5121
5316
  const lines = message !== void 0 ? [message] : [];
5122
5317
  return appendEngineSessionMaterial(lines, engineMaterial).join("\n");
@@ -5145,8 +5340,8 @@ function renderResumeCommand(runId) {
5145
5340
  }
5146
5341
  async function writeRoleRunState(runDirectory, record4) {
5147
5342
  const payload = { ...record4, runDirectory };
5148
- await writeFile4(
5149
- join15(runDirectory, RUN_STATE_FILE),
5343
+ await writeFile5(
5344
+ join16(runDirectory, RUN_STATE_FILE),
5150
5345
  `${JSON.stringify(payload, null, 2)}
5151
5346
  `,
5152
5347
  "utf8"
@@ -5196,7 +5391,7 @@ function parseCurrentCourtState(raw) {
5196
5391
  async function readRoleRunStateDisk(runDirectory) {
5197
5392
  let raw;
5198
5393
  try {
5199
- raw = JSON.parse(await readFile9(join15(runDirectory, RUN_STATE_FILE), "utf8"));
5394
+ raw = JSON.parse(await readFile10(join16(runDirectory, RUN_STATE_FILE), "utf8"));
5200
5395
  } catch (error) {
5201
5396
  if (errorCodeOf2(error) === "ENOENT") return void 0;
5202
5397
  throw error;
@@ -5263,8 +5458,8 @@ async function writeRoleRunStateDisk(runDirectory, disk) {
5263
5458
  ...disk.resumable === void 0 ? {} : { resumable: disk.resumable },
5264
5459
  ...disk.currentCourt === void 0 ? {} : { currentCourt: disk.currentCourt }
5265
5460
  };
5266
- await writeFile4(
5267
- join15(runDirectory, RUN_STATE_FILE),
5461
+ await writeFile5(
5462
+ join16(runDirectory, RUN_STATE_FILE),
5268
5463
  `${JSON.stringify(payload, null, 2)}
5269
5464
  `,
5270
5465
  "utf8"
@@ -5431,7 +5626,7 @@ function isProcessAlive(pid) {
5431
5626
  async function autopsyWriterLock(lockPath) {
5432
5627
  let content;
5433
5628
  try {
5434
- content = await readFile9(lockPath, "utf8");
5629
+ content = await readFile10(lockPath, "utf8");
5435
5630
  } catch (error) {
5436
5631
  if (errorCodeOf2(error) === "ENOENT") return { verdict: "absent" };
5437
5632
  return { verdict: "unknown", reason: "unreadable", readFailure: error };
@@ -5490,7 +5685,7 @@ async function createWriterLease(lockPath, runDirectory, reportCleanupFailure) {
5490
5685
  },
5491
5686
  relocate(nextRunDirectory) {
5492
5687
  currentRunDirectory = nextRunDirectory;
5493
- currentLockPath = join15(nextRunDirectory, WRITER_LOCK_FILE);
5688
+ currentLockPath = join16(nextRunDirectory, WRITER_LOCK_FILE);
5494
5689
  },
5495
5690
  async release() {
5496
5691
  if (released) return;
@@ -5529,10 +5724,10 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
5529
5724
  };
5530
5725
  const reportReadFailure = (error) => {
5531
5726
  reportDiagnostic(
5532
- `writer lease lock read failed (holder liveness unverifiable; lock left in place) at ${join15(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
5727
+ `writer lease lock read failed (holder liveness unverifiable; lock left in place) at ${join16(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
5533
5728
  );
5534
5729
  };
5535
- const lockPath = join15(runDirectory, WRITER_LOCK_FILE);
5730
+ const lockPath = join16(runDirectory, WRITER_LOCK_FILE);
5536
5731
  let lastAutopsy = { verdict: "absent" };
5537
5732
  let lastReclaimFailure;
5538
5733
  for (let reclaimsLeft = WRITER_LEASE_RECLAIM_ROUNDS; ; reclaimsLeft -= 1) {
@@ -5587,7 +5782,7 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
5587
5782
  async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole) {
5588
5783
  if (runId.trim() === "") return void 0;
5589
5784
  const ledgerHome = resolveActivationLedgerHome(home);
5590
- const booksRoot = join15(ledgerHome, "books");
5785
+ const booksRoot = join16(ledgerHome, "books");
5591
5786
  let bookKeys;
5592
5787
  try {
5593
5788
  bookKeys = await readdir4(booksRoot);
@@ -5628,7 +5823,7 @@ async function readRunParentPath(runDirectory) {
5628
5823
  let raw;
5629
5824
  try {
5630
5825
  raw = JSON.parse(
5631
- await readFile9(join15(runDirectory, "admitted-request.json"), "utf8")
5826
+ await readFile10(join16(runDirectory, "admitted-request.json"), "utf8")
5632
5827
  );
5633
5828
  } catch (error) {
5634
5829
  if (errorCodeOf2(error) === "ENOENT") return void 0;
@@ -5649,7 +5844,7 @@ async function readRunParentPath(runDirectory) {
5649
5844
  async function runHasFormedSessionPrincipal(runDirectory) {
5650
5845
  const disk = await readRoleRunStateDisk(runDirectory);
5651
5846
  if (disk === void 0) return false;
5652
- const sessionFile = typeof disk.principalWire.sessionFile === "string" && disk.principalWire.sessionFile.trim() !== "" ? disk.principalWire.sessionFile : join15(disk.principalWire.sessionDirectory, "session.jsonl");
5847
+ const sessionFile = typeof disk.principalWire.sessionFile === "string" && disk.principalWire.sessionFile.trim() !== "" ? disk.principalWire.sessionFile : join16(disk.principalWire.sessionDirectory, "session.jsonl");
5653
5848
  try {
5654
5849
  const stat2 = await lstat2(sessionFile);
5655
5850
  return stat2.isFile() && !stat2.isSymbolicLink();
@@ -5796,7 +5991,7 @@ async function loadResumableRunRecord(home, runId, authority) {
5796
5991
  let sourceRun;
5797
5992
  try {
5798
5993
  const raw = JSON.parse(
5799
- await readFile9(run.admittedRequestPath, "utf8")
5994
+ await readFile10(run.admittedRequestPath, "utf8")
5800
5995
  );
5801
5996
  if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) {
5802
5997
  const record4 = raw;
@@ -5911,7 +6106,7 @@ async function loadResumableRunRecord(home, runId, authority) {
5911
6106
  let model;
5912
6107
  try {
5913
6108
  const invocationRaw = JSON.parse(
5914
- await readFile9(join15(run.runDirectory, "invocation.json"), "utf8")
6109
+ await readFile10(join16(run.runDirectory, "invocation.json"), "utf8")
5915
6110
  );
5916
6111
  if (invocationRaw !== null && typeof invocationRaw === "object" && !Array.isArray(invocationRaw)) {
5917
6112
  const rec = invocationRaw;
@@ -6142,7 +6337,7 @@ __export(notary_source_run_exports, {
6142
6337
  loadNotarySourceRunLocator: () => loadNotarySourceRunLocator,
6143
6338
  resolveNotarySourceRunLocator: () => resolveNotarySourceRunLocator
6144
6339
  });
6145
- import { dirname as dirname8, isAbsolute as isAbsolute6, join as join16, resolve as resolve8, basename as basename5 } from "node:path";
6340
+ import { dirname as dirname9, isAbsolute as isAbsolute6, join as join17, resolve as resolve8, basename as basename5 } from "node:path";
6146
6341
  import { lstat as lstat3, realpath as realpath3 } from "node:fs/promises";
6147
6342
  function parseRunDirectoryName(name) {
6148
6343
  const match = RUN_DIR_NAME.exec(name);
@@ -6188,20 +6383,20 @@ async function resolveNotarySourceRunLocator(options) {
6188
6383
  }
6189
6384
  const ledgerHome = resolveActivationLedgerHome(options.home);
6190
6385
  const bookKey = resolveBookKeyFromGit(options.projectRoot);
6191
- const bookRunsRoot = join16(activationBookDirectory(ledgerHome, bookKey), "runs");
6386
+ const bookRunsRoot = join17(activationBookDirectory(ledgerHome, bookKey), "runs");
6192
6387
  let candidate;
6193
6388
  const bare = parseRunDirectoryName(raw);
6194
6389
  if (bare !== void 0 && !raw.includes("/") && !raw.includes("\\")) {
6195
- candidate = await findRunDirectoryById(options.home, bare.runId, bookKey, bare.role) ?? join16(bookRunsRoot, `${bare.runId}@${bare.role}`);
6390
+ candidate = await findRunDirectoryById(options.home, bare.runId, bookKey, bare.role) ?? join17(bookRunsRoot, `${bare.runId}@${bare.role}`);
6196
6391
  } else {
6197
6392
  candidate = isAbsolute6(raw) ? raw : resolve8(options.projectRoot, raw);
6198
6393
  }
6199
6394
  const real = await requireRunDirectory(candidate, raw);
6200
6395
  const identity = parseRunDirectoryName(basename5(real));
6201
6396
  const bookIdentity = physicalPathIdentity(activationBookDirectory(ledgerHome, bookKey));
6202
- const parentIdentity = physicalPathIdentity(dirname8(real));
6203
- const subjectBookIdentity = physicalPathIdentity(dirname8(dirname8(dirname8(real))));
6204
- if (parentIdentity !== physicalPathIdentity(bookRunsRoot) && !(basename5(dirname8(real)) === "runs" && subjectBookIdentity === bookIdentity)) {
6397
+ const parentIdentity = physicalPathIdentity(dirname9(real));
6398
+ const subjectBookIdentity = physicalPathIdentity(dirname9(dirname9(dirname9(real))));
6399
+ if (parentIdentity !== physicalPathIdentity(bookRunsRoot) && !(basename5(dirname9(real)) === "runs" && subjectBookIdentity === bookIdentity)) {
6205
6400
  throw new NotarySourceRunError(
6206
6401
  "notary --source-run must resolve to a retained run under the project machine-ledger book"
6207
6402
  );
@@ -7342,12 +7537,12 @@ import { execFileSync as execFileSync3 } from "node:child_process";
7342
7537
  import { existsSync as existsSync6 } from "node:fs";
7343
7538
  import {
7344
7539
  lstat as lstat4,
7345
- readFile as readFile10,
7540
+ readFile as readFile11,
7346
7541
  realpath as realpath4,
7347
- rename,
7348
- writeFile as writeFile5
7542
+ rename as rename2,
7543
+ writeFile as writeFile6
7349
7544
  } from "node:fs/promises";
7350
- import { basename as basename6, dirname as dirname9, isAbsolute as isAbsolute7, join as join17, resolve as resolve9, sep as sep4 } from "node:path";
7545
+ import { basename as basename6, dirname as dirname10, isAbsolute as isAbsolute7, join as join18, resolve as resolve9, sep as sep4 } from "node:path";
7351
7546
  function issueAdmissionPlacement(authority, request) {
7352
7547
  const ledgerHome = resolveActivationLedgerHome(request.home);
7353
7548
  const bookKey = resolveBookKeyFromGit(request.cwd);
@@ -7372,7 +7567,7 @@ async function writeAdmittedRequestPersistence(admittedRequestPath, body, coordi
7372
7567
  sessionDirectory: coordinates.sessionDirectory,
7373
7568
  sessionFile: coordinates.sessionFile
7374
7569
  };
7375
- await writeFile5(
7570
+ await writeFile6(
7376
7571
  admittedRequestPath,
7377
7572
  `${JSON.stringify(projection, null, 2)}
7378
7573
  `,
@@ -7400,16 +7595,16 @@ async function writeRoleInvocationLedger(source, role, effectiveModel) {
7400
7595
  ...source.ticketNumber === void 0 ? {} : { ticketNumber: source.ticketNumber },
7401
7596
  ...effectiveModelLedgerFields(effectiveModel)
7402
7597
  };
7403
- await writeFile5(
7404
- join17(source.runDirectory, "invocation.json"),
7598
+ await writeFile6(
7599
+ join18(source.runDirectory, "invocation.json"),
7405
7600
  `${JSON.stringify(identity, null, 2)}
7406
7601
  `,
7407
7602
  "utf8"
7408
7603
  );
7409
7604
  }
7410
7605
  async function recordEffectiveInvocationModel(runDirectory, model, engine, host, engineModel) {
7411
- const ledgerPath = join17(runDirectory, "invocation.json");
7412
- const current = JSON.parse(await readFile10(ledgerPath, "utf8"));
7606
+ const ledgerPath = join18(runDirectory, "invocation.json");
7607
+ const current = JSON.parse(await readFile11(ledgerPath, "utf8"));
7413
7608
  const next = { ...current };
7414
7609
  if (model !== void 0) {
7415
7610
  next.provider = model.provider;
@@ -7433,7 +7628,7 @@ async function recordEffectiveInvocationModel(runDirectory, model, engine, host,
7433
7628
  if (host !== void 0) {
7434
7629
  next.host = host;
7435
7630
  }
7436
- await writeFile5(
7631
+ await writeFile6(
7437
7632
  ledgerPath,
7438
7633
  `${JSON.stringify(next, null, 2)}
7439
7634
  `,
@@ -7441,9 +7636,9 @@ async function recordEffectiveInvocationModel(runDirectory, model, engine, host,
7441
7636
  );
7442
7637
  }
7443
7638
  async function mergeInvocationIdentityPage(runDirectory, fields) {
7444
- const ledgerPath = join17(runDirectory, "invocation.json");
7445
- const current = JSON.parse(await readFile10(ledgerPath, "utf8"));
7446
- await writeFile5(
7639
+ const ledgerPath = join18(runDirectory, "invocation.json");
7640
+ const current = JSON.parse(await readFile11(ledgerPath, "utf8"));
7641
+ await writeFile6(
7447
7642
  ledgerPath,
7448
7643
  `${JSON.stringify({
7449
7644
  ...current,
@@ -7458,14 +7653,14 @@ async function persistAdmittedSourceRunPath(admitted, sourceRunPath) {
7458
7653
  throw new Error("persistAdmittedSourceRunPath requires a non-empty sourceRunPath");
7459
7654
  }
7460
7655
  const admittedPath = admitted.admittedRequestPath;
7461
- const current = JSON.parse(await readFile10(admittedPath, "utf8"));
7656
+ const current = JSON.parse(await readFile11(admittedPath, "utf8"));
7462
7657
  if (typeof current.sourceRunPath === "string") {
7463
7658
  if (current.sourceRunPath === sourceRunPath) return;
7464
7659
  throw new Error(
7465
7660
  `persistAdmittedSourceRunPath refuses to replace ${current.sourceRunPath} with ${sourceRunPath}`
7466
7661
  );
7467
7662
  }
7468
- await writeFile5(
7663
+ await writeFile6(
7469
7664
  admittedPath,
7470
7665
  `${JSON.stringify({ ...current, sourceRunPath }, null, 2)}
7471
7666
  `,
@@ -7507,8 +7702,8 @@ async function bindCourtTicketNumbersOnAdmitted(admitted, courtTicketNumbers) {
7507
7702
  }
7508
7703
  const frozen = Object.freeze([...projected]);
7509
7704
  const admittedPath = admitted.admittedRequestPath;
7510
- const current = JSON.parse(await readFile10(admittedPath, "utf8"));
7511
- await writeFile5(
7705
+ const current = JSON.parse(await readFile11(admittedPath, "utf8"));
7706
+ await writeFile6(
7512
7707
  admittedPath,
7513
7708
  `${JSON.stringify({ ...current, courtTicketNumbers: frozen }, null, 2)}
7514
7709
  `,
@@ -7529,8 +7724,8 @@ async function relocateAdmittedRunToTicket(admitted, authority, heldLease) {
7529
7724
  runId: admitted.runId,
7530
7725
  role: admitted.role
7531
7726
  });
7532
- ensureRoleRunDirectory(ledgerHome, dirname9(target.runDirectory));
7533
- await rename(oldRunDirectory, target.runDirectory);
7727
+ ensureRoleRunDirectory(ledgerHome, dirname10(target.runDirectory));
7728
+ await rename2(oldRunDirectory, target.runDirectory);
7534
7729
  heldLease?.relocate(target.runDirectory);
7535
7730
  const admittedRecord = admitted;
7536
7731
  rewriteRunDirectoryPathFields(
@@ -7567,9 +7762,9 @@ async function bindTicketNumberOnRunDirectory(runDirectory, ticketNumber) {
7567
7762
  ticketNumber,
7568
7763
  "bindTicketNumberOnRunDirectory"
7569
7764
  );
7570
- const admittedPath = join17(runDirectory, "admitted-request.json");
7571
- const invocationPath = join17(runDirectory, "invocation.json");
7572
- const admitted = JSON.parse(await readFile10(admittedPath, "utf8"));
7765
+ const admittedPath = join18(runDirectory, "admitted-request.json");
7766
+ const invocationPath = join18(runDirectory, "invocation.json");
7767
+ const admitted = JSON.parse(await readFile11(admittedPath, "utf8"));
7573
7768
  const existing = admitted.ticketNumber;
7574
7769
  if (typeof existing === "number") {
7575
7770
  if (existing === ticketNumber) return;
@@ -7579,7 +7774,7 @@ async function bindTicketNumberOnRunDirectory(runDirectory, ticketNumber) {
7579
7774
  }
7580
7775
  if (existsSync6(invocationPath)) {
7581
7776
  const invocation = JSON.parse(
7582
- await readFile10(invocationPath, "utf8")
7777
+ await readFile11(invocationPath, "utf8")
7583
7778
  );
7584
7779
  if (typeof invocation.ticketNumber === "number" && invocation.ticketNumber !== ticketNumber) {
7585
7780
  throw new Error(
@@ -7587,7 +7782,7 @@ async function bindTicketNumberOnRunDirectory(runDirectory, ticketNumber) {
7587
7782
  );
7588
7783
  }
7589
7784
  }
7590
- await writeFile5(
7785
+ await writeFile6(
7591
7786
  admittedPath,
7592
7787
  `${JSON.stringify({ ...admitted, ticketNumber }, null, 2)}
7593
7788
  `,
@@ -7604,7 +7799,7 @@ async function recordLaunchedPiIdentity(runDirectory, identity) {
7604
7799
  async function observeLaunchedRolePackageIdentity(packageRoot, selectedRoleEntry) {
7605
7800
  const rolePackageRoot = packageRoot;
7606
7801
  const raw = JSON.parse(
7607
- await readFile10(join17(rolePackageRoot, "package.json"), "utf8")
7802
+ await readFile11(join18(rolePackageRoot, "package.json"), "utf8")
7608
7803
  );
7609
7804
  if (typeof raw.version !== "string" || raw.version.trim() === "") {
7610
7805
  throw new Error(
@@ -7860,10 +8055,10 @@ async function freezeRegularFileAttachment(sourcePath, destinationDir, index) {
7860
8055
  `attachment must be a regular file (not a directory or symlink): ${sourcePath}`
7861
8056
  );
7862
8057
  }
7863
- const bytes = await readFile10(absolute);
8058
+ const bytes = await readFile11(absolute);
7864
8059
  const name = `${String(index).padStart(2, "0")}-${basename6(absolute)}`;
7865
- const frozenPath = join17(destinationDir, name);
7866
- await writeFile5(frozenPath, bytes);
8060
+ const frozenPath = join18(destinationDir, name);
8061
+ await writeFile6(frozenPath, bytes);
7867
8062
  return {
7868
8063
  attachment: {
7869
8064
  provenancePath: absolute,
@@ -7890,7 +8085,7 @@ async function freezeAttachments(attachmentPaths, attachmentsDirectory) {
7890
8085
  async function freezeAttachmentsIntoRun(attachmentPaths, runDirectory, summonsKey = `s-${Date.now().toString(36)}`) {
7891
8086
  if (attachmentPaths.length === 0) return [];
7892
8087
  const ledgerHome = resolveActivationLedgerHome(homeFromRunDirectory(runDirectory));
7893
- const attachmentsDirectory = join17(runDirectory, "attachments", summonsKey);
8088
+ const attachmentsDirectory = join18(runDirectory, "attachments", summonsKey);
7894
8089
  ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
7895
8090
  return freezeAttachments(attachmentPaths, attachmentsDirectory);
7896
8091
  }
@@ -7948,7 +8143,7 @@ async function admitStandardMaterialInvocation(role, options) {
7948
8143
  })),
7949
8144
  ...ticketFields
7950
8145
  };
7951
- const admittedRequestPath = join17(runDirectory, "admitted-request.json");
8146
+ const admittedRequestPath = join18(runDirectory, "admitted-request.json");
7952
8147
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
7953
8148
  sessionDirectory,
7954
8149
  sessionFile
@@ -8050,7 +8245,7 @@ async function admitCountersignInvocation(options) {
8050
8245
  mediaKind: a.mediaKind
8051
8246
  }))
8052
8247
  };
8053
- const admittedRequestPath = join17(runDirectory, "admitted-request.json");
8248
+ const admittedRequestPath = join18(runDirectory, "admitted-request.json");
8054
8249
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
8055
8250
  sessionDirectory,
8056
8251
  sessionFile
@@ -8076,7 +8271,7 @@ function buildCountersignTransportPrompt(admitted, engineMaterial) {
8076
8271
  async function loadAdmittedJudgeRequest(runDirectory) {
8077
8272
  try {
8078
8273
  const raw = JSON.parse(
8079
- await readFile10(join17(runDirectory, "admitted-request.json"), "utf8")
8274
+ await readFile11(join18(runDirectory, "admitted-request.json"), "utf8")
8080
8275
  );
8081
8276
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return void 0;
8082
8277
  const record4 = raw;
@@ -8131,8 +8326,8 @@ async function admitCoderInvocation(options) {
8131
8326
  home: options.home
8132
8327
  });
8133
8328
  const attachments = await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
8134
- const taskPath = join17(runDirectory, "task.md");
8135
- await writeFile5(taskPath, instruction, "utf8");
8329
+ const taskPath = join18(runDirectory, "task.md");
8330
+ await writeFile6(taskPath, instruction, "utf8");
8136
8331
  const admitted = {
8137
8332
  role: "coder",
8138
8333
  phase: options.phase,
@@ -8152,7 +8347,7 @@ async function admitCoderInvocation(options) {
8152
8347
  mediaKind: a.mediaKind
8153
8348
  }))
8154
8349
  };
8155
- const admittedRequestPath = join17(runDirectory, "admitted-request.json");
8350
+ const admittedRequestPath = join18(runDirectory, "admitted-request.json");
8156
8351
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
8157
8352
  sessionDirectory,
8158
8353
  sessionFile
@@ -8202,7 +8397,7 @@ async function admitFixerInvocation(options) {
8202
8397
  if (options.prerequisitesPath !== void 0) {
8203
8398
  const absolutePrereq = isAbsolute7(options.prerequisitesPath) ? options.prerequisitesPath : resolve9(options.prerequisitesPath);
8204
8399
  try {
8205
- prerequisitesSource = await readFile10(absolutePrereq, "utf8");
8400
+ prerequisitesSource = await readFile11(absolutePrereq, "utf8");
8206
8401
  } catch (error) {
8207
8402
  throw new CliUsageError(
8208
8403
  `fixer prerequisites path is unreadable: ${options.prerequisitesPath}`,
@@ -8238,16 +8433,16 @@ async function admitFixerInvocation(options) {
8238
8433
  const attachments = await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
8239
8434
  let prerequisitesPath;
8240
8435
  if (prerequisitesSource !== void 0) {
8241
- prerequisitesPath = join17(runDirectory, "prerequisites.json");
8242
- await writeFile5(
8436
+ prerequisitesPath = join18(runDirectory, "prerequisites.json");
8437
+ await writeFile6(
8243
8438
  prerequisitesPath,
8244
8439
  `${JSON.stringify(prerequisites, null, 2)}
8245
8440
  `,
8246
8441
  "utf8"
8247
8442
  );
8248
8443
  }
8249
- const packetPath = join17(runDirectory, "fix-packet.md");
8250
- await writeFile5(packetPath, instruction, "utf8");
8444
+ const packetPath = join18(runDirectory, "fix-packet.md");
8445
+ await writeFile6(packetPath, instruction, "utf8");
8251
8446
  const admitted = {
8252
8447
  role: "fixer",
8253
8448
  phase: options.phase,
@@ -8272,7 +8467,7 @@ async function admitFixerInvocation(options) {
8272
8467
  mediaKind: a.mediaKind
8273
8468
  }))
8274
8469
  };
8275
- const admittedRequestPath = join17(runDirectory, "admitted-request.json");
8470
+ const admittedRequestPath = join18(runDirectory, "admitted-request.json");
8276
8471
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
8277
8472
  sessionDirectory,
8278
8473
  sessionFile
@@ -8492,8 +8687,8 @@ async function admitCollectorInvocation(options) {
8492
8687
  const prNumber = target.kind === "bound" ? target.prNumber : void 0;
8493
8688
  let requestManifestPath;
8494
8689
  if (manifestCanonicalJson !== void 0) {
8495
- requestManifestPath = join17(runDirectory, "request-manifest.json");
8496
- await writeFile5(requestManifestPath, manifestCanonicalJson, "utf8");
8690
+ requestManifestPath = join18(runDirectory, "request-manifest.json");
8691
+ await writeFile6(requestManifestPath, manifestCanonicalJson, "utf8");
8497
8692
  }
8498
8693
  const admitted = {
8499
8694
  role: "collector",
@@ -8518,7 +8713,7 @@ async function admitCollectorInvocation(options) {
8518
8713
  mediaKind: a.mediaKind
8519
8714
  }))
8520
8715
  };
8521
- const admittedRequestPath = join17(runDirectory, "admitted-request.json");
8716
+ const admittedRequestPath = join18(runDirectory, "admitted-request.json");
8522
8717
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
8523
8718
  sessionDirectory,
8524
8719
  sessionFile
@@ -8616,7 +8811,7 @@ function parseDoctorArgv(args) {
8616
8811
  }
8617
8812
  async function resolveDoctorCaseRunsPath(options) {
8618
8813
  const ledgerHome = resolveActivationLedgerHome(options.home);
8619
- const defaultRuns = join17(
8814
+ const defaultRuns = join18(
8620
8815
  activationBookDirectory(ledgerHome, options.bookKey),
8621
8816
  String(options.issueNumber),
8622
8817
  "runs"
@@ -8747,7 +8942,7 @@ async function admitDoctorInvocation(options) {
8747
8942
  mediaKind: a.mediaKind
8748
8943
  }))
8749
8944
  };
8750
- const admittedRequestPath = join17(runDirectory, "admitted-request.json");
8945
+ const admittedRequestPath = join18(runDirectory, "admitted-request.json");
8751
8946
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
8752
8947
  sessionDirectory,
8753
8948
  sessionFile
@@ -8879,7 +9074,7 @@ async function admitNotaryInvocation(options) {
8879
9074
  ...ticketFields,
8880
9075
  ...options.correlationId === void 0 ? {} : { correlationId: options.correlationId }
8881
9076
  };
8882
- const admittedRequestPath = join17(runDirectory, "admitted-request.json");
9077
+ const admittedRequestPath = join18(runDirectory, "admitted-request.json");
8883
9078
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
8884
9079
  sessionDirectory,
8885
9080
  sessionFile
@@ -8982,7 +9177,7 @@ async function admitGleanerLeftInvocation(options) {
8982
9177
  attachments: [],
8983
9178
  ...options.correlationId === void 0 ? {} : { correlationId: options.correlationId }
8984
9179
  };
8985
- const admittedRequestPath = join17(runDirectory, "admitted-request.json");
9180
+ const admittedRequestPath = join18(runDirectory, "admitted-request.json");
8986
9181
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
8987
9182
  sessionDirectory,
8988
9183
  sessionFile
@@ -9111,7 +9306,7 @@ async function admitReviewerInvocation(options) {
9111
9306
  mediaKind: a.mediaKind
9112
9307
  }))
9113
9308
  };
9114
- const admittedRequestPath = join17(runDirectory, "admitted-request.json");
9309
+ const admittedRequestPath = join18(runDirectory, "admitted-request.json");
9115
9310
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
9116
9311
  sessionDirectory,
9117
9312
  sessionFile
@@ -9256,8 +9451,8 @@ async function admitMergerInvocation(options) {
9256
9451
  resolutionScope: [...derived.resolutionScope],
9257
9452
  authorizedChecks: []
9258
9453
  });
9259
- const mergerInputPath = join17(runDirectory, "merger-input.json");
9260
- await writeFile5(
9454
+ const mergerInputPath = join18(runDirectory, "merger-input.json");
9455
+ await writeFile6(
9261
9456
  mergerInputPath,
9262
9457
  `${JSON.stringify(mergerInput, null, 2)}
9263
9458
  `,
@@ -9287,7 +9482,7 @@ async function admitMergerInvocation(options) {
9287
9482
  mediaKind: a.mediaKind
9288
9483
  }))
9289
9484
  };
9290
- const admittedRequestPath = join17(runDirectory, "admitted-request.json");
9485
+ const admittedRequestPath = join18(runDirectory, "admitted-request.json");
9291
9486
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
9292
9487
  sessionDirectory,
9293
9488
  sessionFile
@@ -9571,15 +9766,15 @@ var init_invocation = __esm({
9571
9766
 
9572
9767
  // src/public-cli/load-production-acp-host.ts
9573
9768
  import { existsSync as existsSync7 } from "node:fs";
9574
- import { join as join18 } from "node:path";
9769
+ import { join as join19 } from "node:path";
9575
9770
  import { pathToFileURL } from "node:url";
9576
9771
  async function loadProductionAcpHostFactory(packageRoot, host) {
9577
9772
  const description = lookupHostDescription(host);
9578
9773
  if (description === void 0) {
9579
9774
  throw new Error(`unregistered host: ${host}`);
9580
9775
  }
9581
- const built = join18(packageRoot, "dist/acp-host/production-host.js");
9582
- const source = join18(packageRoot, "src/acp-host/production-host.ts");
9776
+ const built = join19(packageRoot, "dist/acp-host/production-host.js");
9777
+ const source = join19(packageRoot, "src/acp-host/production-host.ts");
9583
9778
  const target = existsSync7(built) ? built : source;
9584
9779
  const href = pathToFileURL(target).href;
9585
9780
  const mod = await import(href);
@@ -9595,15 +9790,15 @@ var init_load_production_acp_host = __esm({
9595
9790
 
9596
9791
  // src/public-cli/load-production-headless-host.ts
9597
9792
  import { existsSync as existsSync8 } from "node:fs";
9598
- import { join as join19 } from "node:path";
9793
+ import { join as join20 } from "node:path";
9599
9794
  import { pathToFileURL as pathToFileURL2 } from "node:url";
9600
9795
  async function loadProductionHeadlessHostFactory(packageRoot, host) {
9601
9796
  const description = lookupHeadlessHostDescription(host);
9602
9797
  if (description === void 0) {
9603
9798
  throw new Error(`unregistered headless host: ${host}`);
9604
9799
  }
9605
- const built = join19(packageRoot, "dist/headless-host/production-host.js");
9606
- const source = join19(packageRoot, "src/headless-host/production-host.ts");
9800
+ const built = join20(packageRoot, "dist/headless-host/production-host.js");
9801
+ const source = join20(packageRoot, "src/headless-host/production-host.ts");
9607
9802
  const target = existsSync8(built) ? built : source;
9608
9803
  const href = pathToFileURL2(target).href;
9609
9804
  const mod = await import(href);
@@ -9742,15 +9937,15 @@ __export(host_providers_exports, {
9742
9937
  renderHostProvidersTable: () => renderHostProvidersTable
9743
9938
  });
9744
9939
  import { readFileSync as readFileSync3 } from "node:fs";
9745
- import { join as join20 } from "node:path";
9940
+ import { join as join21 } from "node:path";
9746
9941
  function hostProvidersPath(home) {
9747
9942
  if (typeof home !== "string" || home.trim() === "") {
9748
9943
  throw new Error("home must be explicitly provided");
9749
9944
  }
9750
- return join20(home, ".ak-roles", "host-providers.json");
9945
+ return join21(home, ".ak-roles", "host-providers.json");
9751
9946
  }
9752
9947
  function hermesProviderModelsCachePath(home) {
9753
- return join20(home, ".hermes", "provider_models_cache.json");
9948
+ return join21(home, ".hermes", "provider_models_cache.json");
9754
9949
  }
9755
9950
  function parseHostProvidersTable(value) {
9756
9951
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -10083,8 +10278,8 @@ __export(config_exports, {
10083
10278
  setPersistentSeatHost: () => setPersistentSeatHost,
10084
10279
  validatePublicCliConfigAxes: () => validatePublicCliConfigAxes
10085
10280
  });
10086
- import { mkdir, readFile as readFile11, writeFile as writeFile6 } from "node:fs/promises";
10087
- import { dirname as dirname10, join as join21 } from "node:path";
10281
+ import { mkdir, readFile as readFile12, writeFile as writeFile7 } from "node:fs/promises";
10282
+ import { dirname as dirname11, join as join22 } from "node:path";
10088
10283
  function isGateOfficerSeat(value) {
10089
10284
  return GATE_OFFICER_SEATS.includes(value);
10090
10285
  }
@@ -10092,12 +10287,12 @@ function publicCliConfigPath(home) {
10092
10287
  if (typeof home !== "string" || home.trim() === "") {
10093
10288
  throw new Error("home must be explicitly provided");
10094
10289
  }
10095
- return join21(home, ".ak-roles", "public-cli.json");
10290
+ return join22(home, ".ak-roles", "public-cli.json");
10096
10291
  }
10097
10292
  async function loadPublicCliConfig(home) {
10098
10293
  const path = publicCliConfigPath(home);
10099
10294
  try {
10100
- const raw = await readFile11(path, "utf8");
10295
+ const raw = await readFile12(path, "utf8");
10101
10296
  return parsePublicCliConfig(JSON.parse(raw));
10102
10297
  } catch (error) {
10103
10298
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -10108,9 +10303,9 @@ async function loadPublicCliConfig(home) {
10108
10303
  }
10109
10304
  async function savePublicCliConfig(config, home) {
10110
10305
  const path = publicCliConfigPath(home);
10111
- await mkdir(dirname10(path), { recursive: true });
10306
+ await mkdir(dirname11(path), { recursive: true });
10112
10307
  const normalized = parsePublicCliConfig(config);
10113
- await writeFile6(
10308
+ await writeFile7(
10114
10309
  path,
10115
10310
  `${JSON.stringify(serializePublicCliConfig(normalized), null, 2)}
10116
10311
  `,
@@ -10560,7 +10755,7 @@ function credentialProvidersFromAuthData(data) {
10560
10755
  }
10561
10756
  async function loadCredentialProviders(agentDir) {
10562
10757
  try {
10563
- const raw = await readFile11(join21(agentDir, "auth.json"), "utf8");
10758
+ const raw = await readFile12(join22(agentDir, "auth.json"), "utf8");
10564
10759
  return credentialProvidersFromAuthData(JSON.parse(raw));
10565
10760
  } catch (error) {
10566
10761
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -10610,17 +10805,17 @@ var init_seat_ticket_binding = __esm({
10610
10805
  });
10611
10806
 
10612
10807
  // src/session-identity.ts
10613
- import { mkdir as mkdir2, readFile as readFile12, rename as rename2, writeFile as writeFile7 } from "node:fs/promises";
10614
- import { dirname as dirname11, join as join22 } from "node:path";
10808
+ import { mkdir as mkdir2, readFile as readFile13, rename as rename3, writeFile as writeFile8 } from "node:fs/promises";
10809
+ import { dirname as dirname12, join as join23 } from "node:path";
10615
10810
  function createSessionIdentityAuthority(authority, sessionBindingFile) {
10616
- const bindingPath = (principal) => join22(authority.decode(principal).sessionDirectory, sessionBindingFile);
10811
+ const bindingPath = (principal) => join23(authority.decode(principal).sessionDirectory, sessionBindingFile);
10617
10812
  return {
10618
10813
  resolveSessionFile(principal) {
10619
10814
  return authority.decode(principal).sessionFile;
10620
10815
  },
10621
10816
  async load(principal) {
10622
10817
  try {
10623
- const value = JSON.parse(await readFile12(bindingPath(principal), "utf8"));
10818
+ const value = JSON.parse(await readFile13(bindingPath(principal), "utf8"));
10624
10819
  if (typeof value !== "object" || value === null || typeof value.sessionId !== "string") {
10625
10820
  throw new Error("durable session binding is invalid");
10626
10821
  }
@@ -10632,11 +10827,11 @@ function createSessionIdentityAuthority(authority, sessionBindingFile) {
10632
10827
  },
10633
10828
  async bind(principal, sessionId) {
10634
10829
  const target = bindingPath(principal);
10635
- await mkdir2(dirname11(target), { recursive: true });
10830
+ await mkdir2(dirname12(target), { recursive: true });
10636
10831
  const temporary = `${target}.${process.pid}.tmp`;
10637
- await writeFile7(temporary, `${JSON.stringify({ sessionId })}
10832
+ await writeFile8(temporary, `${JSON.stringify({ sessionId })}
10638
10833
  `, { encoding: "utf8", mode: 384 });
10639
- await rename2(temporary, target);
10834
+ await rename3(temporary, target);
10640
10835
  }
10641
10836
  };
10642
10837
  }
@@ -10658,254 +10853,539 @@ var init_session_identity = __esm({
10658
10853
  }
10659
10854
  });
10660
10855
 
10661
- // src/ticket-provenance-contracts.ts
10662
- function isRecord4(value) {
10856
+ // src/ledger-session-read.ts
10857
+ import { readFile as readFile14 } from "node:fs/promises";
10858
+ function isRecord5(value) {
10663
10859
  return typeof value === "object" && value !== null && !Array.isArray(value);
10664
10860
  }
10665
- function projectTicketProvenanceDiagnostic(value) {
10666
- if (!isRecord4(value)) return void 0;
10667
- if (value.recordClass !== TICKET_PROVENANCE_RECORD_CLASS_DIAGNOSTIC) {
10668
- return void 0;
10669
- }
10670
- if (typeof value.diagnosticKind !== "string" || !DIAGNOSTIC_KINDS.has(value.diagnosticKind)) {
10671
- return void 0;
10861
+ async function readLedgerSessionJsonlLines(path) {
10862
+ const text = await readFile14(path, "utf8");
10863
+ const lines = text.split("\n");
10864
+ const out = [];
10865
+ for (let index = 0; index < lines.length; index += 1) {
10866
+ const raw = lines[index];
10867
+ if (!raw.trim()) continue;
10868
+ const lineNumber = index + 1;
10869
+ let row;
10870
+ try {
10871
+ row = JSON.parse(raw);
10872
+ } catch (error) {
10873
+ if (!(error instanceof SyntaxError)) throw error;
10874
+ const completedByTerminator = index < lines.length - 1;
10875
+ if (!completedByTerminator) break;
10876
+ out.push({
10877
+ line: lineNumber,
10878
+ raw,
10879
+ error: `malformed JSONL record in ${path} at line ${lineNumber}: ${error.message}`
10880
+ });
10881
+ continue;
10882
+ }
10883
+ if (!isRecord5(row)) {
10884
+ const kind = row === null ? "null" : Array.isArray(row) ? "array" : typeof row;
10885
+ out.push({
10886
+ line: lineNumber,
10887
+ raw,
10888
+ error: `complete non-object JSONL record in ${path} at line ${lineNumber}: expected object, got ${kind}`
10889
+ });
10890
+ continue;
10891
+ }
10892
+ out.push({ line: lineNumber, raw, row });
10672
10893
  }
10673
- if (typeof value.cause !== "string" || value.cause.length === 0) {
10674
- return void 0;
10894
+ return out;
10895
+ }
10896
+ async function readLedgerSessionJsonl(path) {
10897
+ const rows = [];
10898
+ for (const line2 of await readLedgerSessionJsonlLines(path)) {
10899
+ if (line2.row === void 0) {
10900
+ throw new LedgerSessionJsonlError(line2.error ?? `unreadable JSONL record in ${path} at line ${line2.line}`, {
10901
+ path,
10902
+ line: line2.line,
10903
+ prefixRows: rows
10904
+ });
10905
+ }
10906
+ rows.push(line2.row);
10675
10907
  }
10676
- if (typeof value.recordedAt !== "string" || value.recordedAt.length === 0) {
10677
- return void 0;
10908
+ return rows;
10909
+ }
10910
+ function extractSessionTimestampSpan(rows) {
10911
+ let startedAt;
10912
+ let endedAt;
10913
+ for (const row of rows) {
10914
+ if (typeof row.timestamp !== "string" || !row.timestamp) continue;
10915
+ if (startedAt === void 0) startedAt = row.timestamp;
10916
+ endedAt = row.timestamp;
10678
10917
  }
10679
10918
  return {
10680
- recordClass: TICKET_PROVENANCE_RECORD_CLASS_DIAGNOSTIC,
10681
- diagnosticKind: value.diagnosticKind,
10682
- cause: value.cause,
10683
- recordedAt: value.recordedAt,
10684
- ...typeof value.reason === "string" ? { reason: value.reason } : {}
10919
+ ...startedAt !== void 0 ? { startedAt } : {},
10920
+ ...endedAt !== void 0 ? { endedAt } : {}
10685
10921
  };
10686
10922
  }
10687
- function projectTicketProvenanceEntry(value) {
10688
- if (!isRecord4(value)) return void 0;
10689
- if (value.recordClass === TICKET_PROVENANCE_RECORD_CLASS_DIAGNOSTIC) {
10690
- return void 0;
10923
+ function intervalRowsAroundAnchor(rows, anchorIndex, isBindingRow) {
10924
+ let start = 0;
10925
+ for (let i = anchorIndex; i >= 0; i -= 1) {
10926
+ if (isBindingRow(rows[i])) {
10927
+ start = i;
10928
+ break;
10929
+ }
10691
10930
  }
10692
- if (typeof value.sourceKind !== "string" || typeof value.transcript !== "string") {
10693
- return void 0;
10931
+ let end = rows.length;
10932
+ for (let i = Math.max(anchorIndex, start) + 1; i < rows.length; i += 1) {
10933
+ if (isBindingRow(rows[i])) {
10934
+ end = i;
10935
+ break;
10936
+ }
10694
10937
  }
10695
- return value;
10938
+ return { rows: rows.slice(start, end), closed: end < rows.length };
10696
10939
  }
10697
- var TICKET_PROVENANCE_KIND, TICKET_PROVENANCE_HUMAN_VIEW, TICKET_PROVENANCE_RECORD_CLASS_DIAGNOSTIC, DIAGNOSTIC_KINDS;
10698
- var init_ticket_provenance_contracts = __esm({
10699
- "src/ticket-provenance-contracts.ts"() {
10940
+ var LedgerSessionJsonlError;
10941
+ var init_ledger_session_read = __esm({
10942
+ "src/ledger-session-read.ts"() {
10700
10943
  "use strict";
10701
- TICKET_PROVENANCE_KIND = "ticket-provenance";
10702
- TICKET_PROVENANCE_HUMAN_VIEW = "\u8D77\u5C45\u5F55.md";
10703
- TICKET_PROVENANCE_RECORD_CLASS_DIAGNOSTIC = "diagnostic";
10704
- DIAGNOSTIC_KINDS = /* @__PURE__ */ new Set([
10705
- "collector-failed",
10706
- "issue-source-failed",
10707
- "quote-verify-failed"
10708
- ]);
10944
+ LedgerSessionJsonlError = class extends Error {
10945
+ path;
10946
+ line;
10947
+ prefixRows;
10948
+ constructor(message, init) {
10949
+ super(message);
10950
+ this.name = "LedgerSessionJsonlError";
10951
+ this.path = init.path;
10952
+ this.line = init.line;
10953
+ this.prefixRows = init.prefixRows;
10954
+ }
10955
+ };
10709
10956
  }
10710
10957
  });
10711
10958
 
10712
- // src/ticket-provenance.ts
10713
- import { createHash as createHash6 } from "node:crypto";
10714
- import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "node:fs";
10715
- import { join as join23 } from "node:path";
10716
- function ticketProvenanceSubject(ticketNumber) {
10717
- if (!isSafePositiveTicketNumber(ticketNumber)) {
10718
- throw new Error(`ticket-provenance subject requires a positive ticket number, got ${String(ticketNumber)}`);
10959
+ // src/session-dialogue.ts
10960
+ function isRecord6(value) {
10961
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10962
+ }
10963
+ function nativeEventId(row) {
10964
+ for (const key of ["uuid", "id"]) {
10965
+ const value = row[key];
10966
+ if (typeof value === "string" && value !== "") return value;
10719
10967
  }
10720
- return String(ticketNumber);
10968
+ for (const nestKey of ["message", "payload"]) {
10969
+ const nested = row[nestKey];
10970
+ if (!isRecord6(nested)) continue;
10971
+ for (const key of ["uuid", "id"]) {
10972
+ const value = nested[key];
10973
+ if (typeof value === "string" && value !== "") return value;
10974
+ }
10975
+ }
10976
+ return void 0;
10721
10977
  }
10722
- function ticketProvenanceEntryIdentity(input) {
10723
- const ref = input.sourceRef;
10724
- const refKey = [
10725
- ref.sessionFile ?? "",
10726
- ref.entryId === void 0 ? "" : String(ref.entryId),
10727
- ref.path ?? "",
10728
- ref.url ?? ""
10729
- ].join("");
10730
- const material = [
10731
- String(input.ticketNumber),
10732
- input.sourceKind,
10733
- refKey,
10734
- input.transcript
10735
- ].join("\0");
10736
- return createHash6("sha256").update(material, "utf8").digest("hex");
10737
- }
10738
- function identityFromPayload(ticketNumber, payload) {
10739
- if (typeof payload === "object" && payload !== null && !Array.isArray(payload)) {
10740
- const record4 = payload;
10741
- if (typeof record4.sourceKind === "string" && typeof record4.transcript === "string") {
10742
- const sourceRef = typeof record4.sourceRef === "object" && record4.sourceRef !== null && !Array.isArray(record4.sourceRef) ? record4.sourceRef : {};
10743
- return ticketProvenanceEntryIdentity({
10744
- ticketNumber,
10745
- sourceKind: record4.sourceKind,
10746
- sourceRef,
10747
- transcript: record4.transcript
10748
- });
10978
+ function textParts(content) {
10979
+ if (typeof content === "string") return content === "" ? [] : [content];
10980
+ if (!Array.isArray(content)) return [];
10981
+ const out = [];
10982
+ for (const part of content) {
10983
+ if (!isRecord6(part) || !SPEAKER_TEXT_PART_TYPES.has(String(part.type))) continue;
10984
+ const text = part.text;
10985
+ if (typeof text === "string" && text !== "") out.push(text);
10986
+ }
10987
+ return out;
10988
+ }
10989
+ function responseItemMessage(row) {
10990
+ if (row.type !== "response_item" || !isRecord6(row.payload)) return void 0;
10991
+ if (row.payload.type !== "message") return void 0;
10992
+ return row.payload;
10993
+ }
10994
+ function messageBody(row) {
10995
+ if (isRecord6(row.message)) return row.message;
10996
+ return responseItemMessage(row);
10997
+ }
10998
+ function speakerOf(message) {
10999
+ if (message.role === "assistant") return "runner";
11000
+ if (message.role === "user") return "owner";
11001
+ return void 0;
11002
+ }
11003
+ function codexContentItemKinds(message) {
11004
+ const pass = message.internal_chat_message_metadata_passthrough;
11005
+ if (!isRecord6(pass) || !Array.isArray(pass.content_item_kinds)) return void 0;
11006
+ const kinds = [];
11007
+ for (const kind of pass.content_item_kinds) {
11008
+ if (typeof kind === "string" && kind !== "") kinds.push(kind);
11009
+ }
11010
+ return kinds;
11011
+ }
11012
+ function isCodexOwnerResponseItemUser(message) {
11013
+ if (message.role !== "user") return false;
11014
+ const kinds = codexContentItemKinds(message);
11015
+ if (kinds === void 0) return false;
11016
+ return kinds.some((kind) => kind.startsWith("user."));
11017
+ }
11018
+ function fromQueueEvent(row) {
11019
+ if (row.type !== "queue-operation" || row.operation !== "enqueue") return [];
11020
+ const content = row.content;
11021
+ if (typeof content !== "string" || content === "") return [];
11022
+ const id = nativeEventId(row);
11023
+ return [{ speaker: "owner", text: content, ...id === void 0 ? {} : { id } }];
11024
+ }
11025
+ function fromMessageEvent(row) {
11026
+ const message = messageBody(row);
11027
+ if (message === void 0) return [];
11028
+ if (message.role === "toolResult") return [];
11029
+ const speaker = speakerOf(message);
11030
+ if (speaker === void 0) return [];
11031
+ if (row.type === "response_item" && speaker === "owner") {
11032
+ if (!isCodexOwnerResponseItemUser(message)) return [];
11033
+ }
11034
+ const parts = textParts(message.content);
11035
+ if (parts.length === 0) return [];
11036
+ const text = parts.join("");
11037
+ if (text === "") return [];
11038
+ const id = nativeEventId(row);
11039
+ return [{ speaker, text, ...id === void 0 ? {} : { id } }];
11040
+ }
11041
+ function isOwnerDialogueMessage(row) {
11042
+ if (row.type === "response_item" || row.type === "event_msg") return false;
11043
+ return fromMessageEvent(row).some((event) => event.speaker === "owner");
11044
+ }
11045
+ function isRunnerMessage(row) {
11046
+ const message = messageBody(row);
11047
+ return message !== void 0 && message.role === "assistant";
11048
+ }
11049
+ function ownerMessagesMaterializingQueue(rows) {
11050
+ const skip = /* @__PURE__ */ new Set();
11051
+ const retainedByEnqueue = [];
11052
+ let pendingSkips = 0;
11053
+ for (let index = 0; index < rows.length; index += 1) {
11054
+ const row = rows[index];
11055
+ if (row === void 0) continue;
11056
+ if (row.type === "queue-operation") {
11057
+ if (row.operation === "enqueue") {
11058
+ retainedByEnqueue.push(fromQueueEvent(row).length > 0);
11059
+ continue;
11060
+ }
11061
+ if (row.operation === "dequeue" || row.operation === "remove") {
11062
+ const retained = retainedByEnqueue.shift();
11063
+ if (row.operation === "dequeue" && retained === true) {
11064
+ pendingSkips += 1;
11065
+ }
11066
+ continue;
11067
+ }
11068
+ }
11069
+ if (isRunnerMessage(row)) {
11070
+ pendingSkips = 0;
11071
+ continue;
11072
+ }
11073
+ if (pendingSkips > 0 && isOwnerDialogueMessage(row)) {
11074
+ skip.add(index);
11075
+ pendingSkips -= 1;
10749
11076
  }
10750
11077
  }
10751
- return createHash6("sha256").update(`${String(ticketNumber)}\0${JSON.stringify(payload)}`, "utf8").digest("hex");
11078
+ return skip;
10752
11079
  }
10753
- function appendTicketProvenanceEntry(input) {
10754
- const subject = ticketProvenanceSubject(input.ticketNumber);
10755
- const identity = identityFromPayload(input.ticketNumber, input.payload);
10756
- const record4 = typeof input.payload === "object" && input.payload !== null && !Array.isArray(input.payload) ? input.payload : void 0;
10757
- const sourceRef = record4 !== void 0 && typeof record4.sourceRef === "object" && record4.sourceRef !== null && !Array.isArray(record4.sourceRef) ? record4.sourceRef : void 0;
10758
- return sitianReport({
10759
- level: "event",
10760
- kind: TICKET_PROVENANCE_KIND,
10761
- identity,
10762
- subject,
10763
- cwd: input.cwd,
10764
- sessionParent: input.sessionParent,
10765
- ...input.home === void 0 ? {} : { home: input.home },
10766
- host: input.host ?? "diarist",
10767
- source: input.source ?? "diarist",
10768
- payload: input.payload,
10769
- raw: sourceRef !== void 0 && typeof sourceRef.sessionFile === "string" && (typeof sourceRef.entryId === "string" || typeof sourceRef.entryId === "number") ? {
10770
- sessionFile: sourceRef.sessionFile,
10771
- entryId: sourceRef.entryId
10772
- } : void 0
11080
+ function adaptSessionDialogue(rows) {
11081
+ const skipOwner = ownerMessagesMaterializingQueue(rows);
11082
+ return rows.map((row, index) => {
11083
+ if (row === void 0) return [];
11084
+ const queued = fromQueueEvent(row);
11085
+ if (queued.length > 0) return queued;
11086
+ if (skipOwner.has(index)) return [];
11087
+ return fromMessageEvent(row);
10773
11088
  });
10774
11089
  }
10775
- function resolveTicketProvenanceVolume(ticketNumber, cwd, home) {
10776
- const path = resolveSitianRecordPath({
11090
+ var SPEAKER_TEXT_PART_TYPES;
11091
+ var init_session_dialogue = __esm({
11092
+ "src/session-dialogue.ts"() {
11093
+ "use strict";
11094
+ SPEAKER_TEXT_PART_TYPES = /* @__PURE__ */ new Set(["text", "input_text", "output_text"]);
11095
+ }
11096
+ });
11097
+
11098
+ // src/ticket-provenance.ts
11099
+ import { basename as basename7, dirname as dirname13, join as join24, resolve as resolve10 } from "node:path";
11100
+ function dialogueSessionSourceRoots(home) {
11101
+ const machineHome = typeof home === "string" && home.trim() !== "" ? home : packageMachineHome();
11102
+ return [
11103
+ join24(machineHome, ".claude", "projects"),
11104
+ join24(machineHome, ".codex", "sessions"),
11105
+ join24(machineHome, ".pi", "agent", "sessions")
11106
+ ];
11107
+ }
11108
+ function isLedgerRoleSessionFile(absolute, home) {
11109
+ const machineHome = typeof home === "string" && home.trim() !== "" ? home : packageMachineHome();
11110
+ const ledgerHome = resolveActivationLedgerHome(machineHome);
11111
+ if (!physicallyContainedIn(ledgerHome, absolute)) return false;
11112
+ return basename7(absolute) === "session.jsonl" && basename7(dirname13(absolute)) === "session";
11113
+ }
11114
+ function assertDialogueSessionSourcePath(path, home) {
11115
+ const absolute = resolve10(path);
11116
+ for (const root of dialogueSessionSourceRoots(home)) {
11117
+ if (physicallyContainedIn(root, absolute)) return;
11118
+ }
11119
+ if (isLedgerRoleSessionFile(absolute, home)) return;
11120
+ throw new TicketProvenanceInputError(
11121
+ `session unreadable: ${path} (outside authorized source roots)`
11122
+ );
11123
+ }
11124
+ function ticketProvenanceSubject(ticketNumber) {
11125
+ if (!isSafePositiveTicketNumber(ticketNumber)) {
11126
+ throw new Error(
11127
+ `ticket-provenance subject requires a positive ticket number, got ${String(ticketNumber)}`
11128
+ );
11129
+ }
11130
+ return String(ticketNumber);
11131
+ }
11132
+ function ticketProvenanceRecordInput(ticketNumber, cwd, home) {
11133
+ return {
10777
11134
  level: "event",
10778
11135
  kind: TICKET_PROVENANCE_KIND,
10779
11136
  subject: ticketProvenanceSubject(ticketNumber),
10780
11137
  cwd,
10781
11138
  ...home === void 0 ? {} : { home }
10782
- });
10783
- return {
10784
- recordFile: path.recordFile,
10785
- volumeDir: path.sessionDir,
10786
- humanViewFile: join23(path.sessionDir, TICKET_PROVENANCE_HUMAN_VIEW)
10787
11139
  };
10788
11140
  }
11141
+ function resolveTicketProvenanceVolume(ticketNumber, cwd, home) {
11142
+ return resolveSitianVolume(ticketProvenanceRecordInput(ticketNumber, cwd, home));
11143
+ }
10789
11144
  async function readTicketProvenance(ticketNumber, cwd, home) {
10790
- const { recordFile } = resolveTicketProvenanceVolume(ticketNumber, cwd, home);
10791
- const { records } = await readSitianRecords(recordFile);
10792
- const entries = [];
10793
- const unprojected = [];
10794
- const diagnostics = [];
10795
- let skipped = 0;
10796
- for (const record4 of records) {
10797
- if (record4.kind !== TICKET_PROVENANCE_KIND) {
10798
- skipped += 1;
10799
- continue;
10800
- }
10801
- const diagnostic = projectTicketProvenanceDiagnostic(record4.payload);
10802
- if (diagnostic !== void 0) {
10803
- diagnostics.push(diagnostic);
11145
+ const { recordFile, text } = await readSitianVolumeText(
11146
+ ticketProvenanceRecordInput(ticketNumber, cwd, home)
11147
+ );
11148
+ if (text === void 0) {
11149
+ return { header: void 0, lines: [], recordFile };
11150
+ }
11151
+ const physical = text.split("\n");
11152
+ let header;
11153
+ const lines = [];
11154
+ let sawFirst = false;
11155
+ for (let index = 0; index < physical.length; index += 1) {
11156
+ const raw = physical[index];
11157
+ if (!raw.trim()) continue;
11158
+ let parsed;
11159
+ try {
11160
+ parsed = JSON.parse(raw);
11161
+ } catch {
10804
11162
  continue;
10805
11163
  }
10806
- const entry = projectTicketProvenanceEntry(record4.payload);
10807
- if (entry === void 0) {
10808
- unprojected.push(record4.payload);
10809
- continue;
11164
+ if (!sawFirst) {
11165
+ sawFirst = true;
11166
+ header = projectTicketProvenanceHeader(parsed);
11167
+ if (header !== void 0) continue;
10810
11168
  }
10811
- entries.push(entry);
11169
+ const line2 = projectTicketProvenanceLine(parsed);
11170
+ if (line2 !== void 0) lines.push(line2);
10812
11171
  }
10813
- return { entries, unprojected, diagnostics, records, recordFile, skipped };
11172
+ return { header, lines, recordFile };
10814
11173
  }
10815
- function markdownFenceFor(text) {
10816
- let longest = 0;
10817
- const runs = text.match(/`+/g);
10818
- if (runs !== null) {
10819
- for (const run of runs) {
10820
- if (run.length > longest) longest = run.length;
11174
+ function resolveBoundIndex(bound, sessionLines) {
11175
+ if (typeof bound.id === "string" && bound.id !== "") {
11176
+ for (let index = 0; index < sessionLines.length; index += 1) {
11177
+ const row = sessionLines[index].row;
11178
+ if (row === void 0) continue;
11179
+ if (nativeEventId(row) === bound.id) return index;
10821
11180
  }
11181
+ return void 0;
10822
11182
  }
10823
- return "`".repeat(Math.max(3, longest + 1));
10824
- }
10825
- function renderTicketProvenanceMarkdown(input) {
10826
- const unprojected = input.unprojected ?? [];
10827
- const lines = [
10828
- `# \u8D77\u5C45\u5F55 \xB7 #${input.ticketNumber}`,
10829
- "",
10830
- `\u6761\u76EE\u6570\uFF1A${input.entries.length + unprojected.length}`,
10831
- ""
10832
- ];
10833
- let index = 0;
10834
- for (const entry of input.entries) {
10835
- index += 1;
10836
- const sourceKind = typeof entry.sourceKind === "string" ? entry.sourceKind : "\u672A\u6295\u5F71";
10837
- const timestamp2 = typeof entry.timestamp === "string" ? entry.timestamp : "";
10838
- lines.push(`## ${index}. ${sourceKind} \xB7 ${timestamp2}`);
10839
- lines.push("");
10840
- const basis = entry.basis;
10841
- const method = typeof basis === "object" && basis !== null && !Array.isArray(basis) && typeof basis.method === "string" ? basis.method : "\u672A\u6295\u5F71";
10842
- lines.push(`- basis.method: \`${method}\``);
10843
- if (typeof basis === "object" && basis !== null && !Array.isArray(basis) && Array.isArray(basis.anchors) && basis.anchors.length > 0) {
10844
- lines.push(`- anchors: ${basis.anchors.map((a) => `\`${String(a)}\``).join(", ")}`);
11183
+ if (typeof bound.line === "number") {
11184
+ for (let index = 0; index < sessionLines.length; index += 1) {
11185
+ if (sessionLines[index].line === bound.line) return index;
10845
11186
  }
10846
- if (typeof basis === "object" && basis !== null && !Array.isArray(basis) && basis.note !== void 0) {
10847
- lines.push(`- note: ${String(basis.note)}`);
11187
+ return void 0;
11188
+ }
11189
+ return void 0;
11190
+ }
11191
+ function amendmentKey(s, line2) {
11192
+ return `${s}:${line2}`;
11193
+ }
11194
+ function normalizeResolvedRanges(ranges, sessionLines, sessionPath) {
11195
+ const resolved = [];
11196
+ for (const range of ranges) {
11197
+ const fromIndex = resolveBoundIndex(range.from, sessionLines);
11198
+ const toIndex = resolveBoundIndex(range.to, sessionLines);
11199
+ if (fromIndex === void 0 || toIndex === void 0) {
11200
+ throw new TicketProvenanceInputError(
11201
+ `bound endpoint not found in ${sessionPath} (from=${JSON.stringify(range.from)} to=${JSON.stringify(range.to)})`
11202
+ );
10848
11203
  }
10849
- const sourceRef = typeof entry.sourceRef === "object" && entry.sourceRef !== null && !Array.isArray(entry.sourceRef) ? entry.sourceRef : {};
10850
- const refParts = [];
10851
- if (sourceRef.sessionFile !== void 0) {
10852
- refParts.push(`sessionFile=${String(sourceRef.sessionFile)}`);
11204
+ if (fromIndex > toIndex) {
11205
+ throw new TicketProvenanceInputError(
11206
+ `bound range inverted in ${sessionPath} (from index ${fromIndex} > to index ${toIndex})`
11207
+ );
10853
11208
  }
10854
- if (sourceRef.entryId !== void 0) {
10855
- refParts.push(`entryId=${String(sourceRef.entryId)}`);
11209
+ resolved.push({ fromIndex, toIndex });
11210
+ }
11211
+ resolved.sort(
11212
+ (left, right) => left.fromIndex - right.fromIndex || left.toIndex - right.toIndex
11213
+ );
11214
+ const merged = [];
11215
+ for (const range of resolved) {
11216
+ const last = merged[merged.length - 1];
11217
+ if (last !== void 0 && range.fromIndex <= last.toIndex + 1) {
11218
+ last.toIndex = Math.max(last.toIndex, range.toIndex);
11219
+ continue;
10856
11220
  }
10857
- if (sourceRef.path !== void 0) {
10858
- refParts.push(`path=${String(sourceRef.path)}`);
11221
+ merged.push({ fromIndex: range.fromIndex, toIndex: range.toIndex });
11222
+ }
11223
+ return merged;
11224
+ }
11225
+ async function projectSessionRanges(input) {
11226
+ assertDialogueSessionSourcePath(input.session.path, input.home);
11227
+ let sessionLines;
11228
+ try {
11229
+ sessionLines = await readLedgerSessionJsonlLines(input.session.path);
11230
+ } catch (error) {
11231
+ if (error instanceof TicketProvenanceInputError) throw error;
11232
+ const code = errnoCode(error);
11233
+ if (code === "ENOENT" || code === "ENOTDIR" || code === "EISDIR") {
11234
+ const detail = error instanceof Error ? error.message : String(error);
11235
+ throw new TicketProvenanceInputError(
11236
+ `session unreadable: ${input.session.path} (${detail})`,
11237
+ { cause: error }
11238
+ );
10859
11239
  }
10860
- if (sourceRef.url !== void 0) {
10861
- refParts.push(`url=${String(sourceRef.url)}`);
11240
+ throw error;
11241
+ }
11242
+ const rows = sessionLines.map((entry) => entry.row);
11243
+ const dialogue = adaptSessionDialogue(rows);
11244
+ const seenIds = input.seenIds;
11245
+ const lines = [];
11246
+ const unparsable = [];
11247
+ const ranges = normalizeResolvedRanges(
11248
+ input.session.ranges,
11249
+ sessionLines,
11250
+ input.session.path
11251
+ );
11252
+ for (const range of ranges) {
11253
+ for (let index = range.fromIndex; index <= range.toIndex; index += 1) {
11254
+ const entry = sessionLines[index];
11255
+ if (entry.row === void 0) {
11256
+ const key = amendmentKey(input.s, entry.line);
11257
+ const amendment = input.amendmentsByKey.get(key);
11258
+ if (amendment !== void 0) {
11259
+ lines.push({
11260
+ speaker: amendment.speaker,
11261
+ s: input.s,
11262
+ line: entry.line,
11263
+ text: amendment.text
11264
+ });
11265
+ } else {
11266
+ unparsable.push({ s: input.s, line: entry.line, raw: entry.raw });
11267
+ }
11268
+ continue;
11269
+ }
11270
+ for (const event of dialogue[index] ?? []) {
11271
+ if (event.id !== void 0) {
11272
+ if (seenIds.has(event.id)) continue;
11273
+ seenIds.add(event.id);
11274
+ }
11275
+ lines.push({
11276
+ speaker: event.speaker,
11277
+ s: input.s,
11278
+ line: entry.line,
11279
+ ...event.id === void 0 ? {} : { id: event.id },
11280
+ text: event.text
11281
+ });
11282
+ }
10862
11283
  }
10863
- if (refParts.length > 0) {
10864
- lines.push(`- sourceRef: ${refParts.join(" \xB7 ")}`);
11284
+ }
11285
+ return { lines, unparsable };
11286
+ }
11287
+ async function reprojectTicketProvenance(input) {
11288
+ const recordInput = ticketProvenanceRecordInput(
11289
+ input.ticketNumber,
11290
+ input.cwd,
11291
+ input.home
11292
+ );
11293
+ const prior = await readTicketProvenance(input.ticketNumber, input.cwd, input.home);
11294
+ const priorRaw = await readSitianVolumeText(recordInput);
11295
+ const priorNonEmpty = priorRaw.text !== void 0 && priorRaw.text.trim() !== "";
11296
+ const amendments = input.amendments ?? [];
11297
+ let sessions = input.sessions;
11298
+ if (sessions.length === 0) {
11299
+ if (amendments.length > 0) {
11300
+ const priorSessions = prior.header?.sessions;
11301
+ if (priorSessions === void 0 || priorSessions.length === 0) {
11302
+ throw new TicketProvenanceInputError(
11303
+ "amendments require sessions bounds (none submitted and no prior header sessions)"
11304
+ );
11305
+ }
11306
+ sessions = priorSessions;
11307
+ } else if (priorNonEmpty) {
11308
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
11309
+ const header2 = prior.header ?? {
11310
+ repo: resolveBookKeyFromGit(input.cwd),
11311
+ ticket: input.ticketNumber,
11312
+ createdAt: now2,
11313
+ updatedAt: now2,
11314
+ sessions: []
11315
+ };
11316
+ return {
11317
+ recordFile: prior.recordFile,
11318
+ header: header2,
11319
+ lines: prior.lines,
11320
+ unparsable: []
11321
+ };
10865
11322
  }
10866
- lines.push("");
10867
- const transcript = typeof entry.transcript === "string" ? entry.transcript : JSON.stringify(entry);
10868
- const fence = markdownFenceFor(transcript);
10869
- lines.push(fence);
10870
- lines.push(transcript);
10871
- lines.push(fence);
10872
- lines.push("");
10873
11323
  }
10874
- for (const payload of unprojected) {
10875
- index += 1;
10876
- lines.push(`## ${index}. \u672A\u6295\u5F71`);
10877
- lines.push("");
10878
- const text = typeof payload === "string" ? payload : JSON.stringify(payload);
10879
- const fence = markdownFenceFor(text);
10880
- lines.push(fence);
10881
- lines.push(text);
10882
- lines.push(fence);
10883
- lines.push("");
11324
+ const amendmentsByKey = /* @__PURE__ */ new Map();
11325
+ for (const amendment of amendments) {
11326
+ amendmentsByKey.set(amendmentKey(amendment.s, amendment.line), amendment);
10884
11327
  }
10885
- return lines.join("\n");
10886
- }
10887
- function ensureTicketProvenanceVolume(ticketNumber, cwd, home) {
10888
- const volume = resolveTicketProvenanceVolume(ticketNumber, cwd, home);
10889
- mkdirSync3(volume.volumeDir, { recursive: true });
10890
- appendFileSync2(volume.recordFile, "", "utf8");
10891
- return volume;
10892
- }
10893
- function writeTicketProvenanceHumanView(input) {
10894
- const volume = ensureTicketProvenanceVolume(input.ticketNumber, input.cwd, input.home);
10895
- const md = renderTicketProvenanceMarkdown({
10896
- ticketNumber: input.ticketNumber,
10897
- entries: input.entries,
10898
- ...input.unprojected === void 0 ? {} : { unprojected: input.unprojected }
10899
- });
10900
- writeFileSync3(volume.humanViewFile, md, "utf8");
10901
- return volume.humanViewFile;
11328
+ const lines = [];
11329
+ const unparsable = [];
11330
+ const seenIds = /* @__PURE__ */ new Set();
11331
+ for (let s = 0; s < sessions.length; s += 1) {
11332
+ const projected = await projectSessionRanges({
11333
+ s,
11334
+ session: sessions[s],
11335
+ amendmentsByKey,
11336
+ seenIds,
11337
+ ...input.home === void 0 ? {} : { home: input.home }
11338
+ });
11339
+ lines.push(...projected.lines);
11340
+ unparsable.push(...projected.unparsable);
11341
+ }
11342
+ const now = (/* @__PURE__ */ new Date()).toISOString();
11343
+ const header = {
11344
+ repo: resolveBookKeyFromGit(input.cwd),
11345
+ ticket: input.ticketNumber,
11346
+ createdAt: prior.header?.createdAt ?? now,
11347
+ updatedAt: now,
11348
+ sessions
11349
+ };
11350
+ if (unparsable.length > 0) {
11351
+ return {
11352
+ recordFile: prior.recordFile,
11353
+ header,
11354
+ lines,
11355
+ unparsable
11356
+ };
11357
+ }
11358
+ const body = `${[JSON.stringify(header), ...lines.map((line2) => JSON.stringify(line2))].join("\n")}
11359
+ `;
11360
+ const volume = await rewriteSitianVolume({ ...recordInput, body });
11361
+ return {
11362
+ recordFile: volume.recordFile,
11363
+ header,
11364
+ lines,
11365
+ unparsable
11366
+ };
10902
11367
  }
11368
+ var TicketProvenanceInputError;
10903
11369
  var init_ticket_provenance = __esm({
10904
11370
  "src/ticket-provenance.ts"() {
10905
11371
  "use strict";
10906
- init_sitian_facade();
11372
+ init_activation_ledger_git();
11373
+ init_activation_ledger_topology();
11374
+ init_ledger_session_read();
10907
11375
  init_run_ticket_number();
11376
+ init_session_dialogue();
11377
+ init_sitian_facade();
10908
11378
  init_ticket_provenance_contracts();
11379
+ TicketProvenanceInputError = class extends Error {
11380
+ code = "ticket-provenance-input";
11381
+ constructor(message, options) {
11382
+ super(
11383
+ message,
11384
+ options?.cause === void 0 ? void 0 : { cause: options.cause }
11385
+ );
11386
+ this.name = "TicketProvenanceInputError";
11387
+ }
11388
+ };
10909
11389
  }
10910
11390
  });
10911
11391
 
@@ -10916,9 +11396,9 @@ __export(case_dossier_delivery_exports, {
10916
11396
  loadCaseDossierReadingMaterial: () => loadCaseDossierReadingMaterial,
10917
11397
  projectCaseDossierPointerSection: () => projectCaseDossierPointerSection
10918
11398
  });
10919
- import { mkdtemp as mkdtemp2, readFile as readFile13, rm as rm2, writeFile as writeFile8 } from "node:fs/promises";
11399
+ import { mkdtemp as mkdtemp2, readFile as readFile15, rm as rm3, writeFile as writeFile9 } from "node:fs/promises";
10920
11400
  import { tmpdir as tmpdir2 } from "node:os";
10921
- import { join as join24 } from "node:path";
11401
+ import { join as join25 } from "node:path";
10922
11402
  function describeDossierFile(path) {
10923
11403
  return path;
10924
11404
  }
@@ -10933,7 +11413,6 @@ async function projectCaseDossierPointerSection(input) {
10933
11413
  CASE_DOSSIER_SECTION_HEADING,
10934
11414
  "",
10935
11415
  `\u7968\u53F7\uFF1A#${input.ticketNumber}`,
10936
- `\u4EBA\u8BFB\u89C6\u56FE\uFF1A${describeDossierFile(volume.humanViewFile)}`,
10937
11416
  `\u8BB0\u5F55\u5377\u5B97\uFF1A${describeDossierFile(volume.recordFile)}`
10938
11417
  ].join("\n");
10939
11418
  }
@@ -10944,10 +11423,10 @@ async function deliverCaseDossierAsAttachment(input) {
10944
11423
  home: input.home
10945
11424
  });
10946
11425
  if (section === void 0) return void 0;
10947
- const stagingDir = await mkdtemp2(join24(tmpdir2(), "ak-case-dossier-"));
11426
+ const stagingDir = await mkdtemp2(join25(tmpdir2(), "ak-case-dossier-"));
10948
11427
  try {
10949
- const stagingPath = join24(stagingDir, CASE_DOSSIER_ATTACH_FILE);
10950
- await writeFile8(stagingPath, `${section}
11428
+ const stagingPath = join25(stagingDir, CASE_DOSSIER_ATTACH_FILE);
11429
+ await writeFile9(stagingPath, `${section}
10951
11430
  `, "utf8");
10952
11431
  return await freezeAttachmentsIntoRun(
10953
11432
  [stagingPath],
@@ -10955,11 +11434,11 @@ async function deliverCaseDossierAsAttachment(input) {
10955
11434
  CASE_DOSSIER_ATTACH_KEY
10956
11435
  );
10957
11436
  } finally {
10958
- await rm2(stagingDir, { recursive: true, force: true });
11437
+ await rm3(stagingDir, { recursive: true, force: true });
10959
11438
  }
10960
11439
  }
10961
11440
  async function loadCaseDossierReadingMaterial(runDirectory) {
10962
- const frozenPath = join24(
11441
+ const frozenPath = join25(
10963
11442
  runDirectory,
10964
11443
  "attachments",
10965
11444
  CASE_DOSSIER_ATTACH_KEY,
@@ -10967,7 +11446,7 @@ async function loadCaseDossierReadingMaterial(runDirectory) {
10967
11446
  );
10968
11447
  let section;
10969
11448
  try {
10970
- section = await readFile13(frozenPath, "utf8");
11449
+ section = await readFile15(frozenPath, "utf8");
10971
11450
  } catch (error) {
10972
11451
  if (error.code === "ENOENT") return void 0;
10973
11452
  throw error;
@@ -10989,7 +11468,7 @@ var init_case_dossier_delivery = __esm({
10989
11468
 
10990
11469
  // src/host-transition-prior-native.ts
10991
11470
  import { access as access3, readdir as readdir5 } from "node:fs/promises";
10992
- import { dirname as dirname12, join as join25 } from "node:path";
11471
+ import { dirname as dirname14, join as join26 } from "node:path";
10993
11472
  function isEnoent3(error) {
10994
11473
  return typeof error === "object" && error !== null && error.code === "ENOENT";
10995
11474
  }
@@ -11003,7 +11482,7 @@ async function listPiNativeRecordPaths(sessionFile) {
11003
11482
  }
11004
11483
  }
11005
11484
  async function listSitianRecordPaths(sessionParent) {
11006
- const sessionRoot = dirname12(sessionParent);
11485
+ const sessionRoot = dirname14(sessionParent);
11007
11486
  let entries;
11008
11487
  try {
11009
11488
  entries = await readdir5(sessionRoot, { withFileTypes: true });
@@ -11014,7 +11493,7 @@ async function listSitianRecordPaths(sessionParent) {
11014
11493
  const recordPaths = [];
11015
11494
  for (const entry of entries) {
11016
11495
  if (!entry.isDirectory()) continue;
11017
- const recordFile = join25(sessionRoot, entry.name, "records.jsonl");
11496
+ const recordFile = join26(sessionRoot, entry.name, "records.jsonl");
11018
11497
  try {
11019
11498
  await access3(recordFile);
11020
11499
  recordPaths.push(recordFile);
@@ -11405,13 +11884,13 @@ var init_reviewer_dispatch = __esm({
11405
11884
  });
11406
11885
 
11407
11886
  // src/public-cli/reviewer-dispatch-rejection.ts
11408
- import { readFile as readFile14, unlink as unlink3 } from "node:fs/promises";
11409
- import { join as join26 } from "node:path";
11887
+ import { readFile as readFile16, unlink as unlink3 } from "node:fs/promises";
11888
+ import { join as join27 } from "node:path";
11410
11889
  function isReviewerPreflightViolation(value) {
11411
11890
  return typeof value === "string" && REVIEWER_PREFLIGHT_VIOLATIONS.includes(value);
11412
11891
  }
11413
11892
  function reviewerDispatchRejectionPath(runDirectory) {
11414
- return join26(runDirectory, REVIEWER_DISPATCH_REJECTION_FILE);
11893
+ return join27(runDirectory, REVIEWER_DISPATCH_REJECTION_FILE);
11415
11894
  }
11416
11895
  async function clearReviewerDispatchRejection(runDirectory) {
11417
11896
  try {
@@ -11426,7 +11905,7 @@ async function clearReviewerDispatchRejection(runDirectory) {
11426
11905
  async function readReviewerDispatchRejection(runDirectory) {
11427
11906
  let raw;
11428
11907
  try {
11429
- raw = await readFile14(reviewerDispatchRejectionPath(runDirectory), "utf8");
11908
+ raw = await readFile16(reviewerDispatchRejectionPath(runDirectory), "utf8");
11430
11909
  } catch (error) {
11431
11910
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
11432
11911
  return void 0;
@@ -11461,96 +11940,10 @@ var init_reviewer_dispatch_rejection = __esm({
11461
11940
  }
11462
11941
  });
11463
11942
 
11464
- // src/ledger-session-read.ts
11465
- import { readFile as readFile15 } from "node:fs/promises";
11466
- function isRecord5(value) {
11467
- return typeof value === "object" && value !== null && !Array.isArray(value);
11468
- }
11469
- async function readLedgerSessionJsonl(path) {
11470
- const text = await readFile15(path, "utf8");
11471
- const lines = text.split("\n");
11472
- const rows = [];
11473
- for (let index = 0; index < lines.length; index += 1) {
11474
- const line2 = lines[index];
11475
- if (!line2.trim()) continue;
11476
- let row;
11477
- try {
11478
- row = JSON.parse(line2);
11479
- } catch (error) {
11480
- if (!(error instanceof SyntaxError)) throw error;
11481
- const completedByTerminator = index < lines.length - 1;
11482
- if (completedByTerminator) {
11483
- throw new LedgerSessionJsonlError(
11484
- `malformed JSONL record in ${path} at line ${index + 1}: ${error.message}`,
11485
- { path, line: index + 1, prefixRows: rows }
11486
- );
11487
- }
11488
- break;
11489
- }
11490
- if (!isRecord5(row)) {
11491
- const kind = row === null ? "null" : Array.isArray(row) ? "array" : typeof row;
11492
- throw new LedgerSessionJsonlError(
11493
- `complete non-object JSONL record in ${path} at line ${index + 1}: expected object, got ${kind}`,
11494
- { path, line: index + 1, prefixRows: rows }
11495
- );
11496
- }
11497
- rows.push(row);
11498
- }
11499
- return rows;
11500
- }
11501
- function extractSessionTimestampSpan(rows) {
11502
- let startedAt;
11503
- let endedAt;
11504
- for (const row of rows) {
11505
- if (typeof row.timestamp !== "string" || !row.timestamp) continue;
11506
- if (startedAt === void 0) startedAt = row.timestamp;
11507
- endedAt = row.timestamp;
11508
- }
11509
- return {
11510
- ...startedAt !== void 0 ? { startedAt } : {},
11511
- ...endedAt !== void 0 ? { endedAt } : {}
11512
- };
11513
- }
11514
- function intervalRowsAroundAnchor(rows, anchorIndex, isBindingRow) {
11515
- let start = 0;
11516
- for (let i = anchorIndex; i >= 0; i -= 1) {
11517
- if (isBindingRow(rows[i])) {
11518
- start = i;
11519
- break;
11520
- }
11521
- }
11522
- let end = rows.length;
11523
- for (let i = Math.max(anchorIndex, start) + 1; i < rows.length; i += 1) {
11524
- if (isBindingRow(rows[i])) {
11525
- end = i;
11526
- break;
11527
- }
11528
- }
11529
- return { rows: rows.slice(start, end), closed: end < rows.length };
11530
- }
11531
- var LedgerSessionJsonlError;
11532
- var init_ledger_session_read = __esm({
11533
- "src/ledger-session-read.ts"() {
11534
- "use strict";
11535
- LedgerSessionJsonlError = class extends Error {
11536
- path;
11537
- line;
11538
- prefixRows;
11539
- constructor(message, init) {
11540
- super(message);
11541
- this.name = "LedgerSessionJsonlError";
11542
- this.path = init.path;
11543
- this.line = init.line;
11544
- this.prefixRows = init.prefixRows;
11545
- }
11546
- };
11547
- }
11548
- });
11549
-
11550
11943
  // src/analyst-gate-cycles-read.ts
11551
11944
  import { readdir as readdir6 } from "node:fs/promises";
11552
- import { join as join27 } from "node:path";
11553
- function isRecord6(value) {
11945
+ import { join as join28 } from "node:path";
11946
+ function isRecord7(value) {
11554
11947
  return typeof value === "object" && value !== null && !Array.isArray(value);
11555
11948
  }
11556
11949
  function isParentAttemptBindingRow(row) {
@@ -11580,7 +11973,7 @@ function isGateTerminatingToolName(toolName) {
11580
11973
  function acceptedGateReceiptIds(rows) {
11581
11974
  const accepted = /* @__PURE__ */ new Set();
11582
11975
  for (const row of rows) {
11583
- const message = isRecord6(row.message) ? row.message : void 0;
11976
+ const message = isRecord7(row.message) ? row.message : void 0;
11584
11977
  if (message?.role !== "toolResult") continue;
11585
11978
  if (typeof message.toolCallId !== "string" || message.toolCallId.length === 0) continue;
11586
11979
  if (message.isError === false) accepted.add(message.toolCallId);
@@ -11615,7 +12008,7 @@ function nearestAttemptBindingBefore(rows, beforeIndex) {
11615
12008
  for (let i = beforeIndex - 1; i >= 0; i -= 1) {
11616
12009
  const row = rows[i];
11617
12010
  if (!isParentAttemptBindingRow(row)) continue;
11618
- if (!isRecord6(row.data) || !isRecord6(row.data.parent)) continue;
12011
+ if (!isRecord7(row.data) || !isRecord7(row.data.parent)) continue;
11619
12012
  const id = row.data.parent.attemptEntryId;
11620
12013
  const sessionFile = row.data.parent.sessionFile;
11621
12014
  return {
@@ -11630,10 +12023,10 @@ function extractAllAcceptedGateToolCalls(rows) {
11630
12023
  const out = [];
11631
12024
  for (let rowIndex = 0; rowIndex < rows.length; rowIndex += 1) {
11632
12025
  const row = rows[rowIndex];
11633
- const message = isRecord6(row.message) ? row.message : void 0;
12026
+ const message = isRecord7(row.message) ? row.message : void 0;
11634
12027
  if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
11635
12028
  for (const part of message.content) {
11636
- if (!isRecord6(part) || part.type !== "toolCall") continue;
12029
+ if (!isRecord7(part) || part.type !== "toolCall") continue;
11637
12030
  if (typeof part.id !== "string" || part.id.length === 0) continue;
11638
12031
  if (typeof part.name !== "string" || part.name.length === 0) continue;
11639
12032
  if (!isGateTerminatingToolName(part.name)) continue;
@@ -11641,7 +12034,7 @@ function extractAllAcceptedGateToolCalls(rows) {
11641
12034
  const binding = nearestAttemptBindingBefore(rows, rowIndex);
11642
12035
  out.push({
11643
12036
  toolName: part.name,
11644
- args: isRecord6(part.arguments) ? part.arguments : void 0,
12037
+ args: isRecord7(part.arguments) ? part.arguments : void 0,
11645
12038
  accepted: true,
11646
12039
  rowIndex,
11647
12040
  ...binding
@@ -11764,17 +12157,17 @@ function pairGateRounds(volumes) {
11764
12157
  return rounds.sort((a, b) => a.officerStartedAt.localeCompare(b.officerStartedAt)).map((round, index) => ({ ...round, roundIndex: index + 1 }));
11765
12158
  }
11766
12159
  async function resolveOfficerSessionFromPointerFile(pointerPath) {
11767
- const { readFile: readFile25 } = await import("node:fs/promises");
12160
+ const { readFile: readFile26 } = await import("node:fs/promises");
11768
12161
  let raw;
11769
12162
  try {
11770
- raw = JSON.parse(await readFile25(pointerPath, "utf8"));
12163
+ raw = JSON.parse(await readFile26(pointerPath, "utf8"));
11771
12164
  } catch (error) {
11772
12165
  throw new Error(
11773
12166
  `direct officer run pointer unreadable in ${pointerPath}: ${error instanceof Error ? error.message : String(error)}`,
11774
12167
  { cause: error }
11775
12168
  );
11776
12169
  }
11777
- if (!isRecord6(raw) || raw.kind !== "direct-officer-run-pointer" || raw.version !== 1) {
12170
+ if (!isRecord7(raw) || raw.kind !== "direct-officer-run-pointer" || raw.version !== 1) {
11778
12171
  throw new Error(`direct officer run pointer has unknown shape in ${pointerPath}`);
11779
12172
  }
11780
12173
  const sessionFile = raw.sessionFile;
@@ -11799,7 +12192,7 @@ async function readAnalystGateCyclesFromAuditorRoles(auditorRolesDirectory, opti
11799
12192
  throw error;
11800
12193
  }
11801
12194
  for (const name of names) {
11802
- const path = join27(directory, name);
12195
+ const path = join28(directory, name);
11803
12196
  const fromPointer = name.endsWith(".pointer.json");
11804
12197
  const sessionPath = fromPointer ? await resolveOfficerSessionFromPointerFile(path) : path;
11805
12198
  if (sessionPath === void 0) continue;
@@ -11938,9 +12331,9 @@ var init_audit_escalation = __esm({
11938
12331
  });
11939
12332
 
11940
12333
  // src/run-terminal-artifacts.ts
11941
- import { basename as basename7, dirname as dirname13, join as join28 } from "node:path";
12334
+ import { basename as basename8, dirname as dirname15, join as join29 } from "node:path";
11942
12335
  function runIdFromRunDirectory(runDirectory) {
11943
- const name = basename7(runDirectory);
12336
+ const name = basename8(runDirectory);
11944
12337
  const at = name.lastIndexOf("@");
11945
12338
  if (at <= 0 || at === name.length - 1) return void 0;
11946
12339
  return name.slice(0, at);
@@ -11953,7 +12346,7 @@ var init_run_terminal_artifacts = __esm({
11953
12346
  });
11954
12347
 
11955
12348
  // src/submission-ledger.ts
11956
- import { join as join29 } from "node:path";
12349
+ import { join as join30 } from "node:path";
11957
12350
  function runIdentity(context) {
11958
12351
  const directory = runDirectoryFromHostContext(context);
11959
12352
  if (directory !== void 0) {
@@ -11975,7 +12368,7 @@ async function submissionRecordFile(cwd, runId, scope) {
11975
12368
  if (sessionParent === void 0) {
11976
12369
  const discoveredRun = await findRunDirectoryById(scope.home, runId);
11977
12370
  if (discoveredRun === void 0) return void 0;
11978
- sessionParent = join29(discoveredRun, "session", "session.jsonl");
12371
+ sessionParent = join30(discoveredRun, "session", "session.jsonl");
11979
12372
  }
11980
12373
  return resolveSitianRecordPathInLedger({
11981
12374
  level: "event",
@@ -12180,13 +12573,13 @@ function createSubmissionLedgerHost(host, outputTools, failInfrastructure2 = (er
12180
12573
  const sessionParentFromContext = (context) => {
12181
12574
  const runDirectory = runDirectoryFromHostContext(context);
12182
12575
  if (runDirectory !== void 0) {
12183
- return join29(runDirectory, "session", "session.jsonl");
12576
+ return join30(runDirectory, "session", "session.jsonl");
12184
12577
  }
12185
12578
  const sessionFile = context.sessionManager.getSessionFile?.();
12186
12579
  if (typeof sessionFile === "string" && sessionFile.length > 0) return sessionFile;
12187
12580
  const sessionDir = context.sessionManager.getSessionDir?.();
12188
12581
  if (typeof sessionDir === "string" && sessionDir.length > 0) {
12189
- return join29(sessionDir, "session.jsonl");
12582
+ return join30(sessionDir, "session.jsonl");
12190
12583
  }
12191
12584
  return void 0;
12192
12585
  };
@@ -12348,23 +12741,23 @@ var init_submission_ledger = __esm({
12348
12741
 
12349
12742
  // src/session-opening-materials.ts
12350
12743
  import { existsSync as existsSync9 } from "node:fs";
12351
- import { readFile as readFile16 } from "node:fs/promises";
12352
- import { dirname as dirname14, join as join30 } from "node:path";
12744
+ import { readFile as readFile17 } from "node:fs/promises";
12745
+ import { dirname as dirname16, join as join31 } from "node:path";
12353
12746
  import { fileURLToPath, pathToFileURL as pathToFileURL3 } from "node:url";
12354
12747
  function resolvePackageRootDir(moduleUrl = import.meta.url) {
12355
- let dir = dirname14(fileURLToPath(moduleUrl));
12748
+ let dir = dirname16(fileURLToPath(moduleUrl));
12356
12749
  for (let i = 0; i < 8; i += 1) {
12357
- if (existsSync9(join30(dir, "package.json")) && existsSync9(join30(dir, "souls"))) {
12750
+ if (existsSync9(join31(dir, "package.json")) && existsSync9(join31(dir, "souls"))) {
12358
12751
  return dir;
12359
12752
  }
12360
- const parent = dirname14(dir);
12753
+ const parent = dirname16(dir);
12361
12754
  if (parent === dir) break;
12362
12755
  dir = parent;
12363
12756
  }
12364
12757
  return fileURLToPath(new URL("..", moduleUrl));
12365
12758
  }
12366
12759
  async function readPackageMaterial(relativePath) {
12367
- return readFile16(fileURLToPath(new URL(relativePath, packageRootUrl)), "utf8");
12760
+ return readFile17(fileURLToPath(new URL(relativePath, packageRootUrl)), "utf8");
12368
12761
  }
12369
12762
  async function joinPackageMaterials(relativePaths) {
12370
12763
  const chunks = [];
@@ -12463,7 +12856,7 @@ var init_auditor_soul = __esm({
12463
12856
 
12464
12857
  // src/dossier-resolution.ts
12465
12858
  import { existsSync as existsSync10, statSync as statSync3 } from "node:fs";
12466
- import { resolve as resolve10 } from "node:path";
12859
+ import { resolve as resolve11 } from "node:path";
12467
12860
  function isHostContext(value) {
12468
12861
  return "sessionManager" in value;
12469
12862
  }
@@ -12480,7 +12873,7 @@ function resolveAuditDossier(source) {
12480
12873
  if (raw === void 0) {
12481
12874
  return { status: "ok" };
12482
12875
  }
12483
- const runDirectory = resolve10(raw);
12876
+ const runDirectory = resolve11(raw);
12484
12877
  try {
12485
12878
  if (!existsSync10(runDirectory) || !statSync3(runDirectory).isDirectory()) {
12486
12879
  return { status: "incomplete", observation: { kind: "missing-dossier" } };
@@ -12490,13 +12883,13 @@ function resolveAuditDossier(source) {
12490
12883
  }
12491
12884
  return { status: "ok", runDirectory };
12492
12885
  }
12493
- function isRecord7(value) {
12886
+ function isRecord8(value) {
12494
12887
  return typeof value === "object" && value !== null && !Array.isArray(value);
12495
12888
  }
12496
12889
  function readDoctorAuditSubjects(context) {
12497
12890
  const entries = context.sessionManager.getEntries?.() ?? [];
12498
12891
  for (const entry of entries) {
12499
- if (isRecord7(entry) && entry.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
12892
+ if (isRecord8(entry) && entry.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
12500
12893
  return { status: "ok" };
12501
12894
  }
12502
12895
  }
@@ -12624,18 +13017,18 @@ var init_known_failure = __esm({
12624
13017
  });
12625
13018
 
12626
13019
  // src/collector-evidence.ts
12627
- import { createHash as createHash7 } from "node:crypto";
13020
+ import { createHash as createHash6 } from "node:crypto";
12628
13021
  function createSystemCollectorClock() {
12629
13022
  const start = process.hrtime.bigint();
12630
13023
  return {
12631
13024
  wallNow: () => /* @__PURE__ */ new Date(),
12632
13025
  monoNow: () => Number(process.hrtime.bigint() - start) / 1e6,
12633
- sleep: (ms, signal) => new Promise((resolve20, reject) => {
13026
+ sleep: (ms, signal) => new Promise((resolve21, reject) => {
12634
13027
  if (signal?.aborted) {
12635
13028
  reject(signal.reason ?? new Error("aborted"));
12636
13029
  return;
12637
13030
  }
12638
- const timer = setTimeout(resolve20, ms);
13031
+ const timer = setTimeout(resolve21, ms);
12639
13032
  const onAbort = () => {
12640
13033
  clearTimeout(timer);
12641
13034
  reject(signal?.reason ?? new Error("aborted"));
@@ -12645,7 +13038,7 @@ function createSystemCollectorClock() {
12645
13038
  };
12646
13039
  }
12647
13040
  function sha256Text(text) {
12648
- return createHash7("sha256").update(text, "utf8").digest("hex");
13041
+ return createHash6("sha256").update(text, "utf8").digest("hex");
12649
13042
  }
12650
13043
  function computeWindowRelation(authoritativeTime, activationTime, deadlineTime) {
12651
13044
  if (authoritativeTime === void 0 || authoritativeTime === null || authoritativeTime.length === 0) {
@@ -13782,13 +14175,13 @@ var init_collector_ledger = __esm({
13782
14175
  });
13783
14176
 
13784
14177
  // src/package-resources/method-skill.ts
13785
- import { createHash as createHash8 } from "node:crypto";
13786
- import { readFile as readFile17, realpath as realpath6 } from "node:fs/promises";
13787
- import { join as join31 } from "node:path";
14178
+ import { createHash as createHash7 } from "node:crypto";
14179
+ import { readFile as readFile18, realpath as realpath6 } from "node:fs/promises";
14180
+ import { join as join32 } from "node:path";
13788
14181
  function gitBlobOid(bytes) {
13789
14182
  const body = typeof bytes === "string" ? Buffer.from(bytes, "utf8") : Buffer.from(bytes);
13790
14183
  const header = Buffer.from(`blob ${body.byteLength}\0`, "utf8");
13791
- return createHash8("sha1").update(header).update(body).digest("hex");
14184
+ return createHash7("sha1").update(header).update(body).digest("hex");
13792
14185
  }
13793
14186
  function stripSkillFrontmatter(content) {
13794
14187
  if (!content.startsWith("---")) return content;
@@ -13801,16 +14194,16 @@ function packagedMethodSkillRelativeDirectory(name) {
13801
14194
  return `${METHOD_SKILL_RELATIVE_ROOT}/${name}`;
13802
14195
  }
13803
14196
  function resolvePackagedMethodSkillRoot(packageRoot, name) {
13804
- return join31(packageRoot, packagedMethodSkillRelativeDirectory(name));
14197
+ return join32(packageRoot, packagedMethodSkillRelativeDirectory(name));
13805
14198
  }
13806
14199
  function resolvePackagedMethodSkillPath(packageRoot, name) {
13807
- return join31(resolvePackagedMethodSkillRoot(packageRoot, name), "SKILL.md");
14200
+ return join32(resolvePackagedMethodSkillRoot(packageRoot, name), "SKILL.md");
13808
14201
  }
13809
- function isRecord8(value) {
14202
+ function isRecord9(value) {
13810
14203
  return typeof value === "object" && value !== null && !Array.isArray(value);
13811
14204
  }
13812
14205
  function parseProvenance(raw, expectedName) {
13813
- if (!isRecord8(raw)) {
14206
+ if (!isRecord9(raw)) {
13814
14207
  throw new Error(`Packaged method provenance must be an object for ${expectedName}`);
13815
14208
  }
13816
14209
  if (raw.name !== expectedName) {
@@ -13824,7 +14217,7 @@ function parseProvenance(raw, expectedName) {
13824
14217
  if (typeof raw.packageAdaptation !== "string" || raw.packageAdaptation.trim() === "") {
13825
14218
  throw new Error(`Packaged method provenance packageAdaptation must be nonblank`);
13826
14219
  }
13827
- if (!isRecord8(raw.upstream)) {
14220
+ if (!isRecord9(raw.upstream)) {
13828
14221
  throw new Error(`Packaged method provenance upstream must be an object`);
13829
14222
  }
13830
14223
  const upstream = raw.upstream;
@@ -13851,12 +14244,12 @@ function parseProvenance(raw, expectedName) {
13851
14244
  `Packaged method provenance upstream must include nonblank tag or version`
13852
14245
  );
13853
14246
  }
13854
- if (!isRecord8(raw.files)) {
14247
+ if (!isRecord9(raw.files)) {
13855
14248
  throw new Error(`Packaged method provenance files must be an object`);
13856
14249
  }
13857
14250
  const files = {};
13858
14251
  for (const [rel, entry] of Object.entries(raw.files)) {
13859
- if (!isRecord8(entry)) {
14252
+ if (!isRecord9(entry)) {
13860
14253
  throw new Error(`Packaged method provenance file entry must be an object: ${rel}`);
13861
14254
  }
13862
14255
  if (typeof entry.sha256 !== "string" || !SHA256_RE.test(entry.sha256)) {
@@ -13898,11 +14291,11 @@ function parseProvenance(raw, expectedName) {
13898
14291
  }
13899
14292
  async function loadPackagedMethodSkillMaterial(packageRoot, name) {
13900
14293
  const rootDirectory = resolvePackagedMethodSkillRoot(packageRoot, name);
13901
- const skillPathConfigured = join31(rootDirectory, "SKILL.md");
13902
- const provenancePath = join31(rootDirectory, "provenance.json");
14294
+ const skillPathConfigured = join32(rootDirectory, "SKILL.md");
14295
+ const provenancePath = join32(rootDirectory, "provenance.json");
13903
14296
  let provenanceRaw;
13904
14297
  try {
13905
- provenanceRaw = await readFile17(provenancePath, "utf8");
14298
+ provenanceRaw = await readFile18(provenancePath, "utf8");
13906
14299
  } catch (error) {
13907
14300
  throw new PackagedMethodSkillUnavailableError(name, provenancePath, error);
13908
14301
  }
@@ -13916,10 +14309,10 @@ async function loadPackagedMethodSkillMaterial(packageRoot, name) {
13916
14309
  }
13917
14310
  const provenance = parseProvenance(provenanceJson, name);
13918
14311
  for (const [rel, expected] of Object.entries(provenance.files)) {
13919
- const absolute = join31(rootDirectory, rel);
14312
+ const absolute = join32(rootDirectory, rel);
13920
14313
  let bytes;
13921
14314
  try {
13922
- bytes = await readFile17(absolute);
14315
+ bytes = await readFile18(absolute);
13923
14316
  } catch (error) {
13924
14317
  throw new PackagedMethodSkillUnavailableError(name, absolute, error);
13925
14318
  }
@@ -13935,7 +14328,7 @@ async function loadPackagedMethodSkillMaterial(packageRoot, name) {
13935
14328
  let raw;
13936
14329
  try {
13937
14330
  skillPath = await realpath6(skillPathConfigured);
13938
- raw = await readFile17(skillPath, "utf8");
14331
+ raw = await readFile18(skillPath, "utf8");
13939
14332
  } catch (error) {
13940
14333
  throw new PackagedMethodSkillUnavailableError(name, skillPathConfigured, error);
13941
14334
  }
@@ -13991,7 +14384,7 @@ var init_method_skill = __esm({
13991
14384
  });
13992
14385
 
13993
14386
  // src/work-subject-identity.ts
13994
- import { resolve as resolve11 } from "node:path";
14387
+ import { resolve as resolve12 } from "node:path";
13995
14388
  function issueRoot(value) {
13996
14389
  const normalized = value.replaceAll("\\", "/");
13997
14390
  const marker = ".ak/work/issues/";
@@ -14001,7 +14394,7 @@ function issueRoot(value) {
14001
14394
  return issue === void 0 || issue === "" ? void 0 : normalized.slice(0, index + marker.length) + issue;
14002
14395
  }
14003
14396
  function workIdentityFromCwd(cwd) {
14004
- const resolvedCwd = resolve11(cwd, ".");
14397
+ const resolvedCwd = resolve12(cwd, ".");
14005
14398
  const cwdIssue = issueRoot(resolvedCwd);
14006
14399
  if (cwdIssue !== void 0) return cwdIssue;
14007
14400
  if (resolvedCwd.includes("/.ak/work/")) return resolvedCwd;
@@ -14012,11 +14405,11 @@ function isMachineLedgerSessionPath(sessionPath) {
14012
14405
  }
14013
14406
  function subjectPath(sessionDir, cwd = process.cwd()) {
14014
14407
  if (sessionDir === "") {
14015
- return workIdentityFromCwd(cwd) ?? resolve11(cwd, ".ak/work");
14408
+ return workIdentityFromCwd(cwd) ?? resolve12(cwd, ".ak/work");
14016
14409
  }
14017
- const resolvedSession = resolve11(cwd, sessionDir || ".ak/work");
14410
+ const resolvedSession = resolve12(cwd, sessionDir || ".ak/work");
14018
14411
  if (isMachineLedgerSessionPath(resolvedSession)) {
14019
- return workIdentityFromCwd(cwd) ?? resolve11(cwd, ".ak/work");
14412
+ return workIdentityFromCwd(cwd) ?? resolve12(cwd, ".ak/work");
14020
14413
  }
14021
14414
  const issue = issueRoot(resolvedSession);
14022
14415
  if (issue !== void 0) return issue;
@@ -14199,11 +14592,11 @@ var init_navigator_invocation_identity = __esm({
14199
14592
  });
14200
14593
 
14201
14594
  // src/receipt-delivery-policy.ts
14202
- function isRecord9(value) {
14595
+ function isRecord10(value) {
14203
14596
  return typeof value === "object" && value !== null && !Array.isArray(value);
14204
14597
  }
14205
14598
  function parseNoReceiptLifecycleFacts(input) {
14206
- if (!isRecord9(input) || typeof input.terminalToolCalled !== "boolean" || input.deliveryTurns !== RECEIPT_DELIVERY_TURN_LIMIT || input.sessionCompletion !== "settled-without-accepted-receipt" || input.acceptedReceipt !== false || typeof input.runPointer !== "string" || input.runPointer.trim() === "" || typeof input.attemptPointer !== "string" || input.attemptPointer.trim() === "" || !Array.isArray(input.rejectedReceipts) || !input.rejectedReceipts.every((item) => isRecord9(item) && typeof item.reason === "string")) {
14599
+ if (!isRecord10(input) || typeof input.terminalToolCalled !== "boolean" || input.deliveryTurns !== RECEIPT_DELIVERY_TURN_LIMIT || input.sessionCompletion !== "settled-without-accepted-receipt" || input.acceptedReceipt !== false || typeof input.runPointer !== "string" || input.runPointer.trim() === "" || typeof input.attemptPointer !== "string" || input.attemptPointer.trim() === "" || !Array.isArray(input.rejectedReceipts) || !input.rejectedReceipts.every((item) => isRecord10(item) && typeof item.reason === "string")) {
14207
14600
  throw new TypeError("malformed no-receipt lifecycle facts");
14208
14601
  }
14209
14602
  return {
@@ -14421,16 +14814,16 @@ var init_terminal = __esm({
14421
14814
  });
14422
14815
 
14423
14816
  // src/public-cli/settlement.ts
14424
- import { randomUUID as randomUUID3 } from "node:crypto";
14425
- import { appendFile as appendFile2, readFile as readFile18, readdir as readdir7, writeFile as writeFile9 } from "node:fs/promises";
14426
- import { dirname as dirname15, join as join32 } from "node:path";
14817
+ import { randomUUID as randomUUID4 } from "node:crypto";
14818
+ import { appendFile as appendFile2, readFile as readFile19, readdir as readdir7, writeFile as writeFile10 } from "node:fs/promises";
14819
+ import { dirname as dirname17, join as join33 } from "node:path";
14427
14820
  function sealedLedgerHome(admitted) {
14428
14821
  return homeFromRunDirectory(admitted.runDirectory);
14429
14822
  }
14430
14823
  function ledgerReadScope(admitted, scope) {
14431
14824
  return {
14432
14825
  home: sealedLedgerHome(admitted),
14433
- sessionParent: join32(admitted.runDirectory, "session", "session.jsonl"),
14826
+ sessionParent: join33(admitted.runDirectory, "session", "session.jsonl"),
14434
14827
  ...scope?.courtAttemptId === void 0 || scope.courtAttemptId.length === 0 ? {} : { attemptId: scope.courtAttemptId }
14435
14828
  };
14436
14829
  }
@@ -14560,7 +14953,7 @@ function presentStructuralRejection(error, io) {
14560
14953
  }
14561
14954
  async function inspectJudgeSession(sessionFile) {
14562
14955
  try {
14563
- await readFile18(sessionFile, "utf8");
14956
+ await readFile19(sessionFile, "utf8");
14564
14957
  return { state: "present" };
14565
14958
  } catch (error) {
14566
14959
  if (isMissingPathError3(error)) return { state: "missing" };
@@ -14792,7 +15185,7 @@ function sessionReadFailure(error, fallbackMessage) {
14792
15185
  return failed;
14793
15186
  }
14794
15187
  async function readBoundSessionEntries(sessionFile) {
14795
- const text = await readFile18(sessionFile, "utf8");
15188
+ const text = await readFile19(sessionFile, "utf8");
14796
15189
  const entries = [];
14797
15190
  for (const line2 of text.trim().split("\n").filter(Boolean)) {
14798
15191
  try {
@@ -14853,12 +15246,12 @@ async function readSitianRetainedAuditorProviderStop(sessionFile) {
14853
15246
  kind: "auditor",
14854
15247
  sessionParent: sessionFile,
14855
15248
  // Path is driven by sessionParent when under ledger home; cwd is a fallback only.
14856
- cwd: dirname15(sessionFile)
15249
+ cwd: dirname17(sessionFile)
14857
15250
  });
14858
15251
  const { records } = await readSitianRecords(recordFile);
14859
15252
  for (let i = records.length - 1; i >= 0; i -= 1) {
14860
15253
  const payload = records[i]?.payload;
14861
- if (!isRecord10(payload) || !isRecord10(payload.response)) continue;
15254
+ if (!isRecord11(payload) || !isRecord11(payload.response)) continue;
14862
15255
  if (typeof payload.type === "string") continue;
14863
15256
  const stop = sessionProviderStopFromAssistant(payload.response);
14864
15257
  if (stop !== void 0) return stop;
@@ -14879,7 +15272,7 @@ async function readSessionProviderStop(sessionFile) {
14879
15272
  }
14880
15273
  }
14881
15274
  async function readBoundEvidenceChildKnownFailure(sessionFile) {
14882
- const childDirectory = join32(dirname15(sessionFile), "evidence-children");
15275
+ const childDirectory = join33(dirname17(sessionFile), "evidence-children");
14883
15276
  let names;
14884
15277
  try {
14885
15278
  names = await readdir7(childDirectory);
@@ -14890,12 +15283,12 @@ async function readBoundEvidenceChildKnownFailure(sessionFile) {
14890
15283
  for (const file of names.filter((name) => name.endsWith(".jsonl")).sort().reverse()) {
14891
15284
  let entries;
14892
15285
  try {
14893
- entries = await readBoundSessionEntries(join32(childDirectory, file));
15286
+ entries = await readBoundSessionEntries(join33(childDirectory, file));
14894
15287
  } catch (error) {
14895
15288
  throw sessionReadFailure(error, "failed to read discovered evidence-child session");
14896
15289
  }
14897
15290
  const header = entries.find((entry) => entry.type === "session");
14898
- if (!isRecord10(header) || header.parentSession !== sessionFile) continue;
15291
+ if (!isRecord11(header) || header.parentSession !== sessionFile) continue;
14899
15292
  const stop = extractSessionProviderStop(entries);
14900
15293
  if (stop === void 0) continue;
14901
15294
  const primary = knownFailureFromProviderStop(stop);
@@ -14928,12 +15321,12 @@ async function loadBoundAuditorVolumes(sessionFile) {
14928
15321
  return body.startsWith("\u672C\u6B21\u914D\u7F6E\u7684\u52B3\u52A1\u5F15\u64CE\u53CA\u5176\u624B\u518C\uFF1A") || body.startsWith("- engine:");
14929
15322
  };
14930
15323
  const isResumeEnvelope = (msg) => {
14931
- if (!isRecord10(msg) || msg.role !== "user") return false;
15324
+ if (!isRecord11(msg) || msg.role !== "user") return false;
14932
15325
  const text = typeof msg.text === "string" ? msg.text : typeof msg.content === "string" ? msg.content : void 0;
14933
15326
  if (isResumeEnvelopeBytes(text)) return true;
14934
15327
  const content = msg.content;
14935
15328
  if (Array.isArray(content)) {
14936
- return content.some((p) => isRecord10(p) && (isResumeEnvelopeBytes(p.text) || isResumeEnvelopeBytes(p.content)));
15329
+ return content.some((p) => isRecord11(p) && (isResumeEnvelopeBytes(p.text) || isResumeEnvelopeBytes(p.content)));
14937
15330
  }
14938
15331
  return false;
14939
15332
  };
@@ -14945,7 +15338,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
14945
15338
  latestParentUserIndex = i;
14946
15339
  break;
14947
15340
  }
14948
- const childDirectories = [join32(dirname15(sessionFile), "auditor-roles")];
15341
+ const childDirectories = [join33(dirname17(sessionFile), "auditor-roles")];
14949
15342
  const valid = [];
14950
15343
  let sawAnyDirectory = false;
14951
15344
  for (const childDirectory of childDirectories) {
@@ -14960,12 +15353,12 @@ async function loadBoundAuditorVolumes(sessionFile) {
14960
15353
  for (const file of names.filter((name) => name.endsWith(".jsonl")).sort().reverse()) {
14961
15354
  let entries;
14962
15355
  try {
14963
- entries = await readBoundSessionEntries(join32(childDirectory, file));
15356
+ entries = await readBoundSessionEntries(join33(childDirectory, file));
14964
15357
  } catch (error) {
14965
15358
  throw sessionReadFailure(error, "failed to read discovered auditor session");
14966
15359
  }
14967
15360
  const header = entries.find((entry) => entry.type === "session");
14968
- if (!isRecord10(header)) continue;
15361
+ if (!isRecord11(header)) continue;
14969
15362
  const bindingIndexes = [];
14970
15363
  for (let i = 0; i < entries.length; i += 1) {
14971
15364
  const entry = entries[i];
@@ -14979,7 +15372,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
14979
15372
  end: idx + 1 < bindingIndexes.length ? bindingIndexes[idx + 1] : entries.length
14980
15373
  })) : [{ entry: void 0, start: 0, end: entries.length }];
14981
15374
  for (const { entry: bindingEntry, start, end } of bindingPasses) {
14982
- const bindingParent = bindingEntry !== void 0 && isRecord10(bindingEntry.data) && isRecord10(bindingEntry.data.parent) ? bindingEntry.data.parent : void 0;
15375
+ const bindingParent = bindingEntry !== void 0 && isRecord11(bindingEntry.data) && isRecord11(bindingEntry.data.parent) ? bindingEntry.data.parent : void 0;
14983
15376
  const attemptEntryId = typeof bindingParent?.attemptEntryId === "string" ? bindingParent.attemptEntryId : void 0;
14984
15377
  const attemptEntryIndex = attemptEntryId === void 0 ? -1 : parentEntries.findIndex((entry) => entry.id === attemptEntryId);
14985
15378
  const boundSessionFile = typeof bindingParent?.sessionFile === "string" ? bindingParent.sessionFile : typeof header.parentSession === "string" ? header.parentSession : void 0;
@@ -15006,12 +15399,12 @@ function complianceFailureFromAuditorVolumes(volumes) {
15006
15399
  if (stop === void 0) continue;
15007
15400
  for (let i = entries.length - 1; i >= 0; i -= 1) {
15008
15401
  const entry = entries[i];
15009
- if (entry?.type !== "custom" || entry.customType !== AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE || !isRecord10(entry.data)) continue;
15010
- const parent = isRecord10(entry.data.parent) ? entry.data.parent : void 0;
15011
- const failure2 = isRecord10(entry.data.failure) ? entry.data.failure : void 0;
15402
+ if (entry?.type !== "custom" || entry.customType !== AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE || !isRecord11(entry.data)) continue;
15403
+ const parent = isRecord11(entry.data.parent) ? entry.data.parent : void 0;
15404
+ const failure2 = isRecord11(entry.data.failure) ? entry.data.failure : void 0;
15012
15405
  if (parent?.sessionId !== parentId || parent.sessionFile !== sessionFile || parent.attemptEntryId !== attemptEntryId) continue;
15013
15406
  if (failure2 === void 0) continue;
15014
- const identity = isRecord10(failure2.identity) ? failure2.identity : void 0;
15407
+ const identity = isRecord11(failure2.identity) ? failure2.identity : void 0;
15015
15408
  const typedCause = failure2.cause === "provider" || failure2.cause === "activation" || failure2.cause === "session" || failure2.cause === "output" || failure2.cause === "timeout" ? failure2.cause : void 0;
15016
15409
  return {
15017
15410
  ...typedCause === void 0 ? {} : { cause: typedCause },
@@ -15020,7 +15413,7 @@ function complianceFailureFromAuditorVolumes(volumes) {
15020
15413
  ...typeof identity.code === "string" || typeof identity.code === "number" ? { code: identity.code } : {}
15021
15414
  } },
15022
15415
  ...typeof failure2.diagnostic === "string" ? { diagnostic: failure2.diagnostic } : {},
15023
- ...isRecord10(failure2.details) ? { details: failure2.details } : {}
15416
+ ...isRecord11(failure2.details) ? { details: failure2.details } : {}
15024
15417
  };
15025
15418
  }
15026
15419
  }
@@ -15067,9 +15460,9 @@ function typedFailedTerminatingToolKnownFailure(entries) {
15067
15460
  if (classification.kind !== "infrastructure") continue;
15068
15461
  if (typeof message.toolCallId !== "string" || typeof message.toolName !== "string") continue;
15069
15462
  if (boundRoleToolCallForResult(attemptEntries, i, message, message.toolName) === void 0) continue;
15070
- const textPart = Array.isArray(message.content) ? message.content.find((part) => isRecord10(part) && part.type === "text" && typeof part.text === "string") : void 0;
15071
- const diagnostic = isRecord10(textPart) ? textPart.text : void 0;
15072
- const details = isRecord10(message.details) ? message.details : classification.fact;
15463
+ const textPart = Array.isArray(message.content) ? message.content.find((part) => isRecord11(part) && part.type === "text" && typeof part.text === "string") : void 0;
15464
+ const diagnostic = isRecord11(textPart) ? textPart.text : void 0;
15465
+ const details = isRecord11(message.details) ? message.details : classification.fact;
15073
15466
  return {
15074
15467
  cause: "activation",
15075
15468
  identity: { name: message.toolName, code: message.toolCallId },
@@ -15227,7 +15620,7 @@ function controlledFailureInputFromResolution(resolution) {
15227
15620
  } : {}
15228
15621
  };
15229
15622
  }
15230
- function isRecord10(value) {
15623
+ function isRecord11(value) {
15231
15624
  return typeof value === "object" && value !== null && !Array.isArray(value);
15232
15625
  }
15233
15626
  function toolResultText(message) {
@@ -15252,7 +15645,7 @@ function extractCollectorTargetBindRejection(entries) {
15252
15645
  const diagnostic = toolResultText(message);
15253
15646
  if (diagnostic.length === 0) return void 0;
15254
15647
  const details = message.details;
15255
- const code = isRecord10(details) && typeof details.code === "string" && details.code.trim() !== "" ? details.code : void 0;
15648
+ const code = isRecord11(details) && typeof details.code === "string" && details.code.trim() !== "" ? details.code : void 0;
15256
15649
  return code === void 0 ? { diagnostic } : { diagnostic, code };
15257
15650
  }
15258
15651
  return void 0;
@@ -15313,7 +15706,7 @@ function boundRoleToolCallForResult(entries, resultIndex, message, outputToolNam
15313
15706
  const candidateMessage = entries[index]?.message;
15314
15707
  if (candidateMessage?.role === "assistant" && Array.isArray(candidateMessage.content)) {
15315
15708
  for (const part of candidateMessage.content) {
15316
- if (!isRecord10(part) || part.type !== "toolCall" || part.id !== callId) {
15709
+ if (!isRecord11(part) || part.type !== "toolCall" || part.id !== callId) {
15317
15710
  continue;
15318
15711
  }
15319
15712
  if (part.name !== outputToolName) return void 0;
@@ -15350,7 +15743,7 @@ async function appendRunAttemptHistory(source, outcome) {
15350
15743
  type: "custom",
15351
15744
  customType: ATTEMPT_HISTORY_ENTRY_TYPE,
15352
15745
  data: attemptData,
15353
- id: randomUUID3(),
15746
+ id: randomUUID4(),
15354
15747
  parentId,
15355
15748
  timestamp: timestamp2
15356
15749
  })}
@@ -15385,7 +15778,7 @@ function parseNavigatorAttendanceDetails(details) {
15385
15778
  const advisoryDiagnostic = typeof details.routePlaybookReadFailure === "string" ? { advisoryDiagnostic: details.routePlaybookReadFailure } : {};
15386
15779
  if (disposition === "recommendation") {
15387
15780
  const next = details.next;
15388
- if (!isRecord10(next) || typeof next.role !== "string") {
15781
+ if (!isRecord11(next) || typeof next.role !== "string") {
15389
15782
  return {
15390
15783
  disposition: "unavailable",
15391
15784
  source: "unknown",
@@ -15393,7 +15786,7 @@ function parseNavigatorAttendanceDetails(details) {
15393
15786
  };
15394
15787
  }
15395
15788
  const reason = typeof details.reason === "string" ? details.reason : "";
15396
- const route = Array.isArray(details.route) ? details.route.filter(isRecord10).map((target) => ({
15789
+ const route = Array.isArray(details.route) ? details.route.filter(isRecord11).map((target) => ({
15397
15790
  role: String(target.role),
15398
15791
  phase: navigatorPhaseValue(target.phase)
15399
15792
  })) : void 0;
@@ -15456,8 +15849,8 @@ function projectTerminalGateFact(rounds) {
15456
15849
  };
15457
15850
  }
15458
15851
  async function extractGateFactFromSessionDirectory(sessionDirectory, options = {}) {
15459
- const directories = [join32(sessionDirectory, "auditor-roles")];
15460
- const parentSessionFile = options.parentSessionFile ?? join32(sessionDirectory, "session.jsonl");
15852
+ const directories = [join33(sessionDirectory, "auditor-roles")];
15853
+ const parentSessionFile = options.parentSessionFile ?? join33(sessionDirectory, "session.jsonl");
15461
15854
  const rounds = await readAnalystGateCyclesFromAuditorRoles(directories, {
15462
15855
  parentSessionFile
15463
15856
  });
@@ -15465,7 +15858,7 @@ async function extractGateFactFromSessionDirectory(sessionDirectory, options = {
15465
15858
  }
15466
15859
  async function withOptionalGateProjection(base, sessionDirectory, gateContext = {}) {
15467
15860
  const secondaryEvidence = base.roleOutcome.kind === "failure" ? base.roleOutcome.decisiveFacts.secondaryEvidence : void 0;
15468
- if (isRecord10(secondaryEvidence) && secondaryEvidence.kind === "role_infrastructure_failure" && (secondaryEvidence.stage === "gatekeeper" || secondaryEvidence.stage === "inspector" || secondaryEvidence.stage === "notary")) return base;
15861
+ if (isRecord11(secondaryEvidence) && secondaryEvidence.kind === "role_infrastructure_failure" && (secondaryEvidence.stage === "gatekeeper" || secondaryEvidence.stage === "inspector" || secondaryEvidence.stage === "notary")) return base;
15469
15862
  const gate = await extractGateFactFromSessionDirectory(sessionDirectory, gateContext);
15470
15863
  return gate === void 0 ? base : { ...base, gate };
15471
15864
  }
@@ -15505,7 +15898,7 @@ function extractNavigatorFact(entries) {
15505
15898
  const entry = entries[i];
15506
15899
  if (entry?.type === "custom_message" && entry.customType === "ak-navigator-attendance") {
15507
15900
  const details = entry.message?.details ?? entry.details;
15508
- if (!isRecord10(details)) {
15901
+ if (!isRecord11(details)) {
15509
15902
  return {
15510
15903
  disposition: "unavailable",
15511
15904
  source: "unknown",
@@ -15555,9 +15948,9 @@ async function extractNavigatorFactFromAdmittedSession(sessionFile) {
15555
15948
  async function publishJudgeArtifacts(admitted, roleOutcome, coordinates) {
15556
15949
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
15557
15950
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
15558
- const reportPath = join32(artifactsDir, "report.json");
15559
- const evidencePath = join32(artifactsDir, "evidence.json");
15560
- await writeFile9(
15951
+ const reportPath = join33(artifactsDir, "report.json");
15952
+ const evidencePath = join33(artifactsDir, "evidence.json");
15953
+ await writeFile10(
15561
15954
  reportPath,
15562
15955
  `${JSON.stringify(
15563
15956
  {
@@ -15571,7 +15964,7 @@ async function publishJudgeArtifacts(admitted, roleOutcome, coordinates) {
15571
15964
  `,
15572
15965
  "utf8"
15573
15966
  );
15574
- await writeFile9(
15967
+ await writeFile10(
15575
15968
  evidencePath,
15576
15969
  `${JSON.stringify(
15577
15970
  {
@@ -15638,7 +16031,7 @@ function extractDoctorCandidateCostFact(entries) {
15638
16031
  const entry = entries[i];
15639
16032
  if (entry?.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
15640
16033
  const data = entry.data;
15641
- return isRecord10(data) ? data.cost : void 0;
16034
+ return isRecord11(data) ? data.cost : void 0;
15642
16035
  }
15643
16036
  }
15644
16037
  return void 0;
@@ -15649,7 +16042,7 @@ function extractDoctorCandidateAuditNoReceiptFact(entries) {
15649
16042
  const entry = entries[i];
15650
16043
  if (entry?.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
15651
16044
  const data = entry.data;
15652
- return isRecord10(data) ? data.auditNoReceipt : void 0;
16045
+ return isRecord11(data) ? data.auditNoReceipt : void 0;
15653
16046
  }
15654
16047
  }
15655
16048
  return void 0;
@@ -15657,9 +16050,9 @@ function extractDoctorCandidateAuditNoReceiptFact(entries) {
15657
16050
  async function publishDoctorArtifacts(admitted, roleOutcome, coordinates, options = {}) {
15658
16051
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
15659
16052
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
15660
- const reportPath = join32(artifactsDir, "report.json");
15661
- const evidencePath = join32(artifactsDir, "evidence.json");
15662
- await writeFile9(
16053
+ const reportPath = join33(artifactsDir, "report.json");
16054
+ const evidencePath = join33(artifactsDir, "evidence.json");
16055
+ await writeFile10(
15663
16056
  reportPath,
15664
16057
  `${JSON.stringify(
15665
16058
  {
@@ -15675,7 +16068,7 @@ async function publishDoctorArtifacts(admitted, roleOutcome, coordinates, option
15675
16068
  `,
15676
16069
  "utf8"
15677
16070
  );
15678
- await writeFile9(
16071
+ await writeFile10(
15679
16072
  evidencePath,
15680
16073
  `${JSON.stringify(
15681
16074
  {
@@ -15774,7 +16167,7 @@ async function settleLawfulSeatAcceptedTerminalResult(admitted, authority, spec,
15774
16167
  spec.toolName
15775
16168
  );
15776
16169
  if (residual !== void 0) {
15777
- const details = isRecord10(residual.candidate) ? residual.candidate : { candidate: residual.candidate };
16170
+ const details = isRecord11(residual.candidate) ? residual.candidate : { candidate: residual.candidate };
15778
16171
  const failed = await settleFailureTerminalResult(admitted, {
15779
16172
  cause: "output",
15780
16173
  diagnostic: residual.diagnostic,
@@ -15889,7 +16282,7 @@ function publicationAttemptFromError(path, error) {
15889
16282
  }
15890
16283
  function uniqueFailureFallbackDirs(runDirectory, baseDir) {
15891
16284
  const dirs = [];
15892
- for (const dir of [baseDir, runDirectory, dirname15(runDirectory)]) {
16285
+ for (const dir of [baseDir, runDirectory, dirname17(runDirectory)]) {
15893
16286
  if (!dirs.includes(dir)) dirs.push(dir);
15894
16287
  }
15895
16288
  return dirs;
@@ -15911,13 +16304,13 @@ async function writeFailureJsonRetainingCause(preferredCandidates, uniqueFallbac
15911
16304
  const candidates = [
15912
16305
  ...preferredCandidates,
15913
16306
  // One unique name per fallback dir — collisions on fixed names cannot exhaust this.
15914
- ...uniqueFallbackDirs.map((dir) => join32(dir, `${stem}.${randomUUID3()}.json`))
16307
+ ...uniqueFallbackDirs.map((dir) => join33(dir, `${stem}.${randomUUID4()}.json`))
15915
16308
  ];
15916
16309
  for (let i = 0; i < candidates.length; i += 1) {
15917
16310
  const path = candidates[i];
15918
16311
  const payload = issues.length === 0 ? basePayload : { ...basePayload, publicationIssues: issues };
15919
16312
  try {
15920
- await writeFile9(
16313
+ await writeFile10(
15921
16314
  path,
15922
16315
  `${JSON.stringify(payload, null, 2)}
15923
16316
  `,
@@ -15962,20 +16355,20 @@ async function publishFailureArtifacts(admitted, failure2, authority) {
15962
16355
  baseDir
15963
16356
  );
15964
16357
  const errorCandidates = underArtifacts ? [
15965
- join32(baseDir, "error.json"),
15966
- join32(baseDir, "error.settlement.json"),
15967
- join32(admitted.runDirectory, "error.settlement.json")
16358
+ join33(baseDir, "error.json"),
16359
+ join33(baseDir, "error.settlement.json"),
16360
+ join33(admitted.runDirectory, "error.settlement.json")
15968
16361
  ] : [
15969
- join32(baseDir, "error.settlement.json"),
15970
- join32(baseDir, "error.json")
16362
+ join33(baseDir, "error.settlement.json"),
16363
+ join33(baseDir, "error.json")
15971
16364
  ];
15972
16365
  const evidenceCandidates = underArtifacts ? [
15973
- join32(baseDir, "evidence.json"),
15974
- join32(baseDir, "evidence.settlement.json"),
15975
- join32(admitted.runDirectory, "evidence.settlement.json")
16366
+ join33(baseDir, "evidence.json"),
16367
+ join33(baseDir, "evidence.settlement.json"),
16368
+ join33(admitted.runDirectory, "evidence.settlement.json")
15976
16369
  ] : [
15977
- join32(baseDir, "evidence.settlement.json"),
15978
- join32(baseDir, "evidence.json")
16370
+ join33(baseDir, "evidence.settlement.json"),
16371
+ join33(baseDir, "evidence.json")
15979
16372
  ];
15980
16373
  const errorPayloadBase = {
15981
16374
  kind: "error",
@@ -16137,10 +16530,10 @@ function presentFailureTerminal(terminal, io) {
16137
16530
  }
16138
16531
  function defaultNavigatorGraceSleep() {
16139
16532
  let timer;
16140
- const sleep = ((ms) => new Promise((resolve20) => {
16533
+ const sleep = ((ms) => new Promise((resolve21) => {
16141
16534
  timer = setTimeout(() => {
16142
16535
  timer = void 0;
16143
- resolve20();
16536
+ resolve21();
16144
16537
  }, ms);
16145
16538
  }));
16146
16539
  sleep.cancel = () => {
@@ -16152,7 +16545,7 @@ function defaultNavigatorGraceSleep() {
16152
16545
  return sleep;
16153
16546
  }
16154
16547
  function raceNavigatorGrace(work, graceMs = NAVIGATOR_POST_ROLE_GRACE_MS, sleep = defaultNavigatorGraceSleep()) {
16155
- return new Promise((resolve20, reject) => {
16548
+ return new Promise((resolve21, reject) => {
16156
16549
  let settled = false;
16157
16550
  const finish = (action) => {
16158
16551
  if (settled) return;
@@ -16161,11 +16554,11 @@ function raceNavigatorGrace(work, graceMs = NAVIGATOR_POST_ROLE_GRACE_MS, sleep
16161
16554
  action();
16162
16555
  };
16163
16556
  void work.then(
16164
- (value) => finish(() => resolve20({ status: "done", value })),
16557
+ (value) => finish(() => resolve21({ status: "done", value })),
16165
16558
  (error) => finish(() => reject(error))
16166
16559
  );
16167
16560
  void sleep(graceMs).then(() => {
16168
- finish(() => resolve20({ status: "timeout" }));
16561
+ finish(() => resolve21({ status: "timeout" }));
16169
16562
  });
16170
16563
  });
16171
16564
  }
@@ -16219,9 +16612,9 @@ var init_settlement = __esm({
16219
16612
 
16220
16613
  // src/public-cli/auto-resume.ts
16221
16614
  import { constants as fsConstants2 } from "node:fs";
16222
- import { randomUUID as randomUUID4 } from "node:crypto";
16615
+ import { randomUUID as randomUUID5 } from "node:crypto";
16223
16616
  import { lstat as lstat6, mkdir as mkdir4, open as open2 } from "node:fs/promises";
16224
- import { join as join33 } from "node:path";
16617
+ import { join as join34 } from "node:path";
16225
16618
  async function persistReturnedRunState(admitted, authority, options) {
16226
16619
  if (options?.lawful === true) {
16227
16620
  await markRunTerminal(admitted.runDirectory);
@@ -16336,7 +16729,7 @@ function jsonSafeReplacer() {
16336
16729
  };
16337
16730
  }
16338
16731
  async function writeHardenedArtifactFile(artifactsDir, namePrefix, payload) {
16339
- const filePath = join33(artifactsDir, `${namePrefix}-${randomUUID4()}.json`);
16732
+ const filePath = join34(artifactsDir, `${namePrefix}-${randomUUID5()}.json`);
16340
16733
  const body = `${JSON.stringify(payload, jsonSafeReplacer(), 2)}
16341
16734
  `;
16342
16735
  const noFollowFlag = typeof fsConstants2.O_NOFOLLOW === "number" ? fsConstants2.O_NOFOLLOW : 0;
@@ -16607,9 +17000,9 @@ var init_auto_resume = __esm({
16607
17000
  });
16608
17001
 
16609
17002
  // src/public-cli/post-admission.ts
16610
- import { randomUUID as randomUUID5 } from "node:crypto";
16611
- import { readFile as readFile19, writeFile as writeFile10 } from "node:fs/promises";
16612
- import { isAbsolute as isAbsolute8, join as join34, resolve as resolve12 } from "node:path";
17003
+ import { randomUUID as randomUUID6 } from "node:crypto";
17004
+ import { readFile as readFile20, writeFile as writeFile11 } from "node:fs/promises";
17005
+ import { isAbsolute as isAbsolute8, join as join35, resolve as resolve13 } from "node:path";
16613
17006
  function describeCaughtError(error) {
16614
17007
  if (error instanceof Error) {
16615
17008
  const code = error.code;
@@ -16653,8 +17046,8 @@ async function recordBestEffortPostDispatchDiagnostic(admitted, env, diagnostic,
16653
17046
  } catch (appendError) {
16654
17047
  try {
16655
17048
  const artifactsDir = await ensureRealArtifactsDirectory(admitted.runDirectory);
16656
- await writeFile10(
16657
- join34(artifactsDir, `post-admission-diagnostic-${randomUUID5()}.json`),
17049
+ await writeFile11(
17050
+ join35(artifactsDir, `post-admission-diagnostic-${randomUUID6()}.json`),
16658
17051
  `${JSON.stringify({ version: 1, ...payload }, null, 2)}
16659
17052
  `,
16660
17053
  { encoding: "utf8", flag: "wx" }
@@ -16670,7 +17063,7 @@ async function recordBestEffortPostDispatchDiagnostic(admitted, env, diagnostic,
16670
17063
  }
16671
17064
  async function readInvocationHost(runDirectory) {
16672
17065
  try {
16673
- const raw = JSON.parse(await readFile19(join34(runDirectory, "invocation.json"), "utf8"));
17066
+ const raw = JSON.parse(await readFile20(join35(runDirectory, "invocation.json"), "utf8"));
16674
17067
  return typeof raw.host === "string" && raw.host.trim() !== "" ? raw.host : void 0;
16675
17068
  } catch (error) {
16676
17069
  if (error.code === "ENOENT") return void 0;
@@ -16932,8 +17325,8 @@ async function dispatchPostAdmissionTurn(input) {
16932
17325
  }
16933
17326
  let stderrLogWriteFailure;
16934
17327
  try {
16935
- await writeFile10(
16936
- join34(admitted.runDirectory, "stderr.log"),
17328
+ await writeFile11(
17329
+ join35(admitted.runDirectory, "stderr.log"),
16937
17330
  result.stderr,
16938
17331
  "utf8"
16939
17332
  );
@@ -17162,7 +17555,7 @@ function resumeTurnRequestProjectionOptions(admitted, request, env, summonsPrepa
17162
17555
  kind: "resume",
17163
17556
  prompt
17164
17557
  },
17165
- ...request.message === void 0 ? {} : { courtAttemptId: randomUUID5() },
17558
+ ...request.message === void 0 ? {} : { courtAttemptId: randomUUID6() },
17166
17559
  ...env.stationChild === void 0 ? {} : { stationChild: env.stationChild }
17167
17560
  };
17168
17561
  }
@@ -17179,8 +17572,8 @@ async function dispatchAfterWriterLease(input) {
17179
17572
  }
17180
17573
  }
17181
17574
  function isAlreadyFrozenSummonsAttachment(runDirectory, attachmentPath) {
17182
- const absolute = isAbsolute8(attachmentPath) ? attachmentPath : resolve12(attachmentPath);
17183
- return pathContainedIn(join34(runDirectory, "attachments"), absolute);
17575
+ const absolute = isAbsolute8(attachmentPath) ? attachmentPath : resolve13(attachmentPath);
17576
+ return pathContainedIn(join35(runDirectory, "attachments"), absolute);
17184
17577
  }
17185
17578
  async function prepareSummonsResumeMaterials(runDirectory, summons) {
17186
17579
  if (summons === void 0) return void 0;
@@ -17259,7 +17652,7 @@ async function runPostAdmissionSeatResume(input) {
17259
17652
  }
17260
17653
  let turnRequest = await input.buildTurnRequest(admittedForBuild, request);
17261
17654
  if (openCourtAttemptId !== void 0 || request.summons !== void 0 || request.message !== void 0) {
17262
- const courtAttemptId = openCourtAttemptId ?? (turnRequest.courtAttemptId !== void 0 && turnRequest.courtAttemptId.length > 0 ? turnRequest.courtAttemptId : randomUUID5());
17655
+ const courtAttemptId = openCourtAttemptId ?? (turnRequest.courtAttemptId !== void 0 && turnRequest.courtAttemptId.length > 0 ? turnRequest.courtAttemptId : randomUUID6());
17263
17656
  turnRequest = { ...turnRequest, courtAttemptId };
17264
17657
  if (openCourtAttemptId === void 0) {
17265
17658
  const court = {
@@ -18530,7 +18923,7 @@ __export(public_role_summons_exports, {
18530
18923
  summonPublicRole: () => summonPublicRole
18531
18924
  });
18532
18925
  import { existsSync as existsSync11 } from "node:fs";
18533
- import { join as join35 } from "node:path";
18926
+ import { join as join36 } from "node:path";
18534
18927
  function createCapturingIo() {
18535
18928
  const chunks = [];
18536
18929
  return {
@@ -18553,7 +18946,7 @@ function parentDir(path) {
18553
18946
  function walkPackageRoot(start) {
18554
18947
  let dir = start;
18555
18948
  for (let i = 0; i < 12; i += 1) {
18556
- if (existsSync11(join35(dir, "package.json")) && existsSync11(join35(dir, "souls"))) {
18949
+ if (existsSync11(join36(dir, "package.json")) && existsSync11(join36(dir, "souls"))) {
18557
18950
  return dir;
18558
18951
  }
18559
18952
  const parent = parentDir(dir);
@@ -18647,7 +19040,7 @@ async function createSummonEnv(options) {
18647
19040
  async function summonPublicRole(options) {
18648
19041
  const packageRoot = resolveSummonsPackageRoot(options.packageRoot);
18649
19042
  const home = await resolveSummonHome(options);
18650
- const agentDir = options.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? join35(home, ".pi", "agent");
19043
+ const agentDir = options.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? join36(home, ".pi", "agent");
18651
19044
  const {
18652
19045
  loadCredentialProviders: loadCredentialProviders2,
18653
19046
  loadPublicCliConfig: loadPublicCliConfig2,
@@ -19028,9 +19421,9 @@ import { randomUUID as randomUUID8 } from "node:crypto";
19028
19421
  // src/role-envelope.ts
19029
19422
  init_engine_detour();
19030
19423
  import { randomUUID as randomUUID7 } from "node:crypto";
19031
- import { mkdir as mkdir5, readFile as readFile21, writeFile as writeFile12 } from "node:fs/promises";
19424
+ import { mkdir as mkdir5, readFile as readFile22, writeFile as writeFile12 } from "node:fs/promises";
19032
19425
  import { createServer } from "node:net";
19033
- import { basename as basename8, dirname as dirname19, join as join40 } from "node:path";
19426
+ import { basename as basename9, dirname as dirname20, join as join40 } from "node:path";
19034
19427
  import { fileURLToPath as fileURLToPath2 } from "node:url";
19035
19428
 
19036
19429
  // src/gatekeeper-pass-envelope.ts
@@ -19155,7 +19548,7 @@ import {
19155
19548
  openSync as openSync2,
19156
19549
  writeSync
19157
19550
  } from "node:fs";
19158
- import { dirname as dirname16, isAbsolute as isAbsolute10, resolve as resolve14 } from "node:path";
19551
+ import { dirname as dirname18, isAbsolute as isAbsolute10, resolve as resolve15 } from "node:path";
19159
19552
 
19160
19553
  // src/activation-ledger-session.ts
19161
19554
  init_activation_ledger_topology();
@@ -19163,9 +19556,9 @@ import {
19163
19556
  lstatSync as lstatSync2,
19164
19557
  realpathSync as realpathSync3,
19165
19558
  statSync as statSync4,
19166
- writeFileSync as writeFileSync4
19559
+ writeFileSync as writeFileSync3
19167
19560
  } from "node:fs";
19168
- import { isAbsolute as isAbsolute9, resolve as resolve13 } from "node:path";
19561
+ import { isAbsolute as isAbsolute9, resolve as resolve14 } from "node:path";
19169
19562
  var ActivationSessionFileMissingError = class extends Error {
19170
19563
  code = "AK_ACTIVATION_SESSION_FILE_MISSING";
19171
19564
  path;
@@ -19184,7 +19577,7 @@ function materializeDeferredSessionFile(sessionManager, resolvedFile) {
19184
19577
  throw new ActivationSessionFileMissingError(resolvedFile);
19185
19578
  }
19186
19579
  try {
19187
- writeFileSync4(resolvedFile, `${JSON.stringify(header)}
19580
+ writeFileSync3(resolvedFile, `${JSON.stringify(header)}
19188
19581
  `, { flag: "wx" });
19189
19582
  } catch (error) {
19190
19583
  if (errnoCode(error) !== "EEXIST") {
@@ -19210,7 +19603,7 @@ function durableSessionPointer(sessionManager) {
19210
19603
  `Workflow role activation requires an absolute durable session file path; got relative path: ${file}`
19211
19604
  );
19212
19605
  }
19213
- const resolvedFile = resolve13(file);
19606
+ const resolvedFile = resolve14(file);
19214
19607
  try {
19215
19608
  lstatSync2(resolvedFile);
19216
19609
  } catch (error) {
@@ -19302,9 +19695,9 @@ function appendActivationLedgerLine(ledgerPath, line2, options) {
19302
19695
  `activation ledger home must be absolute: ${options.ledgerHome}`
19303
19696
  );
19304
19697
  }
19305
- const resolvedLedger = resolve14(ledgerPath);
19306
- const resolvedHome = resolve14(options.ledgerHome);
19307
- const parent = dirname16(resolvedLedger);
19698
+ const resolvedLedger = resolve15(ledgerPath);
19699
+ const resolvedHome = resolve15(options.ledgerHome);
19700
+ const parent = dirname18(resolvedLedger);
19308
19701
  ensureRealDirectoryTree(resolvedHome, parent);
19309
19702
  assertLedgerFileInsideHome(resolvedLedger, resolvedHome);
19310
19703
  if (typeof constants2.O_NOFOLLOW !== "number") {
@@ -19612,27 +20005,10 @@ init_collector_evidence();
19612
20005
  init_collector_github();
19613
20006
 
19614
20007
  // src/collector-handbook.ts
19615
- import { readFile as readFile20 } from "node:fs/promises";
19616
- import { join as join37, sep as sep5 } from "node:path";
19617
-
19618
- // src/atomic-write.ts
19619
- import { randomUUID as randomUUID6 } from "node:crypto";
19620
- import { rename as rename3, rm as rm3, writeFile as writeFile11 } from "node:fs/promises";
19621
- import { dirname as dirname17, join as join36 } from "node:path";
19622
- async function writeFileAtomically(destination, contents) {
19623
- const parent = dirname17(destination);
19624
- const temporary = join36(parent, `.atomic-write-${randomUUID6()}.tmp`);
19625
- try {
19626
- await writeFile11(temporary, contents);
19627
- await rename3(temporary, destination);
19628
- } catch (error) {
19629
- await rm3(temporary, { force: true }).catch(() => void 0);
19630
- throw error;
19631
- }
19632
- }
19633
-
19634
- // src/collector-handbook.ts
20008
+ init_atomic_write();
19635
20009
  init_activation_ledger_topology();
20010
+ import { readFile as readFile21 } from "node:fs/promises";
20011
+ import { join as join37, sep as sep5 } from "node:path";
19636
20012
 
19637
20013
  // src/collector-tool-schemas.ts
19638
20014
  init_open_tool_schema();
@@ -19775,7 +20151,7 @@ function createCollectorHandbookStore(input) {
19775
20151
  ensureRealDirectoryTree(input.ledgerHome, parentDir2);
19776
20152
  assertLedgerFileInsideHome(path, input.ledgerHome);
19777
20153
  try {
19778
- const body = await readFile20(path, "utf8");
20154
+ const body = await readFile21(path, "utf8");
19779
20155
  assertHandbookBudget(body, "\u6B63\u6587");
19780
20156
  return body;
19781
20157
  } catch (error) {
@@ -20696,33 +21072,80 @@ var diaristOutputSchema = withInfrastructureFailureDeclaration(
20696
21072
  description: "status \u4E3A escalate \u65F6\uFF1A\u8BA4\u4E0D\u51FA\u672C\u5EAD\u5BF9\u8C61\u7684\u539F\u56E0"
20697
21073
  })
20698
21074
  ),
20699
- entries: Type19.Optional(
21075
+ sessions: Type19.Optional(
20700
21076
  Type19.Array(
20701
21077
  Type19.Object(
20702
21078
  {
20703
- sourceKind: Type19.Optional(Type19.String({
20704
- description: "\u6765\u6E90\u65CF\uFF1Acc-session | issue-body-comment | adr-decision-key | ticket-decree-block"
20705
- })),
20706
- sourceRef: Type19.Optional(Type19.Object(
20707
- {
20708
- sessionFile: Type19.Optional(Type19.String()),
20709
- entryId: Type19.Optional(Type19.Unknown()),
20710
- path: Type19.Optional(Type19.String()),
20711
- url: Type19.Optional(Type19.String())
20712
- },
20713
- { additionalProperties: true, description: "\u4E0D\u53EF\u53D8\u6E90\u6307\u9488" }
20714
- )),
20715
- transcript: Type19.Optional(Type19.String({
20716
- description: "\u6574\u5757\u539F\u6587\uFF08\u8A8A\u5F55\u6574\u5757\uFF0C\u4E0D\u6307\u9488\u5316\uFF09"
20717
- })),
20718
- timestamp: Type19.Optional(Type19.String({ description: "\u6E90\u65F6\u95F4\u6233 ISO" })),
20719
- note: Type19.Optional(
20720
- Type19.String({ description: "\u8BE5\u6750\u6599\u4E0E\u672C\u6848\u7684\u5173\u7CFB\uFF08\u4EBA\u8BFB\uFF09" })
21079
+ path: Type19.Optional(
21080
+ Type19.String({ description: "\u4F1A\u8BDD\u5377\u7EDD\u5BF9\u6216\u53EF\u8BFB\u8DEF\u5F84" })
21081
+ ),
21082
+ ranges: Type19.Optional(
21083
+ Type19.Array(
21084
+ Type19.Object(
21085
+ {
21086
+ from: Type19.Optional(
21087
+ Type19.Object(
21088
+ {
21089
+ id: Type19.Optional(Type19.String()),
21090
+ line: Type19.Optional(Type19.Unknown())
21091
+ },
21092
+ {
21093
+ additionalProperties: true,
21094
+ description: "\u8D77\u70B9\uFF1A\u539F\u751F id \u6216\u672C\u8F6E\u884C\u53F7\u4E8C\u9009\u4E00"
21095
+ }
21096
+ )
21097
+ ),
21098
+ to: Type19.Optional(
21099
+ Type19.Object(
21100
+ {
21101
+ id: Type19.Optional(Type19.String()),
21102
+ line: Type19.Optional(Type19.Unknown())
21103
+ },
21104
+ {
21105
+ additionalProperties: true,
21106
+ description: "\u7EC8\u70B9\uFF1A\u539F\u751F id \u6216\u672C\u8F6E\u884C\u53F7\u4E8C\u9009\u4E00"
21107
+ }
21108
+ )
21109
+ )
21110
+ },
21111
+ { additionalProperties: true, description: "\u4E00\u6BB5\u5BF9\u8BDD\u533A\u95F4" }
21112
+ ),
21113
+ { description: "\u672C\u5377\u672C\u8F6E\u5404\u533A\u95F4\uFF1B\u81F3\u5C11\u4E00\u6BB5" }
21114
+ )
20721
21115
  )
20722
21116
  },
20723
- { additionalProperties: true, description: "\u4E00\u6761\u5165\u5F55\u6574\u5757" }
21117
+ { additionalProperties: true, description: "\u4E00\u5377\u4F1A\u8BDD\u7684\u8FB9\u754C" }
20724
21118
  ),
20725
- { description: "\u5165\u5F55\u6574\u5757\uFF1B\u7A7A\u5217\u8868\u5408\u6CD5\u5B8C\u5C40\uFF1Bescalate \u65F6\u53EF\u4E0D\u4EA4" }
21119
+ {
21120
+ description: "\u672C\u7968\u5BF9\u8BDD\u8FB9\u754C\uFF1B\u7A7A\u5217\u8868\uFF1D\u672C\u8F6E\u65E0\u5BF9\u8BDD\u53EF\u5212\u3002\u7AEF\u70B9\u65E0\u6CD5\u6307\u540D\u65F6\u8D70 reask\uFF0C\u4E0D\u4E2D\u6B62\u3002"
21121
+ }
21122
+ )
21123
+ ),
21124
+ amendments: Type19.Optional(
21125
+ Type19.Array(
21126
+ Type19.Object(
21127
+ {
21128
+ s: Type19.Optional(
21129
+ Type19.Unknown({ description: "\u5377\u4E0B\u6807\uFF08sessions \u4F4D\u7F6E\uFF09" })
21130
+ ),
21131
+ line: Type19.Optional(
21132
+ Type19.Unknown({ description: "\u6E90\u5377 1-based \u884C\u53F7" })
21133
+ ),
21134
+ speaker: Type19.Optional(
21135
+ Type19.String({ description: "owner | runner" })
21136
+ ),
21137
+ text: Type19.Optional(
21138
+ Type19.String({ description: "\u8865\u5199\u6B63\u6587\uFF08\u539F\u8BDD\uFF09" })
21139
+ )
21140
+ },
21141
+ {
21142
+ additionalProperties: true,
21143
+ description: "\u4E00\u6761\u574F\u884C\u8865\u5199\uFF1B\u7F3A\u5B57\u6BB5\u7684\u6210\u5458\u673A\u68B0\u8DF3\u8FC7"
21144
+ }
21145
+ ),
21146
+ {
21147
+ description: "\u53EF\u9009\uFF1B\u673A\u68B0\u89E3\u6790\u4E0D\u4E86\u7684\u884C\u4EA4\u6B64\u8865\u5199\u3002\u7F3A\u672C\u5B57\u6BB5\uFF1D\u65E0\u8865\u5199\uFF0C\u4E0D\u62D2\u6536\u3002"
21148
+ }
20726
21149
  )
20727
21150
  )
20728
21151
  })
@@ -20731,8 +21154,8 @@ var diaristOutputSchema = withInfrastructureFailureDeclaration(
20731
21154
  var DIARIST_TOOL_SPEC = {
20732
21155
  name: DIARIST_OUTPUT_TOOL_NAME,
20733
21156
  label: "\u8D77\u5C45\u90CE\u8F93\u51FA",
20734
- description: "\u8D77\u5C45\u90CE\u5165\u5F55\u6574\u5757\u4E0E\u672C\u7968\u8EAB\u4EFD\u65AD\u8A00\uFF1B\u8BA4\u4E0D\u51FA\u672C\u5EAD\u5BF9\u8C61\u5219 escalate\u3002",
20735
- promptSnippet: "\u8D77\u5C45\u90CE\u5165\u5F55\u6574\u5757\u4E0E\u672C\u7968\u8EAB\u4EFD",
21157
+ description: "\u8D77\u5C45\u90CE\u4EA4\u672C\u7968\u5BF9\u8BDD\u8FB9\u754C\uFF08sessions\uFF09\u4E0E\u53EF\u9009\u574F\u884C\u8865\u5199\uFF08amendments\uFF09\uFF1B\u8BA4\u4E0D\u51FA\u672C\u5EAD\u5BF9\u8C61\u5219 escalate\u3002",
21158
+ promptSnippet: "\u8D77\u5C45\u90CE\u4EA4\u8FB9\u754C\u4E0E\u53EF\u9009\u8865\u5199",
20736
21159
  parameters: diaristOutputSchema
20737
21160
  };
20738
21161
 
@@ -20741,46 +21164,24 @@ init_diarist_contracts();
20741
21164
 
20742
21165
  // src/diarist.ts
20743
21166
  init_ticket_provenance();
20744
- init_ticket_provenance_contracts();
20745
- async function commitDiaristEntries(input) {
20746
- const { ticketNumber, cwd } = input;
20747
- const homeOpt = input.home === void 0 ? {} : { home: input.home };
20748
- const volumePaths = ensureTicketProvenanceVolume(ticketNumber, cwd, input.home);
20749
- const before = await readTicketProvenance(ticketNumber, cwd, input.home);
20750
- let dropped = 0;
20751
- for (const submitted of input.entries) {
20752
- if (projectTicketProvenanceEntry(submitted) === void 0) {
20753
- dropped += 1;
20754
- }
20755
- appendTicketProvenanceEntry({
20756
- ticketNumber,
20757
- cwd,
20758
- sessionParent: input.sessionParent,
20759
- ...homeOpt,
20760
- payload: submitted,
20761
- source: "diarist"
20762
- });
20763
- }
20764
- const volume = await readTicketProvenance(ticketNumber, cwd, input.home);
20765
- const humanViewFile = writeTicketProvenanceHumanView({
20766
- ticketNumber,
20767
- cwd,
20768
- ...homeOpt,
20769
- entries: volume.entries,
20770
- unprojected: volume.unprojected
21167
+ async function commitDiaristProjection(input) {
21168
+ const result = await reprojectTicketProvenance({
21169
+ ticketNumber: input.ticketNumber,
21170
+ cwd: input.cwd,
21171
+ ...input.home === void 0 ? {} : { home: input.home },
21172
+ sessions: input.sessions,
21173
+ ...input.amendments === void 0 ? {} : { amendments: input.amendments }
20771
21174
  });
20772
- const appended = volume.entries.length - before.entries.length;
20773
21175
  return {
20774
- ticketNumber,
20775
- appended,
20776
- dropped,
20777
- volumeRecordFile: volumePaths.recordFile,
20778
- humanViewFile,
20779
- collectorStatus: appended > 0 ? "ok" : input.entries.length === 0 ? "empty-selection" : "nothing-appended"
21176
+ ticketNumber: input.ticketNumber,
21177
+ volumeRecordFile: result.recordFile,
21178
+ lineCount: result.lines.length,
21179
+ unparsable: result.unparsable
20780
21180
  };
20781
21181
  }
20782
21182
 
20783
21183
  // src/role-runtime.ts
21184
+ init_ticket_provenance();
20784
21185
  init_invocation();
20785
21186
  init_gatekeeper_role();
20786
21187
 
@@ -20810,11 +21211,11 @@ init_gatekeeper_output();
20810
21211
  init_navigator_output();
20811
21212
 
20812
21213
  // src/navigator-attendance.ts
20813
- import { createHash as createHash9 } from "node:crypto";
21214
+ import { createHash as createHash8 } from "node:crypto";
20814
21215
  init_navigator_invocation_identity();
20815
21216
  init_packaged_role_registry();
20816
21217
  init_activation_ledger_topology();
20817
- import { resolve as resolve15 } from "node:path";
21218
+ import { resolve as resolve16 } from "node:path";
20818
21219
  import "@earendil-works/pi-coding-agent";
20819
21220
  import { Type as Type21 } from "typebox";
20820
21221
 
@@ -21270,11 +21671,11 @@ function navigatorSubjectKey(subjectRoot, subject, provenance = "role_input") {
21270
21671
  if (provenance === "placeholder") return subjectRoot;
21271
21672
  const normalized = subject.trim().replace(/\s+/g, " ");
21272
21673
  if (normalized === "") return subjectRoot;
21273
- return `${subjectRoot}#${createHash9("sha256").update(normalized).digest("hex").slice(0, 32)}`;
21674
+ return `${subjectRoot}#${createHash8("sha256").update(normalized).digest("hex").slice(0, 32)}`;
21274
21675
  }
21275
21676
  function navigatorSubjectKeyForInput(subjectRoot, reference, cwd = process.cwd()) {
21276
21677
  if (issueRoot(subjectRoot) !== void 0 || !subjectRoot.includes("/.ak/work/")) return subjectRoot;
21277
- const resolvedReference = resolve15(cwd, reference);
21678
+ const resolvedReference = resolve16(cwd, reference);
21278
21679
  const marker = "/runs/";
21279
21680
  if (resolvedReference.includes(marker)) {
21280
21681
  return subjectRoot;
@@ -21908,9 +22309,9 @@ init_reviewer_pinned_git();
21908
22309
  init_reviewer_output();
21909
22310
  import { Type as Type23 } from "typebox";
21910
22311
  var reviewerAmendmentsSchema = Type23.Object({
21911
- standards: Type23.Optional(Type23.String({ description: "\u76F8\u5BF9 Standards \u5B50\u62A5\u544A\u7684\u589E\u91CF\uFF1A\u589E finding\u3001\u64A4\u56DE\u6216\u4E8B\u5B9E\u66F4\u6B63" })),
21912
- spec: Type23.Optional(Type23.String({ description: "\u76F8\u5BF9 Spec \u5B50\u62A5\u544A\u7684\u589E\u91CF\uFF1A\u589E finding\u3001\u64A4\u56DE\u6216\u4E8B\u5B9E\u66F4\u6B63" }))
21913
- }, { additionalProperties: true, description: "\u76F8\u5BF9\u5B50\u62A5\u544A\u7684\u53EF\u9009\u8F74\u589E\u91CF\uFF1B\u975E\u66FF\u4EE3\u62A5\u544A\u3002\u65E0\u589E\u91CF\u7684\u8F74\u53EF\u7701\u7565\u3002" });
22312
+ standards: Type23.Optional(Type23.String({ description: "\u6807\u51C6\u8F74\u5F39\u7AE0\u6B63\u6587" })),
22313
+ spec: Type23.Optional(Type23.String({ description: "\u89C4\u683C\u8F74\u5F39\u7AE0\u6B63\u6587" }))
22314
+ }, { additionalProperties: true, description: "\u9010\u8F74\u5F39\u7AE0\u6B63\u6587\uFF1B\u65E0\u5F39\u7AE0\u7684\u8F74\u53EF\u7701\u7565\u3002" });
21914
22315
  var REVIEWER_STATUS_DESCRIPTION = "completed | refused \u2014 \u5F62\u72B6\u6307\u5F15\uFF0C\u975E schema \u95F8";
21915
22316
  var reviewerOutputVariants = Type23.Union([
21916
22317
  Type23.Object({
@@ -21985,7 +22386,7 @@ init_submission_errors();
21985
22386
  init_submission_errors();
21986
22387
  import { execFileSync as execFileSync4 } from "node:child_process";
21987
22388
  import { existsSync as existsSync12, lstatSync as lstatSync3, readdirSync as readdirSync3, readFileSync as readFileSync4, rmdirSync, rmSync } from "node:fs";
21988
- import { resolve as resolve16 } from "node:path";
22389
+ import { resolve as resolve17 } from "node:path";
21989
22390
  var WORKER_SUBMISSION_GATE_RECORD_KIND = WORKER_SUBMISSION_GATE_KIND;
21990
22391
  var WORKER_COMMIT_BASELINE_ENTRY_TYPE = "commit-baseline";
21991
22392
  var WORKER_COMMIT_REMINDER_BOUNCE_ENTRY_TYPE = "commit-reminder-bounce";
@@ -22034,7 +22435,7 @@ function escapeGitConfigValueRegex(value) {
22034
22435
  function unsetOwnedHooksPath(file) {
22035
22436
  const owned = [];
22036
22437
  for (const value of tryGetAll(file, "core.hooksPath")) {
22037
- if (!ownedHook(resolve16(value, HOOK_FILE))) continue;
22438
+ if (!ownedHook(resolve17(value, HOOK_FILE))) continue;
22038
22439
  try {
22039
22440
  gitFile(file, [
22040
22441
  "--unset-all",
@@ -22049,15 +22450,15 @@ function unsetOwnedHooksPath(file) {
22049
22450
  return owned;
22050
22451
  }
22051
22452
  function rmOwnedDir(dir) {
22052
- const hookPath = resolve16(dir, HOOK_FILE);
22453
+ const hookPath = resolve17(dir, HOOK_FILE);
22053
22454
  if (!ownedHook(hookPath)) return;
22054
22455
  rmSync(hookPath, { force: true });
22055
22456
  if (existsSync12(dir) && readdirSync3(dir).length === 0) rmdirSync(dir);
22056
22457
  }
22057
22458
  function linkedGitDirs(commonDir) {
22058
- const root = resolve16(commonDir, "worktrees");
22459
+ const root = resolve17(commonDir, "worktrees");
22059
22460
  if (!existsSync12(root)) return [];
22060
- return readdirSync3(root).map((name) => resolve16(root, name)).filter((dir) => lstatSync3(dir).isDirectory());
22461
+ return readdirSync3(root).map((name) => resolve17(root, name)).filter((dir) => lstatSync3(dir).isDirectory());
22061
22462
  }
22062
22463
  function uninstallPackageWorkerHooks(cwd) {
22063
22464
  let inside;
@@ -22071,17 +22472,17 @@ function uninstallPackageWorkerHooks(cwd) {
22071
22472
  const clear = (configFile) => {
22072
22473
  for (const hooks of unsetOwnedHooksPath(configFile)) rmOwnedDir(hooks);
22073
22474
  };
22074
- clear(resolve16(commonDir, "config"));
22075
- clear(resolve16(commonDir, "config.worktree"));
22076
- rmOwnedDir(resolve16(commonDir, HOOKS_DIR));
22077
- const legacy = resolve16(commonDir, "hooks", HOOK_FILE);
22475
+ clear(resolve17(commonDir, "config"));
22476
+ clear(resolve17(commonDir, "config.worktree"));
22477
+ rmOwnedDir(resolve17(commonDir, HOOKS_DIR));
22478
+ const legacy = resolve17(commonDir, "hooks", HOOK_FILE);
22078
22479
  if (ownedHook(legacy)) rmSync(legacy, { force: true });
22079
22480
  for (const gitDir of linkedGitDirs(commonDir)) {
22080
- clear(resolve16(gitDir, "config.worktree"));
22081
- rmOwnedDir(resolve16(gitDir, HOOKS_DIR));
22481
+ clear(resolve17(gitDir, "config.worktree"));
22482
+ rmOwnedDir(resolve17(gitDir, HOOKS_DIR));
22082
22483
  }
22083
22484
  }
22084
- function isRecord11(value) {
22485
+ function isRecord12(value) {
22085
22486
  return typeof value === "object" && value !== null && !Array.isArray(value);
22086
22487
  }
22087
22488
  function unfinishedReasonPresent(details) {
@@ -22097,7 +22498,7 @@ function readGateState(session) {
22097
22498
  if (entry.type !== "custom") continue;
22098
22499
  if (entry.customType === WORKER_COMMIT_BASELINE_ENTRY_TYPE) {
22099
22500
  const data = entry.data;
22100
- if (isRecord11(data) && (data.head === null || typeof data.head === "string")) {
22501
+ if (isRecord12(data) && (data.head === null || typeof data.head === "string")) {
22101
22502
  baseline = data.head;
22102
22503
  }
22103
22504
  } else if (entry.customType === WORKER_COMMIT_REMINDER_BOUNCE_ENTRY_TYPE) {
@@ -23081,6 +23482,18 @@ function readDiaristRunCoordinates(ctx) {
23081
23482
  ...bound === void 0 ? {} : { boundTicketNumber: bound }
23082
23483
  };
23083
23484
  }
23485
+ var DIARIST_BOUNDS_REASK = "\u8FB9\u754C\u65E0\u6CD5\u4F7F\u7528\u3002\u8BF7\u91CD\u4EA4 sessions\uFF1A\u6BCF\u5377 path + ranges\uFF0C\u6BCF\u7AEF\u4EE5\u539F\u751F id \u6216\u672C\u8F6E\u884C\u53F7\u4E8C\u9009\u4E00\u6307\u540D\u3002";
23486
+ function diaristUnparsableReask(rows) {
23487
+ const payload = rows.map((row) => ({
23488
+ s: row.s,
23489
+ line: row.line,
23490
+ raw: row.raw
23491
+ }));
23492
+ return [
23493
+ "\u4E0B\u5217\u6E90\u884C\u672A\u80FD\u5F55\u5165\uFF0C\u8BF7\u7ECF amendments \u8865\u5199\uFF08\u6BCF\u6761 s + line + speaker + text\uFF09\uFF1B\u5176\u4F59\u8FB9\u754C\u53EF\u4FDD\u6301\u4E0D\u53D8\u3002",
23494
+ JSON.stringify(payload)
23495
+ ].join("\n");
23496
+ }
23084
23497
  function createDiaristRoleRuntime(roleHost, dependencies) {
23085
23498
  return createFiledOfficerRuntime(
23086
23499
  roleHost,
@@ -23098,13 +23511,33 @@ function createDiaristRoleRuntime(roleHost, dependencies) {
23098
23511
  if (coords.boundTicketNumber === void 0) {
23099
23512
  await bindTicketNumberOnRunDirectory(coords.runDirectory, ticketNumber);
23100
23513
  }
23101
- await commitDiaristEntries({
23102
- ticketNumber,
23103
- cwd: coords.projectRoot,
23104
- sessionParent: join39(coords.runDirectory, "session", "session.jsonl"),
23105
- home: coords.home,
23106
- entries: projectDiaristEntries(parameters)
23107
- });
23514
+ const sessions = projectDiaristSessions(parameters);
23515
+ if (sessions === void 0) {
23516
+ throw new ParentQueueReaskError(DIARIST_BOUNDS_REASK);
23517
+ }
23518
+ const amendments = projectDiaristAmendments(parameters);
23519
+ let facts;
23520
+ try {
23521
+ facts = await commitDiaristProjection({
23522
+ ticketNumber,
23523
+ cwd: coords.projectRoot,
23524
+ home: coords.home,
23525
+ sessions,
23526
+ amendments
23527
+ });
23528
+ } catch (error) {
23529
+ if (error instanceof ParentQueueReaskError) throw error;
23530
+ if (error instanceof TicketProvenanceInputError) {
23531
+ throw new ParentQueueReaskError(
23532
+ `${DIARIST_BOUNDS_REASK}
23533
+ ${error.message}`
23534
+ );
23535
+ }
23536
+ throw error;
23537
+ }
23538
+ if (facts.unparsable.length > 0) {
23539
+ throw new ParentQueueReaskError(diaristUnparsableReask(facts.unparsable));
23540
+ }
23108
23541
  }
23109
23542
  return parameters;
23110
23543
  }
@@ -24017,11 +24450,11 @@ function buildSkillExpansion(methodSkills, prompt) {
24017
24450
  });
24018
24451
  }
24019
24452
  async function listen(server, path) {
24020
- await new Promise((resolve20, reject) => {
24453
+ await new Promise((resolve21, reject) => {
24021
24454
  server.once("error", reject);
24022
24455
  server.listen(path, () => {
24023
24456
  server.off("error", reject);
24024
- resolve20();
24457
+ resolve21();
24025
24458
  });
24026
24459
  });
24027
24460
  }
@@ -24059,12 +24492,12 @@ async function prepareRoleEnvelope(options) {
24059
24492
  await mkdir5(request.runDirectory, { recursive: true });
24060
24493
  for (const method of request.methods) {
24061
24494
  if (method.kind !== "skill") continue;
24062
- const name = basename8(dirname19(method.path));
24063
- const raw = await readFile21(method.path, "utf8");
24495
+ const name = basename9(dirname20(method.path));
24496
+ const raw = await readFile22(method.path, "utf8");
24064
24497
  methodSkills.set(name, { path: method.path, body: stripSkillFrontmatter(raw).trim() });
24065
24498
  }
24066
24499
  let sessionFile = options.sessionFile ?? join40(request.runDirectory, "session", "session.jsonl");
24067
- await mkdir5(dirname19(sessionFile), { recursive: true });
24500
+ await mkdir5(dirname20(sessionFile), { recursive: true });
24068
24501
  if (request.continuation.kind !== "resume") {
24069
24502
  try {
24070
24503
  await writeFile12(
@@ -24093,7 +24526,7 @@ async function prepareRoleEnvelope(options) {
24093
24526
  getLeafEntry: () => sessionEntries.at(-1),
24094
24527
  getLeafId: () => runId,
24095
24528
  getEntries: () => sessionEntries,
24096
- getSessionDir: () => dirname19(sessionFile),
24529
+ getSessionDir: () => dirname20(sessionFile),
24097
24530
  getSessionFile: () => sessionFile,
24098
24531
  getHeader: () => ({ type: "session", id: runId }),
24099
24532
  setSessionFile(path) {
@@ -24403,8 +24836,8 @@ async function prepareRoleEnvelope(options) {
24403
24836
  try {
24404
24837
  const closeAll = server.closeAllConnections;
24405
24838
  if (typeof closeAll === "function") closeAll.call(server);
24406
- await new Promise((resolve20, reject) => {
24407
- server.close((error) => error ? reject(error) : resolve20());
24839
+ await new Promise((resolve21, reject) => {
24840
+ server.close((error) => error ? reject(error) : resolve21());
24408
24841
  });
24409
24842
  } catch (error) {
24410
24843
  cleanupFailures.push(error);
@@ -24468,7 +24901,7 @@ async function prepareRoleEnvelope(options) {
24468
24901
  message: { role: "user", content: prompt }
24469
24902
  });
24470
24903
  }
24471
- const methodPrompt = (await Promise.all(request.methods.map(({ path }) => readFile21(path, "utf8")))).join("\n\n");
24904
+ const methodPrompt = (await Promise.all(request.methods.map(({ path }) => readFile22(path, "utf8")))).join("\n\n");
24472
24905
  const promptResults = await emit("before_agent_start", {
24473
24906
  prompt,
24474
24907
  systemPrompt: methodPrompt,
@@ -24526,18 +24959,18 @@ async function prepareRoleEnvelope(options) {
24526
24959
  }
24527
24960
 
24528
24961
  // src/role-runtime-dependencies.ts
24529
- import { readFile as readFile24 } from "node:fs/promises";
24962
+ import { readFile as readFile25 } from "node:fs/promises";
24530
24963
  import { fileURLToPath as fileURLToPath3 } from "node:url";
24531
24964
 
24532
24965
  // src/canonical-skill-binding.ts
24533
- import { readFile as readFile22, realpath as realpath7 } from "node:fs/promises";
24966
+ import { readFile as readFile23, realpath as realpath7 } from "node:fs/promises";
24534
24967
  import { homedir } from "node:os";
24535
- import { dirname as dirname20, resolve as resolve17 } from "node:path";
24968
+ import { dirname as dirname21, resolve as resolve18 } from "node:path";
24536
24969
  import { stripFrontmatter } from "@earendil-works/pi-coding-agent";
24537
24970
  function captureCanonicalSkillExpansion(name, snapshot, configuredPath, evidence, originalRequest) {
24538
24971
  const matchedPath = evidence?.location === configuredPath ? configuredPath : evidence?.location === snapshot.path ? snapshot.path : void 0;
24539
24972
  const expectedContent = matchedPath === void 0 ? void 0 : snapshot.body;
24540
- const prefixedContent = matchedPath === void 0 ? void 0 : `References are relative to ${dirname20(matchedPath)}.
24973
+ const prefixedContent = matchedPath === void 0 ? void 0 : `References are relative to ${dirname21(matchedPath)}.
24541
24974
 
24542
24975
  ${snapshot.body}`;
24543
24976
  if (evidence?.name !== name || matchedPath === void 0 || evidence.content !== expectedContent && evidence.content !== prefixedContent || evidence.userMessage !== originalRequest) {
@@ -24555,7 +24988,7 @@ var CanonicalSkillUnavailableError = class extends Error {
24555
24988
  code = "canonical-skill-unavailable";
24556
24989
  };
24557
24990
  async function loadCanonicalSkillBinding(name) {
24558
- const configuredPath = resolve17(
24991
+ const configuredPath = resolve18(
24559
24992
  homedir(),
24560
24993
  `.agents/skills/${name}/SKILL.md`
24561
24994
  );
@@ -24563,7 +24996,7 @@ async function loadCanonicalSkillBinding(name) {
24563
24996
  let raw;
24564
24997
  try {
24565
24998
  path = await realpath7(configuredPath);
24566
- raw = await readFile22(path, "utf8");
24999
+ raw = await readFile23(path, "utf8");
24567
25000
  } catch (error) {
24568
25001
  throw new CanonicalSkillUnavailableError(name, configuredPath, error);
24569
25002
  }
@@ -24574,7 +25007,7 @@ async function loadCanonicalSkillBinding(name) {
24574
25007
  const snapshot = Object.freeze({
24575
25008
  raw,
24576
25009
  path,
24577
- baseDir: dirname20(path),
25010
+ baseDir: dirname21(path),
24578
25011
  body,
24579
25012
  snapshotIdentity: Object.freeze({ text: raw })
24580
25013
  });
@@ -24602,8 +25035,8 @@ init_doctor_evidence();
24602
25035
  // src/navigator-work-context.ts
24603
25036
  init_doctor_evidence();
24604
25037
  init_host_contracts();
24605
- import { readFile as readFile23 } from "node:fs/promises";
24606
- import { resolve as resolve18 } from "node:path";
25038
+ import { readFile as readFile24 } from "node:fs/promises";
25039
+ import { resolve as resolve19 } from "node:path";
24607
25040
  init_notary_source_run();
24608
25041
  init_packaged_role_registry();
24609
25042
  init_invocation();
@@ -24611,11 +25044,11 @@ function navigatorInputReference(getFlag, role) {
24611
25044
  if (getFlag === void 0) return void 0;
24612
25045
  const name = packagedRoleInputFlag(role);
24613
25046
  const value = name === void 0 ? void 0 : getFlag(name);
24614
- return typeof value === "string" && value !== "" ? resolve18(value) : void 0;
25047
+ return typeof value === "string" && value !== "" ? resolve19(value) : void 0;
24615
25048
  }
24616
25049
  async function loadNavigatorWorkContext(options) {
24617
25050
  const reference = navigatorInputReference(options.getFlag, options.role);
24618
- const input = reference === void 0 || options.role === "doctor" || options.role === "notary" ? void 0 : await readFile23(reference, "utf8");
25051
+ const input = reference === void 0 || options.role === "doctor" || options.role === "notary" ? void 0 : await readFile24(reference, "utf8");
24619
25052
  const subjectRoot = subjectPath(reference ?? options.context.sessionManager.getSessionDir(), options.context.cwd);
24620
25053
  let subjectKey = reference === void 0 ? subjectRoot : navigatorSubjectKeyForInput(subjectRoot, reference, options.context.cwd);
24621
25054
  let subject = input ?? `work subject: ${subjectKey}`;
@@ -24632,7 +25065,7 @@ async function loadNavigatorWorkContext(options) {
24632
25065
  }
24633
25066
  const publicRunDir = runDirectoryFromHostContext(options.context);
24634
25067
  const currentSessionDir = options.context.sessionManager.getSessionDir();
24635
- const isBoundPublicRun = publicRunDir !== void 0 && resolve18(currentSessionDir) === resolve18(publicRunDir, "session");
25068
+ const isBoundPublicRun = publicRunDir !== void 0 && resolve19(currentSessionDir) === resolve19(publicRunDir, "session");
24636
25069
  if (options.role === "judge" && isBoundPublicRun) {
24637
25070
  let admitted;
24638
25071
  try {
@@ -24665,14 +25098,14 @@ async function loadNavigatorWorkContext(options) {
24665
25098
  }
24666
25099
  const workRoot = subjectRoot.includes("/.ak/work/") ? subjectRoot : void 0;
24667
25100
  const authorityFiles = workRoot === void 0 ? [] : [
24668
- resolve18(workRoot, "authority.md"),
24669
- resolve18(workRoot, "authority.txt"),
24670
- resolve18(workRoot, "design-v2/owner-direction.md")
25101
+ resolve19(workRoot, "authority.md"),
25102
+ resolve19(workRoot, "authority.txt"),
25103
+ resolve19(workRoot, "design-v2/owner-direction.md")
24671
25104
  ];
24672
25105
  let authorityMaterial;
24673
25106
  for (const path of authorityFiles) {
24674
25107
  try {
24675
- const content = await readFile23(path, "utf8");
25108
+ const content = await readFile24(path, "utf8");
24676
25109
  if (content.trim() !== "") {
24677
25110
  authorityMaterial = content;
24678
25111
  break;
@@ -24697,7 +25130,7 @@ async function loadNavigatorWorkContext(options) {
24697
25130
  init_notary_source_run();
24698
25131
 
24699
25132
  // src/package-resources/method-skill-binding.ts
24700
- import { dirname as dirname21 } from "node:path";
25133
+ import { dirname as dirname22 } from "node:path";
24701
25134
  init_method_skill();
24702
25135
  async function loadPackagedCanonicalSkillBinding(packageRoot, name) {
24703
25136
  const material = await loadPackagedMethodSkillMaterial(packageRoot, name);
@@ -24705,7 +25138,7 @@ async function loadPackagedCanonicalSkillBinding(packageRoot, name) {
24705
25138
  const snapshot = Object.freeze({
24706
25139
  raw: material.raw,
24707
25140
  path: material.skillPath,
24708
- baseDir: dirname21(material.skillPath),
25141
+ baseDir: dirname22(material.skillPath),
24709
25142
  body: material.body,
24710
25143
  snapshotIdentity: Object.freeze({ text: material.raw })
24711
25144
  });
@@ -24742,13 +25175,13 @@ function createRoleRuntimeDependencies(packageRoot) {
24742
25175
  packageRoot,
24743
25176
  loadJudgeSoul: () => loadMainRoleSessionMaterials("judge"),
24744
25177
  loadFixerSoul: () => loadMainRoleSessionMaterials("fixer"),
24745
- loadFixPacket: (path) => readFile24(path, "utf8"),
25178
+ loadFixPacket: (path) => readFile25(path, "utf8"),
24746
25179
  loadCoderSoul: () => loadMainRoleSessionMaterials("coder"),
24747
- loadCoderTask: (path) => readFile24(path, "utf8"),
25180
+ loadCoderTask: (path) => readFile25(path, "utf8"),
24748
25181
  loadReviewerSoul: () => loadMainRoleSessionMaterials("reviewer"),
24749
25182
  createReviewerPinnedGitReader: () => createReviewerPinnedGitReader(),
24750
25183
  loadCollectorSoul: () => loadMainRoleSessionMaterials("collector"),
24751
- loadCollectorHandbookSeed: () => readFile24(collectorHandbookSeedPath, "utf8"),
25184
+ loadCollectorHandbookSeed: () => readFile25(collectorHandbookSeedPath, "utf8"),
24752
25185
  createCollectorTransport: () => createGhCollectorGitHubTransport(),
24753
25186
  loadDoctorSoul: () => loadMainRoleSessionMaterials("doctor"),
24754
25187
  loadDoctorCase,
@@ -24762,7 +25195,7 @@ function createRoleRuntimeDependencies(packageRoot) {
24762
25195
  loadDiaristSoul: () => loadMainRoleSessionMaterials("diarist"),
24763
25196
  loadNotarySourceRun: loadNotarySourceRunLocator,
24764
25197
  loadMergerSoul: () => loadMainRoleSessionMaterials("merger"),
24765
- loadMergerInput: async (path) => JSON.parse(await readFile24(path, "utf8")),
25198
+ loadMergerInput: async (path) => JSON.parse(await readFile25(path, "utf8")),
24766
25199
  async loadCanonicalSkillBinding(name) {
24767
25200
  if (name === "tdd") {
24768
25201
  return loadPackagedCanonicalSkillBinding(packageRoot, "tdd");
@@ -24788,7 +25221,7 @@ function createRoleRuntimeDependencies(packageRoot) {
24788
25221
  authority: options.authority,
24789
25222
  invocationId: options.invocationId,
24790
25223
  loadSoul: () => loadMainRoleSessionMaterials("navigator"),
24791
- loadRoutePlaybook: () => readFile24(navigatorRoutePlaybookPath, "utf8"),
25224
+ loadRoutePlaybook: () => readFile25(navigatorRoutePlaybookPath, "utf8"),
24792
25225
  loadRoleHelp: async (role) => formatNavigatorRoleHelp(role),
24793
25226
  createSession: navigatorSessionFactory,
24794
25227
  ...options.contextError === void 0 ? {} : { contextError: options.contextError },
@@ -24852,7 +25285,7 @@ function hostAbortedError(message = "host aborted") {
24852
25285
  function raceAgainstHostAbort(work, abortSignal, message = "host aborted") {
24853
25286
  if (abortSignal?.aborted) return Promise.reject(hostAbortedError(message));
24854
25287
  if (abortSignal === void 0) return work;
24855
- return new Promise((resolve20, reject) => {
25288
+ return new Promise((resolve21, reject) => {
24856
25289
  let settled = false;
24857
25290
  const onAbort = () => {
24858
25291
  if (settled) return;
@@ -24867,7 +25300,7 @@ function raceAgainstHostAbort(work, abortSignal, message = "host aborted") {
24867
25300
  if (settled) return;
24868
25301
  settled = true;
24869
25302
  abortSignal.removeEventListener("abort", onAbort);
24870
- resolve20(value);
25303
+ resolve21(value);
24871
25304
  },
24872
25305
  (error) => {
24873
25306
  if (settled) return;
@@ -25055,8 +25488,8 @@ function connectAcpStdio(options) {
25055
25488
  request(method, params) {
25056
25489
  if (closed) return Promise.reject(terminalError ?? acpError("acp-connection-closed", "ACP connection is closed"));
25057
25490
  const id = ++nextId;
25058
- return new Promise((resolve20, reject) => {
25059
- pending.set(id, { resolve: resolve20, reject });
25491
+ return new Promise((resolve21, reject) => {
25492
+ pending.set(id, { resolve: resolve21, reject });
25060
25493
  child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}
25061
25494
  `, (error) => {
25062
25495
  if (error === null || error === void 0) return;
@@ -25083,7 +25516,7 @@ function connectAcpStdio(options) {
25083
25516
  settleClosed(acpError("acp-connection-closed", "ACP connection is closed"));
25084
25517
  child.stdin.end();
25085
25518
  child.kill("SIGTERM");
25086
- await new Promise((resolve20) => child.once("close", () => resolve20()));
25519
+ await new Promise((resolve21) => child.once("close", () => resolve21()));
25087
25520
  }
25088
25521
  });
25089
25522
  }
@@ -25250,7 +25683,7 @@ function createAcpRoleTurnHost(config) {
25250
25683
  // src/acp-host/seat-profile-soul.ts
25251
25684
  import { constants as constants3 } from "node:fs";
25252
25685
  import { access as access5, copyFile, lstat as lstat7, mkdir as mkdir6, readlink, symlink, unlink as unlink4 } from "node:fs/promises";
25253
- import { dirname as dirname22, join as join42, relative as relative3, resolve as resolve19 } from "node:path";
25686
+ import { dirname as dirname23, join as join42, relative as relative3, resolve as resolve20 } from "node:path";
25254
25687
  function seatProfileName(spec, role) {
25255
25688
  return `${spec.namePrefix}${role}`;
25256
25689
  }
@@ -25268,13 +25701,13 @@ async function pathExists2(path) {
25268
25701
  async function ensureSeatProfileSoul(options) {
25269
25702
  const { spec, operatorHome, packageRoot, role } = options;
25270
25703
  const profileName = seatProfileName(spec, role);
25271
- const soulTarget = resolve19(packageRoleSoulPath(packageRoot, role));
25704
+ const soulTarget = resolve20(packageRoleSoulPath(packageRoot, role));
25272
25705
  if (!await pathExists2(soulTarget)) {
25273
25706
  throw new Error(`packaged role soul missing: ${soulTarget}`);
25274
25707
  }
25275
25708
  const profilesRoot = join42(operatorHome, ...spec.profilesRootFromHome);
25276
25709
  const profileDir = join42(profilesRoot, profileName);
25277
- const hostRoot = dirname22(profilesRoot);
25710
+ const hostRoot = dirname23(profilesRoot);
25278
25711
  const soulPath = join42(profileDir, spec.soulFileName);
25279
25712
  if (!await pathExists2(profileDir)) {
25280
25713
  await mkdir6(profileDir, { recursive: true });