@akagilnc/pi-workflow-roles 0.1.4021 → 0.1.4062

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/acp-host/production-host.js +682 -355
  2. package/dist/doctor-auditor.js +1 -1
  3. package/dist/dossier-resolution.js +21 -8
  4. package/dist/gatekeeper-role.js +34 -27
  5. package/dist/headless-host/description.js +7 -8
  6. package/dist/headless-host/production-host.js +709 -369
  7. package/dist/host-contracts.js +16 -0
  8. package/dist/inspector-contracts.js +8 -0
  9. package/dist/navigator-attendance.js +2 -0
  10. package/dist/navigator-public-session.js +18 -34
  11. package/dist/navigator-session-contracts.js +19 -0
  12. package/dist/packaged-role-registry.js +1 -1
  13. package/dist/pi/known-failure.js +3 -4
  14. package/dist/pi/role-turn-host.js +43 -13
  15. package/dist/public-cli/auto-resume.js +20 -7
  16. package/dist/public-cli/case-dossier-delivery.js +60 -1
  17. package/dist/public-cli/diarist-run.js +9 -23
  18. package/dist/public-cli/inspector-run.js +17 -3
  19. package/dist/public-cli/instruction-seat-run.js +12 -7
  20. package/dist/public-cli/judge-run.js +3 -1
  21. package/dist/public-cli/main.js +440 -222
  22. package/dist/public-cli/notary-run.js +7 -4
  23. package/dist/public-cli/post-admission.js +66 -59
  24. package/dist/public-cli/run-lifecycle.js +3 -0
  25. package/dist/public-cli/settlement.js +78 -58
  26. package/dist/public-cli/terminal.js +1 -11
  27. package/dist/public-role-summons.js +8 -0
  28. package/dist/submission-ledger.js +139 -19
  29. package/dist/user-dialogue-stdin.js +33 -0
  30. package/extensions/role-runtime.ts +1 -0
  31. package/package.json +1 -1
  32. package/resources/836-deleted-machine-instruction-inventory.md +1 -1
  33. package/src/doctor-auditor.ts +1 -1
  34. package/src/dossier-resolution.ts +26 -8
  35. package/src/external-host-turn-loop.ts +9 -0
  36. package/src/gatekeeper-pass-envelope.ts +6 -0
  37. package/src/gatekeeper-role.ts +47 -28
  38. package/src/headless-host/description.ts +8 -11
  39. package/src/headless-host/role-turn-host.ts +20 -5
  40. package/src/host-contracts.ts +30 -7
  41. package/src/inspector-contracts.ts +7 -0
  42. package/src/judge-role.ts +4 -0
  43. package/src/navigator-attendance.ts +2 -0
  44. package/src/navigator-public-session.ts +19 -55
  45. package/src/navigator-session-contracts.ts +39 -0
  46. package/src/navigator-work-context.ts +3 -4
  47. package/src/notary-role.ts +1 -0
  48. package/src/packaged-role-registry.ts +1 -1
  49. package/src/pi/adapter.ts +19 -4
  50. package/src/pi/known-failure.ts +3 -4
  51. package/src/pi/role-turn-host.ts +48 -14
  52. package/src/public-cli/auto-resume.ts +57 -20
  53. package/src/public-cli/case-dossier-delivery.ts +86 -1
  54. package/src/public-cli/cli.ts +2 -2
  55. package/src/public-cli/collector-run.ts +3 -1
  56. package/src/public-cli/countersign-run.ts +34 -27
  57. package/src/public-cli/diarist-run.ts +10 -27
  58. package/src/public-cli/inspector-run.ts +26 -2
  59. package/src/public-cli/instruction-seat-run.ts +20 -10
  60. package/src/public-cli/invocation.ts +2 -0
  61. package/src/public-cli/judge-run.ts +3 -1
  62. package/src/public-cli/notary-run.ts +13 -4
  63. package/src/public-cli/post-admission.ts +74 -65
  64. package/src/public-cli/reviewer-run.ts +3 -1
  65. package/src/public-cli/run-lifecycle.ts +3 -0
  66. package/src/public-cli/settlement.ts +105 -80
  67. package/src/public-cli/terminal.ts +7 -16
  68. package/src/public-role-summons.ts +31 -7
  69. package/src/role-envelope.ts +9 -30
  70. package/src/role-runtime-dependencies.ts +1 -0
  71. package/src/role-runtime.ts +95 -19
  72. package/src/submission-ledger.ts +195 -26
  73. package/src/user-dialogue-stdin.ts +37 -0
  74. package/src/worker-role.ts +4 -0
@@ -737,9 +737,17 @@ var init_auditor_dossier_tool = __esm({
737
737
  });
738
738
 
739
739
  // src/readable-gate-item.ts
740
+ var readable_gate_item_exports = {};
741
+ __export(readable_gate_item_exports, {
742
+ joinReadableGateItems: () => joinReadableGateItems,
743
+ readableGateItem: () => readableGateItem
744
+ });
740
745
  function readableGateItem(value) {
741
746
  return typeof value === "string" ? value : JSON.stringify(value);
742
747
  }
748
+ function joinReadableGateItems(items, separator = "; ") {
749
+ return items.map(readableGateItem).join(separator);
750
+ }
743
751
  var init_readable_gate_item = __esm({
744
752
  "src/readable-gate-item.ts"() {
745
753
  "use strict";
@@ -806,12 +814,19 @@ var init_submission_errors = __esm({
806
814
  });
807
815
 
808
816
  // src/inspector-contracts.ts
809
- var INSPECTOR_OUTPUT_TOOL_NAME, INSPECTOR_ACCEPTED_TEXT;
817
+ var INSPECTOR_OUTPUT_TOOL_NAME, INSPECTOR_ACCEPTED_TEXT, INSPECTOR_SOURCE_RUN_FLAG;
810
818
  var init_inspector_contracts = __esm({
811
819
  "src/inspector-contracts.ts"() {
812
820
  "use strict";
813
821
  INSPECTOR_OUTPUT_TOOL_NAME = "ak_inspector_output";
814
822
  INSPECTOR_ACCEPTED_TEXT = "\u5BDF\u9662\u56DE\u6267\u5DF2\u63A5\u53D7";
823
+ INSPECTOR_SOURCE_RUN_FLAG = {
824
+ name: "ak-inspector-source-run",
825
+ definition: {
826
+ description: "\u5BDF\u9662\u521D\u94F8\u7ED1\u5B9A\u7684\u7236 run \u7EDD\u5BF9\u8DEF\u5F84",
827
+ type: "string"
828
+ }
829
+ };
815
830
  }
816
831
  });
817
832
 
@@ -1478,6 +1493,15 @@ var init_durable_principal = __esm({
1478
1493
  });
1479
1494
 
1480
1495
  // src/host-contracts.ts
1496
+ function isOfficerReviewSeat(role) {
1497
+ return role === "notary" || role === "inspector" || role === "auditor";
1498
+ }
1499
+ function runDirectoryFromHostContext(context) {
1500
+ return typeof context.runDirectory === "string" && context.runDirectory.trim() !== "" ? context.runDirectory : void 0;
1501
+ }
1502
+ function courtAttemptIdFromHostContext(context) {
1503
+ return typeof context.courtAttemptId === "string" && context.courtAttemptId.trim() !== "" ? context.courtAttemptId : void 0;
1504
+ }
1481
1505
  var ExplicitInternalActivationError;
1482
1506
  var init_host_contracts = __esm({
1483
1507
  "src/host-contracts.ts"() {
@@ -2394,7 +2418,7 @@ var init_packaged_role_registry = __esm({
2394
2418
  role: "inspector",
2395
2419
  phases: [null],
2396
2420
  outputTool: INSPECTOR_OUTPUT_TOOL_NAME,
2397
- inputFlag: void 0,
2421
+ inputFlag: "ak-inspector-source-run",
2398
2422
  phaseFlag: void 0,
2399
2423
  activationStage: "load-and-install",
2400
2424
  sessionMaterials: INSPECTOR_SESSION_MATERIALS
@@ -2498,6 +2522,18 @@ var init_role_activation_flags = __esm({
2498
2522
  }
2499
2523
  });
2500
2524
 
2525
+ // src/user-dialogue-stdin.ts
2526
+ function encodeUserDialogueStdin(body) {
2527
+ return JSON.stringify({ kind: USER_DIALOGUE_STDIN_KIND, body });
2528
+ }
2529
+ var USER_DIALOGUE_STDIN_KIND;
2530
+ var init_user_dialogue_stdin = __esm({
2531
+ "src/user-dialogue-stdin.ts"() {
2532
+ "use strict";
2533
+ USER_DIALOGUE_STDIN_KIND = "ak-user-dialogue";
2534
+ }
2535
+ });
2536
+
2501
2537
  // src/sitian-contracts.ts
2502
2538
  function attachDirectErrnoCode(error, cause) {
2503
2539
  if (cause === null || typeof cause !== "object" || !("code" in cause)) return;
@@ -2871,11 +2907,6 @@ function applyPiNativeSkillInvocation(methods, prompt) {
2871
2907
  }
2872
2908
  function buildPiTurnExtraArgs(request, authority, extraPiArgs = []) {
2873
2909
  const { sessionFile, sessionDirectory } = authority.decode(request.principal);
2874
- const rawPrompt = request.continuation.kind === "initial" || request.continuation.kind === "resume" ? request.continuation.prompt : (() => {
2875
- const _exhaustive = request.continuation;
2876
- return _exhaustive;
2877
- })();
2878
- const prompt = applyPiNativeSkillInvocation(request.methods, rawPrompt);
2879
2910
  return [
2880
2911
  "--no-skills",
2881
2912
  ...buildMethodArgs(request.methods),
@@ -2889,12 +2920,24 @@ function buildPiTurnExtraArgs(request, authority, extraPiArgs = []) {
2889
2920
  ...extraPiArgs,
2890
2921
  // Envelope assembly = projectActivationFlags; pi only renders argv pairs.
2891
2922
  ...activationFlagsToPiArgv(projectActivationFlags(request)),
2923
+ ...piEngineModelArgs(request),
2892
2924
  "--mode",
2893
2925
  "json",
2894
- ...buildSeatModelCliArgs(request.model),
2895
- prompt
2926
+ ...buildSeatModelCliArgs(request.model)
2896
2927
  ];
2897
2928
  }
2929
+ function piEngineModelArgs(request) {
2930
+ const model = normalizeEngineName(request.engineModel);
2931
+ if (model === void 0) return [];
2932
+ return [`--${ENGINE_MODEL_FLAG_NAME}`, model];
2933
+ }
2934
+ function piUserDialogueBody(request) {
2935
+ const rawPrompt = request.continuation.kind === "initial" || request.continuation.kind === "resume" ? request.continuation.prompt : (() => {
2936
+ const _exhaustive = request.continuation;
2937
+ return _exhaustive;
2938
+ })();
2939
+ return applyPiNativeSkillInvocation(request.methods, rawPrompt);
2940
+ }
2898
2941
  async function resolveSelectedPi(command, cwd, env) {
2899
2942
  const searchPath = env.PATH ?? (platform === "win32" ? process.env.PATH ?? "" : "/usr/bin:/bin");
2900
2943
  const candidates = isAbsolute3(command) || command.includes("/") ? [resolve6(cwd, command)] : searchPath.split(delimiter).map((dir) => resolve6(cwd, dir, command));
@@ -2934,11 +2977,22 @@ function createDefaultPiSpawnRunner(options) {
2934
2977
  const child = spawn3(piIdentity.executable, [...args], {
2935
2978
  cwd: spawnOptions.cwd,
2936
2979
  env: spawnOptions.env,
2937
- stdio: ["ignore", "ignore", "pipe"]
2980
+ stdio: ["pipe", "ignore", "pipe"]
2938
2981
  });
2982
+ if (child.stdin === null) {
2983
+ throw new Error("Pi child stdin pipe was not created");
2984
+ }
2939
2985
  if (child.stderr === null) {
2940
2986
  throw new Error("Pi child stderr pipe was not created");
2941
2987
  }
2988
+ let stdinDeliveryError;
2989
+ child.stdin.on("error", (error) => {
2990
+ stdinDeliveryError ??= error;
2991
+ });
2992
+ if (spawnOptions.stdin !== void 0) {
2993
+ child.stdin.write(spawnOptions.stdin);
2994
+ }
2995
+ child.stdin.end();
2942
2996
  let stderr = "";
2943
2997
  let timedOut = false;
2944
2998
  let timer;
@@ -2991,6 +3045,10 @@ function createDefaultPiSpawnRunner(options) {
2991
3045
  reject(executionError);
2992
3046
  return;
2993
3047
  }
3048
+ if (stdinDeliveryError !== void 0) {
3049
+ reject(stdinDeliveryError);
3050
+ return;
3051
+ }
2994
3052
  resolveResult({
2995
3053
  code,
2996
3054
  stderr,
@@ -3014,7 +3072,8 @@ function createPiRoleTurnHost(config) {
3014
3072
  return {
3015
3073
  async executeTurn(request) {
3016
3074
  let turnRequest = request;
3017
- const paths = request.hostTransition?.priorNativeKind === "sitian" ? request.hostTransition.priorNativePaths : void 0;
3075
+ const officerStationChild = request.stationChild === true && isOfficerReviewSeat(request.activation.role);
3076
+ const paths = !officerStationChild && request.hostTransition?.priorNativeKind === "sitian" ? request.hostTransition.priorNativePaths : void 0;
3018
3077
  if (request.continuation.kind === "resume" && paths !== void 0 && paths.length > 0) {
3019
3078
  turnRequest = {
3020
3079
  ...request,
@@ -3032,6 +3091,7 @@ ${paths.join("\n")}`
3032
3091
  config.extraPiArgs ?? []
3033
3092
  );
3034
3093
  const args = buildExplicitInternalActivationArgs(roleEntry, extraArgs);
3094
+ const stdin = encodeUserDialogueStdin(piUserDialogueBody(turnRequest));
3035
3095
  const env = {
3036
3096
  ...process.env,
3037
3097
  HOME: request.home,
@@ -3063,6 +3123,7 @@ ${paths.join("\n")}`
3063
3123
  return await spawnRunner(args, {
3064
3124
  cwd: request.cwd,
3065
3125
  env,
3126
+ stdin,
3066
3127
  ...timeoutMs === void 0 ? {} : { timeoutMs },
3067
3128
  ...request.signal === void 0 ? {} : { signal: request.signal }
3068
3129
  });
@@ -3106,6 +3167,7 @@ var init_role_turn_host = __esm({
3106
3167
  init_host_contracts();
3107
3168
  init_engine_detour();
3108
3169
  init_role_activation_flags();
3170
+ init_user_dialogue_stdin();
3109
3171
  init_sitian_facade();
3110
3172
  INTERNAL_ROLE_ENTRYPOINT_RELATIVE = "extensions/role-runtime.ts";
3111
3173
  EXPLICIT_INTERNAL_LOAD_PROBE_ARGS = [
@@ -4813,7 +4875,8 @@ async function loadResumableInspectorRun(home, runId, authority) {
4813
4875
  }
4814
4876
  const admitted = {
4815
4877
  role: "inspector",
4816
- ...resumedBaseAdmitted(loaded)
4878
+ ...resumedBaseAdmitted(loaded),
4879
+ ...loaded.admittedFields.sourceRunPath === void 0 ? {} : { sourceRunPath: loaded.admittedFields.sourceRunPath }
4817
4880
  };
4818
4881
  return seatLoadedResult(loaded, admitted);
4819
4882
  }
@@ -9540,6 +9603,15 @@ var init_ticket_provenance = __esm({
9540
9603
  });
9541
9604
 
9542
9605
  // src/public-cli/case-dossier-delivery.ts
9606
+ var case_dossier_delivery_exports = {};
9607
+ __export(case_dossier_delivery_exports, {
9608
+ deliverCaseDossierAsAttachment: () => deliverCaseDossierAsAttachment,
9609
+ loadCaseDossierReadingMaterial: () => loadCaseDossierReadingMaterial,
9610
+ projectCaseDossierPointerSection: () => projectCaseDossierPointerSection
9611
+ });
9612
+ import { mkdtemp as mkdtemp2, readFile as readFile13, rm as rm2, writeFile as writeFile7 } from "node:fs/promises";
9613
+ import { tmpdir as tmpdir2 } from "node:os";
9614
+ import { join as join19 } from "node:path";
9543
9615
  function describeDossierFile(path) {
9544
9616
  return path;
9545
9617
  }
@@ -9558,18 +9630,59 @@ async function projectCaseDossierPointerSection(input) {
9558
9630
  `\u8BB0\u5F55\u5377\u5B97\uFF1A${describeDossierFile(volume.recordFile)}`
9559
9631
  ].join("\n");
9560
9632
  }
9561
- var CASE_DOSSIER_SECTION_HEADING;
9633
+ async function deliverCaseDossierAsAttachment(input) {
9634
+ const section = await projectCaseDossierPointerSection({
9635
+ ticketNumber: input.ticketNumber,
9636
+ projectRoot: input.projectRoot,
9637
+ home: input.home
9638
+ });
9639
+ if (section === void 0) return void 0;
9640
+ const stagingDir = await mkdtemp2(join19(tmpdir2(), "ak-case-dossier-"));
9641
+ try {
9642
+ const stagingPath = join19(stagingDir, CASE_DOSSIER_ATTACH_FILE);
9643
+ await writeFile7(stagingPath, `${section}
9644
+ `, "utf8");
9645
+ return await freezeAttachmentsIntoRun(
9646
+ [stagingPath],
9647
+ input.runDirectory,
9648
+ CASE_DOSSIER_ATTACH_KEY
9649
+ );
9650
+ } finally {
9651
+ await rm2(stagingDir, { recursive: true, force: true });
9652
+ }
9653
+ }
9654
+ async function loadCaseDossierReadingMaterial(runDirectory) {
9655
+ const frozenPath = join19(
9656
+ runDirectory,
9657
+ "attachments",
9658
+ CASE_DOSSIER_ATTACH_KEY,
9659
+ `00-${CASE_DOSSIER_ATTACH_FILE}`
9660
+ );
9661
+ let section;
9662
+ try {
9663
+ section = await readFile13(frozenPath, "utf8");
9664
+ } catch (error) {
9665
+ if (error.code === "ENOENT") return void 0;
9666
+ throw error;
9667
+ }
9668
+ if (section.trim() === "") return void 0;
9669
+ return { kind: "case-dossier-pointer", frozenPath, section };
9670
+ }
9671
+ var CASE_DOSSIER_SECTION_HEADING, CASE_DOSSIER_ATTACH_KEY, CASE_DOSSIER_ATTACH_FILE;
9562
9672
  var init_case_dossier_delivery = __esm({
9563
9673
  "src/public-cli/case-dossier-delivery.ts"() {
9564
9674
  "use strict";
9565
9675
  init_ticket_provenance();
9676
+ init_invocation();
9566
9677
  CASE_DOSSIER_SECTION_HEADING = "## \u672C\u7968\u8D77\u5C45\u5F55\uFF08\u7CFB\u7EDF\u968F\u6848\u63D0\u4F9B\uFF09";
9678
+ CASE_DOSSIER_ATTACH_KEY = "case-dossier";
9679
+ CASE_DOSSIER_ATTACH_FILE = "case-dossier-pointer.md";
9567
9680
  }
9568
9681
  });
9569
9682
 
9570
9683
  // src/host-transition-prior-native.ts
9571
9684
  import { access as access3, readdir as readdir3 } from "node:fs/promises";
9572
- import { dirname as dirname11, join as join19 } from "node:path";
9685
+ import { dirname as dirname11, join as join20 } from "node:path";
9573
9686
  function isEnoent2(error) {
9574
9687
  return typeof error === "object" && error !== null && error.code === "ENOENT";
9575
9688
  }
@@ -9594,7 +9707,7 @@ async function listSitianRecordPaths(sessionParent) {
9594
9707
  const recordPaths = [];
9595
9708
  for (const entry of entries) {
9596
9709
  if (!entry.isDirectory()) continue;
9597
- const recordFile = join19(sessionRoot, entry.name, "records.jsonl");
9710
+ const recordFile = join20(sessionRoot, entry.name, "records.jsonl");
9598
9711
  try {
9599
9712
  await access3(recordFile);
9600
9713
  recordPaths.push(recordFile);
@@ -9985,13 +10098,13 @@ var init_reviewer_dispatch = __esm({
9985
10098
  });
9986
10099
 
9987
10100
  // src/public-cli/reviewer-dispatch-rejection.ts
9988
- import { readFile as readFile13, unlink as unlink3 } from "node:fs/promises";
9989
- import { join as join20 } from "node:path";
10101
+ import { readFile as readFile14, unlink as unlink3 } from "node:fs/promises";
10102
+ import { join as join21 } from "node:path";
9990
10103
  function isReviewerPreflightViolation(value) {
9991
10104
  return typeof value === "string" && REVIEWER_PREFLIGHT_VIOLATIONS.includes(value);
9992
10105
  }
9993
10106
  function reviewerDispatchRejectionPath(runDirectory) {
9994
- return join20(runDirectory, REVIEWER_DISPATCH_REJECTION_FILE);
10107
+ return join21(runDirectory, REVIEWER_DISPATCH_REJECTION_FILE);
9995
10108
  }
9996
10109
  async function clearReviewerDispatchRejection(runDirectory) {
9997
10110
  try {
@@ -10006,7 +10119,7 @@ async function clearReviewerDispatchRejection(runDirectory) {
10006
10119
  async function readReviewerDispatchRejection(runDirectory) {
10007
10120
  let raw;
10008
10121
  try {
10009
- raw = await readFile13(reviewerDispatchRejectionPath(runDirectory), "utf8");
10122
+ raw = await readFile14(reviewerDispatchRejectionPath(runDirectory), "utf8");
10010
10123
  } catch (error) {
10011
10124
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
10012
10125
  return void 0;
@@ -10042,12 +10155,12 @@ var init_reviewer_dispatch_rejection = __esm({
10042
10155
  });
10043
10156
 
10044
10157
  // src/ledger-session-read.ts
10045
- import { readFile as readFile14 } from "node:fs/promises";
10158
+ import { readFile as readFile15 } from "node:fs/promises";
10046
10159
  function isRecord5(value) {
10047
10160
  return typeof value === "object" && value !== null && !Array.isArray(value);
10048
10161
  }
10049
10162
  async function readLedgerSessionJsonl(path) {
10050
- const text = await readFile14(path, "utf8");
10163
+ const text = await readFile15(path, "utf8");
10051
10164
  const lines = text.split("\n");
10052
10165
  const rows = [];
10053
10166
  for (let index = 0; index < lines.length; index += 1) {
@@ -10129,7 +10242,7 @@ var init_ledger_session_read = __esm({
10129
10242
 
10130
10243
  // src/analyst-gate-cycles-read.ts
10131
10244
  import { readdir as readdir4 } from "node:fs/promises";
10132
- import { join as join21 } from "node:path";
10245
+ import { join as join22 } from "node:path";
10133
10246
  function isRecord6(value) {
10134
10247
  return typeof value === "object" && value !== null && !Array.isArray(value);
10135
10248
  }
@@ -10344,10 +10457,10 @@ function pairGateRounds(volumes) {
10344
10457
  return rounds.sort((a, b) => a.officerStartedAt.localeCompare(b.officerStartedAt)).map((round, index) => ({ ...round, roundIndex: index + 1 }));
10345
10458
  }
10346
10459
  async function resolveOfficerSessionFromPointerFile(pointerPath) {
10347
- const { readFile: readFile23 } = await import("node:fs/promises");
10460
+ const { readFile: readFile24 } = await import("node:fs/promises");
10348
10461
  let raw;
10349
10462
  try {
10350
- raw = JSON.parse(await readFile23(pointerPath, "utf8"));
10463
+ raw = JSON.parse(await readFile24(pointerPath, "utf8"));
10351
10464
  } catch (error) {
10352
10465
  throw new Error(
10353
10466
  `direct officer run pointer unreadable in ${pointerPath}: ${error instanceof Error ? error.message : String(error)}`,
@@ -10379,7 +10492,7 @@ async function readAnalystGateCyclesFromAuditorRoles(auditorRolesDirectory, opti
10379
10492
  throw error;
10380
10493
  }
10381
10494
  for (const name of names) {
10382
- const path = join21(directory, name);
10495
+ const path = join22(directory, name);
10383
10496
  const fromPointer = name.endsWith(".pointer.json");
10384
10497
  const sessionPath = fromPointer ? await resolveOfficerSessionFromPointerFile(path) : path;
10385
10498
  if (sessionPath === void 0) continue;
@@ -10518,7 +10631,7 @@ var init_audit_escalation = __esm({
10518
10631
  });
10519
10632
 
10520
10633
  // src/run-terminal-artifacts.ts
10521
- import { basename as basename7, dirname as dirname12, join as join22 } from "node:path";
10634
+ import { basename as basename7, dirname as dirname12, join as join23 } from "node:path";
10522
10635
  function runIdFromRunDirectory(runDirectory) {
10523
10636
  const name = basename7(runDirectory);
10524
10637
  const at = name.lastIndexOf("@");
@@ -10533,8 +10646,8 @@ var init_run_terminal_artifacts = __esm({
10533
10646
 
10534
10647
  // src/submission-ledger.ts
10535
10648
  function runIdentity(context) {
10536
- const directory = process.env.AK_ROLE_RUN_DIR;
10537
- if (typeof directory === "string" && directory.length > 0) {
10649
+ const directory = runDirectoryFromHostContext(context);
10650
+ if (directory !== void 0) {
10538
10651
  const fromDir = runIdFromRunDirectory(directory);
10539
10652
  if (fromDir !== void 0) return fromDir;
10540
10653
  }
@@ -10543,8 +10656,8 @@ function runIdentity(context) {
10543
10656
  throw new Error("\u63D0\u4EA4\u8D26\u9700\u8981\u5DF2\u53D7\u7406\u7684 run \u8EAB\u4EFD");
10544
10657
  }
10545
10658
  function attemptIdentity(context, runId) {
10546
- const courtAttempt = process.env[COURT_ATTEMPT_ENV];
10547
- if (typeof courtAttempt === "string" && courtAttempt.length > 0) return courtAttempt;
10659
+ const courtAttempt = courtAttemptIdFromHostContext(context);
10660
+ if (courtAttempt !== void 0) return courtAttempt;
10548
10661
  return context.sessionManager.getHeader?.()?.id ?? context.sessionManager.getLeafId?.() ?? `${runId}:initial`;
10549
10662
  }
10550
10663
  function submissionRecordFile(cwd, runId, home) {
@@ -10604,31 +10717,107 @@ function recordedRole(payload) {
10604
10717
  if (isTerminalRoleName(payload.projection?.role)) return payload.projection.role;
10605
10718
  return void 0;
10606
10719
  }
10607
- async function readRecordedSubmissionRows(cwd, runId, homeOrScope) {
10608
- const scope = resolveReadScope(homeOrScope);
10609
- const { owned } = await readOwnedSubmissionRecords(cwd, runId, scope.home);
10610
- const scoped = recordsForAttempt(owned, scope.attemptId);
10720
+ function rowRank(kind) {
10721
+ switch (kind) {
10722
+ case "accepted":
10723
+ return 4;
10724
+ case "audit-escalation":
10725
+ return 3;
10726
+ case "correctable-rejection":
10727
+ case "infrastructure":
10728
+ return 2;
10729
+ case "candidate":
10730
+ return 1;
10731
+ }
10732
+ }
10733
+ function submissionCallKey(attemptId, toolCallId) {
10734
+ return `${attemptId ?? ""}\0${toolCallId}`;
10735
+ }
10736
+ function rowFromPayload(kind, payload, accepted, roleFallback) {
10737
+ const role = recordedRole(payload) ?? roleFallback;
10738
+ return {
10739
+ ...role === void 0 ? {} : { role },
10740
+ kind,
10741
+ accepted,
10742
+ ...typeof payload.toolCallId === "string" && payload.toolCallId.length > 0 ? { toolCallId: payload.toolCallId } : {}
10743
+ };
10744
+ }
10745
+ function mapOwnedToSubmissionRows(owned) {
10746
+ const scoped = owned;
10611
10747
  const out = [];
10748
+ const indexByCall = /* @__PURE__ */ new Map();
10749
+ const roleByCall = /* @__PURE__ */ new Map();
10750
+ for (const record4 of scoped) {
10751
+ const payload = record4.payload;
10752
+ if (typeof payload?.toolCallId !== "string" || payload.toolCallId.length === 0) continue;
10753
+ const role = recordedRole(payload);
10754
+ if (role !== void 0) {
10755
+ roleByCall.set(submissionCallKey(recordAttemptId(record4), payload.toolCallId), role);
10756
+ }
10757
+ }
10758
+ const take = (row, callKey) => {
10759
+ const toolCallId = row.toolCallId;
10760
+ if (toolCallId !== void 0 && callKey !== void 0) {
10761
+ const existingIndex = indexByCall.get(callKey);
10762
+ if (existingIndex !== void 0) {
10763
+ const existing = out[existingIndex];
10764
+ if (rowRank(row.kind) >= rowRank(existing.kind)) {
10765
+ out[existingIndex] = {
10766
+ ...row,
10767
+ toolCallId,
10768
+ // Keep a previously recovered role when the upgraded row still omits it.
10769
+ ...row.role === void 0 && existing.role !== void 0 ? { role: existing.role } : {}
10770
+ };
10771
+ } else if (existing.role === void 0 && row.role !== void 0) {
10772
+ out[existingIndex] = { ...existing, role: row.role };
10773
+ }
10774
+ return;
10775
+ }
10776
+ indexByCall.set(callKey, out.length);
10777
+ }
10778
+ out.push(row);
10779
+ };
10612
10780
  for (const record4 of scoped) {
10781
+ const attemptId = recordAttemptId(record4);
10782
+ if (record4.kind === "candidate") {
10783
+ const payload2 = record4.payload;
10784
+ if (payload2?.type !== "candidate" || payload2.params === void 0) continue;
10785
+ const callKey2 = typeof payload2.toolCallId === "string" ? submissionCallKey(attemptId, payload2.toolCallId) : void 0;
10786
+ const fallback2 = callKey2 !== void 0 ? roleByCall.get(callKey2) : void 0;
10787
+ take(rowFromPayload("candidate", payload2, payload2.params, fallback2), callKey2);
10788
+ continue;
10789
+ }
10613
10790
  if (record4.kind === "sealed") {
10614
10791
  const payload2 = record4.payload;
10615
10792
  if (payload2?.type !== "sealed" || payload2.accepted === void 0) continue;
10616
- const role2 = recordedRole(payload2);
10617
- if (role2 === void 0) continue;
10618
- out.push({ role: role2, kind: "accepted", accepted: payload2.accepted });
10793
+ const callKey2 = typeof payload2.toolCallId === "string" ? submissionCallKey(attemptId, payload2.toolCallId) : void 0;
10794
+ const fallback2 = callKey2 !== void 0 ? roleByCall.get(callKey2) : void 0;
10795
+ take(rowFromPayload("accepted", payload2, payload2.accepted, fallback2), callKey2);
10619
10796
  continue;
10620
10797
  }
10621
10798
  if (record4.kind !== "outcome") continue;
10622
10799
  const payload = record4.payload;
10623
- if (payload?.type !== "outcome" || payload.outcome !== "audit-escalation" || payload.accepted === void 0) {
10624
- continue;
10625
- }
10626
- const role = recordedRole(payload);
10627
- if (role === void 0) continue;
10628
- out.push({ role, kind: "audit-escalation", accepted: payload.accepted });
10800
+ if (payload?.type !== "outcome" || payload.accepted === void 0) continue;
10801
+ const outcome = payload.outcome;
10802
+ const kind = outcome === "audit-escalation" ? "audit-escalation" : outcome === "correctable-rejection" ? "correctable-rejection" : outcome === "infrastructure" ? "infrastructure" : void 0;
10803
+ if (kind === void 0) continue;
10804
+ const callKey = typeof payload.toolCallId === "string" ? submissionCallKey(attemptId, payload.toolCallId) : void 0;
10805
+ const fallback = callKey !== void 0 ? roleByCall.get(callKey) : void 0;
10806
+ take(rowFromPayload(kind, payload, payload.accepted, fallback), callKey);
10629
10807
  }
10630
10808
  return out;
10631
10809
  }
10810
+ async function readRecordedSubmissionRows(cwd, runId, homeOrScope) {
10811
+ const scope = resolveReadScope(homeOrScope);
10812
+ const { owned } = await readOwnedSubmissionRecords(cwd, runId, scope.home);
10813
+ const scoped = recordsForAttempt(owned, scope.attemptId);
10814
+ return mapOwnedToSubmissionRows(scoped);
10815
+ }
10816
+ async function readAttemptScopedSubmissionRows(cwd, runId, attemptId, home) {
10817
+ if (attemptId.length === 0) return [];
10818
+ const { owned } = await readOwnedSubmissionRecords(cwd, runId, home);
10819
+ return mapOwnedToSubmissionRows(owned.filter((record4) => recordAttemptId(record4) === attemptId));
10820
+ }
10632
10821
  async function readRecordedSubmissions(cwd, runId, homeOrScope) {
10633
10822
  return (await readRecordedSubmissionRows(cwd, runId, homeOrScope)).map((row) => row.accepted);
10634
10823
  }
@@ -10704,6 +10893,7 @@ function createSubmissionLedgerHost(host, outputTools, failInfrastructure2 = (er
10704
10893
  toolCallId,
10705
10894
  toolName: tool.name,
10706
10895
  sequence: ++state.sequence,
10896
+ role,
10707
10897
  params
10708
10898
  });
10709
10899
  let result;
@@ -10729,6 +10919,7 @@ function createSubmissionLedgerHost(host, outputTools, failInfrastructure2 = (er
10729
10919
  outcome: "correctable-rejection",
10730
10920
  code: "typed-bounce",
10731
10921
  diagnostic: error instanceof Error ? error.message : String(error),
10922
+ role,
10732
10923
  accepted: params
10733
10924
  });
10734
10925
  throw error;
@@ -10739,6 +10930,7 @@ function createSubmissionLedgerHost(host, outputTools, failInfrastructure2 = (er
10739
10930
  toolCallId,
10740
10931
  outcome: "infrastructure",
10741
10932
  diagnostic: error instanceof Error ? error.message : String(error),
10933
+ role,
10742
10934
  accepted: params
10743
10935
  });
10744
10936
  throw error;
@@ -10780,29 +10972,28 @@ function createSubmissionLedgerHost(host, outputTools, failInfrastructure2 = (er
10780
10972
  }
10781
10973
  };
10782
10974
  }
10783
- var COURT_ATTEMPT_ENV;
10784
10975
  var init_submission_ledger = __esm({
10785
10976
  "src/submission-ledger.ts"() {
10786
10977
  "use strict";
10787
10978
  init_activation_ledger_topology();
10979
+ init_host_contracts();
10788
10980
  init_audit_escalation();
10789
10981
  init_run_terminal_artifacts();
10790
10982
  init_sitian_facade();
10791
10983
  init_submission_correctable_error();
10792
10984
  init_terminating_infrastructure();
10793
- COURT_ATTEMPT_ENV = "AK_ROLE_COURT_ATTEMPT";
10794
10985
  }
10795
10986
  });
10796
10987
 
10797
10988
  // src/session-opening-materials.ts
10798
10989
  import { existsSync as existsSync7 } from "node:fs";
10799
- import { readFile as readFile15 } from "node:fs/promises";
10800
- import { dirname as dirname13, join as join23 } from "node:path";
10990
+ import { readFile as readFile16 } from "node:fs/promises";
10991
+ import { dirname as dirname13, join as join24 } from "node:path";
10801
10992
  import { fileURLToPath, pathToFileURL as pathToFileURL3 } from "node:url";
10802
10993
  function resolvePackageRootDir(moduleUrl = import.meta.url) {
10803
10994
  let dir = dirname13(fileURLToPath(moduleUrl));
10804
10995
  for (let i = 0; i < 8; i += 1) {
10805
- if (existsSync7(join23(dir, "package.json")) && existsSync7(join23(dir, "souls"))) {
10996
+ if (existsSync7(join24(dir, "package.json")) && existsSync7(join24(dir, "souls"))) {
10806
10997
  return dir;
10807
10998
  }
10808
10999
  const parent = dirname13(dir);
@@ -10812,7 +11003,7 @@ function resolvePackageRootDir(moduleUrl = import.meta.url) {
10812
11003
  return fileURLToPath(new URL("..", moduleUrl));
10813
11004
  }
10814
11005
  async function readPackageMaterial(relativePath) {
10815
- return readFile15(fileURLToPath(new URL(relativePath, packageRootUrl)), "utf8");
11006
+ return readFile16(fileURLToPath(new URL(relativePath, packageRootUrl)), "utf8");
10816
11007
  }
10817
11008
  async function joinPackageMaterials(relativePaths) {
10818
11009
  const chunks = [];
@@ -10966,7 +11157,7 @@ function knownFailureFromProviderStop(input) {
10966
11157
  const diagnostic = nonEmptyString(input.errorMessage);
10967
11158
  const details = sessionStopDetails(input);
10968
11159
  return {
10969
- cause: hasUpstreamErrorTestimony(input) ? "provider" : "unrecognized",
11160
+ ...hasUpstreamErrorTestimony(input) ? { cause: "provider" } : {},
10970
11161
  ...diagnostic === void 0 ? {} : { diagnostic },
10971
11162
  ...Object.keys(details).length === 0 ? {} : { details }
10972
11163
  };
@@ -12140,9 +12331,20 @@ var init_collector_ledger = __esm({
12140
12331
  // src/dossier-resolution.ts
12141
12332
  import { existsSync as existsSync8, statSync as statSync2 } from "node:fs";
12142
12333
  import { resolve as resolve11 } from "node:path";
12143
- function resolveAuditDossier(env = process.env) {
12334
+ function isHostContext(value) {
12335
+ return "sessionManager" in value;
12336
+ }
12337
+ function dossierPointerFrom(source) {
12338
+ if (source !== void 0 && isHostContext(source)) {
12339
+ return runDirectoryFromHostContext(source);
12340
+ }
12341
+ const env = source ?? process.env;
12144
12342
  const raw = env[AUDIT_RUN_DIR_ENV];
12145
- if (typeof raw !== "string" || raw.trim() === "") {
12343
+ return typeof raw === "string" && raw.trim() !== "" ? raw : void 0;
12344
+ }
12345
+ function resolveAuditDossier(source) {
12346
+ const raw = dossierPointerFrom(source);
12347
+ if (raw === void 0) {
12146
12348
  return { status: "ok" };
12147
12349
  }
12148
12350
  const runDirectory = resolve11(raw);
@@ -12176,6 +12378,7 @@ var AUDIT_RUN_DIR_ENV, DOCTOR_CANDIDATE_ENTRY_TYPE, AuditMaterialsUnavailableErr
12176
12378
  var init_dossier_resolution = __esm({
12177
12379
  "src/dossier-resolution.ts"() {
12178
12380
  "use strict";
12381
+ init_host_contracts();
12179
12382
  AUDIT_RUN_DIR_ENV = "AK_ROLE_RUN_DIR";
12180
12383
  DOCTOR_CANDIDATE_ENTRY_TYPE = "ak_doctor_audit_candidate";
12181
12384
  AuditMaterialsUnavailableError = class extends Error {
@@ -12194,8 +12397,8 @@ var init_dossier_resolution = __esm({
12194
12397
 
12195
12398
  // src/package-resources/method-skill.ts
12196
12399
  import { createHash as createHash7 } from "node:crypto";
12197
- import { readFile as readFile16, realpath as realpath7 } from "node:fs/promises";
12198
- import { join as join24 } from "node:path";
12400
+ import { readFile as readFile17, realpath as realpath7 } from "node:fs/promises";
12401
+ import { join as join25 } from "node:path";
12199
12402
  function gitBlobOid(bytes) {
12200
12403
  const body = typeof bytes === "string" ? Buffer.from(bytes, "utf8") : Buffer.from(bytes);
12201
12404
  const header = Buffer.from(`blob ${body.byteLength}\0`, "utf8");
@@ -12212,10 +12415,10 @@ function packagedMethodSkillRelativeDirectory(name) {
12212
12415
  return `${METHOD_SKILL_RELATIVE_ROOT}/${name}`;
12213
12416
  }
12214
12417
  function resolvePackagedMethodSkillRoot(packageRoot, name) {
12215
- return join24(packageRoot, packagedMethodSkillRelativeDirectory(name));
12418
+ return join25(packageRoot, packagedMethodSkillRelativeDirectory(name));
12216
12419
  }
12217
12420
  function resolvePackagedMethodSkillPath(packageRoot, name) {
12218
- return join24(resolvePackagedMethodSkillRoot(packageRoot, name), "SKILL.md");
12421
+ return join25(resolvePackagedMethodSkillRoot(packageRoot, name), "SKILL.md");
12219
12422
  }
12220
12423
  function isRecord8(value) {
12221
12424
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -12309,11 +12512,11 @@ function parseProvenance(raw, expectedName) {
12309
12512
  }
12310
12513
  async function loadPackagedMethodSkillMaterial(packageRoot, name) {
12311
12514
  const rootDirectory = resolvePackagedMethodSkillRoot(packageRoot, name);
12312
- const skillPathConfigured = join24(rootDirectory, "SKILL.md");
12313
- const provenancePath = join24(rootDirectory, "provenance.json");
12515
+ const skillPathConfigured = join25(rootDirectory, "SKILL.md");
12516
+ const provenancePath = join25(rootDirectory, "provenance.json");
12314
12517
  let provenanceRaw;
12315
12518
  try {
12316
- provenanceRaw = await readFile16(provenancePath, "utf8");
12519
+ provenanceRaw = await readFile17(provenancePath, "utf8");
12317
12520
  } catch (error) {
12318
12521
  throw new PackagedMethodSkillUnavailableError(name, provenancePath, error);
12319
12522
  }
@@ -12327,10 +12530,10 @@ async function loadPackagedMethodSkillMaterial(packageRoot, name) {
12327
12530
  }
12328
12531
  const provenance = parseProvenance(provenanceJson, name);
12329
12532
  for (const [rel, expected] of Object.entries(provenance.files)) {
12330
- const absolute = join24(rootDirectory, rel);
12533
+ const absolute = join25(rootDirectory, rel);
12331
12534
  let bytes;
12332
12535
  try {
12333
- bytes = await readFile16(absolute);
12536
+ bytes = await readFile17(absolute);
12334
12537
  } catch (error) {
12335
12538
  throw new PackagedMethodSkillUnavailableError(name, absolute, error);
12336
12539
  }
@@ -12346,7 +12549,7 @@ async function loadPackagedMethodSkillMaterial(packageRoot, name) {
12346
12549
  let raw;
12347
12550
  try {
12348
12551
  skillPath = await realpath7(skillPathConfigured);
12349
- raw = await readFile16(skillPath, "utf8");
12552
+ raw = await readFile17(skillPath, "utf8");
12350
12553
  } catch (error) {
12351
12554
  throw new PackagedMethodSkillUnavailableError(name, skillPathConfigured, error);
12352
12555
  }
@@ -12746,15 +12949,6 @@ function isLawfulTypedTerminalOutcome(outcome) {
12746
12949
  function exitCodeForTerminalOutcome(outcome) {
12747
12950
  return isLawfulTypedTerminalOutcome(outcome) ? 0 : 1;
12748
12951
  }
12749
- function lastRolePayloadRecord(payloads) {
12750
- for (let index = payloads.length - 1; index >= 0; index -= 1) {
12751
- const payload = payloads[index];
12752
- if (typeof payload === "object" && payload !== null && !Array.isArray(payload)) {
12753
- return payload;
12754
- }
12755
- }
12756
- return void 0;
12757
- }
12758
12952
  function recommendationNavigatorFact(input) {
12759
12953
  const command = typeof input.modelCommand === "string" && input.modelCommand.trim() !== "" ? input.modelCommand : isPublicCallableRole2(input.next.role) ? renderPublicAkRoleCommand(input.next) : void 0;
12760
12954
  return {
@@ -12769,7 +12963,7 @@ function recommendationNavigatorFact(input) {
12769
12963
  function formatTerminalResult(result) {
12770
12964
  const lines = [];
12771
12965
  lines.push("role outcome status");
12772
- const outcomeStatus = result.roleOutcome.kind === "failure" ? result.roleOutcome.cause : result.roleOutcome.kind === "accepted" ? "accepted" : result.roleOutcome.status;
12966
+ const outcomeStatus = result.roleOutcome.kind === "failure" ? result.roleOutcome.cause ?? "" : result.roleOutcome.kind === "accepted" ? "accepted" : result.roleOutcome.status;
12773
12967
  lines.push(
12774
12968
  `${result.roleOutcome.role} ${result.roleOutcome.kind} ${encodeTerminalField(outcomeStatus)}`
12775
12969
  );
@@ -12842,8 +13036,8 @@ var init_terminal = __esm({
12842
13036
 
12843
13037
  // src/public-cli/settlement.ts
12844
13038
  import { randomUUID as randomUUID3 } from "node:crypto";
12845
- import { appendFile as appendFile2, readFile as readFile17, readdir as readdir5, writeFile as writeFile7 } from "node:fs/promises";
12846
- import { dirname as dirname14, join as join25 } from "node:path";
13039
+ import { appendFile as appendFile2, readFile as readFile18, readdir as readdir5, writeFile as writeFile8 } from "node:fs/promises";
13040
+ import { dirname as dirname14, join as join26 } from "node:path";
12847
13041
  function sealedLedgerHome(admitted) {
12848
13042
  return homeFromRunDirectory(admitted.runDirectory);
12849
13043
  }
@@ -12855,14 +13049,27 @@ function ledgerReadScope(admitted, scope) {
12855
13049
  }
12856
13050
  function roleOutcomeFromRows(role, rows) {
12857
13051
  const mine = rows.filter((row) => row.role === role);
12858
- if (mine.length === 0) return void 0;
13052
+ const terminal = mine.filter(
13053
+ (row) => row.kind === "accepted" || row.kind === "audit-escalation"
13054
+ );
13055
+ if (terminal.length === 0) return void 0;
12859
13056
  const payloads = mine.map((row) => row.accepted);
12860
- if (mine.some((row) => row.kind === "audit-escalation")) {
13057
+ if (terminal.some((row) => row.kind === "audit-escalation")) {
12861
13058
  return { kind: "audit_escalation", role, status: "audit_escalation", payloads };
12862
13059
  }
12863
13060
  return { kind: "accepted", role, payloads };
12864
13061
  }
12865
13062
  async function sealedLedgerOutcome(admitted, role, scope) {
13063
+ const home = sealedLedgerHome(admitted);
13064
+ if (scope?.courtAttemptId !== void 0 && scope.courtAttemptId.length > 0) {
13065
+ const thisCourt = await readAttemptScopedSubmissionRows(
13066
+ admitted.projectRoot,
13067
+ admitted.runId,
13068
+ scope.courtAttemptId,
13069
+ home
13070
+ );
13071
+ return roleOutcomeFromRows(role, thisCourt);
13072
+ }
12866
13073
  const rows = await readRecordedSubmissionRows(
12867
13074
  admitted.projectRoot,
12868
13075
  admitted.runId,
@@ -12893,7 +13100,11 @@ function withSubmissions(terminal, submissions) {
12893
13100
  return { ...terminal, roleOutcome: withPayloads, submissions };
12894
13101
  }
12895
13102
  async function attachRecordedSubmissions(admitted, terminal, scope) {
12896
- return withSubmissions(terminal, await recordedSubmissionPayloads(admitted, scope));
13103
+ void scope;
13104
+ return withSubmissions(
13105
+ terminal,
13106
+ await recordedSubmissionPayloads(admitted, void 0)
13107
+ );
12897
13108
  }
12898
13109
  async function settleHostEndedNoReceipt(admitted, authority) {
12899
13110
  const facts = noReceiptLifecycleFacts({
@@ -12962,7 +13173,7 @@ function presentStructuralRejection(error, io) {
12962
13173
  }
12963
13174
  async function inspectJudgeSession(sessionFile) {
12964
13175
  try {
12965
- await readFile17(sessionFile, "utf8");
13176
+ await readFile18(sessionFile, "utf8");
12966
13177
  return { state: "present" };
12967
13178
  } catch (error) {
12968
13179
  if (isMissingPathError2(error)) return { state: "missing" };
@@ -12985,7 +13196,7 @@ function thrownIdentity(error) {
12985
13196
  function isTypedActivationError(error) {
12986
13197
  if (!(error instanceof Error)) return false;
12987
13198
  const cause = error.knownCause;
12988
- return cause === "provider" || cause === "activation" || cause === "session" || cause === "output" || cause === "timeout" || cause === "unrecognized";
13199
+ return cause === "provider" || cause === "activation" || cause === "session" || cause === "output" || cause === "timeout";
12989
13200
  }
12990
13201
  function flattenThrownFailureLeaves(error) {
12991
13202
  if (!(error instanceof AggregateError)) {
@@ -13005,7 +13216,7 @@ function projectThrownFailureLeaf(error) {
13005
13216
  }
13006
13217
  return {
13007
13218
  cause: error.knownCause,
13008
- diagnostic: error.message || error.name || "unrecognized exception",
13219
+ diagnostic: error.message || error.name || "exception",
13009
13220
  identity,
13010
13221
  ...error.details === void 0 ? {} : { details: error.details }
13011
13222
  };
@@ -13013,13 +13224,11 @@ function projectThrownFailureLeaf(error) {
13013
13224
  if (error instanceof Error) {
13014
13225
  const identity = thrownIdentity(error);
13015
13226
  return {
13016
- cause: "unrecognized",
13017
- diagnostic: error.message || error.name || "unrecognized exception",
13227
+ diagnostic: error.message || error.name || "exception",
13018
13228
  identity
13019
13229
  };
13020
13230
  }
13021
13231
  return {
13022
- cause: "unrecognized",
13023
13232
  diagnostic: String(error)
13024
13233
  };
13025
13234
  }
@@ -13041,7 +13250,7 @@ function classifyThrownFailure(error) {
13041
13250
  ...leaves.slice(1).map((leaf) => {
13042
13251
  const secondary = projectThrownFailureLeaf(leaf);
13043
13252
  return {
13044
- cause: secondary.cause,
13253
+ ...secondary.cause === void 0 ? {} : { cause: secondary.cause },
13045
13254
  diagnostic: secondary.diagnostic,
13046
13255
  ...secondary.identity === void 0 ? {} : { identity: secondary.identity },
13047
13256
  ...secondary.details === void 0 ? {} : { details: secondary.details }
@@ -13049,7 +13258,7 @@ function classifyThrownFailure(error) {
13049
13258
  })
13050
13259
  ];
13051
13260
  return {
13052
- cause: primary.cause,
13261
+ ...primary.cause === void 0 ? {} : { cause: primary.cause },
13053
13262
  diagnostic: primary.diagnostic,
13054
13263
  ...primary.identity === void 0 ? {} : { identity: primary.identity },
13055
13264
  details: {
@@ -13090,6 +13299,24 @@ function classifyPostAdmissionFailure(input) {
13090
13299
  ...input.knownIdentity === void 0 ? {} : { identity: input.knownIdentity }
13091
13300
  };
13092
13301
  }
13302
+ if (input.knownDiagnostic !== void 0 && input.knownDiagnostic.trim() !== "" || input.knownIdentity !== void 0) {
13303
+ const diagnostic = input.knownDiagnostic !== void 0 && input.knownDiagnostic.trim() !== "" ? input.knownDiagnostic : conciseChildDiagnostic(input.stderr, "role run failed");
13304
+ const { timedOut: _knownTimedOut, ...knownDetails } = input.knownDetails ?? {};
13305
+ const remoteCode = knownDetails.code;
13306
+ return withKnownDetails(
13307
+ {
13308
+ diagnostic,
13309
+ details: {
13310
+ ...knownDetails,
13311
+ ...remoteCode === void 0 ? {} : { code: remoteCode },
13312
+ exitCode: input.code,
13313
+ ...input.timedOut ? { timedOut: true } : {}
13314
+ },
13315
+ ...input.knownIdentity === void 0 ? {} : { identity: input.knownIdentity }
13316
+ },
13317
+ void 0
13318
+ );
13319
+ }
13093
13320
  if (input.timedOut) {
13094
13321
  return withKnownDetails(
13095
13322
  {
@@ -13143,7 +13370,7 @@ function classifyPostAdmissionFailure(input) {
13143
13370
  function explicitInternalKnownFailureClassificationInput(failure2) {
13144
13371
  if (failure2 === void 0) return {};
13145
13372
  return {
13146
- knownCause: failure2.cause,
13373
+ ...failure2.cause === void 0 ? {} : { knownCause: failure2.cause },
13147
13374
  ...failure2.identity === void 0 ? {} : { knownIdentity: failure2.identity },
13148
13375
  ...failure2.diagnostic === void 0 ? {} : { knownDiagnostic: failure2.diagnostic },
13149
13376
  ...failure2.details === void 0 ? {} : { knownDetails: failure2.details }
@@ -13178,7 +13405,7 @@ function sessionReadFailure(error, fallbackMessage) {
13178
13405
  return failed;
13179
13406
  }
13180
13407
  async function readBoundSessionEntries(sessionFile) {
13181
- const text = await readFile17(sessionFile, "utf8");
13408
+ const text = await readFile18(sessionFile, "utf8");
13182
13409
  const entries = [];
13183
13410
  for (const line2 of text.trim().split("\n").filter(Boolean)) {
13184
13411
  try {
@@ -13265,7 +13492,7 @@ async function readSessionProviderStop(sessionFile) {
13265
13492
  }
13266
13493
  }
13267
13494
  async function readBoundEvidenceChildKnownFailure(sessionFile) {
13268
- const childDirectory = join25(dirname14(sessionFile), "evidence-children");
13495
+ const childDirectory = join26(dirname14(sessionFile), "evidence-children");
13269
13496
  let names;
13270
13497
  try {
13271
13498
  names = await readdir5(childDirectory);
@@ -13276,7 +13503,7 @@ async function readBoundEvidenceChildKnownFailure(sessionFile) {
13276
13503
  for (const file of names.filter((name) => name.endsWith(".jsonl")).sort().reverse()) {
13277
13504
  let entries;
13278
13505
  try {
13279
- entries = await readBoundSessionEntries(join25(childDirectory, file));
13506
+ entries = await readBoundSessionEntries(join26(childDirectory, file));
13280
13507
  } catch (error) {
13281
13508
  throw sessionReadFailure(error, "failed to read discovered evidence-child session");
13282
13509
  }
@@ -13331,7 +13558,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
13331
13558
  latestParentUserIndex = i;
13332
13559
  break;
13333
13560
  }
13334
- const childDirectories = [join25(dirname14(sessionFile), "auditor-roles")];
13561
+ const childDirectories = [join26(dirname14(sessionFile), "auditor-roles")];
13335
13562
  const valid = [];
13336
13563
  let sawAnyDirectory = false;
13337
13564
  for (const childDirectory of childDirectories) {
@@ -13346,7 +13573,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
13346
13573
  for (const file of names.filter((name) => name.endsWith(".jsonl")).sort().reverse()) {
13347
13574
  let entries;
13348
13575
  try {
13349
- entries = await readBoundSessionEntries(join25(childDirectory, file));
13576
+ entries = await readBoundSessionEntries(join26(childDirectory, file));
13350
13577
  } catch (error) {
13351
13578
  throw sessionReadFailure(error, "failed to read discovered auditor session");
13352
13579
  }
@@ -13395,10 +13622,12 @@ function complianceFailureFromAuditorVolumes(volumes) {
13395
13622
  if (entry?.type !== "custom" || entry.customType !== AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE || !isRecord10(entry.data)) continue;
13396
13623
  const parent = isRecord10(entry.data.parent) ? entry.data.parent : void 0;
13397
13624
  const failure2 = isRecord10(entry.data.failure) ? entry.data.failure : void 0;
13398
- if (parent?.sessionId !== parentId || parent.sessionFile !== sessionFile || parent.attemptEntryId !== attemptEntryId || failure2?.cause !== "provider" && failure2?.cause !== "unrecognized") continue;
13625
+ if (parent?.sessionId !== parentId || parent.sessionFile !== sessionFile || parent.attemptEntryId !== attemptEntryId) continue;
13626
+ if (failure2 === void 0) continue;
13399
13627
  const identity = isRecord10(failure2.identity) ? failure2.identity : void 0;
13628
+ const typedCause = failure2.cause === "provider" || failure2.cause === "activation" || failure2.cause === "session" || failure2.cause === "output" || failure2.cause === "timeout" ? failure2.cause : void 0;
13400
13629
  return {
13401
- cause: failure2.cause === "provider" ? "provider" : "unrecognized",
13630
+ ...typedCause === void 0 ? {} : { cause: typedCause },
13402
13631
  ...identity === void 0 ? {} : { identity: {
13403
13632
  ...typeof identity.name === "string" ? { name: identity.name } : {},
13404
13633
  ...typeof identity.code === "string" || typeof identity.code === "number" ? { code: identity.code } : {}
@@ -13840,8 +14069,8 @@ function projectTerminalGateFact(rounds) {
13840
14069
  };
13841
14070
  }
13842
14071
  async function extractGateFactFromSessionDirectory(sessionDirectory, options = {}) {
13843
- const directories = [join25(sessionDirectory, "auditor-roles")];
13844
- const parentSessionFile = options.parentSessionFile ?? join25(sessionDirectory, "session.jsonl");
14072
+ const directories = [join26(sessionDirectory, "auditor-roles")];
14073
+ const parentSessionFile = options.parentSessionFile ?? join26(sessionDirectory, "session.jsonl");
13845
14074
  const rounds = await readAnalystGateCyclesFromAuditorRoles(directories, {
13846
14075
  parentSessionFile
13847
14076
  });
@@ -13939,9 +14168,9 @@ async function extractNavigatorFactFromAdmittedSession(sessionFile) {
13939
14168
  async function publishJudgeArtifacts(admitted, roleOutcome, coordinates) {
13940
14169
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
13941
14170
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
13942
- const reportPath = join25(artifactsDir, "report.json");
13943
- const evidencePath = join25(artifactsDir, "evidence.json");
13944
- await writeFile7(
14171
+ const reportPath = join26(artifactsDir, "report.json");
14172
+ const evidencePath = join26(artifactsDir, "evidence.json");
14173
+ await writeFile8(
13945
14174
  reportPath,
13946
14175
  `${JSON.stringify(
13947
14176
  {
@@ -13955,7 +14184,7 @@ async function publishJudgeArtifacts(admitted, roleOutcome, coordinates) {
13955
14184
  `,
13956
14185
  "utf8"
13957
14186
  );
13958
- await writeFile7(
14187
+ await writeFile8(
13959
14188
  evidencePath,
13960
14189
  `${JSON.stringify(
13961
14190
  {
@@ -14041,17 +14270,15 @@ function extractDoctorCandidateAuditNoReceiptFact(entries) {
14041
14270
  async function publishDoctorArtifacts(admitted, roleOutcome, coordinates, options = {}) {
14042
14271
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
14043
14272
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
14044
- const reportPath = join25(artifactsDir, "report.json");
14045
- const evidencePath = join25(artifactsDir, "evidence.json");
14046
- await writeFile7(
14273
+ const reportPath = join26(artifactsDir, "report.json");
14274
+ const evidencePath = join26(artifactsDir, "evidence.json");
14275
+ await writeFile8(
14047
14276
  reportPath,
14048
14277
  `${JSON.stringify(
14049
14278
  {
14050
14279
  role: "doctor",
14051
14280
  runId: admitted.runId,
14052
14281
  outcome: roleOutcome,
14053
- ...options.doctorOutput === void 0 ? {} : { receipt: options.doctorOutput },
14054
- // Independent machine fields beside the receipt — not merged into it.
14055
14282
  ...options.cost === void 0 ? {} : { cost: options.cost },
14056
14283
  ...options.auditNoReceipt === void 0 ? {} : { auditNoReceipt: options.auditNoReceipt }
14057
14284
  },
@@ -14061,7 +14288,7 @@ async function publishDoctorArtifacts(admitted, roleOutcome, coordinates, option
14061
14288
  `,
14062
14289
  "utf8"
14063
14290
  );
14064
- await writeFile7(
14291
+ await writeFile8(
14065
14292
  evidencePath,
14066
14293
  `${JSON.stringify(
14067
14294
  {
@@ -14109,7 +14336,6 @@ async function settleLawfulDoctorTerminalResult(admitted, authority, scope) {
14109
14336
  sessionDirectory
14110
14337
  );
14111
14338
  }
14112
- const output = lastRolePayloadRecord(sealed.payloads ?? []) ?? {};
14113
14339
  const roleOutcome = sealed;
14114
14340
  const navigator = extractNavigatorFact(entries);
14115
14341
  const cost = extractDoctorCandidateCostFact(entries);
@@ -14119,7 +14345,6 @@ async function settleLawfulDoctorTerminalResult(admitted, authority, scope) {
14119
14345
  roleOutcome,
14120
14346
  coordinates,
14121
14347
  {
14122
- doctorOutput: output,
14123
14348
  ...cost === void 0 ? {} : { cost },
14124
14349
  ...auditNoReceipt === void 0 ? {} : { auditNoReceipt }
14125
14350
  }
@@ -14283,7 +14508,7 @@ function uniqueFailureFallbackDirs(runDirectory, baseDir) {
14283
14508
  return dirs;
14284
14509
  }
14285
14510
  async function resolveFailureArtifactsBase(runDirectory) {
14286
- const artifactsDir = join25(runDirectory, "artifacts");
14511
+ const artifactsDir = join26(runDirectory, "artifacts");
14287
14512
  try {
14288
14513
  await ensureRunArtifactsDir(runDirectory);
14289
14514
  return { baseDir: artifactsDir };
@@ -14299,13 +14524,13 @@ async function writeFailureJsonRetainingCause(preferredCandidates, uniqueFallbac
14299
14524
  const candidates = [
14300
14525
  ...preferredCandidates,
14301
14526
  // One unique name per fallback dir — collisions on fixed names cannot exhaust this.
14302
- ...uniqueFallbackDirs.map((dir) => join25(dir, `${stem}.${randomUUID3()}.json`))
14527
+ ...uniqueFallbackDirs.map((dir) => join26(dir, `${stem}.${randomUUID3()}.json`))
14303
14528
  ];
14304
14529
  for (let i = 0; i < candidates.length; i += 1) {
14305
14530
  const path = candidates[i];
14306
14531
  const payload = issues.length === 0 ? basePayload : { ...basePayload, publicationIssues: issues };
14307
14532
  try {
14308
- await writeFile7(
14533
+ await writeFile8(
14309
14534
  path,
14310
14535
  `${JSON.stringify(payload, null, 2)}
14311
14536
  `,
@@ -14344,32 +14569,32 @@ async function publishFailureArtifacts(admitted, failure2, authority) {
14344
14569
  } catch (error) {
14345
14570
  priorIssues.push(publicationAttemptFromError(sessionFile, error));
14346
14571
  }
14347
- const underArtifacts = baseDir === join25(admitted.runDirectory, "artifacts");
14572
+ const underArtifacts = baseDir === join26(admitted.runDirectory, "artifacts");
14348
14573
  const uniqueFallbackDirs = uniqueFailureFallbackDirs(
14349
14574
  admitted.runDirectory,
14350
14575
  baseDir
14351
14576
  );
14352
14577
  const errorCandidates = underArtifacts ? [
14353
- join25(baseDir, "error.json"),
14354
- join25(baseDir, "error.settlement.json"),
14355
- join25(admitted.runDirectory, "error.settlement.json")
14578
+ join26(baseDir, "error.json"),
14579
+ join26(baseDir, "error.settlement.json"),
14580
+ join26(admitted.runDirectory, "error.settlement.json")
14356
14581
  ] : [
14357
- join25(baseDir, "error.settlement.json"),
14358
- join25(baseDir, "error.json")
14582
+ join26(baseDir, "error.settlement.json"),
14583
+ join26(baseDir, "error.json")
14359
14584
  ];
14360
14585
  const evidenceCandidates = underArtifacts ? [
14361
- join25(baseDir, "evidence.json"),
14362
- join25(baseDir, "evidence.settlement.json"),
14363
- join25(admitted.runDirectory, "evidence.settlement.json")
14586
+ join26(baseDir, "evidence.json"),
14587
+ join26(baseDir, "evidence.settlement.json"),
14588
+ join26(admitted.runDirectory, "evidence.settlement.json")
14364
14589
  ] : [
14365
- join25(baseDir, "evidence.settlement.json"),
14366
- join25(baseDir, "evidence.json")
14590
+ join26(baseDir, "evidence.settlement.json"),
14591
+ join26(baseDir, "evidence.json")
14367
14592
  ];
14368
14593
  const errorPayloadBase = {
14369
14594
  kind: "error",
14370
14595
  role: admitted.role,
14371
14596
  runId: admitted.runId,
14372
- cause: failure2.cause,
14597
+ ...failure2.cause === void 0 ? {} : { cause: failure2.cause },
14373
14598
  diagnostic: failure2.diagnostic,
14374
14599
  ...failure2.identity === void 0 ? {} : { identity: failure2.identity },
14375
14600
  ...failure2.details === void 0 ? {} : { details: failure2.details }
@@ -14392,7 +14617,7 @@ async function publishFailureArtifacts(admitted, failure2, authority) {
14392
14617
  sha256: a.sha256,
14393
14618
  byteLength: a.byteLength
14394
14619
  })),
14395
- failureCause: failure2.cause
14620
+ ...failure2.cause === void 0 ? {} : { failureCause: failure2.cause }
14396
14621
  };
14397
14622
  const evidenceWrite = await writeFailureJsonRetainingCause(
14398
14623
  evidenceCandidates,
@@ -14456,7 +14681,7 @@ async function settleFailureTerminalResult(admitted, failure2, authority, option
14456
14681
  const navigator = await extractNavigatorFactFromAdmittedSession(sessionFile);
14457
14682
  const artifacts = await publishFailureArtifacts(admitted, failure2, authority);
14458
14683
  const decisiveFacts = {
14459
- cause: failure2.cause,
14684
+ ...failure2.cause === void 0 ? {} : { cause: failure2.cause },
14460
14685
  diagnostic: failure2.diagnostic
14461
14686
  };
14462
14687
  if (failure2.identity?.name !== void 0) {
@@ -14472,7 +14697,7 @@ async function settleFailureTerminalResult(admitted, failure2, authority, option
14472
14697
  const roleOutcome2 = {
14473
14698
  kind: "failure",
14474
14699
  role: admitted.role,
14475
- cause: failure2.cause,
14700
+ ...failure2.cause === void 0 ? {} : { cause: failure2.cause },
14476
14701
  diagnostic: failure2.diagnostic,
14477
14702
  decisiveFacts
14478
14703
  };
@@ -14489,7 +14714,7 @@ async function settleFailureTerminalResult(admitted, failure2, authority, option
14489
14714
  const roleOutcome = {
14490
14715
  kind: "failure",
14491
14716
  role: admitted.role,
14492
- cause: failure2.cause,
14717
+ ...failure2.cause === void 0 ? {} : { cause: failure2.cause },
14493
14718
  diagnostic: failure2.diagnostic,
14494
14719
  decisiveFacts
14495
14720
  };
@@ -14510,7 +14735,7 @@ function presentFailureTerminal(terminal, io) {
14510
14735
  io.stdout(formatTerminalResult(terminal));
14511
14736
  if (terminal.roleOutcome.kind === "failure") {
14512
14737
  io.stderr(formatFailureStderrDiagnostic({
14513
- cause: terminal.roleOutcome.cause,
14738
+ ...terminal.roleOutcome.cause === void 0 ? {} : { cause: terminal.roleOutcome.cause },
14514
14739
  diagnostic: terminal.roleOutcome.diagnostic
14515
14740
  }));
14516
14741
  return;
@@ -14608,7 +14833,7 @@ var init_settlement = __esm({
14608
14833
  import { constants as fsConstants2 } from "node:fs";
14609
14834
  import { randomUUID as randomUUID4 } from "node:crypto";
14610
14835
  import { lstat as lstat5, mkdir as mkdir5, open as open2 } from "node:fs/promises";
14611
- import { join as join26 } from "node:path";
14836
+ import { join as join27 } from "node:path";
14612
14837
  async function persistReturnedRunState(admitted, authority, options) {
14613
14838
  if (options?.lawful === true) {
14614
14839
  await markRunTerminal(admitted.runDirectory);
@@ -14644,7 +14869,7 @@ async function finalizeExceptionRunBestEffort(runDirectory, io) {
14644
14869
  }
14645
14870
  }
14646
14871
  function runArtifactsDirectory(runDirectory) {
14647
- return join26(runDirectory, "artifacts");
14872
+ return join27(runDirectory, "artifacts");
14648
14873
  }
14649
14874
  async function ensureRealArtifactsDirectory(runDirectory) {
14650
14875
  const runStat = await lstat5(runDirectory);
@@ -14726,7 +14951,7 @@ function jsonSafeReplacer() {
14726
14951
  };
14727
14952
  }
14728
14953
  async function writeHardenedArtifactFile(artifactsDir, namePrefix, payload) {
14729
- const filePath = join26(artifactsDir, `${namePrefix}-${randomUUID4()}.json`);
14954
+ const filePath = join27(artifactsDir, `${namePrefix}-${randomUUID4()}.json`);
14730
14955
  const body = `${JSON.stringify(payload, jsonSafeReplacer(), 2)}
14731
14956
  `;
14732
14957
  const noFollowFlag = typeof fsConstants2.O_NOFOLLOW === "number" ? fsConstants2.O_NOFOLLOW : 0;
@@ -14780,12 +15005,29 @@ function unwrapTurnDispatchedFailure(error) {
14780
15005
  }
14781
15006
  return current;
14782
15007
  }
15008
+ async function attachDispatchExceptionTerminal(admitted, terminal, io) {
15009
+ try {
15010
+ return await attachRecordedSubmissions(
15011
+ {
15012
+ projectRoot: admitted.projectRoot,
15013
+ runId: admitted.runId,
15014
+ runDirectory: admitted.runDirectory
15015
+ },
15016
+ terminal
15017
+ );
15018
+ } catch (error) {
15019
+ io.stderr(
15020
+ `dispatch exception ledger attach failed (best-effort continue): ${describeErrorIdentity(error)}
15021
+ `
15022
+ );
15023
+ return terminal;
15024
+ }
15025
+ }
14783
15026
  function dispatchExceptionFailureTerminal(input) {
14784
15027
  const causeError = unwrapTurnDispatchedFailure(input.causeError);
14785
15028
  const history = input.everyAttemptThrew ? "dispatch threw an exception on every attempt" : "the final dispatch threw an exception";
14786
15029
  const diagnostic = `${history} (${input.endReason}; resumes used ${input.autoResumeAttempts}); last cause: ${describeErrorIdentity(causeError)}`;
14787
15030
  const decisiveFacts = {
14788
- cause: "unrecognized",
14789
15031
  diagnostic,
14790
15032
  resumesUsed: input.autoResumeAttempts,
14791
15033
  dispatchErrorFiles: [...input.errorFiles]
@@ -14806,7 +15048,6 @@ function dispatchExceptionFailureTerminal(input) {
14806
15048
  roleOutcome: {
14807
15049
  kind: "failure",
14808
15050
  role: input.role,
14809
- cause: "unrecognized",
14810
15051
  diagnostic,
14811
15052
  decisiveFacts
14812
15053
  },
@@ -14906,15 +15147,19 @@ async function runWithAutoResumeLoop(options) {
14906
15147
  }
14907
15148
  } else {
14908
15149
  if (autoResumeAttempts >= limit) {
14909
- const terminal = dispatchExceptionFailureTerminal({
14910
- role: options.admitted.role,
14911
- runId: options.admitted.runId,
14912
- causeError: lastThrownError,
14913
- errorFiles: retainedErrorFiles,
14914
- autoResumeAttempts,
14915
- endReason: "auto-resume budget exhausted",
14916
- everyAttemptThrew
14917
- });
15150
+ const terminal = await attachDispatchExceptionTerminal(
15151
+ options.admitted,
15152
+ dispatchExceptionFailureTerminal({
15153
+ role: options.admitted.role,
15154
+ runId: options.admitted.runId,
15155
+ causeError: lastThrownError,
15156
+ errorFiles: retainedErrorFiles,
15157
+ autoResumeAttempts,
15158
+ endReason: "auto-resume budget exhausted",
15159
+ everyAttemptThrew
15160
+ }),
15161
+ options.io
15162
+ );
14918
15163
  await finalizeExceptionRunBestEffort(options.admitted.runDirectory, options.io);
14919
15164
  presentTerminal(terminal, options.io);
14920
15165
  return {
@@ -14923,15 +15168,19 @@ async function runWithAutoResumeLoop(options) {
14923
15168
  };
14924
15169
  }
14925
15170
  if (!await isPrincipalAvailable(options.admitted.principal)) {
14926
- const terminal = dispatchExceptionFailureTerminal({
14927
- role: options.admitted.role,
14928
- runId: options.admitted.runId,
14929
- causeError: lastThrownError,
14930
- errorFiles: retainedErrorFiles,
14931
- autoResumeAttempts,
14932
- endReason: "session principal unavailable before further resume",
14933
- everyAttemptThrew
14934
- });
15171
+ const terminal = await attachDispatchExceptionTerminal(
15172
+ options.admitted,
15173
+ dispatchExceptionFailureTerminal({
15174
+ role: options.admitted.role,
15175
+ runId: options.admitted.runId,
15176
+ causeError: lastThrownError,
15177
+ errorFiles: retainedErrorFiles,
15178
+ autoResumeAttempts,
15179
+ endReason: "session principal unavailable before further resume",
15180
+ everyAttemptThrew
15181
+ }),
15182
+ options.io
15183
+ );
14935
15184
  await finalizeExceptionRunBestEffort(options.admitted.runDirectory, options.io);
14936
15185
  presentTerminal(terminal, options.io);
14937
15186
  return {
@@ -14973,8 +15222,8 @@ var init_auto_resume = __esm({
14973
15222
 
14974
15223
  // src/public-cli/post-admission.ts
14975
15224
  import { randomUUID as randomUUID5 } from "node:crypto";
14976
- import { readFile as readFile18, writeFile as writeFile8 } from "node:fs/promises";
14977
- import { isAbsolute as isAbsolute8, join as join27, resolve as resolve13 } from "node:path";
15225
+ import { readFile as readFile19, writeFile as writeFile9 } from "node:fs/promises";
15226
+ import { isAbsolute as isAbsolute8, join as join28, resolve as resolve13 } from "node:path";
14978
15227
  function describeCaughtError(error) {
14979
15228
  if (error instanceof Error) {
14980
15229
  const code = error.code;
@@ -14988,6 +15237,9 @@ function appendContinuationSection(continuation, section) {
14988
15237
  ${section}`;
14989
15238
  return continuation.kind === "initial" ? { kind: "initial", prompt } : { kind: "resume", prompt };
14990
15239
  }
15240
+ function isStationChildOfficerDialogue(role, env) {
15241
+ return env.stationChild === true && isOfficerReviewSeat(role);
15242
+ }
14991
15243
  function withOnceSuccessfulBeforeDispatch(adapters) {
14992
15244
  const hook = adapters.beforeDispatch;
14993
15245
  if (hook === void 0) return adapters;
@@ -15015,8 +15267,8 @@ async function recordBestEffortPostDispatchDiagnostic(admitted, env, diagnostic,
15015
15267
  } catch (appendError) {
15016
15268
  try {
15017
15269
  const artifactsDir = await ensureRealArtifactsDirectory(admitted.runDirectory);
15018
- await writeFile8(
15019
- join27(artifactsDir, `post-admission-diagnostic-${randomUUID5()}.json`),
15270
+ await writeFile9(
15271
+ join28(artifactsDir, `post-admission-diagnostic-${randomUUID5()}.json`),
15020
15272
  `${JSON.stringify({ version: 1, ...payload }, null, 2)}
15021
15273
  `,
15022
15274
  { encoding: "utf8", flag: "wx" }
@@ -15032,7 +15284,7 @@ async function recordBestEffortPostDispatchDiagnostic(admitted, env, diagnostic,
15032
15284
  }
15033
15285
  async function readInvocationHost(runDirectory) {
15034
15286
  try {
15035
- const raw = JSON.parse(await readFile18(join27(runDirectory, "invocation.json"), "utf8"));
15287
+ const raw = JSON.parse(await readFile19(join28(runDirectory, "invocation.json"), "utf8"));
15036
15288
  return typeof raw.host === "string" && raw.host.trim() !== "" ? raw.host : void 0;
15037
15289
  } catch (error) {
15038
15290
  if (error.code === "ENOENT") return void 0;
@@ -15205,19 +15457,28 @@ async function dispatchPostAdmissionTurn(input) {
15205
15457
  if (hostTransition !== void 0) {
15206
15458
  turnRequest = { ...turnRequest, hostTransition };
15207
15459
  }
15208
- const dossierSection = await projectCaseDossierPointerSection({
15209
- ticketNumber: admitted.ticketNumber,
15210
- projectRoot: admitted.projectRoot,
15211
- home: env.home
15212
- });
15213
- if (dossierSection !== void 0) {
15214
- turnRequest = {
15215
- ...turnRequest,
15216
- continuation: appendContinuationSection(
15217
- turnRequest.continuation,
15218
- dossierSection
15219
- )
15220
- };
15460
+ if (isStationChildOfficerDialogue(admitted.role, env)) {
15461
+ await deliverCaseDossierAsAttachment({
15462
+ ticketNumber: admitted.ticketNumber,
15463
+ projectRoot: admitted.projectRoot,
15464
+ home: env.home,
15465
+ runDirectory: admitted.runDirectory
15466
+ });
15467
+ } else {
15468
+ const dossierSection = await projectCaseDossierPointerSection({
15469
+ ticketNumber: admitted.ticketNumber,
15470
+ projectRoot: admitted.projectRoot,
15471
+ home: env.home
15472
+ });
15473
+ if (dossierSection !== void 0) {
15474
+ turnRequest = {
15475
+ ...turnRequest,
15476
+ continuation: appendContinuationSection(
15477
+ turnRequest.continuation,
15478
+ dossierSection
15479
+ )
15480
+ };
15481
+ }
15221
15482
  }
15222
15483
  await markRunRunning(
15223
15484
  admitted.runDirectory,
@@ -15247,8 +15508,8 @@ async function dispatchPostAdmissionTurn(input) {
15247
15508
  }
15248
15509
  let stderrLogWriteFailure;
15249
15510
  try {
15250
- await writeFile8(
15251
- join27(admitted.runDirectory, "stderr.log"),
15511
+ await writeFile9(
15512
+ join28(admitted.runDirectory, "stderr.log"),
15252
15513
  result.stderr,
15253
15514
  "utf8"
15254
15515
  );
@@ -15437,25 +15698,17 @@ async function dispatchPostAdmissionTurn(input) {
15437
15698
  }
15438
15699
  }
15439
15700
  function resumeTurnRequestProjectionOptions(admitted, request, env, summonsPrepared) {
15440
- const officerSourcePath = request.summons?.sourceRunPath;
15441
- const withReread = (body) => {
15442
- if (officerSourcePath === void 0 || admitted.role !== "notary" && admitted.role !== "inspector" && admitted.role !== "auditor") {
15443
- return body;
15444
- }
15445
- if (body.startsWith("\u8BF7\u91CD\u8BFB")) return body;
15446
- return `\u8BF7\u91CD\u8BFB
15447
- ${body}`;
15448
- };
15701
+ const officerDialogue = isStationChildOfficerDialogue(admitted.role, env);
15449
15702
  let prompt;
15450
15703
  if (request.message !== void 0) {
15451
15704
  if (summonsPrepared !== void 0) {
15452
- prompt = withReread(buildInstructionTransportPrompt({
15705
+ prompt = officerDialogue ? request.message : buildInstructionTransportPrompt({
15453
15706
  instruction: request.message,
15454
15707
  instructionEmpty: false,
15455
15708
  attachments: summonsPrepared.attachments
15456
- }));
15709
+ });
15457
15710
  } else if (request.summons !== void 0) {
15458
- prompt = withReread(request.message);
15711
+ prompt = request.message;
15459
15712
  } else {
15460
15713
  prompt = buildResumeContinuationPrompt({
15461
15714
  packageRoot: env.packageRoot,
@@ -15464,17 +15717,9 @@ ${body}`;
15464
15717
  });
15465
15718
  }
15466
15719
  } else if (summonsPrepared !== void 0) {
15467
- prompt = withReread(buildInstructionTransportPrompt(summonsPrepared));
15720
+ prompt = officerDialogue ? summonsPrepared.instructionEmpty ? "" : summonsPrepared.instruction : buildInstructionTransportPrompt(summonsPrepared);
15468
15721
  } else if (request.summons !== void 0) {
15469
- const path = request.summons.sourceRunPath;
15470
- if (path !== void 0 && (admitted.role === "notary" || admitted.role === "inspector" || admitted.role === "auditor")) {
15471
- prompt = `\u8BF7\u91CD\u8BFB
15472
- ${GATE_DOSSIER_POINTER_PREFIX}${path}`;
15473
- } else if (admitted.role === "notary" || admitted.role === "inspector" || admitted.role === "auditor") {
15474
- prompt = "\u8BF7\u91CD\u8BFB";
15475
- } else {
15476
- prompt = "";
15477
- }
15722
+ prompt = "";
15478
15723
  } else {
15479
15724
  prompt = buildResumeContinuationPrompt({
15480
15725
  packageRoot: env.packageRoot,
@@ -15511,7 +15756,7 @@ async function dispatchAfterWriterLease(input) {
15511
15756
  }
15512
15757
  function isAlreadyFrozenSummonsAttachment(runDirectory, attachmentPath) {
15513
15758
  const absolute = isAbsolute8(attachmentPath) ? attachmentPath : resolve13(attachmentPath);
15514
- return pathContainedIn(join27(runDirectory, "attachments"), absolute);
15759
+ return pathContainedIn(join28(runDirectory, "attachments"), absolute);
15515
15760
  }
15516
15761
  async function prepareSummonsResumeMaterials(runDirectory, summons) {
15517
15762
  if (summons === void 0) return void 0;
@@ -15807,6 +16052,7 @@ var init_post_admission = __esm({
15807
16052
  init_activation_ledger_topology();
15808
16053
  init_engine_material();
15809
16054
  init_session_identity();
16055
+ init_host_contracts();
15810
16056
  init_case_dossier_delivery();
15811
16057
  init_host_transition_prior_native();
15812
16058
  init_public_run_credentials();
@@ -15900,7 +16146,7 @@ async function runPublicNotary(argv, env, io, parseNotaryArgv2) {
15900
16146
  throw error;
15901
16147
  }
15902
16148
  {
15903
- const resumeInstruction = env.reviewReask;
16149
+ const resumeInstruction = env.reviewReask ?? env.gateReviewInstruction;
15904
16150
  const summons = {
15905
16151
  sourceRunPath: source.runDirectory,
15906
16152
  sourceRun: source,
@@ -15955,7 +16201,9 @@ async function runPublicNotary(argv, env, io, parseNotaryArgv2) {
15955
16201
  ...env.correlationId === void 0 || env.correlationId.trim() === "" ? {} : { correlationId: env.correlationId },
15956
16202
  continuation: {
15957
16203
  kind: "initial",
15958
- prompt: buildNotaryTransportPrompt(admitted, engineMaterial)
16204
+ // #879: gate path first mint carries parent payload as dialogue content;
16205
+ // external zero-prompt kickoff unchanged when no body/reask.
16206
+ prompt: env.reviewReask ?? env.gateReviewInstruction ?? buildNotaryTransportPrompt(admitted, engineMaterial)
15959
16207
  }
15960
16208
  });
15961
16209
  return await runPostAdmissionOneShot({
@@ -16043,12 +16291,20 @@ __export(inspector_run_exports, {
16043
16291
  runPublicInspector: () => runPublicInspector,
16044
16292
  runPublicInspectorResume: () => runPublicInspectorResume
16045
16293
  });
16294
+ function inspectorParentRunPath(admitted) {
16295
+ if (typeof admitted.sourceRunPath === "string" && admitted.sourceRunPath.trim() !== "") {
16296
+ return admitted.sourceRunPath;
16297
+ }
16298
+ return parentRunPathFromGatePointerInstruction(admitted.instruction);
16299
+ }
16046
16300
  function buildInspectorTurnRequest(admitted, options) {
16301
+ const sourceRun = inspectorParentRunPath(admitted);
16047
16302
  return projectRoleTurnRequest(
16048
16303
  admitted,
16049
16304
  {
16050
16305
  activation: {
16051
- role: "inspector"
16306
+ role: "inspector",
16307
+ ...sourceRun === void 0 ? {} : { sourceRun }
16052
16308
  }
16053
16309
  },
16054
16310
  options
@@ -16068,7 +16324,7 @@ async function runPublicInspector(argv, env, io, parseInspectorArgv2) {
16068
16324
  const projectRoot = parsed.project ?? env.cwd;
16069
16325
  const parentRunPath = parentRunPathFromGatePointerInstruction(parsed.instruction);
16070
16326
  if (parentRunPath !== void 0) {
16071
- const resumeInstruction = env.reviewReask;
16327
+ const resumeInstruction = env.reviewReask ?? env.gateReviewInstruction;
16072
16328
  const summons = {
16073
16329
  sourceRunPath: parentRunPath,
16074
16330
  ...resumeInstruction === void 0 ? {
@@ -16113,6 +16369,10 @@ async function runPublicInspector(argv, env, io, parseInspectorArgv2) {
16113
16369
  throw error;
16114
16370
  }
16115
16371
  await markRunAdmitted(admitted, env.principalAuthority);
16372
+ if (parentRunPath !== void 0) {
16373
+ await persistAdmittedSourceRunPath(admitted, parentRunPath);
16374
+ admitted = { ...admitted, sourceRunPath: parentRunPath };
16375
+ }
16116
16376
  const engineMaterial = engineSessionMaterialFromOptions({
16117
16377
  ...pickEngineAxis(env),
16118
16378
  packageRoot: env.packageRoot
@@ -16127,7 +16387,8 @@ async function runPublicInspector(argv, env, io, parseInspectorArgv2) {
16127
16387
  ...env.correlationId === void 0 || env.correlationId.trim() === "" ? {} : { correlationId: env.correlationId },
16128
16388
  continuation: {
16129
16389
  kind: "initial",
16130
- prompt: buildInspectorTransportPrompt(admitted, engineMaterial)
16390
+ // #879: gate first mint uses parent payload as content; binding stays typed activation.
16391
+ prompt: env.reviewReask ?? env.gateReviewInstruction ?? buildInspectorTransportPrompt(admitted, engineMaterial)
16131
16392
  }
16132
16393
  });
16133
16394
  return await runPostAdmissionOneShot({
@@ -16229,7 +16490,7 @@ function instructionSeatAdapters(options) {
16229
16490
  }) => {
16230
16491
  const infrastructureFailure = await readEngineDetourInfrastructureFailure(sessionFile);
16231
16492
  return infrastructureFailure === void 0 ? result.knownFailure : {
16232
- cause: infrastructureFailure.cause,
16493
+ ...infrastructureFailure.cause === void 0 ? {} : { cause: infrastructureFailure.cause },
16233
16494
  diagnostic: infrastructureFailure.diagnostic,
16234
16495
  ...infrastructureFailure.identity === void 0 ? {} : { identity: infrastructureFailure.identity }
16235
16496
  };
@@ -16351,7 +16612,7 @@ async function runPublicInstructionSeat(argv, env, io, role, parseArgv) {
16351
16612
  return { exitCode: 2 };
16352
16613
  }
16353
16614
  }
16354
- const resumeInstruction = env.reviewReask;
16615
+ const resumeInstruction = env.reviewReask ?? env.gateReviewInstruction;
16355
16616
  const summons = {
16356
16617
  ...resumeInstruction === void 0 ? {
16357
16618
  instruction: parsed.instruction,
@@ -16417,7 +16678,8 @@ async function runPublicInstructionSeat(argv, env, io, role, parseArgv) {
16417
16678
  ...env.correlationId === void 0 || env.correlationId.trim() === "" ? {} : { correlationId: env.correlationId },
16418
16679
  continuation: {
16419
16680
  kind: "initial",
16420
- prompt: buildInstructionTransportPrompt(
16681
+ // #879: gate first mint uses parent payload as content when present.
16682
+ prompt: env.reviewReask ?? env.gateReviewInstruction ?? buildInstructionTransportPrompt(
16421
16683
  admitted,
16422
16684
  engineSessionMaterialFromOptions({
16423
16685
  ...pickEngineAxis(env),
@@ -16474,7 +16736,7 @@ function judgeAdapters() {
16474
16736
  resolveRunnerKnownFailure: async ({ result, sessionFile }) => {
16475
16737
  const infrastructureFailure = await readEngineDetourInfrastructureFailure(sessionFile);
16476
16738
  return result.knownFailure ?? (infrastructureFailure === void 0 ? void 0 : {
16477
- cause: infrastructureFailure.cause,
16739
+ ...infrastructureFailure.cause === void 0 ? {} : { cause: infrastructureFailure.cause },
16478
16740
  diagnostic: infrastructureFailure.diagnostic,
16479
16741
  ...infrastructureFailure.identity === void 0 ? {} : { identity: infrastructureFailure.identity }
16480
16742
  });
@@ -16786,15 +17048,11 @@ async function runPublicDiarist(argv, env, io, parseDiaristArgv2) {
16786
17048
  ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
16787
17049
  }).then(async (result) => {
16788
17050
  if (admitted.ticketNumber === void 0 && result.admitted !== void 0) {
16789
- const roleOutcome = result.terminal?.roleOutcome;
16790
- const facts = roleOutcome?.kind === "accepted" ? lastRolePayloadRecord(roleOutcome.payloads ?? []) : void 0;
16791
- if (roleOutcome !== void 0 && roleOutcome.kind === "accepted" && facts?.status !== "escalate") {
16792
- const raw = typeof facts?.ticketNumber === "number" ? facts.ticketNumber : typeof facts?.sitian === "object" && facts.sitian !== null && typeof facts.sitian.ticketNumber === "number" ? facts.sitian.ticketNumber : void 0;
16793
- if (typeof raw === "number" && Number.isSafeInteger(raw) && raw >= 1) {
16794
- admitted.ticketNumber = raw;
16795
- if (result.admitted.ticketNumber === void 0) {
16796
- result.admitted.ticketNumber = raw;
16797
- }
17051
+ const fromPages = await readRunTicketNumber(admitted.runDirectory);
17052
+ if (fromPages !== void 0) {
17053
+ await bindAdmittedTicketNumber(admitted, fromPages);
17054
+ if (result.admitted.ticketNumber === void 0) {
17055
+ result.admitted.ticketNumber = fromPages;
16798
17056
  }
16799
17057
  }
16800
17058
  }
@@ -16836,8 +17094,8 @@ var init_diarist_run = __esm({
16836
17094
  init_run_lifecycle();
16837
17095
  init_seat_ticket_binding();
16838
17096
  init_settlement();
16839
- init_terminal();
16840
17097
  init_turn_request();
17098
+ init_run_ticket_number();
16841
17099
  }
16842
17100
  });
16843
17101
 
@@ -16850,7 +17108,7 @@ __export(public_role_summons_exports, {
16850
17108
  summonPublicRole: () => summonPublicRole
16851
17109
  });
16852
17110
  import { existsSync as existsSync9 } from "node:fs";
16853
- import { join as join28 } from "node:path";
17111
+ import { join as join29 } from "node:path";
16854
17112
  function createCapturingIo() {
16855
17113
  const chunks = [];
16856
17114
  return {
@@ -16873,7 +17131,7 @@ function parentDir(path) {
16873
17131
  function walkPackageRoot(start) {
16874
17132
  let dir = start;
16875
17133
  for (let i = 0; i < 12; i += 1) {
16876
- if (existsSync9(join28(dir, "package.json")) && existsSync9(join28(dir, "souls"))) {
17134
+ if (existsSync9(join29(dir, "package.json")) && existsSync9(join29(dir, "souls"))) {
16877
17135
  return dir;
16878
17136
  }
16879
17137
  const parent = parentDir(dir);
@@ -16967,7 +17225,7 @@ async function createSummonEnv(options) {
16967
17225
  async function summonPublicRole(options) {
16968
17226
  const packageRoot = resolveSummonsPackageRoot(options.packageRoot);
16969
17227
  const home = await resolveSummonHome(options);
16970
- const agentDir = options.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? join28(home, ".pi", "agent");
17228
+ const agentDir = options.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? join29(home, ".pi", "agent");
16971
17229
  const {
16972
17230
  loadCredentialProviders: loadCredentialProviders2,
16973
17231
  loadPublicCliConfig: loadPublicCliConfig2,
@@ -17008,6 +17266,8 @@ async function summonPublicRole(options) {
17008
17266
  ...options.signal === void 0 ? {} : { signal: options.signal },
17009
17267
  // #753: reask rides the existing notary same-ticket resume summons.instruction.
17010
17268
  ...options.reviewReask === void 0 ? {} : { reviewReask: options.reviewReask },
17269
+ // #879: verbatim submission body on officer dialogue content channel.
17270
+ ...options.gateReviewInstruction === void 0 ? {} : { gateReviewInstruction: options.gateReviewInstruction },
17011
17271
  ...options.boundTicketNumber === void 0 ? {} : { boundTicketNumber: options.boundTicketNumber },
17012
17272
  // createRunId is the only remaining env overlay — host is seat-selected above.
17013
17273
  ...options.createRunId === void 0 ? {} : { createRunId: options.createRunId }
@@ -17115,6 +17375,11 @@ async function summonGateOfficer(options) {
17115
17375
  const { homeFromRunDirectory: homeFromRunDirectory3 } = await Promise.resolve().then(() => (init_activation_ledger_topology(), activation_ledger_topology_exports));
17116
17376
  home = homeFromRunDirectory3(options.sourceRunDirectory);
17117
17377
  }
17378
+ let gateReviewInstruction;
17379
+ if (options.reask === void 0 && options.submission !== void 0) {
17380
+ const { readableGateItem: readableGateItem2 } = await Promise.resolve().then(() => (init_readable_gate_item(), readable_gate_item_exports));
17381
+ gateReviewInstruction = readableGateItem2(options.submission);
17382
+ }
17118
17383
  const common = {
17119
17384
  cwd: options.cwd,
17120
17385
  ...home === void 0 ? {} : { home },
@@ -17122,6 +17387,7 @@ async function summonGateOfficer(options) {
17122
17387
  ...options.io === void 0 ? {} : { io: options.io },
17123
17388
  ...options.signal === void 0 ? {} : { signal: options.signal },
17124
17389
  ...options.reask === void 0 ? {} : { reviewReask: options.reask },
17390
+ ...gateReviewInstruction === void 0 ? {} : { gateReviewInstruction },
17125
17391
  ...options.roleTurnHost === void 0 ? {} : { roleTurnHost: options.roleTurnHost },
17126
17392
  ...options.hostAdapters === void 0 ? {} : { hostAdapters: options.hostAdapters },
17127
17393
  ...options.createRunId === void 0 ? {} : { createRunId: options.createRunId }
@@ -17195,11 +17461,18 @@ function projectOfficerDecision(officer, decision, fallbackStatus) {
17195
17461
  }
17196
17462
  return { status: "needs_reask", officer, receipt };
17197
17463
  }
17198
- function officerPayloads(terminal) {
17464
+ function thisCourtOfficerPayloads(terminal) {
17199
17465
  const outcome = terminal?.roleOutcome;
17200
17466
  if (outcome !== void 0 && (outcome.kind === "accepted" || outcome.kind === "audit_escalation")) {
17201
- return outcome.payloads ?? terminal?.submissions ?? [];
17467
+ if (outcome.payloads !== void 0 && outcome.payloads.length > 0) return outcome.payloads;
17202
17468
  }
17469
+ if (outcome?.kind === "failure" && outcome.payloads !== void 0 && outcome.payloads.length > 0) {
17470
+ return outcome.payloads;
17471
+ }
17472
+ return [];
17473
+ }
17474
+ function officerFailurePayloads(terminal) {
17475
+ const outcome = terminal?.roleOutcome;
17203
17476
  if (outcome?.kind === "failure") return outcome.payloads ?? terminal?.submissions ?? [];
17204
17477
  return terminal?.submissions ?? [];
17205
17478
  }
@@ -17207,24 +17480,20 @@ function projectOfficerPayloads(officer, payloads, fallbackStatus) {
17207
17480
  if (payloads.length === 0) {
17208
17481
  return projectOfficerDecision(officer, void 0, fallbackStatus);
17209
17482
  }
17210
- const queued = projectOfficerDecision(officer, payloads[payloads.length - 1], fallbackStatus);
17211
- if (payloads.length === 1) return queued;
17212
- if (queued.status === "pass" || queued.status === "bounce" || queued.status === "escalate" || queued.status === "needs_reask") {
17213
- return { ...queued, receipt: payloads };
17214
- }
17215
- return queued;
17483
+ return projectOfficerDecision(officer, payloads[payloads.length - 1], fallbackStatus);
17216
17484
  }
17217
17485
  function projectOfficerTerminal(officer, summoned) {
17218
17486
  const terminal = summoned.terminal;
17219
17487
  const outcome = terminal?.roleOutcome;
17220
- const recorded = officerPayloads(terminal);
17488
+ const thisCourt = thisCourtOfficerPayloads(terminal);
17221
17489
  if (outcome === void 0) {
17222
17490
  const detail = summoned.stderr ?? "";
17491
+ const failurePayloads = officerFailurePayloads(terminal);
17223
17492
  return {
17224
17493
  status: "transport_failure",
17225
17494
  stage: officer,
17226
17495
  reason: detail.length > 0 ? `${gateSeatLabel(officer)} public summon exit ${summoned.exitCode}: ${detail}` : `${gateSeatLabel(officer)} public summon produced no terminal (exit ${summoned.exitCode})`,
17227
- submission: recorded.length > 0 ? recorded : summoned
17496
+ submission: failurePayloads.length > 0 ? failurePayloads : summoned
17228
17497
  };
17229
17498
  }
17230
17499
  if (outcome.kind === "no_receipt") {
@@ -17236,27 +17505,30 @@ function projectOfficerTerminal(officer, summoned) {
17236
17505
  };
17237
17506
  }
17238
17507
  if (outcome.kind === "failure") {
17508
+ const failurePayloads = officerFailurePayloads(terminal);
17239
17509
  return {
17240
17510
  status: "transport_failure",
17241
17511
  stage: officer,
17242
17512
  reason: outcome.diagnostic,
17243
- submission: recorded.length > 0 ? recorded : outcome.decisiveFacts
17513
+ submission: failurePayloads.length > 0 ? failurePayloads : outcome.decisiveFacts
17244
17514
  };
17245
17515
  }
17246
17516
  if (outcome.kind === "audit_escalation") {
17247
17517
  return {
17248
17518
  status: "escalate",
17249
17519
  officer,
17250
- receipt: recorded.length === 1 ? recorded[0] : recorded
17520
+ // This-court receipt only (#879) — historical rows remain on terminal.submissions.
17521
+ receipt: thisCourt.length > 0 ? thisCourt[thisCourt.length - 1] : retainedReceipt(outcome)
17251
17522
  };
17252
17523
  }
17253
17524
  if (outcome.kind === "accepted") {
17254
- return projectOfficerPayloads(officer, recorded, outcome.status);
17525
+ return projectOfficerPayloads(officer, thisCourt, outcome.status);
17255
17526
  }
17256
17527
  return {
17257
17528
  status: "needs_reask",
17258
17529
  officer,
17259
- receipt: recorded.length > 0 ? recorded : retainedReceipt(outcome)
17530
+ // This-court receipt only (#879).
17531
+ receipt: thisCourt.length > 0 ? thisCourt[thisCourt.length - 1] : retainedReceipt(outcome)
17260
17532
  };
17261
17533
  }
17262
17534
  async function projectGatekeeperRun(options) {
@@ -17274,7 +17546,7 @@ async function projectGatekeeperRun(options) {
17274
17546
  }
17275
17547
  let summoned;
17276
17548
  try {
17277
- const summon = options.summonOfficer ?? (async (nextOfficer, sourceRunDirectory, officerSignal, reask) => {
17549
+ const summon = options.summonOfficer ?? (async (nextOfficer, sourceRunDirectory, officerSignal, reask, nextSubmission) => {
17278
17550
  const { summonGateOfficer: summonGateOfficer2 } = await Promise.resolve().then(() => (init_public_role_summons(), public_role_summons_exports));
17279
17551
  return summonGateOfficer2({
17280
17552
  officer: nextOfficer,
@@ -17282,6 +17554,7 @@ async function projectGatekeeperRun(options) {
17282
17554
  cwd: options.context.cwd ?? process.cwd(),
17283
17555
  ...officerSignal === void 0 ? {} : { signal: officerSignal },
17284
17556
  ...reask === void 0 ? {} : { reask },
17557
+ ...nextSubmission === void 0 ? {} : { submission: nextSubmission },
17285
17558
  ...options.home === void 0 ? {} : { home: options.home },
17286
17559
  ...options.packageRoot === void 0 ? {} : { packageRoot: options.packageRoot },
17287
17560
  ...options.roleTurnHost === void 0 ? {} : { roleTurnHost: options.roleTurnHost },
@@ -17292,7 +17565,8 @@ async function projectGatekeeperRun(options) {
17292
17565
  officer,
17293
17566
  runDirectory,
17294
17567
  options.signal,
17295
- options.reask
17568
+ options.reask,
17569
+ options.submission
17296
17570
  );
17297
17571
  } catch (error) {
17298
17572
  return {
@@ -17333,12 +17607,12 @@ __export(session_assistant_usage_exports, {
17333
17607
  sessionFileFromPublicSummon: () => sessionFileFromPublicSummon,
17334
17608
  usageFromPublicSummon: () => usageFromPublicSummon
17335
17609
  });
17336
- import { join as join29 } from "node:path";
17610
+ import { join as join30 } from "node:path";
17337
17611
  async function readAssistantUsageFromSessionFile(sessionFile) {
17338
- const { readFile: readFile23 } = await import("node:fs/promises");
17612
+ const { readFile: readFile24 } = await import("node:fs/promises");
17339
17613
  let text;
17340
17614
  try {
17341
- text = await readFile23(sessionFile, "utf8");
17615
+ text = await readFile24(sessionFile, "utf8");
17342
17616
  } catch (error) {
17343
17617
  if (error?.code === "ENOENT") return void 0;
17344
17618
  throw error;
@@ -17403,7 +17677,7 @@ async function readAssistantUsageFromSessionFile(sessionFile) {
17403
17677
  }
17404
17678
  function sessionFileFromPublicSummon(summoned) {
17405
17679
  if (typeof summoned.runDirectory === "string" && summoned.runDirectory.trim() !== "") {
17406
- return join29(summoned.runDirectory, "session", "session.jsonl");
17680
+ return join30(summoned.runDirectory, "session", "session.jsonl");
17407
17681
  }
17408
17682
  const fromArtifacts = summoned.terminal?.artifacts?.map((a) => a.path).find((p) => typeof p === "string" && p.endsWith("session.jsonl"));
17409
17683
  if (fromArtifacts !== void 0) return fromArtifacts;
@@ -17412,7 +17686,7 @@ function sessionFileFromPublicSummon(summoned) {
17412
17686
  const facts = outcome.decisiveFacts;
17413
17687
  const pointer = facts?.runPointer;
17414
17688
  if (typeof pointer === "string" && pointer.trim() !== "") {
17415
- return join29(pointer, "session", "session.jsonl");
17689
+ return join30(pointer, "session", "session.jsonl");
17416
17690
  }
17417
17691
  return void 0;
17418
17692
  }
@@ -17568,7 +17842,7 @@ var init_compliance_transport = __esm({
17568
17842
  // src/doctor-auditor.ts
17569
17843
  function createPiDoctorAuditor() {
17570
17844
  return async (options) => {
17571
- const dossier = resolveAuditDossier();
17845
+ const dossier = resolveAuditDossier(options.context);
17572
17846
  requireAuditMaterials(dossier);
17573
17847
  const subjects = readDoctorAuditSubjects(options.context);
17574
17848
  requireAuditMaterials(subjects);
@@ -17592,11 +17866,11 @@ var init_doctor_auditor = __esm({
17592
17866
 
17593
17867
  // src/archivist-record-topology.ts
17594
17868
  import { createHash as createHash8 } from "node:crypto";
17595
- import { join as join30 } from "node:path";
17869
+ import { join as join31 } from "node:path";
17596
17870
  function subjectKeyedRecordDirectory(input) {
17597
17871
  const ledgerHome = input.parentSessionFile !== void 0 && input.parentSessionFile.length > 0 ? resolveActivationLedgerHomeForPath(input.parentSessionFile) : resolveActivationLedgerHome(input.home);
17598
17872
  const digest = createHash8("sha256").update(input.subject).digest("hex").slice(0, 32);
17599
- return join30(
17873
+ return join31(
17600
17874
  activationBookDirectory(ledgerHome, resolveBookKeyFromGit(input.cwd)),
17601
17875
  input.kind,
17602
17876
  digest
@@ -17621,10 +17895,10 @@ __export(archivist_record_entry_exports, {
17621
17895
  subjectKeyedRecordDirectory: () => subjectKeyedRecordDirectory
17622
17896
  });
17623
17897
  import { existsSync as existsSync10, mkdirSync as mkdirSync3, readFileSync as readFileSync3, realpathSync as realpathSync2, writeFileSync as writeFileSync3 } from "node:fs";
17624
- import { dirname as dirname15, resolve as resolve14, join as join31 } from "node:path";
17898
+ import { dirname as dirname15, resolve as resolve14, join as join32 } from "node:path";
17625
17899
  import { SessionManager } from "@earendil-works/pi-coding-agent";
17626
17900
  function readCurrentSession(sessionDir) {
17627
- const ledger = join31(sessionDir, CURRENT_SESSION_LEDGER);
17901
+ const ledger = join32(sessionDir, CURRENT_SESSION_LEDGER);
17628
17902
  try {
17629
17903
  const value = JSON.parse(readFileSync3(ledger, "utf8"));
17630
17904
  if (typeof value !== "object" || value === null || typeof value.sessionFile !== "string" || value.sessionFile.length === 0) {
@@ -17639,7 +17913,7 @@ function readCurrentSession(sessionDir) {
17639
17913
  }
17640
17914
  }
17641
17915
  function writeCurrentSession(sessionDir, sessionFile) {
17642
- const ledger = join31(sessionDir, CURRENT_SESSION_LEDGER);
17916
+ const ledger = join32(sessionDir, CURRENT_SESSION_LEDGER);
17643
17917
  try {
17644
17918
  writeFileSync3(ledger, `${JSON.stringify({ sessionFile })}
17645
17919
  `, { flag: "wx" });
@@ -17700,7 +17974,7 @@ function createRecordSessionOpen(options) {
17700
17974
  return { session: SessionManager.inMemory(cwd), resumed: false };
17701
17975
  } else {
17702
17976
  const parentResolved = resolve14(parentFile);
17703
- sessionDir = physicallyContainedIn(ledgerHome, parentResolved) ? join31(dirname15(parentResolved), options.kind) : join31(activationBookDirectory(ledgerHome, resolveBookKeyFromGit(cwd)), options.kind);
17977
+ sessionDir = physicallyContainedIn(ledgerHome, parentResolved) ? join32(dirname15(parentResolved), options.kind) : join32(activationBookDirectory(ledgerHome, resolveBookKeyFromGit(cwd)), options.kind);
17704
17978
  parentSession = parentFile;
17705
17979
  }
17706
17980
  const nestAlreadyExists = existsSync10(sessionDir);
@@ -17739,7 +18013,7 @@ function createRecordSession(options) {
17739
18013
  return createRecordSessionOpen(options).session;
17740
18014
  }
17741
18015
  function bookDirectOfficerRunPointer(options) {
17742
- const nest = join31(dirname15(options.parentSessionFile), "auditor-roles");
18016
+ const nest = join32(dirname15(options.parentSessionFile), "auditor-roles");
17743
18017
  mkdirSync3(nest, { recursive: true });
17744
18018
  const pointer = {
17745
18019
  version: 1,
@@ -17749,7 +18023,7 @@ function bookDirectOfficerRunPointer(options) {
17749
18023
  ...options.runDirectory !== void 0 && options.runDirectory.trim() !== "" ? { runDirectory: options.runDirectory } : {}
17750
18024
  };
17751
18025
  writeFileSync3(
17752
- join31(nest, `${options.officer}.pointer.json`),
18026
+ join32(nest, `${options.officer}.pointer.json`),
17753
18027
  `${JSON.stringify(pointer)}
17754
18028
  `,
17755
18029
  "utf8"
@@ -17774,7 +18048,7 @@ var init_archivist_record_entry = __esm({
17774
18048
  import { randomUUID as randomUUID9 } from "node:crypto";
17775
18049
 
17776
18050
  // src/role-runtime-dependencies.ts
17777
- import { readFile as readFile21 } from "node:fs/promises";
18051
+ import { readFile as readFile22 } from "node:fs/promises";
17778
18052
  import { fileURLToPath as fileURLToPath2 } from "node:url";
17779
18053
 
17780
18054
  // src/canonical-skill-binding.ts
@@ -17951,6 +18225,24 @@ function navigatorProviderFailureFromDiagnostics(diagnostics) {
17951
18225
  }
17952
18226
  return void 0;
17953
18227
  }
18228
+ function navigatorProviderFailureFromPublicTerminal(outcome) {
18229
+ const facts = outcome.decisiveFacts;
18230
+ const secondary = typeof facts.secondaryEvidence === "object" && facts.secondaryEvidence !== null ? facts.secondaryEvidence : void 0;
18231
+ const httpStatus = typeof secondary?.httpStatus === "number" ? secondary.httpStatus : typeof facts.httpStatus === "number" ? facts.httpStatus : typeof facts.errorCode === "number" ? facts.errorCode : void 0;
18232
+ const fromStatus = navigatorProviderFailureFromStatus(httpStatus);
18233
+ if (fromStatus !== void 0) return fromStatus;
18234
+ const diagnostics = secondary?.diagnostics ?? facts.diagnostics;
18235
+ const fromDiagnostics = navigatorProviderFailureFromDiagnostics(diagnostics);
18236
+ if (fromDiagnostics !== void 0) return fromDiagnostics;
18237
+ const fromCode = navigatorProviderFailureFromError({
18238
+ code: secondary?.code ?? facts.errorCode
18239
+ });
18240
+ if (fromCode !== void 0) return fromCode;
18241
+ if (outcome.cause === "provider") return { source: "transport", cause: "unknown" };
18242
+ const typed = navigatorUnavailableKey(outcome.cause);
18243
+ if (typed !== void 0) return { source: typed, cause: typed };
18244
+ return { source: "unknown", cause: "unknown" };
18245
+ }
17954
18246
  var navigatorProviderFailureSchema = Type12.Object({
17955
18247
  source: Type12.Union([
17956
18248
  Type12.Literal("context"),
@@ -18032,23 +18324,6 @@ async function resolveNavigatorSeatSelection(context) {
18032
18324
  }
18033
18325
 
18034
18326
  // src/navigator-public-session.ts
18035
- init_terminal();
18036
- function providerFailureFromPublicTerminal(outcome) {
18037
- const facts = outcome.decisiveFacts;
18038
- const secondary = typeof facts.secondaryEvidence === "object" && facts.secondaryEvidence !== null ? facts.secondaryEvidence : void 0;
18039
- const httpStatus = typeof secondary?.httpStatus === "number" ? secondary.httpStatus : typeof facts.httpStatus === "number" ? facts.httpStatus : typeof facts.errorCode === "number" ? facts.errorCode : void 0;
18040
- const fromStatus = navigatorProviderFailureFromStatus(httpStatus);
18041
- if (fromStatus !== void 0) return fromStatus;
18042
- const diagnostics = secondary?.diagnostics ?? facts.diagnostics;
18043
- const fromDiagnostics = navigatorProviderFailureFromDiagnostics(diagnostics);
18044
- if (fromDiagnostics !== void 0) return fromDiagnostics;
18045
- const fromCode = navigatorProviderFailureFromError({
18046
- code: secondary?.code ?? facts.errorCode
18047
- });
18048
- if (fromCode !== void 0) return fromCode;
18049
- if (outcome.cause === "provider") return { source: "transport", cause: "transport" };
18050
- return { source: "session", cause: "session" };
18051
- }
18052
18327
  function createNativeNavigatorSessionFactory() {
18053
18328
  return async ({ context, subject, tool }) => {
18054
18329
  const resolved = await resolveNavigatorSeatSelection(context);
@@ -18104,14 +18379,15 @@ function createNativeNavigatorSessionFactory() {
18104
18379
  const outcome = summoned.terminal?.roleOutcome;
18105
18380
  if (outcome === void 0) {
18106
18381
  const detail = summoned.stderr?.trim() || `exit ${summoned.exitCode}`;
18107
- providerFailure = { source: "transport", cause: "transport" };
18382
+ providerFailure = { source: "transport", cause: "unknown" };
18108
18383
  throw navigatorUnavailableError(
18109
- "transport",
18110
- new Error(`Navigator public summon produced no terminal (${detail})`)
18384
+ providerFailure.source,
18385
+ new Error(`Navigator public summon produced no terminal (${detail})`),
18386
+ providerFailure.cause
18111
18387
  );
18112
18388
  }
18113
18389
  if (outcome.kind === "failure") {
18114
- providerFailure = providerFailureFromPublicTerminal(outcome);
18390
+ providerFailure = navigatorProviderFailureFromPublicTerminal(outcome);
18115
18391
  throw navigatorUnavailableError(
18116
18392
  providerFailure.source,
18117
18393
  new Error(outcome.diagnostic),
@@ -18125,21 +18401,22 @@ function createNativeNavigatorSessionFactory() {
18125
18401
  if (outcome.kind !== "accepted") {
18126
18402
  return;
18127
18403
  }
18128
- const candidates = lastRolePayloadRecord(outcome.payloads ?? [])?.candidates;
18129
- if (!Array.isArray(candidates)) {
18130
- return;
18404
+ for (const payload of outcome.payloads ?? []) {
18405
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) continue;
18406
+ const candidates = payload.candidates;
18407
+ if (!Array.isArray(candidates)) continue;
18408
+ await tool.execute(
18409
+ "navigator-public-prepare",
18410
+ { candidates },
18411
+ void 0,
18412
+ void 0,
18413
+ context
18414
+ );
18131
18415
  }
18132
- await tool.execute(
18133
- "navigator-public-prepare",
18134
- { candidates },
18135
- void 0,
18136
- void 0,
18137
- context
18138
- );
18139
18416
  } catch (error) {
18140
18417
  if (error instanceof NavigatorUnavailableError) throw error;
18141
18418
  const fact = navigatorProviderFailureFromError(error);
18142
- providerFailure = fact ?? { source: "transport", cause: "transport" };
18419
+ providerFailure = fact ?? { source: "transport", cause: "unknown" };
18143
18420
  throw navigatorUnavailableError(providerFailure.source, error, providerFailure.cause);
18144
18421
  }
18145
18422
  })();
@@ -18822,7 +19099,8 @@ ${helpContext}
18822
19099
 
18823
19100
  // src/navigator-work-context.ts
18824
19101
  init_doctor_evidence();
18825
- import { readFile as readFile19 } from "node:fs/promises";
19102
+ init_host_contracts();
19103
+ import { readFile as readFile20 } from "node:fs/promises";
18826
19104
  import { resolve as resolve16 } from "node:path";
18827
19105
  init_notary_source_run();
18828
19106
  init_packaged_role_registry();
@@ -18835,7 +19113,7 @@ function navigatorInputReference(getFlag, role) {
18835
19113
  }
18836
19114
  async function loadNavigatorWorkContext(options) {
18837
19115
  const reference = navigatorInputReference(options.getFlag, options.role);
18838
- const input = reference === void 0 || options.role === "doctor" || options.role === "notary" ? void 0 : await readFile19(reference, "utf8");
19116
+ const input = reference === void 0 || options.role === "doctor" || options.role === "notary" ? void 0 : await readFile20(reference, "utf8");
18839
19117
  const subjectRoot = subjectPath(reference ?? options.context.sessionManager.getSessionDir(), options.context.cwd);
18840
19118
  let subjectKey = reference === void 0 ? subjectRoot : navigatorSubjectKeyForInput(subjectRoot, reference, options.context.cwd);
18841
19119
  let subject = input ?? `work subject: ${subjectKey}`;
@@ -18850,9 +19128,9 @@ async function loadNavigatorWorkContext(options) {
18850
19128
  subject = JSON.stringify({ sourceRun: locator });
18851
19129
  subjectProvenance = "role_input";
18852
19130
  }
18853
- const publicRunDir = process.env.AK_ROLE_RUN_DIR;
19131
+ const publicRunDir = runDirectoryFromHostContext(options.context);
18854
19132
  const currentSessionDir = options.context.sessionManager.getSessionDir();
18855
- const isBoundPublicRun = typeof publicRunDir === "string" && publicRunDir.trim() !== "" && resolve16(currentSessionDir) === resolve16(publicRunDir, "session");
19133
+ const isBoundPublicRun = publicRunDir !== void 0 && resolve16(currentSessionDir) === resolve16(publicRunDir, "session");
18856
19134
  if (options.role === "judge" && isBoundPublicRun) {
18857
19135
  let admitted;
18858
19136
  try {
@@ -18892,7 +19170,7 @@ async function loadNavigatorWorkContext(options) {
18892
19170
  let authorityMaterial;
18893
19171
  for (const path of authorityFiles) {
18894
19172
  try {
18895
- const content = await readFile19(path, "utf8");
19173
+ const content = await readFile20(path, "utf8");
18896
19174
  if (content.trim() !== "") {
18897
19175
  authorityMaterial = content;
18898
19176
  break;
@@ -18951,7 +19229,7 @@ init_sitian_facade();
18951
19229
  init_submission_ledger();
18952
19230
  init_collector_ledger();
18953
19231
  import { readFileSync as readFileSync5, writeSync as writeSync4 } from "node:fs";
18954
- import { join as join35 } from "node:path";
19232
+ import { join as join36 } from "node:path";
18955
19233
  import { Value as Value4 } from "typebox/value";
18956
19234
 
18957
19235
  // src/activation-trace.ts
@@ -19360,6 +19638,7 @@ function createToolExecutionObservationFace(options) {
19360
19638
 
19361
19639
  // src/role-runtime.ts
19362
19640
  init_engine_detour();
19641
+ init_engine_material();
19363
19642
 
19364
19643
  // src/engine-detour-tool.ts
19365
19644
  init_engine_detour();
@@ -19457,21 +19736,21 @@ init_collector_evidence();
19457
19736
  init_collector_github();
19458
19737
 
19459
19738
  // src/collector-handbook.ts
19460
- import { readFile as readFile20 } from "node:fs/promises";
19461
- import { join as join34, sep as sep4 } from "node:path";
19739
+ import { readFile as readFile21 } from "node:fs/promises";
19740
+ import { join as join35, sep as sep4 } from "node:path";
19462
19741
 
19463
19742
  // src/atomic-write.ts
19464
19743
  import { randomUUID as randomUUID6 } from "node:crypto";
19465
- import { rename as rename2, rm as rm2, writeFile as writeFile9 } from "node:fs/promises";
19466
- import { dirname as dirname19, join as join33 } from "node:path";
19744
+ import { rename as rename2, rm as rm3, writeFile as writeFile10 } from "node:fs/promises";
19745
+ import { dirname as dirname19, join as join34 } from "node:path";
19467
19746
  async function writeFileAtomically(destination, contents) {
19468
19747
  const parent = dirname19(destination);
19469
- const temporary = join33(parent, `.atomic-write-${randomUUID6()}.tmp`);
19748
+ const temporary = join34(parent, `.atomic-write-${randomUUID6()}.tmp`);
19470
19749
  try {
19471
- await writeFile9(temporary, contents);
19750
+ await writeFile10(temporary, contents);
19472
19751
  await rename2(temporary, destination);
19473
19752
  } catch (error) {
19474
- await rm2(temporary, { force: true }).catch(() => void 0);
19753
+ await rm3(temporary, { force: true }).catch(() => void 0);
19475
19754
  throw error;
19476
19755
  }
19477
19756
  }
@@ -19592,7 +19871,7 @@ function resolveCollectorHandbookRoot(sessionPath) {
19592
19871
  throw new Error(`\u901A\u8FDB\u53F8\u624B\u518C\u62D2\u7EDD\u4E0D\u5B89\u5168 bookKey ${JSON.stringify(bookKey)}`);
19593
19872
  }
19594
19873
  const ledgerHome = resolveActivationLedgerHomeForPath(sessionPath);
19595
- const root = join34(activationBookDirectory(ledgerHome, bookKey), "collector-handbook");
19874
+ const root = join35(activationBookDirectory(ledgerHome, bookKey), "collector-handbook");
19596
19875
  return { ledgerHome, bookKey, root };
19597
19876
  }
19598
19877
  function collectorHandbookRepoFileName(repositoryCanonical) {
@@ -19604,9 +19883,9 @@ function collectorHandbookRepoFileName(repositoryCanonical) {
19604
19883
  return `${repositoryCanonical.replaceAll("/", "__")}.md`;
19605
19884
  }
19606
19885
  function createCollectorHandbookStore(input) {
19607
- const generalPath = join34(input.handbookRoot, "general.md");
19608
- const repoDir = join34(input.handbookRoot, "repos");
19609
- const repoPath = join34(repoDir, collectorHandbookRepoFileName(input.repositoryCanonical));
19886
+ const generalPath = join35(input.handbookRoot, "general.md");
19887
+ const repoDir = join35(input.handbookRoot, "repos");
19888
+ const repoPath = join35(repoDir, collectorHandbookRepoFileName(input.repositoryCanonical));
19610
19889
  const assertHandbookBudget = (body, label) => {
19611
19890
  const byteLength = Buffer.byteLength(body, "utf8");
19612
19891
  if (byteLength > COLLECTOR_HANDBOOK_MAX_BYTES) {
@@ -19620,7 +19899,7 @@ function createCollectorHandbookStore(input) {
19620
19899
  ensureRealDirectoryTree(input.ledgerHome, parentDir2);
19621
19900
  assertLedgerFileInsideHome(path, input.ledgerHome);
19622
19901
  try {
19623
- const body = await readFile20(path, "utf8");
19902
+ const body = await readFile21(path, "utf8");
19624
19903
  assertHandbookBudget(body, "\u6B63\u6587");
19625
19904
  return body;
19626
19905
  } catch (error) {
@@ -20730,14 +21009,18 @@ function createJudgeRoleRuntime(pi, dependencies, hostActions) {
20730
21009
  subject: { kind: "judge_draft" },
20731
21010
  ...signal === void 0 ? {} : { signal },
20732
21011
  hostActions,
20733
- toolCallId
21012
+ toolCallId,
21013
+ // #879: this-turn typed payload — identity-bound at submit site.
21014
+ submission: parameters
20734
21015
  });
20735
21016
  await pi.requireGatekeeperPass({
20736
21017
  context: ctx,
20737
21018
  subject: { kind: "judge_compliance" },
20738
21019
  ...signal === void 0 ? {} : { signal },
20739
21020
  hostActions,
20740
- toolCallId
21021
+ toolCallId,
21022
+ // #879: same parent payload for 审刑院; not recovered from session latest.
21023
+ submission: parameters
20741
21024
  });
20742
21025
  return {
20743
21026
  content: [{ type: "text", text: JUDGE_ACCEPTED_TEXT }],
@@ -21248,7 +21531,9 @@ function createFixerRoleRuntime(pi, dependencies, hostActions) {
21248
21531
  subject: { kind: "worker_completion" },
21249
21532
  ..._signal === void 0 ? {} : { signal: _signal },
21250
21533
  hostActions,
21251
- toolCallId
21534
+ toolCallId,
21535
+ // #879: this-turn typed payload — identity-bound at submit site.
21536
+ submission: output
21252
21537
  });
21253
21538
  }
21254
21539
  const acceptedDetails = output;
@@ -21384,7 +21669,9 @@ function createCoderRoleRuntime(pi, dependencies, hostActions) {
21384
21669
  subject: { kind: "worker_completion" },
21385
21670
  ..._signal === void 0 ? {} : { signal: _signal },
21386
21671
  hostActions,
21387
- toolCallId
21672
+ toolCallId,
21673
+ // #879: this-turn typed payload — identity-bound at submit site.
21674
+ submission: output
21388
21675
  });
21389
21676
  }
21390
21677
  const acceptedDetails = output;
@@ -21919,12 +22206,12 @@ function readDiaristTicketAssertion(submitted) {
21919
22206
  }
21920
22207
  return { kind: "invalid" };
21921
22208
  }
21922
- function readDiaristRunCoordinates() {
21923
- const runDirectory = process.env.AK_ROLE_RUN_DIR;
21924
- if (typeof runDirectory !== "string" || runDirectory.trim() === "") {
22209
+ function readDiaristRunCoordinates(ctx) {
22210
+ const runDirectory = runDirectoryFromHostContext(ctx);
22211
+ if (runDirectory === void 0) {
21925
22212
  throw new Error("diarist accept requires AK_ROLE_RUN_DIR");
21926
22213
  }
21927
- const admittedPath = join35(runDirectory, "admitted-request.json");
22214
+ const admittedPath = join36(runDirectory, "admitted-request.json");
21928
22215
  const admitted = JSON.parse(readFileSync5(admittedPath, "utf8"));
21929
22216
  if (typeof admitted.projectRoot !== "string" || admitted.projectRoot.trim() === "") {
21930
22217
  throw new Error(`diarist admitted-request missing projectRoot (${admittedPath})`);
@@ -21945,10 +22232,10 @@ function createDiaristRoleRuntime(roleHost, dependencies) {
21945
22232
  tool: DIARIST_TOOL_SPEC,
21946
22233
  acceptedText: DIARIST_ACCEPTED_TEXT,
21947
22234
  soulTag: "diarist",
21948
- beforeAccept: async ({ parameters }) => {
22235
+ beforeAccept: async ({ parameters, ctx }) => {
21949
22236
  const submitted = parameters !== null && typeof parameters === "object" && !Array.isArray(parameters) ? parameters : void 0;
21950
22237
  const assertion = readDiaristTicketAssertion(submitted);
21951
- const coords = readDiaristRunCoordinates();
22238
+ const coords = readDiaristRunCoordinates(ctx);
21952
22239
  const ticketNumber = assertion.kind === "ticket" ? assertion.ticketNumber : void 0;
21953
22240
  if (ticketNumber !== void 0) {
21954
22241
  if (coords.boundTicketNumber === void 0) {
@@ -21984,7 +22271,9 @@ function createCountersignRoleRuntime(roleHost, dependencies, hostActions) {
21984
22271
  subject: { kind: "countersign_verdict" },
21985
22272
  ...signal === void 0 ? {} : { signal },
21986
22273
  hostActions,
21987
- toolCallId
22274
+ toolCallId,
22275
+ // #879: this-turn typed payload — identity-bound at submit site.
22276
+ submission: parameters
21988
22277
  });
21989
22278
  } : void 0;
21990
22279
  return createFiledOfficerRuntime(
@@ -22017,6 +22306,10 @@ function createRoleRuntimeExtension(dependencies) {
22017
22306
  for (const flag of NOTARY_TRANSPORT_FLAGS) {
22018
22307
  roleHost.registerFlag(flag.name, flag.definition);
22019
22308
  }
22309
+ roleHost.registerFlag(
22310
+ INSPECTOR_SOURCE_RUN_FLAG.name,
22311
+ INSPECTOR_SOURCE_RUN_FLAG.definition
22312
+ );
22020
22313
  for (const flag of GLEANER_LEFT_TRANSPORT_FLAGS) {
22021
22314
  roleHost.registerFlag(flag.name, flag.definition);
22022
22315
  }
@@ -22024,6 +22317,11 @@ function createRoleRuntimeExtension(dependencies) {
22024
22317
  roleHost.registerFlag(flag.name, flag.definition);
22025
22318
  }
22026
22319
  roleHost.registerFlag(STATION_CHILD_FLAG.name, STATION_CHILD_FLAG.definition);
22320
+ roleHost.registerFlag(ENGINE_MODEL_FLAG_NAME, {
22321
+ description: "\u672C\u6B21\u52B3\u52A1\u5F15\u64CE\u6A21\u578B",
22322
+ type: "string",
22323
+ default: ""
22324
+ });
22027
22325
  let admitted = false;
22028
22326
  let selectedRole;
22029
22327
  let activeReviewerParent;
@@ -22108,19 +22406,21 @@ function createRoleRuntimeExtension(dependencies) {
22108
22406
  settleNavigatorProjection
22109
22407
  );
22110
22408
  roleHost.on("input", (event) => {
22409
+ const text = event.text;
22111
22410
  const role = roleHost.getFlag(ROLE_FLAG.name);
22112
22411
  if (role !== void 0 && !admitted) return { action: "handled" };
22113
22412
  if (role === "reviewer" && admitted && activeReviewerParent !== void 0 && reviewerOriginalRequest === void 0) {
22114
22413
  reviewerOriginalRequest = roleHost.capabilities?.skillOriginalRequest?.(
22115
22414
  activeReviewerParent.skillBinding.name,
22116
- event.text
22117
- ) ?? event.text;
22118
- return { action: "continue" };
22415
+ text
22416
+ ) ?? text;
22417
+ return text === event.text ? { action: "continue" } : { action: "transform", text };
22119
22418
  }
22120
- return { action: "continue" };
22419
+ return text === event.text ? { action: "continue" } : { action: "transform", text };
22121
22420
  });
22122
22421
  roleHost.on("before_agent_start", async (event, ctx) => {
22123
22422
  const role = roleHost.getFlag(ROLE_FLAG.name);
22423
+ const prompt = event.prompt;
22124
22424
  if (role === void 0) return;
22125
22425
  if (!admitted || selectedRole !== role) {
22126
22426
  failInfrastructure(new ActivationBarrierError(role), ctx);
@@ -22133,7 +22433,7 @@ function createRoleRuntimeExtension(dependencies) {
22133
22433
  }
22134
22434
  if (navigatorAttendance !== void 0 && navigatorWorkContext !== void 0 && navigatorWorkContext.contextError === void 0) {
22135
22435
  if (navigatorWorkContext.subjectProvenance === "placeholder") {
22136
- const subject = event.prompt.trim();
22436
+ const subject = prompt.trim();
22137
22437
  if (subject !== "") {
22138
22438
  const root = subjectPath(ctx.sessionManager.getSessionDir(), ctx.cwd);
22139
22439
  const subjectProvenance = "user_prompt";
@@ -22154,7 +22454,7 @@ function createRoleRuntimeExtension(dependencies) {
22154
22454
  if (!reviewerExpansionCaptured) {
22155
22455
  if (reviewerOriginalRequest !== void 0) {
22156
22456
  activeReviewerParent.skillBinding.captureExpansion(
22157
- roleHost.capabilities?.skillExpansion(event.prompt),
22457
+ roleHost.capabilities?.skillExpansion(prompt),
22158
22458
  reviewerOriginalRequest
22159
22459
  );
22160
22460
  }
@@ -22177,6 +22477,46 @@ function createRoleRuntimeExtension(dependencies) {
22177
22477
  };
22178
22478
  }
22179
22479
  });
22480
+ roleHost.on("before_agent_start", () => {
22481
+ const role = selectedRole ?? roleHost.getFlag(ROLE_FLAG.name);
22482
+ if (typeof role !== "string" || !isOfficerReviewSeat(role)) return;
22483
+ if (roleHost.getFlag(STATION_CHILD_FLAG.name) !== true) return;
22484
+ const engine = resolveEngineName((name) => roleHost.getFlag(name));
22485
+ if (engine === void 0 || dependencies.packageRoot === void 0) return;
22486
+ const engineModel = resolveEngineModel((name) => roleHost.getFlag(name));
22487
+ const material = engineSessionMaterialFromOptions({
22488
+ engine,
22489
+ ...engineModel === void 0 ? {} : { engineModel },
22490
+ packageRoot: dependencies.packageRoot
22491
+ });
22492
+ if (material === void 0) return;
22493
+ return {
22494
+ readingMaterial: {
22495
+ kind: "engine-session-material",
22496
+ name: material.name,
22497
+ ...material.model === void 0 ? {} : { model: material.model },
22498
+ ...material.materialPath === void 0 ? {} : { materialPath: material.materialPath }
22499
+ }
22500
+ };
22501
+ });
22502
+ roleHost.on("before_agent_start", () => {
22503
+ const path = roleHost.getFlag(INSPECTOR_SOURCE_RUN_FLAG.name);
22504
+ if (typeof path !== "string" || path.trim() === "") return;
22505
+ return {
22506
+ readingMaterial: {
22507
+ kind: "inspector-parent-binding",
22508
+ sourceRunPath: path
22509
+ }
22510
+ };
22511
+ });
22512
+ roleHost.on("before_agent_start", async (_event, ctx) => {
22513
+ const runDir = runDirectoryFromHostContext(ctx);
22514
+ if (runDir === void 0) return;
22515
+ const { loadCaseDossierReadingMaterial: loadCaseDossierReadingMaterial2 } = await Promise.resolve().then(() => (init_case_dossier_delivery(), case_dossier_delivery_exports));
22516
+ const caseDossier = await loadCaseDossierReadingMaterial2(runDir);
22517
+ if (caseDossier === void 0) return;
22518
+ return { readingMaterial: caseDossier };
22519
+ });
22180
22520
  roleHost.on("tool_result", async (event) => {
22181
22521
  const role = selectedRole;
22182
22522
  if (role === void 0) return;
@@ -22237,7 +22577,7 @@ function createRoleRuntimeExtension(dependencies) {
22237
22577
  display: false
22238
22578
  }, { triggerTurn: true, deliverAs: "followUp" });
22239
22579
  } else if (receiptDelivery.nextAction() === "no-receipt" && !noReceiptRecorded) {
22240
- const runPointer = process.env.AK_ROLE_RUN_DIR;
22580
+ const runPointer = runDirectoryFromHostContext(ctx);
22241
22581
  if (runPointer !== void 0) {
22242
22582
  noReceiptRecorded = true;
22243
22583
  const facts = receiptDelivery.facts({ runPointer, attemptPointer: `current:${runPointer}` });
@@ -22599,8 +22939,8 @@ function createRoleRuntimeExtension(dependencies) {
22599
22939
  await observe(() => observationFace.onEnd(event), ctx);
22600
22940
  });
22601
22941
  const recordHttpObservation = async (status, provider, ctx) => {
22602
- const runDir = process.env.AK_ROLE_RUN_DIR;
22603
- if (typeof runDir !== "string" || runDir.trim() === "") return;
22942
+ const runDir = runDirectoryFromHostContext(ctx);
22943
+ if (runDir === void 0) return;
22604
22944
  try {
22605
22945
  await recordTypedProviderHttpStatus(runDir, { httpStatus: status, provider });
22606
22946
  } catch (error) {
@@ -22623,8 +22963,8 @@ function createRoleRuntimeExtension(dependencies) {
22623
22963
  const underlying = priorFetch;
22624
22964
  globalThis.fetch = (async (input, init) => {
22625
22965
  const response = await underlying(input, init);
22626
- const runDir = process.env.AK_ROLE_RUN_DIR;
22627
- if (typeof runDir === "string" && runDir.trim() !== "" && typeof response?.status === "number" && (response.status < 200 || response.status >= 300)) {
22966
+ const runDir = runDirectoryFromHostContext(ctx);
22967
+ if (runDir !== void 0 && typeof response?.status === "number" && (response.status < 200 || response.status >= 300)) {
22628
22968
  const provider = typeof ctx.model?.provider === "string" && ctx.model.provider.trim() !== "" ? ctx.model.provider : "unknown";
22629
22969
  try {
22630
22970
  await recordTypedProviderHttpStatus(runDir, {
@@ -22810,15 +23150,16 @@ function createRoleRuntimeDependencies(packageRoot) {
22810
23150
  const doctorAuditor = createPiDoctorAuditor();
22811
23151
  const navigatorSessionFactory = createNativeNavigatorSessionFactory();
22812
23152
  return {
23153
+ packageRoot,
22813
23154
  loadJudgeSoul: () => loadMainRoleSessionMaterials("judge"),
22814
23155
  loadFixerSoul: () => loadMainRoleSessionMaterials("fixer"),
22815
- loadFixPacket: (path) => readFile21(path, "utf8"),
23156
+ loadFixPacket: (path) => readFile22(path, "utf8"),
22816
23157
  loadCoderSoul: () => loadMainRoleSessionMaterials("coder"),
22817
- loadCoderTask: (path) => readFile21(path, "utf8"),
23158
+ loadCoderTask: (path) => readFile22(path, "utf8"),
22818
23159
  loadReviewerSoul: () => loadMainRoleSessionMaterials("reviewer"),
22819
23160
  createReviewerPinnedGitReader: () => createReviewerPinnedGitReader(),
22820
23161
  loadCollectorSoul: () => loadMainRoleSessionMaterials("collector"),
22821
- loadCollectorHandbookSeed: () => readFile21(collectorHandbookSeedPath, "utf8"),
23162
+ loadCollectorHandbookSeed: () => readFile22(collectorHandbookSeedPath, "utf8"),
22822
23163
  createCollectorTransport: () => createGhCollectorGitHubTransport(),
22823
23164
  loadDoctorSoul: () => loadMainRoleSessionMaterials("doctor"),
22824
23165
  loadDoctorCase,
@@ -22832,7 +23173,7 @@ function createRoleRuntimeDependencies(packageRoot) {
22832
23173
  loadDiaristSoul: () => loadMainRoleSessionMaterials("diarist"),
22833
23174
  loadNotarySourceRun: loadNotarySourceRunLocator,
22834
23175
  loadMergerSoul: () => loadMainRoleSessionMaterials("merger"),
22835
- loadMergerInput: async (path) => JSON.parse(await readFile21(path, "utf8")),
23176
+ loadMergerInput: async (path) => JSON.parse(await readFile22(path, "utf8")),
22836
23177
  async loadCanonicalSkillBinding(name) {
22837
23178
  if (name === "tdd") {
22838
23179
  return loadPackagedCanonicalSkillBinding(packageRoot, "tdd");
@@ -22858,7 +23199,7 @@ function createRoleRuntimeDependencies(packageRoot) {
22858
23199
  authority: options.authority,
22859
23200
  invocationId: options.invocationId,
22860
23201
  loadSoul: () => loadMainRoleSessionMaterials("navigator"),
22861
- loadRoutePlaybook: () => readFile21(navigatorRoutePlaybookPath, "utf8"),
23202
+ loadRoutePlaybook: () => readFile22(navigatorRoutePlaybookPath, "utf8"),
22862
23203
  loadRoleHelp: async (role) => formatNavigatorRoleHelp(role),
22863
23204
  createSession: navigatorSessionFactory,
22864
23205
  ...options.contextError === void 0 ? {} : { contextError: options.contextError },
@@ -22870,9 +23211,9 @@ function createRoleRuntimeDependencies(packageRoot) {
22870
23211
  // src/role-envelope.ts
22871
23212
  init_engine_detour();
22872
23213
  import { randomUUID as randomUUID7 } from "node:crypto";
22873
- import { mkdir as mkdir6, readFile as readFile22, writeFile as writeFile10 } from "node:fs/promises";
23214
+ import { mkdir as mkdir6, readFile as readFile23, writeFile as writeFile11 } from "node:fs/promises";
22874
23215
  import { createServer } from "node:net";
22875
- import { basename as basename8, dirname as dirname20, join as join36 } from "node:path";
23216
+ import { basename as basename8, dirname as dirname20, join as join37 } from "node:path";
22876
23217
  import { fileURLToPath as fileURLToPath3 } from "node:url";
22877
23218
 
22878
23219
  // src/gatekeeper-pass-envelope.ts
@@ -22904,6 +23245,7 @@ async function requireGatekeeperPass(options) {
22904
23245
  subject: options.subject,
22905
23246
  ...options.signal === void 0 ? {} : { signal: options.signal },
22906
23247
  ...options.summonOfficer === void 0 ? {} : { summonOfficer: options.summonOfficer },
23248
+ ...options.submission === void 0 ? {} : { submission: options.submission },
22907
23249
  ...reask === void 0 ? {} : { reask }
22908
23250
  });
22909
23251
  const gatekeeper = projected.result;
@@ -22999,14 +23341,14 @@ async function prepareRoleEnvelope(options) {
22999
23341
  for (const method of request.methods) {
23000
23342
  if (method.kind !== "skill") continue;
23001
23343
  const name = basename8(dirname20(method.path));
23002
- const raw = await readFile22(method.path, "utf8");
23344
+ const raw = await readFile23(method.path, "utf8");
23003
23345
  methodSkills.set(name, { path: method.path, body: stripSkillFrontmatter(raw).trim() });
23004
23346
  }
23005
- let sessionFile = options.sessionFile ?? join36(request.runDirectory, "session", "session.jsonl");
23347
+ let sessionFile = options.sessionFile ?? join37(request.runDirectory, "session", "session.jsonl");
23006
23348
  await mkdir6(dirname20(sessionFile), { recursive: true });
23007
23349
  if (request.continuation.kind !== "resume") {
23008
23350
  try {
23009
- await writeFile10(
23351
+ await writeFile11(
23010
23352
  sessionFile,
23011
23353
  `${JSON.stringify({
23012
23354
  type: "session",
@@ -23026,6 +23368,8 @@ async function prepareRoleEnvelope(options) {
23026
23368
  cwd: request.cwd,
23027
23369
  mode: "print",
23028
23370
  model: request.model === void 0 ? void 0 : { provider: request.model.provider },
23371
+ runDirectory: request.runDirectory,
23372
+ ...request.courtAttemptId === void 0 ? {} : { courtAttemptId: request.courtAttemptId },
23029
23373
  sessionManager: {
23030
23374
  getLeafEntry: () => sessionEntries.at(-1),
23031
23375
  getLeafId: () => runId,
@@ -23100,7 +23444,8 @@ async function prepareRoleEnvelope(options) {
23100
23444
  failInfrastructure: (error, _context, toolCallId) => options2.hostActions.failInfrastructure(error, options2.context, toolCallId),
23101
23445
  bindSubmissionNonPass: options2.hostActions.bindSubmissionNonPass
23102
23446
  },
23103
- toolCallId: options2.toolCallId
23447
+ toolCallId: options2.toolCallId,
23448
+ ...options2.submission === void 0 ? {} : { submission: options2.submission }
23104
23449
  });
23105
23450
  },
23106
23451
  on(...registration) {
@@ -23327,17 +23672,6 @@ async function prepareRoleEnvelope(options) {
23327
23672
  const relay = fileURLToPath3(new URL("./mcp-relay.mjs", import.meta.url));
23328
23673
  await listen(server, options.socketPath);
23329
23674
  let disposed = false;
23330
- let priorAkRoleRunDir;
23331
- let priorAkRoleCourtAttempt;
23332
- let runDirInjected = false;
23333
- const restoreAkRoleRunEnv = () => {
23334
- if (!runDirInjected) return;
23335
- runDirInjected = false;
23336
- if (priorAkRoleRunDir === void 0) delete process.env.AK_ROLE_RUN_DIR;
23337
- else process.env.AK_ROLE_RUN_DIR = priorAkRoleRunDir;
23338
- if (priorAkRoleCourtAttempt === void 0) delete process.env.AK_ROLE_COURT_ATTEMPT;
23339
- else process.env.AK_ROLE_COURT_ATTEMPT = priorAkRoleCourtAttempt;
23340
- };
23341
23675
  const dispose = async () => {
23342
23676
  if (disposed) return;
23343
23677
  disposed = true;
@@ -23347,11 +23681,6 @@ async function prepareRoleEnvelope(options) {
23347
23681
  } catch (error) {
23348
23682
  cleanupFailures.push(error);
23349
23683
  }
23350
- try {
23351
- restoreAkRoleRunEnv();
23352
- } catch (error) {
23353
- cleanupFailures.push(error);
23354
- }
23355
23684
  try {
23356
23685
  const closeAll = server.closeAllConnections;
23357
23686
  if (typeof closeAll === "function") closeAll.call(server);
@@ -23420,7 +23749,7 @@ async function prepareRoleEnvelope(options) {
23420
23749
  message: { role: "user", content: prompt }
23421
23750
  });
23422
23751
  }
23423
- const methodPrompt = (await Promise.all(request.methods.map(({ path }) => readFile22(path, "utf8")))).join("\n\n");
23752
+ const methodPrompt = (await Promise.all(request.methods.map(({ path }) => readFile23(path, "utf8")))).join("\n\n");
23424
23753
  const promptResults = await emit("before_agent_start", {
23425
23754
  prompt,
23426
23755
  systemPrompt: methodPrompt,
@@ -23439,12 +23768,6 @@ async function prepareRoleEnvelope(options) {
23439
23768
  const material = value.readingMaterial;
23440
23769
  if (material !== void 0) readingMaterials.push(material);
23441
23770
  }
23442
- priorAkRoleRunDir = process.env.AK_ROLE_RUN_DIR;
23443
- priorAkRoleCourtAttempt = process.env.AK_ROLE_COURT_ATTEMPT;
23444
- process.env.AK_ROLE_RUN_DIR = request.runDirectory;
23445
- if (request.courtAttemptId === void 0) delete process.env.AK_ROLE_COURT_ATTEMPT;
23446
- else process.env.AK_ROLE_COURT_ATTEMPT = request.courtAttemptId;
23447
- runDirInjected = true;
23448
23771
  const terminating = tools.get(terminatingToolName);
23449
23772
  if (terminating === void 0) {
23450
23773
  throw new Error(`terminating tool not registered after activation: ${terminatingToolName}`);
@@ -23487,7 +23810,7 @@ async function prepareRoleEnvelope(options) {
23487
23810
  init_session_identity();
23488
23811
 
23489
23812
  // src/headless-host/description.ts
23490
- import { join as join37 } from "node:path";
23813
+ import { join as join38 } from "node:path";
23491
23814
  function isClaudePrintDescription(description) {
23492
23815
  return description.protocol === "claude-print";
23493
23816
  }
@@ -23495,13 +23818,12 @@ function isCodexExecDescription(description) {
23495
23818
  return description.protocol === "codex-exec";
23496
23819
  }
23497
23820
  function resolveHeadlessBinary(description, operatorHome) {
23498
- return join37(operatorHome, ...description.binaryFromHome);
23821
+ return join38(operatorHome, ...description.binaryFromHome);
23499
23822
  }
23500
23823
  function headlessTurnArgs(options) {
23501
23824
  const { description } = options;
23502
23825
  const args = [
23503
23826
  description.promptFlag,
23504
- options.prompt,
23505
23827
  ...description.fixedArgs,
23506
23828
  description.systemPromptFlag,
23507
23829
  options.systemPromptPath,
@@ -23729,7 +24051,7 @@ function codexTurnArgs(options) {
23729
24051
  if (options.skipGitRepoCheck === true) {
23730
24052
  args.push("--skip-git-repo-check");
23731
24053
  }
23732
- args.push("--", options.prompt);
24054
+ args.push("--", "-");
23733
24055
  return args;
23734
24056
  }
23735
24057
  function headlessMcpConfigDocument(mcpServers) {
@@ -23751,10 +24073,11 @@ function headlessMcpConfigDocument(mcpServers) {
23751
24073
  import { spawn as spawn4, spawnSync } from "node:child_process";
23752
24074
  import { randomUUID as randomUUID8 } from "node:crypto";
23753
24075
  import { existsSync as existsSync12 } from "node:fs";
23754
- import { writeFile as writeFile11 } from "node:fs/promises";
23755
- import { dirname as dirname21, isAbsolute as isAbsolute11, join as join38, resolve as resolve20 } from "node:path";
24076
+ import { writeFile as writeFile12 } from "node:fs/promises";
24077
+ import { dirname as dirname21, isAbsolute as isAbsolute11, join as join39, resolve as resolve20 } from "node:path";
23756
24078
 
23757
24079
  // src/external-host-turn-loop.ts
24080
+ init_host_contracts();
23758
24081
  var EXTERNAL_ROLE_TURN_ROUND_LIMIT = 8;
23759
24082
  function mergeRoleTurnAbortSignals(prepared, request) {
23760
24083
  if (request === void 0) return prepared;
@@ -23763,6 +24086,9 @@ function mergeRoleTurnAbortSignals(prepared, request) {
23763
24086
  }
23764
24087
  function promptWithPriorNativePaths(basePrompt, request) {
23765
24088
  if (request.continuation.kind !== "resume") return basePrompt;
24089
+ if (request.stationChild === true && isOfficerReviewSeat(request.activation.role)) {
24090
+ return basePrompt;
24091
+ }
23766
24092
  const paths = request.hostTransition?.priorNativePaths;
23767
24093
  if (paths === void 0 || paths.length === 0) return basePrompt;
23768
24094
  return `${basePrompt}
@@ -23967,7 +24293,7 @@ function formatCodexFailurePayload(payload) {
23967
24293
  function cwdIsGitWorkTree(cwd) {
23968
24294
  let dir = cwd;
23969
24295
  for (; ; ) {
23970
- if (existsSync12(join38(dir, ".git"))) return true;
24296
+ if (existsSync12(join39(dir, ".git"))) return true;
23971
24297
  const parent = dirname21(dir);
23972
24298
  if (parent === dir) return false;
23973
24299
  dir = parent;
@@ -24007,8 +24333,20 @@ function spawnHeadlessTurn(options) {
24007
24333
  const child = spawn4(options.binary, [...options.args], {
24008
24334
  cwd: options.cwd,
24009
24335
  env: options.env,
24010
- stdio: ["ignore", "pipe", "pipe"]
24336
+ stdio: ["pipe", "pipe", "pipe"]
24337
+ });
24338
+ if (child.stdin === null) {
24339
+ reject(new Error("headless child stdin pipe was not created"));
24340
+ return;
24341
+ }
24342
+ let stdinDeliveryError;
24343
+ child.stdin.on("error", (error) => {
24344
+ stdinDeliveryError ??= error;
24011
24345
  });
24346
+ if (options.stdin !== void 0) {
24347
+ child.stdin.write(options.stdin);
24348
+ }
24349
+ child.stdin.end();
24012
24350
  let resultStdout = "";
24013
24351
  let stderr = "";
24014
24352
  let lineBuffer = "";
@@ -24058,6 +24396,10 @@ function spawnHeadlessTurn(options) {
24058
24396
  settled = true;
24059
24397
  if (timer !== void 0) clearTimeout(timer);
24060
24398
  options.signal?.removeEventListener("abort", onAbort);
24399
+ if (stdinDeliveryError !== void 0) {
24400
+ reject(stdinDeliveryError);
24401
+ return;
24402
+ }
24061
24403
  resolve21({ code, stdout: resultStdout, stderr, timedOut });
24062
24404
  };
24063
24405
  const onAbort = () => {
@@ -24121,7 +24463,6 @@ function buildTurnArgs(options) {
24121
24463
  }
24122
24464
  if (options.outputSchemaPath === void 0) throw new Error("codex requires an output schema path");
24123
24465
  return codexTurnArgs({
24124
- prompt: options.prompt,
24125
24466
  systemPromptPath: options.systemPromptPath,
24126
24467
  outputSchemaPath: options.outputSchemaPath,
24127
24468
  mcpServers: options.mcpServers,
@@ -24137,7 +24478,6 @@ function buildTurnArgs(options) {
24137
24478
  if (options.mcpConfigPath === void 0) throw new Error("claude print-mode requires an MCP config path");
24138
24479
  return headlessTurnArgs({
24139
24480
  description: options.description,
24140
- prompt: options.prompt,
24141
24481
  systemPromptPath: options.systemPromptPath,
24142
24482
  jsonSchema: options.jsonSchema,
24143
24483
  mcpConfigPath: options.mcpConfigPath,
@@ -24160,18 +24500,18 @@ function createHeadlessRoleTurnHost(config) {
24160
24500
  await config.sessionIdentity.bind(request.principal, sessionId);
24161
24501
  }
24162
24502
  const env = { ...process.env, ...config.env ?? {} };
24163
- const systemPromptPath = join38(request.runDirectory, "headless-system-prompt.txt");
24164
- await writeFile11(systemPromptPath, systemPrompt, "utf8");
24503
+ const systemPromptPath = join39(request.runDirectory, "headless-system-prompt.txt");
24504
+ await writeFile12(systemPromptPath, systemPrompt, "utf8");
24165
24505
  let mcpConfigPath;
24166
24506
  let outputSchemaPath;
24167
24507
  if (codex) {
24168
- outputSchemaPath = join38(request.runDirectory, "headless-output-schema.json");
24508
+ outputSchemaPath = join39(request.runDirectory, "headless-output-schema.json");
24169
24509
  const closed = closeJsonSchemaForCodex(prepared.jsonSchema);
24170
- await writeFile11(outputSchemaPath, `${JSON.stringify(closed, null, 2)}
24510
+ await writeFile12(outputSchemaPath, `${JSON.stringify(closed, null, 2)}
24171
24511
  `, "utf8");
24172
24512
  } else {
24173
- mcpConfigPath = join38(request.runDirectory, "headless-mcp-config.json");
24174
- await writeFile11(
24513
+ mcpConfigPath = join39(request.runDirectory, "headless-mcp-config.json");
24514
+ await writeFile12(
24175
24515
  mcpConfigPath,
24176
24516
  `${JSON.stringify(headlessMcpConfigDocument(prepared.mcpServers), null, 2)}
24177
24517
  `,
@@ -24191,7 +24531,6 @@ function createHeadlessRoleTurnHost(config) {
24191
24531
  const gitCommonDir = codex ? resolveGitCommonDir(request.cwd) : void 0;
24192
24532
  args = buildTurnArgs({
24193
24533
  description: config.description,
24194
- prompt,
24195
24534
  systemPromptPath,
24196
24535
  jsonSchema: prepared.jsonSchema,
24197
24536
  mcpServers: prepared.mcpServers,
@@ -24219,6 +24558,7 @@ function createHeadlessRoleTurnHost(config) {
24219
24558
  args,
24220
24559
  cwd: request.cwd,
24221
24560
  env,
24561
+ stdin: prompt,
24222
24562
  ...abortSignal === void 0 ? {} : { signal: abortSignal },
24223
24563
  ...request.timeoutMs === void 0 ? {} : { timeoutMs: request.timeoutMs },
24224
24564
  onStdoutLine(line2) {