@akagilnc/pi-workflow-roles 0.1.3565 → 0.1.3621

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 (142) hide show
  1. package/README.md +4 -1
  2. package/README.zh-CN.md +1 -1
  3. package/dist/acp-host/production-host.js +18477 -8099
  4. package/dist/analyst-gate-cycles-read.js +387 -0
  5. package/dist/archivist-record-entry.js +22 -1
  6. package/dist/audit-escalation.js +6 -0
  7. package/dist/auditor-soul.js +74 -0
  8. package/dist/collector-config.js +86 -0
  9. package/dist/collector-evidence.js +316 -0
  10. package/dist/collector-github.js +527 -0
  11. package/dist/collector-ledger.js +853 -0
  12. package/dist/collector-tool-schemas.js +33 -0
  13. package/dist/compliance-transport.js +104 -52
  14. package/dist/diarist-contracts.js +72 -0
  15. package/dist/diarist-mechanical.js +411 -0
  16. package/dist/diarist-ticket-resolution.js +177 -0
  17. package/dist/diarist.js +311 -0
  18. package/dist/doctor-auditor.js +25 -0
  19. package/dist/doctor-contracts.js +2 -0
  20. package/dist/doctor-evidence.js +142 -0
  21. package/dist/gatekeeper-role.js +104 -81
  22. package/dist/host-transition-prior-native.js +78 -0
  23. package/dist/institutional-resolution.js +1 -95
  24. package/dist/judge-auditor.js +26 -0
  25. package/dist/ledger-session-read.js +227 -0
  26. package/dist/merger-git-state.js +78 -0
  27. package/dist/navigator-attendance.js +15 -7
  28. package/dist/navigator-public-session.js +170 -0
  29. package/dist/navigator-session-contracts.js +36 -40
  30. package/dist/notary-source-run.js +122 -0
  31. package/dist/package-contracts/auditor-output.js +66 -0
  32. package/dist/package-contracts/evidence-child-output.js +34 -0
  33. package/dist/package-contracts/judge-output.js +2 -0
  34. package/dist/package-contracts/terminating-tools.js +44 -3
  35. package/dist/package-resources/method-skill.js +254 -0
  36. package/dist/packaged-role-registry.js +56 -0
  37. package/dist/pi/durable-principal.js +61 -0
  38. package/dist/pi/in-process-session.js +25 -6
  39. package/dist/pi/known-failure.js +52 -0
  40. package/dist/pi/role-turn-host.js +430 -0
  41. package/dist/public-cli/auto-resume.js +414 -0
  42. package/dist/public-cli/cli-errors.js +8 -0
  43. package/dist/public-cli/cli-io.js +1 -0
  44. package/dist/public-cli/command-renderer.js +5 -0
  45. package/dist/public-cli/doctor-run.js +84 -0
  46. package/dist/public-cli/inspector-run.js +136 -0
  47. package/dist/public-cli/instruction-seat-run.js +256 -0
  48. package/dist/public-cli/invocation.js +2225 -0
  49. package/dist/public-cli/judge-run.js +118 -0
  50. package/dist/public-cli/load-production-acp-host.js +40 -0
  51. package/dist/public-cli/main.js +1511 -1124
  52. package/dist/public-cli/notary-run.js +161 -0
  53. package/dist/public-cli/option-definitions.js +1192 -0
  54. package/dist/public-cli/post-admission.js +667 -0
  55. package/dist/public-cli/public-run-credentials.js +49 -0
  56. package/dist/public-cli/registry.js +8 -2
  57. package/dist/public-cli/reviewer-dispatch-rejection.js +77 -0
  58. package/dist/public-cli/run-lifecycle.js +1344 -0
  59. package/dist/public-cli/seat-ticket-binding.js +113 -0
  60. package/dist/public-cli/settlement.js +3441 -0
  61. package/dist/public-cli/terminal.js +135 -0
  62. package/dist/public-cli/turn-request.js +25 -0
  63. package/dist/public-role-summons.js +301 -0
  64. package/dist/receipt-delivery-policy.js +10 -0
  65. package/dist/reviewer-child-executor.js +80 -8
  66. package/dist/reviewer-execution-ledger.js +2 -1
  67. package/dist/run-terminal-artifacts.js +195 -0
  68. package/dist/run-ticket-number.js +40 -0
  69. package/dist/session-assistant-usage.js +107 -0
  70. package/dist/shape-unreadable-failure.js +34 -0
  71. package/dist/submission-errors.js +3 -0
  72. package/dist/submission-ledger.js +388 -0
  73. package/dist/ticket-provenance-contracts.js +115 -0
  74. package/dist/ticket-provenance.js +340 -0
  75. package/extensions/role-runtime.ts +8 -0
  76. package/package.json +1 -1
  77. package/resources/diarist-collect.md +6 -10
  78. package/scripts/build-package.mjs +2 -1
  79. package/souls/diarist.md +9 -0
  80. package/souls/doctor-auditor.md +1 -0
  81. package/souls/evidence-child.md +1 -0
  82. package/src/acp-host/production-host.ts +4 -0
  83. package/src/acp-host/role-envelope.ts +4 -3
  84. package/src/acp-host/role-turn-host.ts +9 -1
  85. package/src/analyst-gate-cycles-read.ts +37 -2
  86. package/src/archivist-record-entry.ts +45 -1
  87. package/src/audit-escalation.ts +17 -0
  88. package/src/auditor-role.ts +22 -0
  89. package/src/auditor-soul.ts +42 -0
  90. package/src/compliance-transport.ts +177 -66
  91. package/src/diarist-contracts.ts +88 -0
  92. package/src/diarist-role.ts +60 -0
  93. package/src/diarist.ts +253 -179
  94. package/src/doctor-auditor.ts +10 -14
  95. package/src/doctor-contracts.ts +1 -0
  96. package/src/doctor-role.ts +2 -2
  97. package/src/evidence-child-role.ts +22 -0
  98. package/src/gatekeeper-pass-envelope.ts +109 -0
  99. package/src/gatekeeper-role.ts +145 -104
  100. package/src/host-contracts.ts +15 -2
  101. package/src/institutional-resolution.ts +8 -163
  102. package/src/judge-auditor.ts +10 -15
  103. package/src/judge-role.ts +8 -0
  104. package/src/navigator-attendance.ts +25 -9
  105. package/src/navigator-public-session.ts +217 -0
  106. package/src/navigator-session-contracts.ts +61 -54
  107. package/src/notary-source-run.ts +3 -1
  108. package/src/package-contracts/auditor-output.ts +82 -0
  109. package/src/package-contracts/evidence-child-output.ts +51 -0
  110. package/src/package-contracts/judge-output.ts +1 -0
  111. package/src/package-contracts/reviewer-output.ts +2 -2
  112. package/src/package-contracts/terminating-tools.ts +53 -3
  113. package/src/packaged-role-registry.ts +63 -0
  114. package/src/pi/adapter.ts +2 -1
  115. package/src/pi/in-process-session.ts +38 -12
  116. package/src/pi/role-turn-host.ts +42 -0
  117. package/src/public-cli/cli.ts +43 -6
  118. package/src/public-cli/countersign-run.ts +9 -129
  119. package/src/public-cli/diarist-run.ts +312 -0
  120. package/src/public-cli/instruction-seat-run.ts +289 -50
  121. package/src/public-cli/invocation.ts +87 -25
  122. package/src/public-cli/option-definitions.ts +79 -0
  123. package/src/public-cli/post-admission.ts +9 -3
  124. package/src/public-cli/registry.ts +7 -1
  125. package/src/public-cli/run-lifecycle.ts +53 -6
  126. package/src/public-cli/settlement.ts +170 -7
  127. package/src/public-cli/terminal.ts +4 -1
  128. package/src/public-role-summons.ts +431 -0
  129. package/src/receipt-delivery-policy.ts +10 -0
  130. package/src/reviewer-agent.ts +1 -1
  131. package/src/reviewer-child-executor.ts +114 -12
  132. package/src/reviewer-execution-ledger.ts +3 -2
  133. package/src/role-runtime.ts +275 -23
  134. package/src/session-assistant-usage.ts +119 -0
  135. package/src/session-opening-materials.ts +1 -1
  136. package/src/shape-unreadable-failure.ts +49 -0
  137. package/src/submission-errors.ts +3 -0
  138. package/src/ticket-provenance-contracts.ts +1 -0
  139. package/src/ticket-provenance.ts +0 -23
  140. package/dist/evidence-child-executor.js +0 -829
  141. package/src/diarist-llm-collector.ts +0 -324
  142. package/src/evidence-child-executor.ts +0 -1140
@@ -15023,11 +15023,157 @@ var init_inspector_contracts = __esm({
15023
15023
  }
15024
15024
  });
15025
15025
 
15026
+ // src/package-contracts/auditor-output.ts
15027
+ function isRecord6(value) {
15028
+ return typeof value === "object" && value !== null && !Array.isArray(value);
15029
+ }
15030
+ function projectLawfulAuditorOutput(value) {
15031
+ if (!isRecord6(value)) return void 0;
15032
+ if (value.status === "pass") return { status: "pass" };
15033
+ if (value.status === "revise") {
15034
+ return {
15035
+ status: "revise",
15036
+ ...Object.hasOwn(value, "violations") ? { violations: value.violations } : {}
15037
+ };
15038
+ }
15039
+ if (value.status === "escalate") {
15040
+ return {
15041
+ status: "escalate",
15042
+ ...Object.hasOwn(value, "conflicts") ? { conflicts: value.conflicts } : {},
15043
+ ...Object.hasOwn(value, "decisionGate") ? { decisionGate: value.decisionGate } : {}
15044
+ };
15045
+ }
15046
+ return void 0;
15047
+ }
15048
+ function validateRecordedAuditorOutput(value) {
15049
+ const projected = projectLawfulAuditorOutput(value);
15050
+ if (projected === void 0) {
15051
+ throw new Error("Auditor output has no recognized execution discriminator");
15052
+ }
15053
+ return projected;
15054
+ }
15055
+ function auditorDecisiveFacts(output) {
15056
+ const facts = { status: output.status };
15057
+ if (output.status === "revise" && output.violations !== void 0) {
15058
+ facts.violations = output.violations;
15059
+ }
15060
+ if (output.status === "escalate") {
15061
+ if (output.conflicts !== void 0) facts.conflicts = output.conflicts;
15062
+ if (output.decisionGate !== void 0) facts.decisionGate = output.decisionGate;
15063
+ }
15064
+ return facts;
15065
+ }
15066
+ var AUDITOR_OUTPUT_TOOL_NAME, auditorOutputSchema;
15067
+ var init_auditor_output = __esm({
15068
+ "src/package-contracts/auditor-output.ts"() {
15069
+ "use strict";
15070
+ init_build();
15071
+ init_open_tool_schema();
15072
+ init_terminating_infrastructure();
15073
+ AUDITOR_OUTPUT_TOOL_NAME = "ak_auditor_output";
15074
+ auditorOutputSchema = withInfrastructureFailureDeclaration(
15075
+ openToolObject(
15076
+ typebox_exports.Object({
15077
+ status: typebox_exports.Unknown({
15078
+ description: "pass | revise | escalate \u2014 \u5F62\u72B6\u6307\u5F15\uFF0C\u975E schema \u95F8"
15079
+ }),
15080
+ violations: typebox_exports.Optional(typebox_exports.Unknown({
15081
+ description: "status \u4E3A revise \u65F6\u7684\u8FDD\u89C4\u6761\u76EE"
15082
+ })),
15083
+ conflicts: typebox_exports.Optional(typebox_exports.Unknown({
15084
+ description: "status \u4E3A escalate \u65F6\u7684\u51B2\u7A81"
15085
+ })),
15086
+ decisionGate: typebox_exports.Optional(typebox_exports.Unknown({
15087
+ description: "status \u4E3A escalate \u65F6\u7684\u51B3\u7B56\u95F8"
15088
+ }))
15089
+ })
15090
+ )
15091
+ );
15092
+ }
15093
+ });
15094
+
15095
+ // src/package-contracts/evidence-child-output.ts
15096
+ function isRecord7(value) {
15097
+ return typeof value === "object" && value !== null && !Array.isArray(value);
15098
+ }
15099
+ function projectLawfulEvidenceChildOutput(value) {
15100
+ if (!isRecord7(value)) return void 0;
15101
+ return { report: Object.hasOwn(value, "report") ? value.report : value };
15102
+ }
15103
+ function validateRecordedEvidenceChildOutput(value) {
15104
+ const projected = projectLawfulEvidenceChildOutput(value);
15105
+ if (projected === void 0) {
15106
+ throw new Error("Evidence-child output is not an object");
15107
+ }
15108
+ return projected;
15109
+ }
15110
+ function evidenceChildDecisiveFacts(output) {
15111
+ return { report: output.report };
15112
+ }
15113
+ var EVIDENCE_CHILD_OUTPUT_TOOL_NAME, evidenceChildOutputSchema;
15114
+ var init_evidence_child_output = __esm({
15115
+ "src/package-contracts/evidence-child-output.ts"() {
15116
+ "use strict";
15117
+ init_build();
15118
+ init_open_tool_schema();
15119
+ init_terminating_infrastructure();
15120
+ EVIDENCE_CHILD_OUTPUT_TOOL_NAME = "ak_evidence_child_output";
15121
+ evidenceChildOutputSchema = withInfrastructureFailureDeclaration(
15122
+ openToolObject(
15123
+ typebox_exports.Object({
15124
+ report: typebox_exports.Unknown({
15125
+ description: "\u53D6\u8BC1\u62A5\u544A\u6B63\u6587 \u2014 \u5F62\u72B6\u6307\u5F15\uFF0C\u975E schema \u95F8"
15126
+ })
15127
+ })
15128
+ )
15129
+ );
15130
+ }
15131
+ });
15132
+
15133
+ // src/diarist-contracts.ts
15134
+ function validateRecordedDiaristOutput(value) {
15135
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
15136
+ throw new Error("Diarist output has no execution discriminator");
15137
+ }
15138
+ let status;
15139
+ try {
15140
+ status = value.status;
15141
+ } catch {
15142
+ throw new Error("Diarist output has no execution discriminator");
15143
+ }
15144
+ if (status === "completed") {
15145
+ return value;
15146
+ }
15147
+ throw new Error("Diarist output has no execution discriminator");
15148
+ }
15149
+ function diaristDecisiveFacts(output) {
15150
+ const facts = { status: output.status };
15151
+ const selections = output.selections;
15152
+ if (Array.isArray(selections)) facts.selections = selections;
15153
+ const sitian = output.sitian;
15154
+ if (sitian !== void 0) facts.sitian = sitian;
15155
+ return facts;
15156
+ }
15157
+ var DIARIST_OUTPUT_TOOL_NAME, DIARIST_SOURCES_FLAG;
15158
+ var init_diarist_contracts = __esm({
15159
+ "src/diarist-contracts.ts"() {
15160
+ "use strict";
15161
+ DIARIST_OUTPUT_TOOL_NAME = "ak_diarist_output";
15162
+ DIARIST_SOURCES_FLAG = {
15163
+ name: "ak-diarist-sources",
15164
+ definition: {
15165
+ description: "Frozen per-ticket source catalog the diarist selects from",
15166
+ type: "string"
15167
+ }
15168
+ };
15169
+ }
15170
+ });
15171
+
15026
15172
  // src/packaged-role-registry.ts
15027
15173
  function packagedRoleMetadata(role) {
15028
15174
  return PACKAGED_ROLE_REGISTRY.find((entry) => entry.role === role);
15029
15175
  }
15030
- var NOTARY_SESSION_MATERIALS, INSPECTOR_SESSION_MATERIALS, PUBLIC_ROLE_RECORDS, PACKAGED_ROLE_REGISTRY;
15176
+ var NOTARY_SESSION_MATERIALS, INSPECTOR_SESSION_MATERIALS, AUDITOR_PUBLIC_SESSION_MATERIALS, EVIDENCE_CHILD_SESSION_MATERIALS, PUBLIC_ROLE_RECORDS, PACKAGED_ROLE_REGISTRY;
15031
15177
  var init_packaged_role_registry = __esm({
15032
15178
  "src/packaged-role-registry.ts"() {
15033
15179
  "use strict";
@@ -15043,6 +15189,9 @@ var init_packaged_role_registry = __esm({
15043
15189
  init_countersign_contracts();
15044
15190
  init_gleaner_left_contracts();
15045
15191
  init_inspector_contracts();
15192
+ init_auditor_output();
15193
+ init_evidence_child_output();
15194
+ init_diarist_contracts();
15046
15195
  NOTARY_SESSION_MATERIALS = [
15047
15196
  "CLAUDE.md",
15048
15197
  "souls/notary.md",
@@ -15056,6 +15205,19 @@ var init_packaged_role_registry = __esm({
15056
15205
  "souls/quality-law.md",
15057
15206
  "souls/gate-output-guide.md"
15058
15207
  ];
15208
+ AUDITOR_PUBLIC_SESSION_MATERIALS = [
15209
+ "CLAUDE.md",
15210
+ "souls/judge-auditor.md",
15211
+ "souls/doctor-auditor.md",
15212
+ "souls/audit-law.md",
15213
+ "souls/quality-law.md"
15214
+ ];
15215
+ EVIDENCE_CHILD_SESSION_MATERIALS = [
15216
+ "CLAUDE.md",
15217
+ "souls/evidence-child.md",
15218
+ "souls/audit-law.md",
15219
+ "souls/quality-law.md"
15220
+ ];
15059
15221
  PUBLIC_ROLE_RECORDS = [
15060
15222
  {
15061
15223
  role: "judge",
@@ -15208,6 +15370,41 @@ var init_packaged_role_registry = __esm({
15208
15370
  phaseFlag: void 0,
15209
15371
  activationStage: "load-and-install",
15210
15372
  sessionMaterials: ["CLAUDE.md", "souls/navigator.md"]
15373
+ },
15374
+ // #675: 审刑院 / evidence-child are roles like any other — public ak-role entries.
15375
+ {
15376
+ role: "auditor",
15377
+ phases: [null],
15378
+ outputTool: AUDITOR_OUTPUT_TOOL_NAME,
15379
+ inputFlag: void 0,
15380
+ phaseFlag: void 0,
15381
+ activationStage: "load-and-install",
15382
+ sessionMaterials: AUDITOR_PUBLIC_SESSION_MATERIALS
15383
+ },
15384
+ {
15385
+ role: "evidence-child",
15386
+ phases: [null],
15387
+ outputTool: EVIDENCE_CHILD_OUTPUT_TOOL_NAME,
15388
+ inputFlag: void 0,
15389
+ phaseFlag: void 0,
15390
+ activationStage: "load-and-install",
15391
+ sessionMaterials: EVIDENCE_CHILD_SESSION_MATERIALS
15392
+ },
15393
+ // #708 / ADR 0075 `diarist-is-role`: 起居郎 is a seat like any other. The
15394
+ // frozen source catalog rides the shared input-flag seam; it is absent for a
15395
+ // true-unbound summons (no ticket → no diary).
15396
+ {
15397
+ role: "diarist",
15398
+ phases: [null],
15399
+ outputTool: DIARIST_OUTPUT_TOOL_NAME,
15400
+ inputFlag: DIARIST_SOURCES_FLAG.name,
15401
+ phaseFlag: void 0,
15402
+ activationStage: "load-and-install",
15403
+ sessionMaterials: [
15404
+ "CLAUDE.md",
15405
+ "souls/diarist.md",
15406
+ "resources/diarist-collect.md"
15407
+ ]
15211
15408
  }
15212
15409
  ];
15213
15410
  PACKAGED_ROLE_REGISTRY = PUBLIC_ROLE_RECORDS.map(({ sessionMaterials: _omit, ...metadata }) => metadata);
@@ -15313,30 +15510,25 @@ var init_registry2 = __esm({
15313
15510
  // #620: subordinate officers inherit gatekeeper; no package startup model.
15314
15511
  notary: [],
15315
15512
  // #453/#620/#639: gatekeeper callable but no package startup model — caller
15316
- // configures it or the institutional resolution applies on the province path.
15513
+ // configures it or inherits on the province path.
15317
15514
  gatekeeper: [],
15318
15515
  inspector: [],
15319
15516
  navigator: [
15320
15517
  { provider: "openai-codex", model: "gpt-5.6-luna", thinking: "medium" },
15321
15518
  { provider: "xai", model: "grok-4.5", thinking: "high" }
15322
- ]
15519
+ ],
15520
+ // #675: auditor / evidence-child public seats — no package startup; caller configures.
15521
+ auditor: [],
15522
+ "evidence-child": [],
15523
+ // #708 `diarist-seat-default`: owner-set initial value; changed in the seat
15524
+ // table like any other seat. No engine axis, package-default host.
15525
+ diarist: [{ provider: "xai", model: "grok-4.5", thinking: "medium" }]
15323
15526
  };
15324
15527
  PUBLIC_DETERMINISTIC_COMMANDS = ["analyst"];
15325
15528
  }
15326
15529
  });
15327
15530
 
15328
15531
  // src/institutional-resolution.ts
15329
- import { readFile, writeFile } from "node:fs/promises";
15330
- import { join as join5 } from "node:path";
15331
- function cleanSelection(model) {
15332
- if (model === void 0) return void 0;
15333
- if (typeof model.provider !== "string" || typeof model.model !== "string") return void 0;
15334
- return {
15335
- provider: model.provider,
15336
- model: model.model,
15337
- ...model.thinking === void 0 ? {} : { thinking: model.thinking }
15338
- };
15339
- }
15340
15532
  function resolveConfiguredProvinceOfficer(config, officer) {
15341
15533
  const ownModel = seatModelOnly(config.seats[officer]);
15342
15534
  if (ownModel !== void 0) {
@@ -15351,37 +15543,10 @@ function resolveConfiguredProvinceOfficer(config, officer) {
15351
15543
  }
15352
15544
  return { source: "unconfigured" };
15353
15545
  }
15354
- function resolveInstitutionalSeatSelections(config, parentEffectiveModel) {
15355
- const parentSelection = cleanSelection(parentEffectiveModel);
15356
- const gatekeeper = resolveConfiguredProvinceOfficer(config, "gatekeeper").selection ?? parentSelection;
15357
- const inspector = resolveConfiguredProvinceOfficer(config, "inspector").selection ?? parentSelection;
15358
- const notary = resolveConfiguredProvinceOfficer(config, "notary").selection ?? parentSelection;
15359
- const auditor = parentSelection;
15360
- const evidenceChild = parentSelection;
15361
- const navigator = cleanSelection(seatModelOnly(config.seats?.navigator));
15362
- return {
15363
- version: 1,
15364
- seats: {
15365
- ...gatekeeper === void 0 ? {} : { gatekeeper },
15366
- ...inspector === void 0 ? {} : { inspector },
15367
- ...notary === void 0 ? {} : { notary },
15368
- ...auditor === void 0 ? {} : { auditor },
15369
- ...evidenceChild === void 0 ? {} : { evidenceChild },
15370
- ...navigator === void 0 ? {} : { navigator }
15371
- }
15372
- };
15373
- }
15374
- async function writeInstitutionalResolutionPage(runDirectory, page) {
15375
- const filePath = join5(runDirectory, INSTITUTIONAL_RESOLUTION_FILE);
15376
- await writeFile(filePath, `${JSON.stringify(page, null, 2)}
15377
- `, "utf8");
15378
- }
15379
- var INSTITUTIONAL_RESOLUTION_FILE;
15380
15546
  var init_institutional_resolution = __esm({
15381
15547
  "src/institutional-resolution.ts"() {
15382
15548
  "use strict";
15383
15549
  init_registry2();
15384
- INSTITUTIONAL_RESOLUTION_FILE = "institutional-resolution.json";
15385
15550
  }
15386
15551
  });
15387
15552
 
@@ -15428,8 +15593,8 @@ var init_host_descriptions = __esm({
15428
15593
  });
15429
15594
 
15430
15595
  // src/public-cli/config.ts
15431
- import { mkdir, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
15432
- import { dirname as dirname4, join as join6 } from "node:path";
15596
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
15597
+ import { dirname as dirname4, join as join5 } from "node:path";
15433
15598
  function isGateOfficerSeat(value) {
15434
15599
  return GATE_OFFICER_SEATS.includes(value);
15435
15600
  }
@@ -15437,12 +15602,12 @@ function publicCliConfigPath(home) {
15437
15602
  if (typeof home !== "string" || home.trim() === "") {
15438
15603
  throw new Error("home must be explicitly provided");
15439
15604
  }
15440
- return join6(home, ".ak-roles", "public-cli.json");
15605
+ return join5(home, ".ak-roles", "public-cli.json");
15441
15606
  }
15442
15607
  async function loadPublicCliConfig(home) {
15443
15608
  const path = publicCliConfigPath(home);
15444
15609
  try {
15445
- const raw = await readFile2(path, "utf8");
15610
+ const raw = await readFile(path, "utf8");
15446
15611
  return parsePublicCliConfig(JSON.parse(raw));
15447
15612
  } catch (error) {
15448
15613
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -15455,7 +15620,7 @@ async function savePublicCliConfig(config, home) {
15455
15620
  const path = publicCliConfigPath(home);
15456
15621
  await mkdir(dirname4(path), { recursive: true });
15457
15622
  const normalized = parsePublicCliConfig(config);
15458
- await writeFile2(
15623
+ await writeFile(
15459
15624
  path,
15460
15625
  `${JSON.stringify(serializePublicCliConfig(normalized), null, 2)}
15461
15626
  `,
@@ -15829,7 +15994,7 @@ function credentialProvidersFromAuthData(data) {
15829
15994
  }
15830
15995
  async function loadCredentialProviders(agentDir) {
15831
15996
  try {
15832
- const raw = await readFile2(join6(agentDir, "auth.json"), "utf8");
15997
+ const raw = await readFile(join5(agentDir, "auth.json"), "utf8");
15833
15998
  return credentialProvidersFromAuthData(JSON.parse(raw));
15834
15999
  } catch (error) {
15835
16000
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -15874,15 +16039,15 @@ var init_cli_errors = __esm({
15874
16039
 
15875
16040
  // src/public-cli/load-production-acp-host.ts
15876
16041
  import { existsSync as existsSync3 } from "node:fs";
15877
- import { join as join7 } from "node:path";
16042
+ import { join as join6 } from "node:path";
15878
16043
  import { pathToFileURL } from "node:url";
15879
16044
  async function loadProductionAcpHostFactory(packageRoot2, host) {
15880
16045
  const description = lookupHostDescription(host);
15881
16046
  if (description === void 0) {
15882
16047
  throw new Error(`unregistered host: ${host}`);
15883
16048
  }
15884
- const built = join7(packageRoot2, "dist/acp-host/production-host.js");
15885
- const source = join7(packageRoot2, "src/acp-host/production-host.ts");
16049
+ const built = join6(packageRoot2, "dist/acp-host/production-host.js");
16050
+ const source = join6(packageRoot2, "src/acp-host/production-host.ts");
15886
16051
  const target = existsSync3(built) ? built : source;
15887
16052
  const href = pathToFileURL(target).href;
15888
16053
  const mod = await import(href);
@@ -15922,9 +16087,9 @@ var init_host_contracts = __esm({
15922
16087
 
15923
16088
  // src/engine-detour.ts
15924
16089
  import { spawn } from "node:child_process";
15925
- import { mkdtemp, rm, writeFile as writeFile3 } from "node:fs/promises";
16090
+ import { mkdtemp, rm, writeFile as writeFile2 } from "node:fs/promises";
15926
16091
  import { tmpdir } from "node:os";
15927
- import { join as join8 } from "node:path";
16092
+ import { join as join7 } from "node:path";
15928
16093
  function applyEngineChildEnv(childEnv, engine) {
15929
16094
  delete childEnv[AK_ROLE_ENGINE_ENV];
15930
16095
  if (engine !== void 0 && engine.trim() !== "") {
@@ -16019,12 +16184,12 @@ async function runEngineDetourOnce(input) {
16019
16184
  if (input.stagedPrompt === void 0) {
16020
16185
  return spawnEngineDetourOnce(input);
16021
16186
  }
16022
- const stagingDir = await mkdtemp(join8(tmpdir(), "ak-engine-detour-"));
16023
- const stagedPath = join8(stagingDir, "prompt.txt");
16187
+ const stagingDir = await mkdtemp(join7(tmpdir(), "ak-engine-detour-"));
16188
+ const stagedPath = join7(stagingDir, "prompt.txt");
16024
16189
  let result2;
16025
16190
  let runError;
16026
16191
  try {
16027
- await writeFile3(stagedPath, input.stagedPrompt, "utf8");
16192
+ await writeFile2(stagedPath, input.stagedPrompt, "utf8");
16028
16193
  const argv = resolveArgvWithStagedPrompt(input.argv, stagedPath);
16029
16194
  result2 = await spawnEngineDetourOnce({
16030
16195
  argv,
@@ -16091,8 +16256,8 @@ import {
16091
16256
  unlinkSync,
16092
16257
  writeFileSync
16093
16258
  } from "node:fs";
16094
- import { basename as basename3, dirname as dirname5, join as join9, resolve as resolve3 } from "node:path";
16095
- function isRecord6(value) {
16259
+ import { basename as basename3, dirname as dirname5, join as join8, resolve as resolve3 } from "node:path";
16260
+ function isRecord8(value) {
16096
16261
  return typeof value === "object" && value !== null && !Array.isArray(value);
16097
16262
  }
16098
16263
  function errorCodeOf(error) {
@@ -16120,7 +16285,7 @@ function findIdentityPointer(recordFile, identity, kind, level) {
16120
16285
  if (!trimmed) continue;
16121
16286
  try {
16122
16287
  const parsed = JSON.parse(trimmed);
16123
- if (isRecord6(parsed) && parsed.identity === identity) {
16288
+ if (isRecord8(parsed) && parsed.identity === identity) {
16124
16289
  return { identity, recordFile, kind, level };
16125
16290
  }
16126
16291
  } catch {
@@ -16230,7 +16395,7 @@ function resolveSitianRecordPathInLedger(input, ledgerHome) {
16230
16395
  const category = resolveSitianVolumeCategory(input.kind);
16231
16396
  let sessionDir;
16232
16397
  if (input.sessionParent !== void 0 && input.sessionParent.length > 0 && physicallyContainedIn(ledgerHome, input.sessionParent)) {
16233
- sessionDir = join9(dirname5(input.sessionParent), category);
16398
+ sessionDir = join8(dirname5(input.sessionParent), category);
16234
16399
  } else {
16235
16400
  const bookKey = safeBookKey(cwd);
16236
16401
  const bookDir = activationBookDirectory(ledgerHome, bookKey);
@@ -16244,12 +16409,12 @@ function resolveSitianRecordPathInLedger(input, ledgerHome) {
16244
16409
  subjectStr = JSON.stringify(input.subject);
16245
16410
  }
16246
16411
  const digest = createHash2("sha256").update(subjectStr).digest("hex").slice(0, 32);
16247
- sessionDir = join9(bookDir, category, digest);
16412
+ sessionDir = join8(bookDir, category, digest);
16248
16413
  } else {
16249
- sessionDir = join9(bookDir, category);
16414
+ sessionDir = join8(bookDir, category);
16250
16415
  }
16251
16416
  }
16252
- const recordFile = join9(sessionDir, "records.jsonl");
16417
+ const recordFile = join8(sessionDir, "records.jsonl");
16253
16418
  return { sessionDir, recordFile, ledgerHome };
16254
16419
  }
16255
16420
  function resolveSitianRecordPath(input) {
@@ -16307,15 +16472,15 @@ var init_sitian_appender = __esm({
16307
16472
 
16308
16473
  // src/sitian-reader.ts
16309
16474
  import { existsSync as existsSync5 } from "node:fs";
16310
- import { readFile as readFile3 } from "node:fs/promises";
16311
- function isRecord7(value) {
16475
+ import { readFile as readFile2 } from "node:fs/promises";
16476
+ function isRecord9(value) {
16312
16477
  return typeof value === "object" && value !== null && !Array.isArray(value);
16313
16478
  }
16314
16479
  async function readSitianRecords(recordFile) {
16315
16480
  if (!existsSync5(recordFile)) {
16316
16481
  return { records: [], diagnostics: [] };
16317
16482
  }
16318
- const text = await readFile3(recordFile, "utf8");
16483
+ const text = await readFile2(recordFile, "utf8");
16319
16484
  const lines = text.split("\n");
16320
16485
  const records2 = [];
16321
16486
  const diagnostics = [];
@@ -16324,7 +16489,7 @@ async function readSitianRecords(recordFile) {
16324
16489
  if (!line2.trim()) continue;
16325
16490
  try {
16326
16491
  const parsed = JSON.parse(line2);
16327
- if (isRecord7(parsed)) {
16492
+ if (isRecord9(parsed)) {
16328
16493
  records2.push(parsed);
16329
16494
  } else {
16330
16495
  const typeDesc = parsed === null ? "null" : Array.isArray(parsed) ? "array" : typeof parsed;
@@ -16369,13 +16534,13 @@ var init_sitian_facade = __esm({
16369
16534
  // src/pi/role-turn-host.ts
16370
16535
  import { execFile, spawn as spawn2 } from "node:child_process";
16371
16536
  import { constants } from "node:fs";
16372
- import { access, appendFile, readFile as readFile4, realpath } from "node:fs/promises";
16373
- import { delimiter as delimiter2, isAbsolute as isAbsolute3, join as join10, resolve as resolve4 } from "node:path";
16537
+ import { access, appendFile, readFile as readFile3, realpath } from "node:fs/promises";
16538
+ import { delimiter as delimiter2, isAbsolute as isAbsolute3, join as join9, resolve as resolve4 } from "node:path";
16374
16539
  import { platform } from "node:process";
16375
16540
  import { promisify } from "node:util";
16376
16541
  import { randomUUID as randomUUID2 } from "node:crypto";
16377
16542
  function resolveInternalRoleEntrypoint(packageRoot2) {
16378
- return join10(packageRoot2, INTERNAL_ROLE_ENTRYPOINT_RELATIVE2);
16543
+ return join9(packageRoot2, INTERNAL_ROLE_ENTRYPOINT_RELATIVE2);
16379
16544
  }
16380
16545
  function buildExplicitInternalActivationArgs(selectedRoleEntry, extraArgs = []) {
16381
16546
  return ["--no-extensions", "-e", selectedRoleEntry, ...extraArgs];
@@ -16459,6 +16624,16 @@ function buildActivationFlagArgs(activation) {
16459
16624
  return ["--ak-role", "gatekeeper"];
16460
16625
  case "navigator":
16461
16626
  return ["--ak-role", "navigator"];
16627
+ case "auditor":
16628
+ return ["--ak-role", "auditor"];
16629
+ case "evidence-child":
16630
+ return ["--ak-role", "evidence-child"];
16631
+ case "diarist":
16632
+ return [
16633
+ "--ak-role",
16634
+ "diarist",
16635
+ ...activation.sourcesPath === void 0 ? [] : ["--ak-diarist-sources", activation.sourcesPath]
16636
+ ];
16462
16637
  default: {
16463
16638
  const _exhaustive = activation;
16464
16639
  return _exhaustive;
@@ -16555,9 +16730,15 @@ function createDefaultPiSpawnRunner(options) {
16555
16730
  child.kill("SIGTERM");
16556
16731
  }, spawnOptions.timeoutMs);
16557
16732
  };
16733
+ const parentSignal = spawnOptions.signal;
16734
+ const terminateForParentAbort = () => {
16735
+ child.kill("SIGTERM");
16736
+ };
16737
+ parentSignal?.addEventListener("abort", terminateForParentAbort, { once: true });
16558
16738
  let identityRecorded = Promise.resolve();
16559
16739
  child.once("spawn", () => {
16560
16740
  hasSpawned = true;
16741
+ if (parentSignal?.aborted === true) terminateForParentAbort();
16561
16742
  armTimeoutAfterChildReady();
16562
16743
  const runDirectory = spawnOptions.env.AK_ROLE_RUN_DIR;
16563
16744
  if (typeof runDirectory === "string" && runDirectory !== "" && options.recordLaunchedPiIdentity !== void 0) {
@@ -16573,11 +16754,13 @@ function createDefaultPiSpawnRunner(options) {
16573
16754
  return;
16574
16755
  }
16575
16756
  if (timer !== void 0) clearTimeout(timer);
16757
+ parentSignal?.removeEventListener("abort", terminateForParentAbort);
16576
16758
  settled = true;
16577
16759
  reject(error);
16578
16760
  });
16579
16761
  child.on("close", (code) => {
16580
16762
  if (timer !== void 0) clearTimeout(timer);
16763
+ parentSignal?.removeEventListener("abort", terminateForParentAbort);
16581
16764
  void identityRecorded.then(
16582
16765
  () => {
16583
16766
  if (settled) return;
@@ -16631,11 +16814,20 @@ ${paths.join("\n")}`
16631
16814
  ...process.env,
16632
16815
  HOME: request.home,
16633
16816
  PI_CODING_AGENT_DIR: request.agentDir,
16634
- AK_ROLE_RUN_DIR: request.runDirectory
16817
+ AK_ROLE_RUN_DIR: request.runDirectory,
16818
+ // Nested public summons resolve package root without import.meta under jiti (#675).
16819
+ // Child-process scoped only — not written back onto the parent process.env.
16820
+ AK_ROLE_PACKAGE_ROOT: config.packageRoot
16635
16821
  };
16636
16822
  if (request.courtAttemptId === void 0) delete env.AK_ROLE_COURT_ATTEMPT;
16637
16823
  else env.AK_ROLE_COURT_ATTEMPT = request.courtAttemptId;
16638
16824
  applyEngineChildEnv(env, request.engine);
16825
+ if (typeof process.env.AK_ROLE_AUDITOR_SOURCE_RUN === "string" && process.env.AK_ROLE_AUDITOR_SOURCE_RUN.trim() !== "") {
16826
+ env.AK_ROLE_AUDITOR_SOURCE_RUN = process.env.AK_ROLE_AUDITOR_SOURCE_RUN;
16827
+ }
16828
+ if (typeof process.env.AK_ROLE_AUDITOR_SUBJECT === "string" && process.env.AK_ROLE_AUDITOR_SUBJECT.trim() !== "") {
16829
+ env.AK_ROLE_AUDITOR_SUBJECT = process.env.AK_ROLE_AUDITOR_SUBJECT;
16830
+ }
16639
16831
  if (request.correlationId !== void 0 && request.correlationId.trim() !== "") {
16640
16832
  env.AK_CORRELATION_ID = request.correlationId;
16641
16833
  }
@@ -16649,14 +16841,15 @@ ${paths.join("\n")}`
16649
16841
  return await spawnRunner(args, {
16650
16842
  cwd: request.cwd,
16651
16843
  env,
16652
- ...timeoutMs === void 0 ? {} : { timeoutMs }
16844
+ ...timeoutMs === void 0 ? {} : { timeoutMs },
16845
+ ...request.signal === void 0 ? {} : { signal: request.signal }
16653
16846
  });
16654
16847
  }
16655
16848
  };
16656
16849
  }
16657
16850
  async function appendPiSessionCustomEntry(authority, principal, customType, data) {
16658
16851
  const { sessionFile } = authority.decode(principal);
16659
- const text = await readFile4(sessionFile, "utf8");
16852
+ const text = await readFile3(sessionFile, "utf8");
16660
16853
  let parentId = null;
16661
16854
  for (const line2 of text.trim().split("\n").filter(Boolean)) {
16662
16855
  const entry = JSON.parse(line2);
@@ -16697,8 +16890,8 @@ var init_role_turn_host = __esm({
16697
16890
  });
16698
16891
 
16699
16892
  // src/run-ticket-number.ts
16700
- import { readFile as readFile5 } from "node:fs/promises";
16701
- import { join as join11 } from "node:path";
16893
+ import { readFile as readFile4 } from "node:fs/promises";
16894
+ import { join as join10 } from "node:path";
16702
16895
  function isEnoent(error) {
16703
16896
  return error instanceof Error && "code" in error && error.code === "ENOENT";
16704
16897
  }
@@ -16711,7 +16904,7 @@ function ticketFromRecord(record4) {
16711
16904
  }
16712
16905
  async function readPageTicketNumber(runDirectory, page) {
16713
16906
  try {
16714
- const raw = JSON.parse(await readFile5(join11(runDirectory, page), "utf8"));
16907
+ const raw = JSON.parse(await readFile4(join10(runDirectory, page), "utf8"));
16715
16908
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
16716
16909
  return void 0;
16717
16910
  }
@@ -16803,12 +16996,16 @@ function validateAcceptedDetails(toolName, details) {
16803
16996
  [GLEANER_LEFT_OUTPUT_TOOL_NAME]: ["completed"],
16804
16997
  [INSPECTOR_OUTPUT_TOOL_NAME]: ["pass", "bounce"],
16805
16998
  [GATEKEEPER_OUTPUT_TOOL_NAME]: ["dispatch", "pass"],
16806
- [NAVIGATOR_OUTPUT_TOOL_NAME]: ["advice"]
16999
+ [NAVIGATOR_OUTPUT_TOOL_NAME]: ["advice"],
17000
+ [AUDITOR_OUTPUT_TOOL_NAME]: ["pass", "revise", "escalate"],
17001
+ [EVIDENCE_CHILD_OUTPUT_TOOL_NAME]: [],
17002
+ [DIARIST_OUTPUT_TOOL_NAME]: ["completed"]
16807
17003
  };
16808
17004
  const collectorDiscriminator = toolName === COLLECTOR_OUTPUT_TOOL && Array.isArray(candidate?.groups);
17005
+ const evidenceChildDiscriminator = toolName === EVIDENCE_CHILD_OUTPUT_TOOL_NAME && candidate !== null && typeof candidate === "object" && !Array.isArray(candidate);
16809
17006
  const baseDiscriminator = discriminator;
16810
17007
  const runtimeBindingMissing = toolName === DOCTOR_OUTPUT_TOOL_NAME && baseDiscriminator === "completed" && !(candidate?.cost !== null && typeof candidate?.cost === "object") || toolName === REVIEWER_OUTPUT_TOOL_NAME && candidate?.version !== 2;
16811
- if (runtimeBindingMissing || !collectorDiscriminator && (typeof discriminator !== "string" || !lawfulStatuses[toolName].includes(baseDiscriminator))) {
17008
+ if (runtimeBindingMissing || !collectorDiscriminator && !evidenceChildDiscriminator && (typeof discriminator !== "string" || !lawfulStatuses[toolName].includes(baseDiscriminator))) {
16812
17009
  throw new AcceptedDetailsContractError("terminating receipt has no recognized execution discriminator");
16813
17010
  }
16814
17011
  try {
@@ -16839,6 +17036,12 @@ function validateAcceptedDetails(toolName, details) {
16839
17036
  return validateRecordedGatekeeperOutput(details);
16840
17037
  case NAVIGATOR_OUTPUT_TOOL_NAME:
16841
17038
  return validateRecordedNavigatorOutput(details);
17039
+ case AUDITOR_OUTPUT_TOOL_NAME:
17040
+ return validateRecordedAuditorOutput(details);
17041
+ case EVIDENCE_CHILD_OUTPUT_TOOL_NAME:
17042
+ return validateRecordedEvidenceChildOutput(details);
17043
+ case DIARIST_OUTPUT_TOOL_NAME:
17044
+ return validateRecordedDiaristOutput(details);
16842
17045
  }
16843
17046
  } catch (error) {
16844
17047
  if (error instanceof Error && error.constructor === Error) throw new AcceptedDetailsContractError(error.message, { cause: error });
@@ -16856,6 +17059,11 @@ function acceptedFacts(toolName, details) {
16856
17059
  case INSPECTOR_OUTPUT_TOOL_NAME:
16857
17060
  case GATEKEEPER_OUTPUT_TOOL_NAME:
16858
17061
  case NAVIGATOR_OUTPUT_TOOL_NAME:
17062
+ case AUDITOR_OUTPUT_TOOL_NAME:
17063
+ return { status: details.status };
17064
+ case EVIDENCE_CHILD_OUTPUT_TOOL_NAME:
17065
+ return { status: "report" };
17066
+ case DIARIST_OUTPUT_TOOL_NAME:
16859
17067
  return { status: details.status };
16860
17068
  case JUDGE_OUTPUT_TOOL_NAME:
16861
17069
  return { status: details.judgeStatus };
@@ -16882,11 +17090,14 @@ var init_terminating_tools = __esm({
16882
17090
  init_doctor_contracts();
16883
17091
  init_gatekeeper_output();
16884
17092
  init_navigator_output();
17093
+ init_auditor_output();
17094
+ init_evidence_child_output();
16885
17095
  init_merger_contracts();
16886
17096
  init_notary_contracts();
16887
17097
  init_countersign_contracts();
16888
17098
  init_gleaner_left_contracts();
16889
17099
  init_inspector_contracts();
17100
+ init_diarist_contracts();
16890
17101
  init_worker_output();
16891
17102
  TERMINATING_TOOL_NAMES = [
16892
17103
  CODER_OUTPUT_TOOL_NAME,
@@ -16901,7 +17112,10 @@ var init_terminating_tools = __esm({
16901
17112
  GLEANER_LEFT_OUTPUT_TOOL_NAME,
16902
17113
  INSPECTOR_OUTPUT_TOOL_NAME,
16903
17114
  GATEKEEPER_OUTPUT_TOOL_NAME,
16904
- NAVIGATOR_OUTPUT_TOOL_NAME
17115
+ NAVIGATOR_OUTPUT_TOOL_NAME,
17116
+ AUDITOR_OUTPUT_TOOL_NAME,
17117
+ EVIDENCE_CHILD_OUTPUT_TOOL_NAME,
17118
+ DIARIST_OUTPUT_TOOL_NAME
16905
17119
  ];
16906
17120
  AcceptedDetailsContractError = class extends CorrectableSubmissionError {
16907
17121
  code = "accepted_details_contract";
@@ -16914,7 +17128,7 @@ var init_terminating_tools = __esm({
16914
17128
  });
16915
17129
 
16916
17130
  // src/doctor-evidence.ts
16917
- import { readdir, readFile as readFile6, realpath as realpath2, stat } from "node:fs/promises";
17131
+ import { readdir, readFile as readFile5, realpath as realpath2, stat } from "node:fs/promises";
16918
17132
  import { dirname as dirname6, relative as relative2, resolve as resolve5, sep as sep2 } from "node:path";
16919
17133
  function record2(value) {
16920
17134
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -17033,7 +17247,7 @@ async function loadDoctorCase(runsPath) {
17033
17247
  const turns = { count: 0, sources: [] }, calls = { count: 0, sources: [] }, tokens = { count: 0, sources: [] };
17034
17248
  for (const path of await discoverCaseFiles(root)) {
17035
17249
  const id = relative2(root, path).split(sep2).join("/");
17036
- const bytes = await readFile6(path);
17250
+ const bytes = await readFile5(path);
17037
17251
  const content = bytes.toString("utf8");
17038
17252
  const kind = id.endsWith(".jsonl") ? "session" : "stderr";
17039
17253
  evidence.push({ id, kind, byteLength: bytes.byteLength, contentLength: content.length, sha256: sha256Hex(bytes), content });
@@ -17063,7 +17277,7 @@ var init_doctor_evidence = __esm({
17063
17277
 
17064
17278
  // src/collector-config.ts
17065
17279
  import { createHash as createHash3 } from "node:crypto";
17066
- import { readFile as readFile7 } from "node:fs/promises";
17280
+ import { readFile as readFile6 } from "node:fs/promises";
17067
17281
  function fail3(message, cause) {
17068
17282
  throw new Error(message, cause === void 0 ? void 0 : { cause });
17069
17283
  }
@@ -17106,7 +17320,7 @@ function emptyCollectorManifest() {
17106
17320
  async function loadCollectorManifest(path) {
17107
17321
  let bytes;
17108
17322
  try {
17109
- bytes = await readFile7(path);
17323
+ bytes = await readFile6(path);
17110
17324
  } catch (error) {
17111
17325
  fail3(`Collector request manifest is unreadable at ${path}`, error);
17112
17326
  }
@@ -17241,10 +17455,10 @@ var init_uuidv7 = __esm({
17241
17455
  });
17242
17456
 
17243
17457
  // src/typed-provider-http.ts
17244
- import { readFile as readFile8, unlink, writeFile as writeFile4 } from "node:fs/promises";
17245
- import { join as join12 } from "node:path";
17458
+ import { readFile as readFile7, unlink, writeFile as writeFile3 } from "node:fs/promises";
17459
+ import { join as join11 } from "node:path";
17246
17460
  function typedProviderHttpPath(runDirectory) {
17247
- return join12(runDirectory, TYPED_HTTP_FILE);
17461
+ return join11(runDirectory, TYPED_HTTP_FILE);
17248
17462
  }
17249
17463
  async function clearTypedProviderHttpObservation(runDirectory) {
17250
17464
  try {
@@ -17259,7 +17473,7 @@ async function clearTypedProviderHttpObservation(runDirectory) {
17259
17473
  async function readLatestTypedProviderHttpObservation(runDirectory) {
17260
17474
  let text;
17261
17475
  try {
17262
- text = await readFile8(typedProviderHttpPath(runDirectory), "utf8");
17476
+ text = await readFile7(typedProviderHttpPath(runDirectory), "utf8");
17263
17477
  } catch (error) {
17264
17478
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
17265
17479
  return void 0;
@@ -17288,8 +17502,8 @@ var init_typed_provider_http = __esm({
17288
17502
  });
17289
17503
 
17290
17504
  // src/public-cli/run-lifecycle.ts
17291
- import { chmod, open, readdir as readdir2, readFile as readFile9, unlink as unlink2, writeFile as writeFile5 } from "node:fs/promises";
17292
- import { join as join13 } from "node:path";
17505
+ import { chmod, open, readdir as readdir2, readFile as readFile8, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
17506
+ import { join as join12 } from "node:path";
17293
17507
  function selectResumeContinuationPrompt(message, engineMaterial) {
17294
17508
  const base = message !== void 0 ? message : RESUME_TRANSPORT_ENVELOPE;
17295
17509
  return appendEngineSessionMaterial([base], engineMaterial).join("\n");
@@ -17318,8 +17532,8 @@ function renderResumeCommand(runId) {
17318
17532
  }
17319
17533
  async function writeRoleRunState(runDirectory, record4) {
17320
17534
  const payload = { ...record4, runDirectory };
17321
- await writeFile5(
17322
- join13(runDirectory, RUN_STATE_FILE),
17535
+ await writeFile4(
17536
+ join12(runDirectory, RUN_STATE_FILE),
17323
17537
  `${JSON.stringify(payload, null, 2)}
17324
17538
  `,
17325
17539
  "utf8"
@@ -17369,7 +17583,7 @@ function parseCurrentCourtState(raw) {
17369
17583
  async function readRoleRunStateDisk(runDirectory) {
17370
17584
  let raw;
17371
17585
  try {
17372
- raw = JSON.parse(await readFile9(join13(runDirectory, RUN_STATE_FILE), "utf8"));
17586
+ raw = JSON.parse(await readFile8(join12(runDirectory, RUN_STATE_FILE), "utf8"));
17373
17587
  } catch {
17374
17588
  return void 0;
17375
17589
  }
@@ -17380,7 +17594,7 @@ async function readRoleRunStateDisk(runDirectory) {
17380
17594
  if (typeof record4.runId !== "string" || record4.runId.trim() === "") {
17381
17595
  return void 0;
17382
17596
  }
17383
- if (record4.role !== "judge" && record4.role !== "coder" && record4.role !== "fixer" && record4.role !== "collector" && record4.role !== "doctor" && record4.role !== "reviewer" && record4.role !== "merger" && record4.role !== "notary" && record4.role !== "countersign" && record4.role !== "gleaner-left" && record4.role !== "inspector" && record4.role !== "gatekeeper" && record4.role !== "navigator") {
17597
+ if (record4.role !== "judge" && record4.role !== "coder" && record4.role !== "fixer" && record4.role !== "collector" && record4.role !== "doctor" && record4.role !== "reviewer" && record4.role !== "merger" && record4.role !== "notary" && record4.role !== "countersign" && record4.role !== "gleaner-left" && record4.role !== "inspector" && record4.role !== "gatekeeper" && record4.role !== "navigator" && record4.role !== "auditor" && record4.role !== "evidence-child" && record4.role !== "diarist") {
17384
17598
  return void 0;
17385
17599
  }
17386
17600
  if (record4.state !== "admitted" && record4.state !== "running" && record4.state !== "resumable" && record4.state !== "terminal") {
@@ -17435,8 +17649,8 @@ async function writeRoleRunStateDisk(runDirectory, disk) {
17435
17649
  ...disk.resumable === void 0 ? {} : { resumable: disk.resumable },
17436
17650
  ...disk.currentCourt === void 0 ? {} : { currentCourt: disk.currentCourt }
17437
17651
  };
17438
- await writeFile5(
17439
- join13(runDirectory, RUN_STATE_FILE),
17652
+ await writeFile4(
17653
+ join12(runDirectory, RUN_STATE_FILE),
17440
17654
  `${JSON.stringify(payload, null, 2)}
17441
17655
  `,
17442
17656
  "utf8"
@@ -17601,7 +17815,7 @@ function isProcessAlive(pid) {
17601
17815
  async function autopsyWriterLock(lockPath) {
17602
17816
  let content;
17603
17817
  try {
17604
- content = await readFile9(lockPath, "utf8");
17818
+ content = await readFile8(lockPath, "utf8");
17605
17819
  } catch (error) {
17606
17820
  if (errorCodeOf2(error) === "ENOENT") return { verdict: "absent" };
17607
17821
  return { verdict: "absent", readFailure: error };
@@ -17680,15 +17894,15 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
17680
17894
  };
17681
17895
  const reportCleanupFailure = (error) => {
17682
17896
  reportDiagnostic(
17683
- `writer lease lock cleanup failed (release is best-effort; residual lock left in place) at ${join13(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
17897
+ `writer lease lock cleanup failed (release is best-effort; residual lock left in place) at ${join12(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
17684
17898
  );
17685
17899
  };
17686
17900
  const reportReadFailure = (error) => {
17687
17901
  reportDiagnostic(
17688
- `writer lease lock read failed (holder liveness unverifiable; lock left in place) at ${join13(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
17902
+ `writer lease lock read failed (holder liveness unverifiable; lock left in place) at ${join12(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
17689
17903
  );
17690
17904
  };
17691
- const lockPath = join13(runDirectory, WRITER_LOCK_FILE);
17905
+ const lockPath = join12(runDirectory, WRITER_LOCK_FILE);
17692
17906
  let lastAutopsy = { verdict: "absent" };
17693
17907
  let lastReclaimFailure;
17694
17908
  for (let reclaimsLeft = WRITER_LEASE_RECLAIM_ROUNDS; ; reclaimsLeft -= 1) {
@@ -17738,7 +17952,7 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
17738
17952
  async function findRunDirectoryById(home, runId) {
17739
17953
  if (runId.trim() === "") return void 0;
17740
17954
  const ledgerHome = resolveActivationLedgerHome(home);
17741
- const booksRoot = join13(ledgerHome, "books");
17955
+ const booksRoot = join12(ledgerHome, "books");
17742
17956
  let bookKeys;
17743
17957
  try {
17744
17958
  bookKeys = await readdir2(booksRoot);
@@ -17746,7 +17960,7 @@ async function findRunDirectoryById(home, runId) {
17746
17960
  return void 0;
17747
17961
  }
17748
17962
  for (const bookKey of bookKeys) {
17749
- const runsDir = join13(activationBookDirectory(ledgerHome, bookKey), "runs");
17963
+ const runsDir = join12(activationBookDirectory(ledgerHome, bookKey), "runs");
17750
17964
  let entries;
17751
17965
  try {
17752
17966
  entries = await readdir2(runsDir);
@@ -17755,7 +17969,7 @@ async function findRunDirectoryById(home, runId) {
17755
17969
  }
17756
17970
  for (const entry of entries) {
17757
17971
  if (entry === `${runId}@judge` || entry.startsWith(`${runId}@`)) {
17758
- return join13(runsDir, entry);
17972
+ return join12(runsDir, entry);
17759
17973
  }
17760
17974
  }
17761
17975
  }
@@ -17763,7 +17977,7 @@ async function findRunDirectoryById(home, runId) {
17763
17977
  }
17764
17978
  async function findLatestRunIdForSeatTicket(input) {
17765
17979
  const ledgerHome = resolveActivationLedgerHome(input.home);
17766
- const runsDir = join13(
17980
+ const runsDir = join12(
17767
17981
  activationBookDirectory(ledgerHome, input.bookKey),
17768
17982
  "runs"
17769
17983
  );
@@ -17780,7 +17994,7 @@ async function findLatestRunIdForSeatTicket(input) {
17780
17994
  if (!entry.endsWith(suffix)) continue;
17781
17995
  const runId = entry.slice(0, entry.length - suffix.length);
17782
17996
  if (runId.length === 0) continue;
17783
- const ticketNumber = await readRunTicketNumber(join13(runsDir, entry));
17997
+ const ticketNumber = await readRunTicketNumber(join12(runsDir, entry));
17784
17998
  if (ticketNumber !== input.ticketNumber) continue;
17785
17999
  if (best === void 0 || runId > best) best = runId;
17786
18000
  }
@@ -17849,7 +18063,7 @@ async function loadResumableRunRecord(home, runId, authority) {
17849
18063
  let sourceRun;
17850
18064
  try {
17851
18065
  const raw = JSON.parse(
17852
- await readFile9(run.admittedRequestPath, "utf8")
18066
+ await readFile8(run.admittedRequestPath, "utf8")
17853
18067
  );
17854
18068
  if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) {
17855
18069
  const record4 = raw;
@@ -17962,7 +18176,7 @@ async function loadResumableRunRecord(home, runId, authority) {
17962
18176
  let model;
17963
18177
  try {
17964
18178
  const invocationRaw = JSON.parse(
17965
- await readFile9(join13(run.runDirectory, "invocation.json"), "utf8")
18179
+ await readFile8(join12(run.runDirectory, "invocation.json"), "utf8")
17966
18180
  );
17967
18181
  if (invocationRaw !== null && typeof invocationRaw === "object" && !Array.isArray(invocationRaw)) {
17968
18182
  const rec = invocationRaw;
@@ -18164,7 +18378,7 @@ async function loadResumableCountersignRun(home, runId, authority) {
18164
18378
  }
18165
18379
  async function loadResumableInstructionSeatRun(home, runId, authority) {
18166
18380
  const loaded = await loadResumableRunRecord(home, runId, authority);
18167
- if (loaded.run.role !== "gatekeeper" && loaded.run.role !== "navigator") {
18381
+ if (loaded.run.role !== "gatekeeper" && loaded.run.role !== "navigator" && loaded.run.role !== "auditor" && loaded.run.role !== "evidence-child") {
18168
18382
  throw new CliUsageError(
18169
18383
  `role run ${runId} belongs to ${loaded.run.role}, not an instruction seat`
18170
18384
  );
@@ -18195,6 +18409,19 @@ async function loadResumableGleanerLeftRun(home, runId, authority) {
18195
18409
  };
18196
18410
  return seatLoadedResult(loaded, admitted);
18197
18411
  }
18412
+ async function loadResumableDiaristRun(home, runId, authority) {
18413
+ const loaded = await loadResumableRunRecord(home, runId, authority);
18414
+ if (loaded.run.role !== "diarist") {
18415
+ throw new CliUsageError(
18416
+ `role run ${runId} belongs to ${loaded.run.role}, not diarist`
18417
+ );
18418
+ }
18419
+ const admitted = {
18420
+ role: "diarist",
18421
+ ...resumedBaseAdmitted(loaded)
18422
+ };
18423
+ return seatLoadedResult(loaded, admitted);
18424
+ }
18198
18425
  async function loadResumableMergerRun(home, runId, authority) {
18199
18426
  const loaded = await loadResumableRunRecord(home, runId, authority);
18200
18427
  if (loaded.run.role !== "merger") {
@@ -18354,7 +18581,13 @@ var init_run_lifecycle = __esm({
18354
18581
  });
18355
18582
 
18356
18583
  // src/notary-source-run.ts
18357
- import { dirname as dirname7, isAbsolute as isAbsolute4, join as join14, resolve as resolve6, basename as basename4 } from "node:path";
18584
+ var notary_source_run_exports = {};
18585
+ __export(notary_source_run_exports, {
18586
+ NotarySourceRunError: () => NotarySourceRunError,
18587
+ loadNotarySourceRunLocator: () => loadNotarySourceRunLocator,
18588
+ resolveNotarySourceRunLocator: () => resolveNotarySourceRunLocator
18589
+ });
18590
+ import { dirname as dirname7, isAbsolute as isAbsolute4, join as join13, resolve as resolve6, basename as basename4 } from "node:path";
18358
18591
  import { lstat as lstat2, realpath as realpath3 } from "node:fs/promises";
18359
18592
  function parseRunDirectoryName(name) {
18360
18593
  const match = RUN_DIR_NAME.exec(name);
@@ -18400,11 +18633,11 @@ async function resolveNotarySourceRunLocator(options) {
18400
18633
  }
18401
18634
  const ledgerHome = resolveActivationLedgerHome(options.home);
18402
18635
  const bookKey = resolveBookKeyFromGit(options.projectRoot);
18403
- const bookRunsRoot = join14(activationBookDirectory(ledgerHome, bookKey), "runs");
18636
+ const bookRunsRoot = join13(activationBookDirectory(ledgerHome, bookKey), "runs");
18404
18637
  let candidate;
18405
18638
  const bare = parseRunDirectoryName(raw);
18406
18639
  if (bare !== void 0 && !raw.includes("/") && !raw.includes("\\")) {
18407
- candidate = join14(bookRunsRoot, `${bare.runId}@${bare.role}`);
18640
+ candidate = join13(bookRunsRoot, `${bare.runId}@${bare.role}`);
18408
18641
  } else {
18409
18642
  candidate = isAbsolute4(raw) ? raw : resolve6(options.projectRoot, raw);
18410
18643
  }
@@ -18444,6 +18677,31 @@ async function resolveNotarySourceRunLocator(options) {
18444
18677
  role: identity.role
18445
18678
  };
18446
18679
  }
18680
+ async function loadNotarySourceRunLocator(path) {
18681
+ const real = await requireRunDirectory(path, path);
18682
+ const identity = parseRunDirectoryName(basename4(real));
18683
+ const runState = await readRoleRunIdentity(real);
18684
+ if (runState === void 0) {
18685
+ throw new NotarySourceRunError(
18686
+ "notary source-run lacks retained run-state identity"
18687
+ );
18688
+ }
18689
+ if (runState.runId !== identity.runId || runState.role !== identity.role) {
18690
+ throw new NotarySourceRunError(
18691
+ "notary source-run retained identity does not match directory name"
18692
+ );
18693
+ }
18694
+ if (physicalPathIdentity(runState.runDirectory) !== physicalPathIdentity(real)) {
18695
+ throw new NotarySourceRunError(
18696
+ "notary source-run retained runDirectory does not match locator path"
18697
+ );
18698
+ }
18699
+ return {
18700
+ runDirectory: real,
18701
+ runId: identity.runId,
18702
+ role: identity.role
18703
+ };
18704
+ }
18447
18705
  var RUN_DIR_NAME, NotarySourceRunError;
18448
18706
  var init_notary_source_run = __esm({
18449
18707
  "src/notary-source-run.ts"() {
@@ -18451,7 +18709,7 @@ var init_notary_source_run = __esm({
18451
18709
  init_activation_ledger_git();
18452
18710
  init_activation_ledger_topology();
18453
18711
  init_run_lifecycle();
18454
- RUN_DIR_NAME = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})@([A-Za-z][A-Za-z0-9_-]*)$/i;
18712
+ RUN_DIR_NAME = /^([A-Za-z0-9][A-Za-z0-9._-]*)@([A-Za-z][A-Za-z0-9_-]*)$/;
18455
18713
  NotarySourceRunError = class extends Error {
18456
18714
  constructor(message, options) {
18457
18715
  super(message, options);
@@ -18711,7 +18969,7 @@ function renderHumanOwnerOptionLines(owner, locale2 = "en") {
18711
18969
  }
18712
18970
  return lines;
18713
18971
  }
18714
- var ANALYST_REQUIRE_ANY_OF, ANALYST_DEFAULT_MODE, REJECTED_PUBLIC_SPELLINGS, GLOBAL_OPTIONS, SHARED_PROJECT_SEMANTICS, SHARED_ATTACH_SEMANTICS, JUDGE_OPTIONS, GLEANER_LEFT_OPTIONS, INSPECTOR_OPTIONS, GATEKEEPER_OPTIONS, NAVIGATOR_OPTIONS, COUNTERSIGN_OPTIONS, CODER_OPTIONS, FIXER_OPTIONS, REVIEWER_OPTIONS, COLLECTOR_OPTIONS, DOCTOR_OPTIONS, NOTARY_OPTIONS, MERGER_OPTIONS, ANALYST_OPTIONS, PUBLIC_OPTION_TABLE, PUBLIC_NAVIGATOR_HELP_NOTE, TOP_LEVEL_HELP, ROLE_COMMAND_HELP, SUPPORT_COMMAND_HELP, PUBLIC_COMMAND_HELP;
18972
+ var ANALYST_REQUIRE_ANY_OF, ANALYST_DEFAULT_MODE, REJECTED_PUBLIC_SPELLINGS, GLOBAL_OPTIONS, SHARED_PROJECT_SEMANTICS, SHARED_ATTACH_SEMANTICS, JUDGE_OPTIONS, GLEANER_LEFT_OPTIONS, INSPECTOR_OPTIONS, GATEKEEPER_OPTIONS, NAVIGATOR_OPTIONS, AUDITOR_OPTIONS, EVIDENCE_CHILD_OPTIONS, COUNTERSIGN_OPTIONS, DIARIST_OPTIONS, CODER_OPTIONS, FIXER_OPTIONS, REVIEWER_OPTIONS, COLLECTOR_OPTIONS, DOCTOR_OPTIONS, NOTARY_OPTIONS, MERGER_OPTIONS, ANALYST_OPTIONS, PUBLIC_OPTION_TABLE, PUBLIC_NAVIGATOR_HELP_NOTE, TOP_LEVEL_HELP, ROLE_COMMAND_HELP, SUPPORT_COMMAND_HELP, PUBLIC_COMMAND_HELP;
18715
18973
  var init_option_definitions = __esm({
18716
18974
  "src/public-cli/option-definitions.ts"() {
18717
18975
  "use strict";
@@ -18884,10 +19142,50 @@ var init_option_definitions = __esm({
18884
19142
  bindOwner("navigator", SHARED_PROJECT_SEMANTICS),
18885
19143
  bindOwner("navigator", SHARED_ATTACH_SEMANTICS)
18886
19144
  ];
19145
+ AUDITOR_OPTIONS = [
19146
+ bindOwner("auditor", SHARED_PROJECT_SEMANTICS),
19147
+ bindOwner("auditor", SHARED_ATTACH_SEMANTICS),
19148
+ {
19149
+ id: "subject",
19150
+ owner: "auditor",
19151
+ canonical: "--subject",
19152
+ aliases: [],
19153
+ valueMetavar: "judge|doctor",
19154
+ required: true,
19155
+ repeatable: false,
19156
+ form: "option",
19157
+ description: {
19158
+ en: "Required audited subject: judge or doctor (selects judge-auditor.md / doctor-auditor.md).",
19159
+ zh: "\u5FC5\u586B\u53D7\u5BA1\u5BF9\u8C61\uFF1Ajudge \u6216 doctor\uFF08\u88C5 judge-auditor.md / doctor-auditor.md\uFF09\u3002"
19160
+ }
19161
+ },
19162
+ {
19163
+ id: "source-run",
19164
+ owner: "auditor",
19165
+ canonical: "--source-run",
19166
+ aliases: [],
19167
+ valueMetavar: "runId@role|path",
19168
+ required: true,
19169
+ repeatable: false,
19170
+ form: "option",
19171
+ description: {
19172
+ en: "Required source run locator of the audited subject volume (same input for direct and nested summons).",
19173
+ zh: "\u5FC5\u586B\u53D7\u5BA1\u5377\u5B97 locator\uFF08\u76F4\u8C03\u4E0E\u4F20\u53EC\u540C\u4E00\u8F93\u5165\u9762\uFF09\u3002"
19174
+ }
19175
+ }
19176
+ ];
19177
+ EVIDENCE_CHILD_OPTIONS = [
19178
+ bindOwner("evidence-child", SHARED_PROJECT_SEMANTICS),
19179
+ bindOwner("evidence-child", SHARED_ATTACH_SEMANTICS)
19180
+ ];
18887
19181
  COUNTERSIGN_OPTIONS = [
18888
19182
  bindOwner("countersign", SHARED_PROJECT_SEMANTICS),
18889
19183
  bindOwner("countersign", SHARED_ATTACH_SEMANTICS)
18890
19184
  ];
19185
+ DIARIST_OPTIONS = [
19186
+ bindOwner("diarist", SHARED_PROJECT_SEMANTICS),
19187
+ bindOwner("diarist", SHARED_ATTACH_SEMANTICS)
19188
+ ];
18891
19189
  CODER_OPTIONS = [
18892
19190
  {
18893
19191
  id: "phase",
@@ -19233,6 +19531,9 @@ var init_option_definitions = __esm({
19233
19531
  inspector: INSPECTOR_OPTIONS,
19234
19532
  gatekeeper: GATEKEEPER_OPTIONS,
19235
19533
  navigator: NAVIGATOR_OPTIONS,
19534
+ auditor: AUDITOR_OPTIONS,
19535
+ "evidence-child": EVIDENCE_CHILD_OPTIONS,
19536
+ diarist: DIARIST_OPTIONS,
19236
19537
  analyst: ANALYST_OPTIONS
19237
19538
  };
19238
19539
  PUBLIC_NAVIGATOR_HELP_NOTE = "Navigator also attends automatically on every run; that sidecar is unchanged by direct `ak-role navigator` calls.";
@@ -19351,6 +19652,32 @@ var init_option_definitions = __esm({
19351
19652
  'ak-role navigator "\u521A\u5B8C\u6210 coder apply \u6536\u655B\uFF0C\u4E0B\u4E00\u6B65\uFF1F"'
19352
19653
  ]
19353
19654
  },
19655
+ auditor: {
19656
+ command: "auditor",
19657
+ summary: "Direct Auditor (\u5BA1\u5211\u9662) compliance audit: pass, revise, or escalate.",
19658
+ usage: ["ak-role auditor --subject <judge|doctor> --source-run <runId@role|path> [options] [instruction]"],
19659
+ examples: [
19660
+ 'ak-role auditor --subject judge --source-run 01abc\u2026@judge --attach ./dossier "\u5BA1\uFF1A\u672C run \u662F\u5426\u5408\u89C4\u3002"',
19661
+ 'ak-role auditor --subject doctor --source-run 01abc\u2026@doctor "\u5BA1\uFF1A\u592A\u533B\u5019\u9009\u662F\u5426\u5408\u89C4\u3002"'
19662
+ ]
19663
+ },
19664
+ "evidence-child": {
19665
+ command: "evidence-child",
19666
+ summary: "Direct evidence-child fact gathering; submit one report.",
19667
+ usage: ["ak-role evidence-child [options] [instruction]"],
19668
+ examples: [
19669
+ 'ak-role evidence-child "\u67E5\uFF1A\u672C\u5DE5\u4F5C\u6811 diff \u4E0E\u7968\u9762\u662F\u5426\u4E00\u81F4\u3002"'
19670
+ ]
19671
+ },
19672
+ diarist: {
19673
+ command: "diarist",
19674
+ summary: "Direct Diarist (\u8D77\u5C45\u90CE) pass: gather and organize this case's decision basis into its \u8D77\u5C45\u5F55.",
19675
+ usage: ["ak-role diarist [options] [instruction]"],
19676
+ examples: [
19677
+ 'ak-role diarist "\u6574\u7406 #708 \u7684\u672C\u6848\u4F9D\u636E\u3002"',
19678
+ 'ak-role diarist --attach ./design.md "\u8865\u5F55\u672C\u8F6E\u8BBE\u8BA1\u4FEE\u8BA2\u3002"'
19679
+ ]
19680
+ },
19354
19681
  notary: {
19355
19682
  command: "notary",
19356
19683
  summary: "Direct Notary document check (quote fidelity + ticket alignment); zero prompt/attachment.",
@@ -19443,15 +19770,15 @@ import { execFileSync as execFileSync2 } from "node:child_process";
19443
19770
  import {
19444
19771
  lstat as lstat3,
19445
19772
  mkdir as mkdir2,
19446
- readFile as readFile10,
19773
+ readFile as readFile9,
19447
19774
  realpath as realpath4,
19448
- writeFile as writeFile6
19775
+ writeFile as writeFile5
19449
19776
  } from "node:fs/promises";
19450
- import { basename as basename5, isAbsolute as isAbsolute5, join as join15, resolve as resolve7, sep as sep3 } from "node:path";
19777
+ import { basename as basename5, isAbsolute as isAbsolute5, join as join14, resolve as resolve7, sep as sep3 } from "node:path";
19451
19778
  function issueAdmissionPlacement(authority, request) {
19452
19779
  const principal = authority.issue(request);
19453
19780
  const { sessionDirectory, sessionFile } = authority.decode(principal);
19454
- const runDirectory = join15(sessionDirectory, "..");
19781
+ const runDirectory = join14(sessionDirectory, "..");
19455
19782
  const ledgerHome = resolveActivationLedgerHome(request.home);
19456
19783
  const bookKey = resolveBookKeyFromGit(request.cwd);
19457
19784
  return {
@@ -19470,7 +19797,7 @@ async function writeAdmittedRequestPersistence(admittedRequestPath, body, coordi
19470
19797
  sessionDirectory: coordinates.sessionDirectory,
19471
19798
  sessionFile: coordinates.sessionFile
19472
19799
  };
19473
- await writeFile6(
19800
+ await writeFile5(
19474
19801
  admittedRequestPath,
19475
19802
  `${JSON.stringify(projection, null, 2)}
19476
19803
  `,
@@ -19498,20 +19825,16 @@ async function writeRoleInvocationLedger(source, role, effectiveModel) {
19498
19825
  ...source.ticketNumber === void 0 ? {} : { ticketNumber: source.ticketNumber },
19499
19826
  ...effectiveModelLedgerFields(effectiveModel)
19500
19827
  };
19501
- await writeFile6(
19502
- join15(source.runDirectory, "invocation.json"),
19828
+ await writeFile5(
19829
+ join14(source.runDirectory, "invocation.json"),
19503
19830
  `${JSON.stringify(identity, null, 2)}
19504
19831
  `,
19505
19832
  "utf8"
19506
19833
  );
19507
- const home = homeFromRunDirectory(source.runDirectory);
19508
- const config = await loadPublicCliConfig(home);
19509
- const institutionalPage = resolveInstitutionalSeatSelections(config, effectiveModel);
19510
- await writeInstitutionalResolutionPage(source.runDirectory, institutionalPage);
19511
19834
  }
19512
19835
  async function recordEffectiveInvocationModel(runDirectory, model, engine, host) {
19513
- const ledgerPath = join15(runDirectory, "invocation.json");
19514
- const current = JSON.parse(await readFile10(ledgerPath, "utf8"));
19836
+ const ledgerPath = join14(runDirectory, "invocation.json");
19837
+ const current = JSON.parse(await readFile9(ledgerPath, "utf8"));
19515
19838
  const next = { ...current };
19516
19839
  if (model !== void 0) {
19517
19840
  next.provider = model.provider;
@@ -19530,26 +19853,17 @@ async function recordEffectiveInvocationModel(runDirectory, model, engine, host)
19530
19853
  if (host !== void 0) {
19531
19854
  next.host = host;
19532
19855
  }
19533
- await writeFile6(
19856
+ await writeFile5(
19534
19857
  ledgerPath,
19535
19858
  `${JSON.stringify(next, null, 2)}
19536
19859
  `,
19537
19860
  "utf8"
19538
19861
  );
19539
- const effectiveModel = typeof next.provider === "string" && typeof next.model === "string" ? {
19540
- provider: next.provider,
19541
- model: next.model,
19542
- ...typeof next.thinking === "string" ? { thinking: next.thinking } : {}
19543
- } : void 0;
19544
- const home = homeFromRunDirectory(runDirectory);
19545
- const config = await loadPublicCliConfig(home);
19546
- const institutionalPage = resolveInstitutionalSeatSelections(config, effectiveModel);
19547
- await writeInstitutionalResolutionPage(runDirectory, institutionalPage);
19548
19862
  }
19549
19863
  async function mergeInvocationIdentityPage(runDirectory, fields) {
19550
- const ledgerPath = join15(runDirectory, "invocation.json");
19551
- const current = JSON.parse(await readFile10(ledgerPath, "utf8"));
19552
- await writeFile6(
19864
+ const ledgerPath = join14(runDirectory, "invocation.json");
19865
+ const current = JSON.parse(await readFile9(ledgerPath, "utf8"));
19866
+ await writeFile5(
19553
19867
  ledgerPath,
19554
19868
  `${JSON.stringify({
19555
19869
  ...current,
@@ -19577,8 +19891,8 @@ async function bindAdmittedTicketNumber(admitted, ticketNumber) {
19577
19891
  admitted.ticketNumber = ticketNumber;
19578
19892
  await mergeInvocationIdentityPage(admitted.runDirectory, { ticketNumber });
19579
19893
  const admittedPath = admitted.admittedRequestPath;
19580
- const current = JSON.parse(await readFile10(admittedPath, "utf8"));
19581
- await writeFile6(
19894
+ const current = JSON.parse(await readFile9(admittedPath, "utf8"));
19895
+ await writeFile5(
19582
19896
  admittedPath,
19583
19897
  `${JSON.stringify({ ...current, ticketNumber }, null, 2)}
19584
19898
  `,
@@ -19597,8 +19911,8 @@ async function recordTrueUnboundTicketResolution(admitted) {
19597
19911
  ticketResolution: "true-unbound"
19598
19912
  });
19599
19913
  const admittedPath = admitted.admittedRequestPath;
19600
- const current = JSON.parse(await readFile10(admittedPath, "utf8"));
19601
- await writeFile6(
19914
+ const current = JSON.parse(await readFile9(admittedPath, "utf8"));
19915
+ await writeFile5(
19602
19916
  admittedPath,
19603
19917
  `${JSON.stringify({ ...current, ticketResolution: "true-unbound" }, null, 2)}
19604
19918
  `,
@@ -19614,7 +19928,7 @@ async function recordLaunchedPiIdentity(runDirectory, identity) {
19614
19928
  async function observeLaunchedRolePackageIdentity(packageRoot2, selectedRoleEntry) {
19615
19929
  const rolePackageRoot = packageRoot2;
19616
19930
  const raw = JSON.parse(
19617
- await readFile10(join15(rolePackageRoot, "package.json"), "utf8")
19931
+ await readFile9(join14(rolePackageRoot, "package.json"), "utf8")
19618
19932
  );
19619
19933
  if (typeof raw.version !== "string" || raw.version.trim() === "") {
19620
19934
  throw new Error(
@@ -19639,6 +19953,8 @@ async function recordLaunchedRolePackageIdentity(runDirectory, identity) {
19639
19953
  function parseInstructionArgv(args, owner) {
19640
19954
  const attachmentPaths = [];
19641
19955
  let project;
19956
+ let subject;
19957
+ let sourceRun;
19642
19958
  const positional = [];
19643
19959
  const tokens = [...args];
19644
19960
  const definitions = roleOptions(owner);
@@ -19659,6 +19975,24 @@ function parseInstructionArgv(args, owner) {
19659
19975
  project = requireOptionPath(taken.def.canonical, taken.value);
19660
19976
  continue;
19661
19977
  }
19978
+ if (taken.def.id === "subject") {
19979
+ const raw = typeof taken.value === "string" ? taken.value.trim() : "";
19980
+ if (raw !== "judge" && raw !== "doctor") {
19981
+ throw new CliUsageError(
19982
+ `auditor --subject must be judge|doctor, got ${taken.value ?? "(missing)"}`
19983
+ );
19984
+ }
19985
+ subject = raw;
19986
+ continue;
19987
+ }
19988
+ if (taken.def.id === "source-run") {
19989
+ const raw = typeof taken.value === "string" ? taken.value.trim() : "";
19990
+ if (raw === "") {
19991
+ throw new CliUsageError("auditor --source-run requires a run locator");
19992
+ }
19993
+ sourceRun = raw;
19994
+ continue;
19995
+ }
19662
19996
  throw new CliUsageError(`unknown ${owner} option: ${taken.def.canonical}`);
19663
19997
  }
19664
19998
  const token = tokens.shift();
@@ -19671,7 +20005,9 @@ function parseInstructionArgv(args, owner) {
19671
20005
  return {
19672
20006
  instruction: positional.join(" "),
19673
20007
  attachmentPaths,
19674
- ...project === void 0 ? {} : { project }
20008
+ ...project === void 0 ? {} : { project },
20009
+ ...subject === void 0 ? {} : { subject },
20010
+ ...sourceRun === void 0 ? {} : { sourceRun }
19675
20011
  };
19676
20012
  }
19677
20013
  function requireOptionPath(flag, value) {
@@ -19729,6 +20065,15 @@ function parseGatekeeperArgv(args) {
19729
20065
  function parseNavigatorArgv(args) {
19730
20066
  return parseInstructionArgv(args, "navigator");
19731
20067
  }
20068
+ function parseAuditorArgv(args) {
20069
+ return parseInstructionArgv(args, "auditor");
20070
+ }
20071
+ function parseEvidenceChildArgv(args) {
20072
+ return parseInstructionArgv(args, "evidence-child");
20073
+ }
20074
+ function parseDiaristArgv(args) {
20075
+ return parseInstructionArgv(args, "diarist");
20076
+ }
19732
20077
  function parseCoderArgv(args) {
19733
20078
  const attachmentPaths = [];
19734
20079
  let project;
@@ -19831,10 +20176,10 @@ async function freezeRegularFileAttachment(sourcePath, destinationDir, index) {
19831
20176
  `attachment must be a regular file (not a directory or symlink): ${sourcePath}`
19832
20177
  );
19833
20178
  }
19834
- const bytes = await readFile10(absolute);
20179
+ const bytes = await readFile9(absolute);
19835
20180
  const name = `${String(index).padStart(2, "0")}-${basename5(absolute)}`;
19836
- const frozenPath = join15(destinationDir, name);
19837
- await writeFile6(frozenPath, bytes);
20181
+ const frozenPath = join14(destinationDir, name);
20182
+ await writeFile5(frozenPath, bytes);
19838
20183
  return {
19839
20184
  attachment: {
19840
20185
  provenancePath: absolute,
@@ -19861,7 +20206,7 @@ async function freezeAttachments(attachmentPaths, attachmentsDirectory) {
19861
20206
  async function freezeAttachmentsIntoRun(attachmentPaths, runDirectory, summonsKey = `s-${Date.now().toString(36)}`) {
19862
20207
  if (attachmentPaths.length === 0) return [];
19863
20208
  const ledgerHome = resolveActivationLedgerHome(homeFromRunDirectory(runDirectory));
19864
- const attachmentsDirectory = join15(runDirectory, "attachments", summonsKey);
20209
+ const attachmentsDirectory = join14(runDirectory, "attachments", summonsKey);
19865
20210
  ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
19866
20211
  return freezeAttachments(attachmentPaths, attachmentsDirectory);
19867
20212
  }
@@ -19887,7 +20232,7 @@ async function admitStandardMaterialInvocation(role, options) {
19887
20232
  role,
19888
20233
  home: options.home
19889
20234
  });
19890
- const attachmentsDirectory = join15(runDirectory, "attachments");
20235
+ const attachmentsDirectory = join14(runDirectory, "attachments");
19891
20236
  ensureRealDirectoryTree(ledgerHome, sessionDirectory);
19892
20237
  ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
19893
20238
  const attachments = await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
@@ -19912,7 +20257,7 @@ async function admitStandardMaterialInvocation(role, options) {
19912
20257
  mediaKind: a.mediaKind
19913
20258
  }))
19914
20259
  };
19915
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
20260
+ const admittedRequestPath = join14(runDirectory, "admitted-request.json");
19916
20261
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
19917
20262
  sessionDirectory,
19918
20263
  sessionFile
@@ -19948,6 +20293,15 @@ async function admitGatekeeperInvocation(options) {
19948
20293
  async function admitNavigatorInvocation(options) {
19949
20294
  return admitStandardMaterialInvocation("navigator", options);
19950
20295
  }
20296
+ async function admitAuditorInvocation(options) {
20297
+ return admitStandardMaterialInvocation("auditor", options);
20298
+ }
20299
+ async function admitEvidenceChildInvocation(options) {
20300
+ return admitStandardMaterialInvocation("evidence-child", options);
20301
+ }
20302
+ async function admitDiaristInvocation(options) {
20303
+ return admitStandardMaterialInvocation("diarist", options);
20304
+ }
19951
20305
  function buildInstructionTransportPrompt(admitted, engineMaterial) {
19952
20306
  const lines = [admitted.instructionEmpty ? "" : admitted.instruction];
19953
20307
  if (admitted.attachments.length > 0) {
@@ -19984,7 +20338,7 @@ async function admitCountersignInvocation(options) {
19984
20338
  role: "countersign",
19985
20339
  home: options.home
19986
20340
  });
19987
- const attachmentsDirectory = join15(runDirectory, "attachments");
20341
+ const attachmentsDirectory = join14(runDirectory, "attachments");
19988
20342
  ensureRealDirectoryTree(ledgerHome, sessionDirectory);
19989
20343
  ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
19990
20344
  const attachments = await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
@@ -20008,7 +20362,7 @@ async function admitCountersignInvocation(options) {
20008
20362
  mediaKind: a.mediaKind
20009
20363
  }))
20010
20364
  };
20011
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
20365
+ const admittedRequestPath = join14(runDirectory, "admitted-request.json");
20012
20366
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
20013
20367
  sessionDirectory,
20014
20368
  sessionFile
@@ -20032,7 +20386,7 @@ function buildCountersignTransportPrompt(admitted, engineMaterial) {
20032
20386
  return buildInstructionTransportPrompt(admitted, engineMaterial);
20033
20387
  }
20034
20388
  async function ensureRunArtifactsDir(runDirectory) {
20035
- const dir = join15(runDirectory, "artifacts");
20389
+ const dir = join14(runDirectory, "artifacts");
20036
20390
  await mkdir2(dir, { recursive: true });
20037
20391
  return dir;
20038
20392
  }
@@ -20064,12 +20418,12 @@ async function admitCoderInvocation(options) {
20064
20418
  role: "coder",
20065
20419
  home: options.home
20066
20420
  });
20067
- const attachmentsDirectory = join15(runDirectory, "attachments");
20421
+ const attachmentsDirectory = join14(runDirectory, "attachments");
20068
20422
  ensureRealDirectoryTree(ledgerHome, sessionDirectory);
20069
20423
  ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
20070
20424
  const attachments = await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
20071
- const taskPath = join15(runDirectory, "task.md");
20072
- await writeFile6(taskPath, instruction, "utf8");
20425
+ const taskPath = join14(runDirectory, "task.md");
20426
+ await writeFile5(taskPath, instruction, "utf8");
20073
20427
  const admitted = {
20074
20428
  role: "coder",
20075
20429
  phase: options.phase,
@@ -20089,7 +20443,7 @@ async function admitCoderInvocation(options) {
20089
20443
  mediaKind: a.mediaKind
20090
20444
  }))
20091
20445
  };
20092
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
20446
+ const admittedRequestPath = join14(runDirectory, "admitted-request.json");
20093
20447
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
20094
20448
  sessionDirectory,
20095
20449
  sessionFile
@@ -20139,7 +20493,7 @@ async function admitFixerInvocation(options) {
20139
20493
  if (options.prerequisitesPath !== void 0) {
20140
20494
  const absolutePrereq = isAbsolute5(options.prerequisitesPath) ? options.prerequisitesPath : resolve7(options.prerequisitesPath);
20141
20495
  try {
20142
- prerequisitesSource = await readFile10(absolutePrereq, "utf8");
20496
+ prerequisitesSource = await readFile9(absolutePrereq, "utf8");
20143
20497
  } catch (error) {
20144
20498
  throw new CliUsageError(
20145
20499
  `fixer prerequisites path is unreadable: ${options.prerequisitesPath}`,
@@ -20170,22 +20524,22 @@ async function admitFixerInvocation(options) {
20170
20524
  role: "fixer",
20171
20525
  home: options.home
20172
20526
  });
20173
- const attachmentsDirectory = join15(runDirectory, "attachments");
20527
+ const attachmentsDirectory = join14(runDirectory, "attachments");
20174
20528
  ensureRealDirectoryTree(ledgerHome, sessionDirectory);
20175
20529
  ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
20176
20530
  const attachments = await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
20177
20531
  let prerequisitesPath;
20178
20532
  if (prerequisitesSource !== void 0) {
20179
- prerequisitesPath = join15(runDirectory, "prerequisites.json");
20180
- await writeFile6(
20533
+ prerequisitesPath = join14(runDirectory, "prerequisites.json");
20534
+ await writeFile5(
20181
20535
  prerequisitesPath,
20182
20536
  `${JSON.stringify(prerequisites, null, 2)}
20183
20537
  `,
20184
20538
  "utf8"
20185
20539
  );
20186
20540
  }
20187
- const packetPath = join15(runDirectory, "fix-packet.md");
20188
- await writeFile6(packetPath, instruction, "utf8");
20541
+ const packetPath = join14(runDirectory, "fix-packet.md");
20542
+ await writeFile5(packetPath, instruction, "utf8");
20189
20543
  const admitted = {
20190
20544
  role: "fixer",
20191
20545
  phase: options.phase,
@@ -20210,7 +20564,7 @@ async function admitFixerInvocation(options) {
20210
20564
  mediaKind: a.mediaKind
20211
20565
  }))
20212
20566
  };
20213
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
20567
+ const admittedRequestPath = join14(runDirectory, "admitted-request.json");
20214
20568
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
20215
20569
  sessionDirectory,
20216
20570
  sessionFile
@@ -20419,14 +20773,14 @@ async function admitCollectorInvocation(options) {
20419
20773
  role: "collector",
20420
20774
  home: options.home
20421
20775
  });
20422
- const attachmentsDirectory = join15(runDirectory, "attachments");
20776
+ const attachmentsDirectory = join14(runDirectory, "attachments");
20423
20777
  ensureRealDirectoryTree(ledgerHome, sessionDirectory);
20424
20778
  ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
20425
20779
  const attachments = await freezeAttachments(options.attachmentPaths ?? [], attachmentsDirectory);
20426
20780
  let requestManifestPath;
20427
20781
  if (manifestCanonicalJson !== void 0) {
20428
- requestManifestPath = join15(runDirectory, "request-manifest.json");
20429
- await writeFile6(requestManifestPath, manifestCanonicalJson, "utf8");
20782
+ requestManifestPath = join14(runDirectory, "request-manifest.json");
20783
+ await writeFile5(requestManifestPath, manifestCanonicalJson, "utf8");
20430
20784
  }
20431
20785
  const instruction = options.instruction ?? "";
20432
20786
  const instructionEmpty = instruction.trim() === "";
@@ -20452,7 +20806,7 @@ async function admitCollectorInvocation(options) {
20452
20806
  mediaKind: a.mediaKind
20453
20807
  }))
20454
20808
  };
20455
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
20809
+ const admittedRequestPath = join14(runDirectory, "admitted-request.json");
20456
20810
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
20457
20811
  sessionDirectory,
20458
20812
  sessionFile
@@ -20549,7 +20903,7 @@ function parseDoctorArgv(args) {
20549
20903
  }
20550
20904
  async function resolveDoctorCaseRunsPath(options) {
20551
20905
  const ledgerHome = resolveActivationLedgerHome(options.home);
20552
- const defaultRuns = join15(
20906
+ const defaultRuns = join14(
20553
20907
  activationBookDirectory(ledgerHome, options.bookKey),
20554
20908
  "issues",
20555
20909
  String(options.issueNumber),
@@ -20656,7 +21010,7 @@ async function admitDoctorInvocation(options) {
20656
21010
  { cause: error }
20657
21011
  );
20658
21012
  }
20659
- const attachmentsDirectory = join15(runDirectory, "attachments");
21013
+ const attachmentsDirectory = join14(runDirectory, "attachments");
20660
21014
  ensureRealDirectoryTree(ledgerHome, sessionDirectory);
20661
21015
  ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
20662
21016
  const attachments = await freezeAttachments(options.attachmentPaths ?? [], attachmentsDirectory);
@@ -20682,7 +21036,7 @@ async function admitDoctorInvocation(options) {
20682
21036
  mediaKind: a.mediaKind
20683
21037
  }))
20684
21038
  };
20685
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
21039
+ const admittedRequestPath = join14(runDirectory, "admitted-request.json");
20686
21040
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
20687
21041
  sessionDirectory,
20688
21042
  sessionFile
@@ -20814,7 +21168,7 @@ async function admitNotaryInvocation(options) {
20814
21168
  ...ticketFields,
20815
21169
  ...options.correlationId === void 0 ? {} : { correlationId: options.correlationId }
20816
21170
  };
20817
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
21171
+ const admittedRequestPath = join14(runDirectory, "admitted-request.json");
20818
21172
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
20819
21173
  sessionDirectory,
20820
21174
  sessionFile
@@ -20916,7 +21270,7 @@ async function admitGleanerLeftInvocation(options) {
20916
21270
  attachments: [],
20917
21271
  ...options.correlationId === void 0 ? {} : { correlationId: options.correlationId }
20918
21272
  };
20919
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
21273
+ const admittedRequestPath = join14(runDirectory, "admitted-request.json");
20920
21274
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
20921
21275
  sessionDirectory,
20922
21276
  sessionFile
@@ -21021,7 +21375,7 @@ async function admitReviewerInvocation(options) {
21021
21375
  role: "reviewer",
21022
21376
  home: options.home
21023
21377
  });
21024
- const attachmentsDirectory = join15(runDirectory, "attachments");
21378
+ const attachmentsDirectory = join14(runDirectory, "attachments");
21025
21379
  ensureRealDirectoryTree(ledgerHome, sessionDirectory);
21026
21380
  ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
21027
21381
  const attachments = await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
@@ -21046,7 +21400,7 @@ async function admitReviewerInvocation(options) {
21046
21400
  mediaKind: a.mediaKind
21047
21401
  }))
21048
21402
  };
21049
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
21403
+ const admittedRequestPath = join14(runDirectory, "admitted-request.json");
21050
21404
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
21051
21405
  sessionDirectory,
21052
21406
  sessionFile
@@ -21173,7 +21527,7 @@ async function admitMergerInvocation(options) {
21173
21527
  role: "merger",
21174
21528
  home: options.home
21175
21529
  });
21176
- const attachmentsDirectory = join15(runDirectory, "attachments");
21530
+ const attachmentsDirectory = join14(runDirectory, "attachments");
21177
21531
  ensureRealDirectoryTree(ledgerHome, sessionDirectory);
21178
21532
  ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
21179
21533
  const attachments = await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
@@ -21201,8 +21555,8 @@ async function admitMergerInvocation(options) {
21201
21555
  // Authorized checks remain available on the assignment; default none.
21202
21556
  authorizedChecks: []
21203
21557
  });
21204
- const mergerInputPath = join15(runDirectory, "merger-input.json");
21205
- await writeFile6(
21558
+ const mergerInputPath = join14(runDirectory, "merger-input.json");
21559
+ await writeFile5(
21206
21560
  mergerInputPath,
21207
21561
  `${JSON.stringify(mergerInput, null, 2)}
21208
21562
  `,
@@ -21233,7 +21587,7 @@ async function admitMergerInvocation(options) {
21233
21587
  mediaKind: a.mediaKind
21234
21588
  }))
21235
21589
  };
21236
- const admittedRequestPath = join15(runDirectory, "admitted-request.json");
21590
+ const admittedRequestPath = join14(runDirectory, "admitted-request.json");
21237
21591
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
21238
21592
  sessionDirectory,
21239
21593
  sessionFile
@@ -21506,8 +21860,6 @@ var init_invocation = __esm({
21506
21860
  init_engine_material();
21507
21861
  init_cli_errors();
21508
21862
  init_option_definitions();
21509
- init_config2();
21510
- init_institutional_resolution();
21511
21863
  MergerEnvelopeDerivationError = class extends Error {
21512
21864
  code = "merger-envelope-derivation";
21513
21865
  /** Typed cause for #107 classifyPostAdmissionFailure (isTypedActivationError). */
@@ -21525,8 +21877,8 @@ var init_invocation = __esm({
21525
21877
 
21526
21878
  // src/package-resources/method-skill.ts
21527
21879
  import { createHash as createHash4 } from "node:crypto";
21528
- import { readFile as readFile11, realpath as realpath5 } from "node:fs/promises";
21529
- import { join as join16 } from "node:path";
21880
+ import { readFile as readFile10, realpath as realpath5 } from "node:fs/promises";
21881
+ import { join as join15 } from "node:path";
21530
21882
  function gitBlobOid(bytes) {
21531
21883
  const body = typeof bytes === "string" ? Buffer.from(bytes, "utf8") : Buffer.from(bytes);
21532
21884
  const header = Buffer.from(`blob ${body.byteLength}\0`, "utf8");
@@ -21543,16 +21895,16 @@ function packagedMethodSkillRelativeDirectory(name) {
21543
21895
  return `${METHOD_SKILL_RELATIVE_ROOT}/${name}`;
21544
21896
  }
21545
21897
  function resolvePackagedMethodSkillRoot(packageRoot2, name) {
21546
- return join16(packageRoot2, packagedMethodSkillRelativeDirectory(name));
21898
+ return join15(packageRoot2, packagedMethodSkillRelativeDirectory(name));
21547
21899
  }
21548
21900
  function resolvePackagedMethodSkillPath(packageRoot2, name) {
21549
- return join16(resolvePackagedMethodSkillRoot(packageRoot2, name), "SKILL.md");
21901
+ return join15(resolvePackagedMethodSkillRoot(packageRoot2, name), "SKILL.md");
21550
21902
  }
21551
- function isRecord8(value) {
21903
+ function isRecord10(value) {
21552
21904
  return typeof value === "object" && value !== null && !Array.isArray(value);
21553
21905
  }
21554
21906
  function parseProvenance(raw, expectedName) {
21555
- if (!isRecord8(raw)) {
21907
+ if (!isRecord10(raw)) {
21556
21908
  throw new Error(`Packaged method provenance must be an object for ${expectedName}`);
21557
21909
  }
21558
21910
  if (raw.name !== expectedName) {
@@ -21566,7 +21918,7 @@ function parseProvenance(raw, expectedName) {
21566
21918
  if (typeof raw.packageAdaptation !== "string" || raw.packageAdaptation.trim() === "") {
21567
21919
  throw new Error(`Packaged method provenance packageAdaptation must be nonblank`);
21568
21920
  }
21569
- if (!isRecord8(raw.upstream)) {
21921
+ if (!isRecord10(raw.upstream)) {
21570
21922
  throw new Error(`Packaged method provenance upstream must be an object`);
21571
21923
  }
21572
21924
  const upstream = raw.upstream;
@@ -21593,12 +21945,12 @@ function parseProvenance(raw, expectedName) {
21593
21945
  `Packaged method provenance upstream must include nonblank tag or version`
21594
21946
  );
21595
21947
  }
21596
- if (!isRecord8(raw.files)) {
21948
+ if (!isRecord10(raw.files)) {
21597
21949
  throw new Error(`Packaged method provenance files must be an object`);
21598
21950
  }
21599
21951
  const files = {};
21600
21952
  for (const [rel, entry] of Object.entries(raw.files)) {
21601
- if (!isRecord8(entry)) {
21953
+ if (!isRecord10(entry)) {
21602
21954
  throw new Error(`Packaged method provenance file entry must be an object: ${rel}`);
21603
21955
  }
21604
21956
  if (typeof entry.sha256 !== "string" || !SHA256_RE.test(entry.sha256)) {
@@ -21640,11 +21992,11 @@ function parseProvenance(raw, expectedName) {
21640
21992
  }
21641
21993
  async function loadPackagedMethodSkillMaterial(packageRoot2, name) {
21642
21994
  const rootDirectory = resolvePackagedMethodSkillRoot(packageRoot2, name);
21643
- const skillPathConfigured = join16(rootDirectory, "SKILL.md");
21644
- const provenancePath = join16(rootDirectory, "provenance.json");
21995
+ const skillPathConfigured = join15(rootDirectory, "SKILL.md");
21996
+ const provenancePath = join15(rootDirectory, "provenance.json");
21645
21997
  let provenanceRaw;
21646
21998
  try {
21647
- provenanceRaw = await readFile11(provenancePath, "utf8");
21999
+ provenanceRaw = await readFile10(provenancePath, "utf8");
21648
22000
  } catch (error) {
21649
22001
  throw new PackagedMethodSkillUnavailableError(name, provenancePath, error);
21650
22002
  }
@@ -21658,10 +22010,10 @@ async function loadPackagedMethodSkillMaterial(packageRoot2, name) {
21658
22010
  }
21659
22011
  const provenance = parseProvenance(provenanceJson, name);
21660
22012
  for (const [rel, expected] of Object.entries(provenance.files)) {
21661
- const absolute = join16(rootDirectory, rel);
22013
+ const absolute = join15(rootDirectory, rel);
21662
22014
  let bytes;
21663
22015
  try {
21664
- bytes = await readFile11(absolute);
22016
+ bytes = await readFile10(absolute);
21665
22017
  } catch (error) {
21666
22018
  throw new PackagedMethodSkillUnavailableError(name, absolute, error);
21667
22019
  }
@@ -21677,7 +22029,7 @@ async function loadPackagedMethodSkillMaterial(packageRoot2, name) {
21677
22029
  let raw;
21678
22030
  try {
21679
22031
  skillPath = await realpath5(skillPathConfigured);
21680
- raw = await readFile11(skillPath, "utf8");
22032
+ raw = await readFile10(skillPath, "utf8");
21681
22033
  } catch (error) {
21682
22034
  throw new PackagedMethodSkillUnavailableError(name, skillPathConfigured, error);
21683
22035
  }
@@ -21757,7 +22109,7 @@ var init_method_skill = __esm({
21757
22109
 
21758
22110
  // src/collector-github.ts
21759
22111
  import { spawn as spawn3 } from "node:child_process";
21760
- function isRecord9(value) {
22112
+ function isRecord11(value) {
21761
22113
  return typeof value === "object" && value !== null && !Array.isArray(value);
21762
22114
  }
21763
22115
  function requireString(value, label) {
@@ -21798,25 +22150,25 @@ function commentFailureCause(error) {
21798
22150
  };
21799
22151
  }
21800
22152
  function requireUserLogin(raw) {
21801
- if (!isRecord9(raw) || typeof raw["login"] !== "string") {
22153
+ if (!isRecord11(raw) || typeof raw["login"] !== "string") {
21802
22154
  throw new Error("GitHub payload missing user.login");
21803
22155
  }
21804
22156
  return raw["login"];
21805
22157
  }
21806
22158
  function optionalUserLogin(raw) {
21807
22159
  if (raw === null) return null;
21808
- if (!isRecord9(raw) || typeof raw["login"] !== "string") {
22160
+ if (!isRecord11(raw) || typeof raw["login"] !== "string") {
21809
22161
  throw new Error("GitHub payload missing user.login");
21810
22162
  }
21811
22163
  return raw["login"];
21812
22164
  }
21813
22165
  function machineIdentity(raw) {
21814
22166
  const user = raw["user"];
21815
- if (!isRecord9(user) || typeof user["type"] !== "string" || typeof user["id"] !== "number") {
22167
+ if (!isRecord11(user) || typeof user["type"] !== "string" || typeof user["id"] !== "number") {
21816
22168
  return null;
21817
22169
  }
21818
22170
  const app = raw["performed_via_github_app"];
21819
- const appId = isRecord9(app) && typeof app["id"] === "number" ? app["id"] : void 0;
22171
+ const appId = isRecord11(app) && typeof app["id"] === "number" ? app["id"] : void 0;
21820
22172
  return {
21821
22173
  userType: user["type"],
21822
22174
  userId: user["id"],
@@ -21824,9 +22176,9 @@ function machineIdentity(raw) {
21824
22176
  };
21825
22177
  }
21826
22178
  function normalizePullRequest(raw) {
21827
- if (!isRecord9(raw)) throw new Error("GitHub pull request payload must be an object");
22179
+ if (!isRecord11(raw)) throw new Error("GitHub pull request payload must be an object");
21828
22180
  const head = raw["head"];
21829
- if (!isRecord9(head) || typeof head["sha"] !== "string" || head["sha"].length === 0) {
22181
+ if (!isRecord11(head) || typeof head["sha"] !== "string" || head["sha"].length === 0) {
21830
22182
  throw new Error("GitHub pull request payload missing head.sha");
21831
22183
  }
21832
22184
  const number = requireNumber(raw["number"], "number");
@@ -21842,7 +22194,7 @@ function normalizePullRequest(raw) {
21842
22194
  };
21843
22195
  }
21844
22196
  function normalizePullRequestReaction(raw) {
21845
- if (!isRecord9(raw)) throw new Error("GitHub reaction payload must be an object");
22197
+ if (!isRecord11(raw)) throw new Error("GitHub reaction payload must be an object");
21846
22198
  return {
21847
22199
  id: requireNumber(raw["id"], "reaction.id"),
21848
22200
  userLogin: optionalUserLogin(raw["user"]),
@@ -21853,7 +22205,7 @@ function normalizePullRequestReaction(raw) {
21853
22205
  };
21854
22206
  }
21855
22207
  function normalizeReview(raw) {
21856
- if (!isRecord9(raw)) throw new Error("GitHub review payload must be an object");
22208
+ if (!isRecord11(raw)) throw new Error("GitHub review payload must be an object");
21857
22209
  return {
21858
22210
  id: requireNumber(raw["id"], "review.id"),
21859
22211
  ...typeof raw["node_id"] === "string" ? { nodeId: raw["node_id"] } : {},
@@ -21868,7 +22220,7 @@ function normalizeReview(raw) {
21868
22220
  };
21869
22221
  }
21870
22222
  function normalizeIssueComment(raw) {
21871
- if (!isRecord9(raw)) throw new Error("GitHub issue comment payload must be an object");
22223
+ if (!isRecord11(raw)) throw new Error("GitHub issue comment payload must be an object");
21872
22224
  return {
21873
22225
  id: requireNumber(raw["id"], "comment.id"),
21874
22226
  userLogin: optionalUserLogin(raw["user"]),
@@ -21881,7 +22233,7 @@ function normalizeIssueComment(raw) {
21881
22233
  };
21882
22234
  }
21883
22235
  function normalizeReviewComment(raw) {
21884
- if (!isRecord9(raw)) throw new Error("GitHub review comment payload must be an object");
22236
+ if (!isRecord11(raw)) throw new Error("GitHub review comment payload must be an object");
21885
22237
  return {
21886
22238
  id: requireNumber(raw["id"], "review_comment.id"),
21887
22239
  pullRequestReviewId: typeof raw["pull_request_review_id"] === "number" ? raw["pull_request_review_id"] : null,
@@ -22190,11 +22542,11 @@ function createGhCollectorGitHubTransport(runner = createGhApiRunner()) {
22190
22542
  if (input.signal?.aborted) {
22191
22543
  throw error;
22192
22544
  }
22193
- if (isRecord9(error) && error["ambiguousGhFailure"] === true) {
22545
+ if (isRecord11(error) && error["ambiguousGhFailure"] === true) {
22194
22546
  const cause = commentFailureCause(error);
22195
22547
  return { kind: "ambiguous_loss", diagnostics: cause.message, cause };
22196
22548
  }
22197
- if (isRecord9(error) && error["name"] === "AbortError") {
22549
+ if (isRecord11(error) && error["name"] === "AbortError") {
22198
22550
  throw error;
22199
22551
  }
22200
22552
  throw error;
@@ -22212,10 +22564,10 @@ var init_collector_github = __esm({
22212
22564
 
22213
22565
  // src/diarist-ticket-resolution.ts
22214
22566
  import { existsSync as existsSync6, readFileSync as readFileSync2 } from "node:fs";
22215
- import { join as join17 } from "node:path";
22567
+ import { join as join16 } from "node:path";
22216
22568
  import { fileURLToPath } from "node:url";
22217
22569
  function resolveDiaristResolveTicketMethodPath(packageRoot2 = fileURLToPath(new URL("..", import.meta.url))) {
22218
- return join17(packageRoot2, DIARIST_RESOLVE_TICKET_METHOD_RELATIVE);
22570
+ return join16(packageRoot2, DIARIST_RESOLVE_TICKET_METHOD_RELATIVE);
22219
22571
  }
22220
22572
  function instructionContainsTicketNumber(instruction, ticketNumber) {
22221
22573
  if (!Number.isSafeInteger(ticketNumber) || ticketNumber < 1) return false;
@@ -22438,7 +22790,7 @@ var init_adr_path_refs = __esm({
22438
22790
  // src/diarist-mechanical.ts
22439
22791
  import { createHash as createHash5 } from "node:crypto";
22440
22792
  import { existsSync as existsSync7, readdirSync as readdirSync2, readFileSync as readFileSync3, realpathSync as realpathSync3, statSync as statSync2 } from "node:fs";
22441
- import { basename as basename6, join as join18, resolve as resolve8 } from "node:path";
22793
+ import { basename as basename6, join as join17, resolve as resolve8 } from "node:path";
22442
22794
  import { homedir } from "node:os";
22443
22795
  function extractCornerQuotes(text, minLength = DEFAULT_QUOTE_MIN) {
22444
22796
  const out = [];
@@ -22450,21 +22802,6 @@ function extractCornerQuotes(text, minLength = DEFAULT_QUOTE_MIN) {
22450
22802
  }
22451
22803
  return out;
22452
22804
  }
22453
- function buildDiaristAnchors(input) {
22454
- const fromBody = input.ticketBody === void 0 ? [] : extractCornerQuotes(input.ticketBody);
22455
- const quotes = [...fromBody, ...input.extraQuotes ?? []];
22456
- const seen = /* @__PURE__ */ new Set();
22457
- const uniqueQuotes = [];
22458
- for (const q of quotes) {
22459
- if (seen.has(q)) continue;
22460
- seen.add(q);
22461
- uniqueQuotes.push(q);
22462
- }
22463
- return {
22464
- ticketNumber: input.ticketNumber,
22465
- quotes: uniqueQuotes
22466
- };
22467
- }
22468
22805
  function filterNotifications(blocks) {
22469
22806
  return blocks.filter((b) => !b.isNotification);
22470
22807
  }
@@ -22490,15 +22827,6 @@ function dedupeSourceBlocks(blocks) {
22490
22827
  }
22491
22828
  return out;
22492
22829
  }
22493
- function verifyQuotesVerbatim(sourceText, quotes) {
22494
- const failed = [];
22495
- for (const q of quotes) {
22496
- if (q.length === 0) continue;
22497
- if (!sourceText.includes(q)) failed.push(q);
22498
- }
22499
- if (failed.length === 0) return { ok: true };
22500
- return { ok: false, failedQuotes: failed };
22501
- }
22502
22830
  function mechanicalSafeguardPipeline(blocks) {
22503
22831
  return dedupeSourceBlocks(filterNotifications(blocks));
22504
22832
  }
@@ -22506,12 +22834,12 @@ function encodeClaudeProjectDir(cwd) {
22506
22834
  const abs = cwd.startsWith("/") ? cwd : `/${cwd}`;
22507
22835
  return abs.replace(/\//g, "-");
22508
22836
  }
22509
- function isRecord10(value) {
22837
+ function isRecord12(value) {
22510
22838
  return typeof value === "object" && value !== null && !Array.isArray(value);
22511
22839
  }
22512
22840
  function messageText(message) {
22513
22841
  if (typeof message === "string") return message;
22514
- if (!isRecord10(message)) return "";
22842
+ if (!isRecord12(message)) return "";
22515
22843
  const content = message.content;
22516
22844
  if (typeof content === "string") return content;
22517
22845
  if (!Array.isArray(content)) return "";
@@ -22521,7 +22849,7 @@ function messageText(message) {
22521
22849
  parts.push(part);
22522
22850
  continue;
22523
22851
  }
22524
- if (!isRecord10(part)) continue;
22852
+ if (!isRecord12(part)) continue;
22525
22853
  if (typeof part.text === "string") parts.push(part.text);
22526
22854
  else if (typeof part.content === "string") parts.push(part.content);
22527
22855
  }
@@ -22542,16 +22870,16 @@ function isNotificationRow(type, text) {
22542
22870
  return false;
22543
22871
  }
22544
22872
  function readCcSessionBlocks(options) {
22545
- const root = options.projectsRoot ?? join18(homedir(), ".claude", "projects");
22873
+ const root = options.projectsRoot ?? join17(homedir(), ".claude", "projects");
22546
22874
  if (!existsSync7(root)) return [];
22547
22875
  const blocks = [];
22548
22876
  const dirs = /* @__PURE__ */ new Set();
22549
22877
  for (const cwd of options.cwds) {
22550
- dirs.add(join18(root, encodeClaudeProjectDir(cwd)));
22878
+ dirs.add(join17(root, encodeClaudeProjectDir(cwd)));
22551
22879
  }
22552
22880
  for (const cwd of options.cwds) {
22553
22881
  if (cwd.includes("projects")) continue;
22554
- const direct = join18(root, cwd);
22882
+ const direct = join17(root, cwd);
22555
22883
  if (existsSync7(direct)) dirs.add(direct);
22556
22884
  }
22557
22885
  for (const dir of dirs) {
@@ -22580,7 +22908,7 @@ function readCcSessionBlocks(options) {
22580
22908
  );
22581
22909
  }
22582
22910
  for (const name of files) {
22583
- const sessionFile = join18(dir, name);
22911
+ const sessionFile = join17(dir, name);
22584
22912
  let text;
22585
22913
  try {
22586
22914
  text = readFileSync3(sessionFile, "utf8");
@@ -22607,9 +22935,9 @@ function readCcSessionBlocks(options) {
22607
22935
  { cause: error }
22608
22936
  );
22609
22937
  }
22610
- if (!isRecord10(parsed)) continue;
22938
+ if (!isRecord12(parsed)) continue;
22611
22939
  const type = typeof parsed.type === "string" ? parsed.type : "";
22612
- const queuedCommand = type === "attachment" && isRecord10(parsed.attachment) && parsed.attachment.type === "queued_command" && isRecord10(parsed.attachment.origin) && parsed.attachment.origin.kind === "human" && typeof parsed.attachment.prompt === "string" ? parsed.attachment.prompt : void 0;
22940
+ const queuedCommand = type === "attachment" && isRecord12(parsed.attachment) && parsed.attachment.type === "queued_command" && isRecord12(parsed.attachment.origin) && parsed.attachment.origin.kind === "human" && typeof parsed.attachment.prompt === "string" ? parsed.attachment.prompt : void 0;
22613
22941
  if (type !== "user" && type !== "assistant" && queuedCommand === void 0) {
22614
22942
  continue;
22615
22943
  }
@@ -22754,38 +23082,6 @@ function readAdrDecisionKeyBlocks(input) {
22754
23082
  }
22755
23083
  return blocks;
22756
23084
  }
22757
- function blockToLlmEntry(block, input) {
22758
- const verify = verifyQuotesVerbatim(block.transcript, input.quotes);
22759
- if (!verify.ok) {
22760
- return {
22761
- ok: false,
22762
- failedQuotes: verify.failedQuotes,
22763
- cause: `verbatim verify failed: ${verify.failedQuotes.join(" | ")}`
22764
- };
22765
- }
22766
- const anchorNotes = [`#${input.anchors.ticketNumber}`];
22767
- const seen = new Set(anchorNotes);
22768
- for (const q of [...input.anchors.quotes, ...input.quotes]) {
22769
- if (seen.has(q)) continue;
22770
- seen.add(q);
22771
- anchorNotes.push(q);
22772
- if (anchorNotes.length >= 12) break;
22773
- }
22774
- return {
22775
- ok: true,
22776
- entry: {
22777
- basis: {
22778
- method: "llm-semantic",
22779
- anchors: anchorNotes,
22780
- ...input.note === void 0 ? {} : { note: input.note }
22781
- },
22782
- sourceKind: block.sourceKind,
22783
- sourceRef: block.sourceRef,
22784
- transcript: block.transcript,
22785
- timestamp: block.timestamp
22786
- }
22787
- };
22788
- }
22789
23085
  var DEFAULT_QUOTE_MIN, DiaristSourceReadError, DIARIST_ADR_ROOT_REL;
22790
23086
  var init_diarist_mechanical = __esm({
22791
23087
  "src/diarist-mechanical.ts"() {
@@ -22807,193 +23103,6 @@ var init_diarist_mechanical = __esm({
22807
23103
  }
22808
23104
  });
22809
23105
 
22810
- // src/diarist-llm-collector.ts
22811
- import { existsSync as existsSync8, readFileSync as readFileSync4 } from "node:fs";
22812
- import { join as join19 } from "node:path";
22813
- import { fileURLToPath as fileURLToPath2 } from "node:url";
22814
- function resolveDiaristCollectMethodPath(packageRoot2 = fileURLToPath2(packageRootUrl)) {
22815
- return join19(packageRoot2, DIARIST_COLLECT_METHOD_RELATIVE);
22816
- }
22817
- function isRecord11(value) {
22818
- return typeof value === "object" && value !== null && !Array.isArray(value);
22819
- }
22820
- function parseDiaristLlmStdout(stdout, candidateCount) {
22821
- const trimmed = stdout.trim();
22822
- if (trimmed.length === 0) {
22823
- throw new DiaristLlmStdoutError("empty-stdout", "diarist collector stdout is empty");
22824
- }
22825
- let parsed;
22826
- try {
22827
- parsed = JSON.parse(trimmed);
22828
- } catch (error) {
22829
- throw new DiaristLlmStdoutError(
22830
- "unparseable-json",
22831
- "diarist collector stdout is not JSON",
22832
- { cause: error }
22833
- );
22834
- }
22835
- if (!isRecord11(parsed)) {
22836
- throw new DiaristLlmStdoutError(
22837
- "not-object",
22838
- "diarist collector stdout must be one JSON object"
22839
- );
22840
- }
22841
- if (!Object.prototype.hasOwnProperty.call(parsed, "selections")) {
22842
- throw new DiaristLlmStdoutError(
22843
- "selections-missing",
22844
- "diarist collector stdout missing selections"
22845
- );
22846
- }
22847
- if (!Array.isArray(parsed.selections)) {
22848
- throw new DiaristLlmStdoutError(
22849
- "selections-wrong-type",
22850
- "diarist collector selections must be an array"
22851
- );
22852
- }
22853
- const out = [];
22854
- for (let rowIndex = 0; rowIndex < parsed.selections.length; rowIndex += 1) {
22855
- const row = parsed.selections[rowIndex];
22856
- if (!isRecord11(row)) {
22857
- throw new DiaristLlmStdoutError(
22858
- "selection-uninterpretable",
22859
- `diarist collector selection[${rowIndex}] is not an object`
22860
- );
22861
- }
22862
- if (typeof row.candidateIndex !== "number" || !Number.isInteger(row.candidateIndex)) {
22863
- throw new DiaristLlmStdoutError(
22864
- "selection-uninterpretable",
22865
- `diarist collector selection[${rowIndex}].candidateIndex is not an integer`
22866
- );
22867
- }
22868
- const index = row.candidateIndex;
22869
- if (index < 0 || index >= candidateCount) {
22870
- throw new DiaristLlmStdoutError(
22871
- "selection-uninterpretable",
22872
- `diarist collector selection[${rowIndex}].candidateIndex ${index} out of range 0..${candidateCount - 1}`
22873
- );
22874
- }
22875
- if (!Object.prototype.hasOwnProperty.call(row, "quotes")) {
22876
- throw new DiaristLlmStdoutError(
22877
- "selection-uninterpretable",
22878
- `diarist collector selection[${rowIndex}].quotes missing`
22879
- );
22880
- }
22881
- if (!Array.isArray(row.quotes)) {
22882
- throw new DiaristLlmStdoutError(
22883
- "selection-uninterpretable",
22884
- `diarist collector selection[${rowIndex}].quotes must be an array`
22885
- );
22886
- }
22887
- const quotes = [];
22888
- for (let qIndex = 0; qIndex < row.quotes.length; qIndex += 1) {
22889
- const q = row.quotes[qIndex];
22890
- if (typeof q !== "string") {
22891
- throw new DiaristLlmStdoutError(
22892
- "selection-uninterpretable",
22893
- `diarist collector selection[${rowIndex}].quotes[${qIndex}] is not a string`
22894
- );
22895
- }
22896
- if (q.length > 0) quotes.push(q);
22897
- }
22898
- const triage = row.triage === "relevant" || row.triage === "context" || row.triage === "irrelevant" ? row.triage : void 0;
22899
- out.push({
22900
- candidateIndex: index,
22901
- quotes,
22902
- ...typeof row.note === "string" ? { note: row.note } : {},
22903
- ...triage === void 0 ? {} : { triage }
22904
- });
22905
- }
22906
- return out;
22907
- }
22908
- function buildDiaristCollectorEnginePayload(input) {
22909
- return {
22910
- method: input.method,
22911
- ticketNumber: input.ticketNumber,
22912
- candidates: input.candidates.map((block, index) => ({
22913
- candidateIndex: index,
22914
- sourceKind: block.sourceKind,
22915
- isUserTurn: block.isUserTurn,
22916
- timestamp: block.timestamp,
22917
- transcript: block.transcript
22918
- }))
22919
- };
22920
- }
22921
- function serializeDiaristCollectorEnginePayload(payload) {
22922
- return JSON.stringify(payload);
22923
- }
22924
- function createHermesDiaristCollector(options = {}) {
22925
- const executable = options.executable ?? "hermes";
22926
- const methodPath = resolveDiaristCollectMethodPath(options.packageRoot);
22927
- if (!existsSync8(methodPath)) {
22928
- throw new Error(`diarist collect method material missing (${methodPath})`);
22929
- }
22930
- const method = readFileSync4(methodPath, "utf8");
22931
- if (method.trim().length === 0) {
22932
- throw new Error(`diarist collect method material is empty (${methodPath})`);
22933
- }
22934
- return async (input) => {
22935
- const payload = buildDiaristCollectorEnginePayload({
22936
- ticketNumber: input.ticketNumber,
22937
- candidates: input.candidates,
22938
- method
22939
- });
22940
- const prompt = serializeDiaristCollectorEnginePayload(payload);
22941
- const argv = [
22942
- executable,
22943
- ...options.extraArgv ?? [],
22944
- "chat",
22945
- "--query-file",
22946
- ENGINE_DETOUR_STAGED_PROMPT_TOKEN,
22947
- "-Q",
22948
- "--no-restore-cwd",
22949
- "--ignore-rules",
22950
- "-t",
22951
- HERMES_DIARIST_COLLECTOR_TOOLSET
22952
- ];
22953
- const result2 = await runEngineDetourOnce({
22954
- argv,
22955
- stagedPrompt: prompt,
22956
- cwd: options.cwd ?? process.cwd(),
22957
- ...options.env === void 0 ? {} : { env: options.env },
22958
- ...input.signal === void 0 ? {} : { signal: input.signal }
22959
- });
22960
- if (result2.code !== 0) {
22961
- throw new Error(
22962
- `diarist LLM collector engine exited ${result2.code}: ${result2.stderr.slice(0, 500)}`
22963
- );
22964
- }
22965
- const selections = parseDiaristLlmStdout(
22966
- result2.stdout,
22967
- input.candidates.length
22968
- );
22969
- return {
22970
- selections,
22971
- rawStdout: result2.stdout,
22972
- // Staged body redacted — argv face shows the path token only.
22973
- engineArgv: argv
22974
- };
22975
- };
22976
- }
22977
- var DIARIST_COLLECT_METHOD_RELATIVE, packageRootUrl, DiaristLlmStdoutError, HERMES_DIARIST_COLLECTOR_TOOLSET;
22978
- var init_diarist_llm_collector = __esm({
22979
- "src/diarist-llm-collector.ts"() {
22980
- "use strict";
22981
- init_engine_detour();
22982
- DIARIST_COLLECT_METHOD_RELATIVE = "resources/diarist-collect.md";
22983
- packageRootUrl = new URL("..", import.meta.url);
22984
- DiaristLlmStdoutError = class extends Error {
22985
- code = "diarist-llm-stdout";
22986
- reason;
22987
- constructor(reason, message, options) {
22988
- super(message, options);
22989
- this.name = "DiaristLlmStdoutError";
22990
- this.reason = reason;
22991
- }
22992
- };
22993
- HERMES_DIARIST_COLLECTOR_TOOLSET = "context_engine";
22994
- }
22995
- });
22996
-
22997
23106
  // src/reviewer-git-snapshot.ts
22998
23107
  var init_reviewer_git_snapshot = __esm({
22999
23108
  "src/reviewer-git-snapshot.ts"() {
@@ -23052,11 +23161,11 @@ var init_reviewer_pinned_git = __esm({
23052
23161
  });
23053
23162
 
23054
23163
  // src/ticket-provenance-contracts.ts
23055
- function isRecord12(value) {
23164
+ function isRecord13(value) {
23056
23165
  return typeof value === "object" && value !== null && !Array.isArray(value);
23057
23166
  }
23058
23167
  function projectTicketProvenanceDiagnostic(value) {
23059
- if (!isRecord12(value)) return void 0;
23168
+ if (!isRecord13(value)) return void 0;
23060
23169
  if (value.recordClass !== TICKET_PROVENANCE_RECORD_CLASS_DIAGNOSTIC) {
23061
23170
  return void 0;
23062
23171
  }
@@ -23078,18 +23187,18 @@ function projectTicketProvenanceDiagnostic(value) {
23078
23187
  };
23079
23188
  }
23080
23189
  function projectTicketProvenanceEntry(value) {
23081
- if (!isRecord12(value)) return void 0;
23190
+ if (!isRecord13(value)) return void 0;
23082
23191
  if (value.recordClass === TICKET_PROVENANCE_RECORD_CLASS_DIAGNOSTIC) {
23083
23192
  return void 0;
23084
23193
  }
23085
- if (!isRecord12(value.basis)) return void 0;
23194
+ if (!isRecord13(value.basis)) return void 0;
23086
23195
  if (typeof value.basis.method !== "string" || !BASIS_METHODS.has(value.basis.method)) {
23087
23196
  return void 0;
23088
23197
  }
23089
23198
  if (typeof value.sourceKind !== "string" || !SOURCE_KINDS.has(value.sourceKind)) {
23090
23199
  return void 0;
23091
23200
  }
23092
- if (!isRecord12(value.sourceRef)) return void 0;
23201
+ if (!isRecord13(value.sourceRef)) return void 0;
23093
23202
  if (typeof value.transcript !== "string" || value.transcript.length === 0) {
23094
23203
  return void 0;
23095
23204
  }
@@ -23144,8 +23253,8 @@ var init_ticket_provenance_contracts = __esm({
23144
23253
 
23145
23254
  // src/ticket-provenance.ts
23146
23255
  import { createHash as createHash6 } from "node:crypto";
23147
- import { appendFileSync as appendFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "node:fs";
23148
- import { join as join20 } from "node:path";
23256
+ import { appendFileSync as appendFileSync2, existsSync as existsSync8, mkdirSync as mkdirSync3, readFileSync as readFileSync4, writeFileSync as writeFileSync2 } from "node:fs";
23257
+ import { join as join18 } from "node:path";
23149
23258
  function ticketProvenanceSubject(ticketNumber) {
23150
23259
  if (!Number.isSafeInteger(ticketNumber) || ticketNumber < 1) {
23151
23260
  throw new Error(`ticket-provenance subject requires a positive ticket number, got ${String(ticketNumber)}`);
@@ -23168,30 +23277,6 @@ function ticketProvenanceEntryIdentity(input) {
23168
23277
  ].join("\0");
23169
23278
  return createHash6("sha256").update(material, "utf8").digest("hex");
23170
23279
  }
23171
- function appendTicketProvenanceEntry(input) {
23172
- const subject = ticketProvenanceSubject(input.ticketNumber);
23173
- const identity = ticketProvenanceEntryIdentity({
23174
- ticketNumber: input.ticketNumber,
23175
- sourceKind: input.entry.sourceKind,
23176
- sourceRef: input.entry.sourceRef,
23177
- transcript: input.entry.transcript
23178
- });
23179
- return sitianReport({
23180
- level: "event",
23181
- kind: TICKET_PROVENANCE_KIND,
23182
- identity,
23183
- subject,
23184
- cwd: input.cwd,
23185
- ...input.home === void 0 ? {} : { home: input.home },
23186
- host: input.host ?? "diarist",
23187
- source: input.source ?? "diarist",
23188
- payload: input.entry,
23189
- raw: input.entry.sourceRef.sessionFile !== void 0 && input.entry.sourceRef.entryId !== void 0 ? {
23190
- sessionFile: input.entry.sourceRef.sessionFile,
23191
- entryId: input.entry.sourceRef.entryId
23192
- } : void 0
23193
- });
23194
- }
23195
23280
  function resolveTicketProvenanceVolume(ticketNumber, cwd, home) {
23196
23281
  const path = resolveSitianRecordPath({
23197
23282
  level: "event",
@@ -23203,16 +23288,16 @@ function resolveTicketProvenanceVolume(ticketNumber, cwd, home) {
23203
23288
  return {
23204
23289
  recordFile: path.recordFile,
23205
23290
  volumeDir: path.sessionDir,
23206
- humanViewFile: join20(path.sessionDir, TICKET_PROVENANCE_HUMAN_VIEW),
23207
- offeredWatermarkFile: join20(path.sessionDir, TICKET_PROVENANCE_OFFERED_WATERMARK)
23291
+ humanViewFile: join18(path.sessionDir, TICKET_PROVENANCE_HUMAN_VIEW),
23292
+ offeredWatermarkFile: join18(path.sessionDir, TICKET_PROVENANCE_OFFERED_WATERMARK)
23208
23293
  };
23209
23294
  }
23210
23295
  function readOfferedIdentities(ticketNumber, cwd, home) {
23211
23296
  const { offeredWatermarkFile } = resolveTicketProvenanceVolume(ticketNumber, cwd, home);
23212
- if (!existsSync9(offeredWatermarkFile)) return /* @__PURE__ */ new Set();
23297
+ if (!existsSync8(offeredWatermarkFile)) return /* @__PURE__ */ new Set();
23213
23298
  let text;
23214
23299
  try {
23215
- text = readFileSync5(offeredWatermarkFile, "utf8");
23300
+ text = readFileSync4(offeredWatermarkFile, "utf8");
23216
23301
  } catch (error) {
23217
23302
  throw new TicketProvenanceWatermarkError(
23218
23303
  "unreadable",
@@ -23245,25 +23330,6 @@ function readOfferedIdentities(ticketNumber, cwd, home) {
23245
23330
  }
23246
23331
  return seen;
23247
23332
  }
23248
- function recordOfferedIdentities(input) {
23249
- if (input.identities.length === 0) return;
23250
- const { volumeDir, offeredWatermarkFile } = resolveTicketProvenanceVolume(
23251
- input.ticketNumber,
23252
- input.cwd,
23253
- input.home
23254
- );
23255
- const already = new Set(readOfferedIdentities(input.ticketNumber, input.cwd, input.home));
23256
- const rows = [];
23257
- for (const identity of input.identities) {
23258
- if (identity.length === 0 || already.has(identity)) continue;
23259
- rows.push(`${JSON.stringify({ identity })}
23260
- `);
23261
- already.add(identity);
23262
- }
23263
- if (rows.length === 0) return;
23264
- mkdirSync3(volumeDir, { recursive: true });
23265
- appendFileSync2(offeredWatermarkFile, rows.join(""), "utf8");
23266
- }
23267
23333
  async function readTicketProvenance(ticketNumber, cwd, home) {
23268
23334
  const { recordFile } = resolveTicketProvenanceVolume(ticketNumber, cwd, home);
23269
23335
  const { records: records2 } = await readSitianRecords(recordFile);
@@ -23378,21 +23444,6 @@ function appendTicketProvenanceDiagnostic(input) {
23378
23444
  payload: input.diagnostic
23379
23445
  });
23380
23446
  }
23381
- function appendCollectorFailureDiagnostic(input) {
23382
- const recordedAt = input.recordedAt ?? (/* @__PURE__ */ new Date()).toISOString();
23383
- return appendTicketProvenanceDiagnostic({
23384
- ticketNumber: input.ticketNumber,
23385
- cwd: input.cwd,
23386
- ...input.home === void 0 ? {} : { home: input.home },
23387
- source: "diarist-collector-fail",
23388
- diagnostic: {
23389
- recordClass: TICKET_PROVENANCE_RECORD_CLASS_DIAGNOSTIC,
23390
- diagnosticKind: "collector-failed",
23391
- cause: input.collectorError,
23392
- recordedAt
23393
- }
23394
- });
23395
- }
23396
23447
  function appendIssueSourceFailureDiagnostic(input) {
23397
23448
  const recordedAt = input.recordedAt ?? (/* @__PURE__ */ new Date()).toISOString();
23398
23449
  return appendTicketProvenanceDiagnostic({
@@ -23409,21 +23460,6 @@ function appendIssueSourceFailureDiagnostic(input) {
23409
23460
  }
23410
23461
  });
23411
23462
  }
23412
- function appendQuoteVerifyFailureDiagnostic(input) {
23413
- const recordedAt = input.recordedAt ?? (/* @__PURE__ */ new Date()).toISOString();
23414
- return appendTicketProvenanceDiagnostic({
23415
- ticketNumber: input.ticketNumber,
23416
- cwd: input.cwd,
23417
- ...input.home === void 0 ? {} : { home: input.home },
23418
- source: "diarist-quote-verify",
23419
- diagnostic: {
23420
- recordClass: TICKET_PROVENANCE_RECORD_CLASS_DIAGNOSTIC,
23421
- diagnosticKind: "quote-verify-failed",
23422
- cause: input.cause,
23423
- recordedAt
23424
- }
23425
- });
23426
- }
23427
23463
  function writeTicketProvenanceHumanView(input) {
23428
23464
  const volume = ensureTicketProvenanceVolume(input.ticketNumber, input.cwd, input.home);
23429
23465
  const md = renderTicketProvenanceMarkdown({
@@ -23533,6 +23569,43 @@ function resolveDiaristGithubOrigin(projectRoot) {
23533
23569
  if (remoteUrl.length === 0) return void 0;
23534
23570
  return parseGitHubOriginRemote(remoteUrl);
23535
23571
  }
23572
+ async function loadDiaristIssueFace(input) {
23573
+ const persistAndThrow = (error) => {
23574
+ appendIssueSourceFailureDiagnostic({
23575
+ ticketNumber: input.ticketNumber,
23576
+ cwd: input.projectRoot,
23577
+ ...input.home === void 0 ? {} : { home: input.home },
23578
+ cause: error.message,
23579
+ reason: error.reason
23580
+ });
23581
+ return error;
23582
+ };
23583
+ const origin = resolveDiaristGithubOrigin(input.projectRoot);
23584
+ if (origin === void 0) {
23585
+ throw persistAndThrow(
23586
+ new DiaristIssueSourceError(
23587
+ "origin-unresolved",
23588
+ `bound ticket #${input.ticketNumber} issue face requires a resolvable github.com origin remote`
23589
+ )
23590
+ );
23591
+ }
23592
+ const fetcher = input.fetcher ?? createDiaristIssueFaceFetcher();
23593
+ try {
23594
+ return await fetcher({
23595
+ owner: origin.owner,
23596
+ repo: origin.repo,
23597
+ ticketNumber: input.ticketNumber
23598
+ });
23599
+ } catch (error) {
23600
+ throw persistAndThrow(
23601
+ error instanceof DiaristIssueSourceError ? error : new DiaristIssueSourceError(
23602
+ "issue-unavailable",
23603
+ `issue face fetch failed for ${origin.owner}/${origin.repo}#${input.ticketNumber}`,
23604
+ { cause: error }
23605
+ )
23606
+ );
23607
+ }
23608
+ }
23536
23609
  async function loadSeenEntryIdentities(ticketNumber, cwd, home) {
23537
23610
  const { recordFile } = resolveTicketProvenanceVolume(ticketNumber, cwd, home);
23538
23611
  const { records: records2 } = await readSitianRecords(recordFile);
@@ -23555,7 +23628,7 @@ function blockEntryIdentity(ticketNumber, block) {
23555
23628
  transcript: block.transcript
23556
23629
  });
23557
23630
  }
23558
- async function loadSourceBlocks(input) {
23631
+ function loadSourceBlocks(input) {
23559
23632
  const cwds = input.sessionCwds ?? [input.cwd];
23560
23633
  const blocks = [...readCcSessionBlocks({ cwds })];
23561
23634
  if (input.issueFace !== void 0) {
@@ -23576,124 +23649,31 @@ async function loadSourceBlocks(input) {
23576
23649
  }
23577
23650
  return blocks;
23578
23651
  }
23579
- function faceTextForAnchors(face) {
23580
- if (face === void 0) return void 0;
23581
- const parts = [face.body, ...face.comments.map((c) => c.body)].filter(
23582
- (t) => t.trim() !== ""
23583
- );
23584
- if (parts.length === 0) return void 0;
23585
- return parts.join("\n");
23586
- }
23587
- async function runDiarist(input) {
23588
- const homeOpt = input.home === void 0 ? {} : { home: input.home };
23589
- const volumePaths = ensureTicketProvenanceVolume(input.ticketNumber, input.cwd, input.home);
23590
- const anchorText = faceTextForAnchors(input.issueFace);
23591
- const anchors = buildDiaristAnchors({
23652
+ async function prepareDiaristSourceCatalog(input) {
23653
+ ensureTicketProvenanceVolume(input.ticketNumber, input.cwd, input.home);
23654
+ const volume = await readTicketProvenance(input.ticketNumber, input.cwd, input.home);
23655
+ writeTicketProvenanceHumanView({
23592
23656
  ticketNumber: input.ticketNumber,
23593
- ...anchorText === void 0 ? {} : { ticketBody: anchorText }
23657
+ cwd: input.cwd,
23658
+ ...input.home === void 0 ? {} : { home: input.home },
23659
+ entries: volume.entries
23594
23660
  });
23595
- const rawBlocks = await loadSourceBlocks(input);
23661
+ const rawBlocks = loadSourceBlocks(input);
23596
23662
  const safeguarded = mechanicalSafeguardPipeline(rawBlocks);
23597
23663
  const seen = await loadSeenEntryIdentities(input.ticketNumber, input.cwd, input.home);
23598
23664
  const fresh = safeguarded.filter(
23599
23665
  (block) => !seen.has(blockEntryIdentity(input.ticketNumber, block))
23600
23666
  );
23601
- let collectorStatus;
23602
- let collectorError;
23603
- let llmRawStdout;
23604
- let collect;
23605
- const collector = createHermesDiaristCollector({
23606
- cwd: input.cwd,
23607
- ...input.packageRoot === void 0 ? {} : { packageRoot: input.packageRoot }
23608
- });
23609
- if (fresh.length === 0) {
23610
- collectorStatus = "skipped-no-fresh";
23611
- } else {
23612
- try {
23613
- collect = await collector({
23614
- ticketNumber: input.ticketNumber,
23615
- candidates: fresh,
23616
- ...input.signal === void 0 ? {} : { signal: input.signal }
23617
- });
23618
- llmRawStdout = collect.rawStdout;
23619
- collectorStatus = collect.selections.length === 0 ? "empty-selection" : "ok";
23620
- } catch (error) {
23621
- collectorStatus = "failed";
23622
- collectorError = error instanceof Error ? error.message : String(error);
23623
- appendCollectorFailureDiagnostic({
23624
- ticketNumber: input.ticketNumber,
23625
- cwd: input.cwd,
23626
- ...homeOpt,
23627
- collectorError
23628
- });
23629
- }
23630
- }
23631
- const pointers = [];
23632
- const accepted = [];
23633
- let rejectedQuotes = 0;
23634
- if (collect !== void 0 && collectorStatus === "ok") {
23635
- for (const selection of collect.selections) {
23636
- const block = fresh[selection.candidateIndex];
23637
- if (block === void 0) continue;
23638
- const projected = blockToLlmEntry(block, {
23639
- anchors,
23640
- quotes: selection.quotes,
23641
- ...selection.note === void 0 ? {} : { note: selection.note }
23642
- });
23643
- if (!projected.ok) {
23644
- rejectedQuotes += 1;
23645
- const ptr2 = appendQuoteVerifyFailureDiagnostic({
23646
- ticketNumber: input.ticketNumber,
23647
- cwd: input.cwd,
23648
- ...homeOpt,
23649
- cause: projected.cause
23650
- });
23651
- pointers.push(ptr2);
23652
- continue;
23653
- }
23654
- const ptr = appendTicketProvenanceEntry({
23655
- ticketNumber: input.ticketNumber,
23656
- cwd: input.cwd,
23657
- ...homeOpt,
23658
- entry: projected.entry,
23659
- source: "diarist"
23660
- });
23661
- pointers.push(ptr);
23662
- accepted.push(projected.entry);
23663
- }
23664
- }
23665
- if (collect !== void 0 && (collectorStatus === "ok" || collectorStatus === "empty-selection")) {
23666
- recordOfferedIdentities({
23667
- ticketNumber: input.ticketNumber,
23668
- cwd: input.cwd,
23669
- ...homeOpt,
23670
- identities: fresh.map(
23671
- (block) => blockEntryIdentity(input.ticketNumber, block)
23672
- )
23673
- });
23674
- }
23675
- const volume = await readTicketProvenance(input.ticketNumber, input.cwd, input.home);
23676
- const humanViewFile = writeTicketProvenanceHumanView({
23677
- ticketNumber: input.ticketNumber,
23678
- cwd: input.cwd,
23679
- ...homeOpt,
23680
- entries: volume.entries
23681
- });
23682
23667
  return {
23683
23668
  ticketNumber: input.ticketNumber,
23684
- candidateCount: safeguarded.length,
23685
- freshCount: fresh.length,
23686
- appended: accepted.length,
23687
- rejectedQuotes,
23688
- pointers,
23689
- entries: volume.entries,
23690
- humanViewFile,
23691
- volumeRecordFile: volumePaths.recordFile,
23692
- collectorStatus,
23693
- ...collectorError === void 0 ? {} : { collectorError },
23694
- ...llmRawStdout === void 0 ? {} : { llmRawStdout }
23669
+ cwd: input.cwd,
23670
+ ...input.home === void 0 ? {} : { home: input.home },
23671
+ candidates: fresh.map((block, candidateIndex) => ({ ...block, candidateIndex }))
23695
23672
  };
23696
23673
  }
23674
+ function serializeDiaristSourceCatalog(catalog) {
23675
+ return JSON.stringify(catalog);
23676
+ }
23697
23677
  var DiaristIssueSourceError;
23698
23678
  var init_diarist = __esm({
23699
23679
  "src/diarist.ts"() {
@@ -23701,7 +23681,6 @@ var init_diarist = __esm({
23701
23681
  init_adr_path_refs();
23702
23682
  init_collector_github();
23703
23683
  init_diarist_mechanical();
23704
- init_diarist_llm_collector();
23705
23684
  init_reviewer_pinned_git();
23706
23685
  init_ticket_provenance();
23707
23686
  init_sitian_facade();
@@ -23796,190 +23775,40 @@ var init_seat_ticket_binding = __esm({
23796
23775
  init_invocation();
23797
23776
  init_run_lifecycle();
23798
23777
  }
23799
- });
23800
-
23801
- // src/auditor-dossier-tool.ts
23802
- var init_auditor_dossier_tool = __esm({
23803
- "src/auditor-dossier-tool.ts"() {
23804
- "use strict";
23805
- init_build();
23806
- }
23807
- });
23808
-
23809
- // src/engine-detour-tool.ts
23810
- var engineDetourArgsSchema;
23811
- var init_engine_detour_tool = __esm({
23812
- "src/engine-detour-tool.ts"() {
23813
- "use strict";
23814
- init_build();
23815
- init_engine_detour();
23816
- engineDetourArgsSchema = typebox_exports.Object(
23817
- {
23818
- argv: typebox_exports.Array(typebox_exports.String({ minLength: 1 }), {
23819
- minItems: 1,
23820
- description: "\u9996\u9879\u4E3A PATH \u4E2D\u7684\u53EF\u6267\u884C\u6587\u4EF6\uFF0C\u5176\u4F59\u9879\u4E3A\u53C2\u6570\u3002"
23821
- })
23822
- },
23823
- { additionalProperties: false }
23824
- );
23825
- }
23826
- });
23827
-
23828
- // src/session-opening-materials.ts
23829
- import { existsSync as existsSync10 } from "node:fs";
23830
- import { dirname as dirname8, join as join21 } from "node:path";
23831
- import { fileURLToPath as fileURLToPath3, pathToFileURL as pathToFileURL2 } from "node:url";
23832
- function resolvePackageRootDir(moduleUrl = import.meta.url) {
23833
- let dir = dirname8(fileURLToPath3(moduleUrl));
23834
- for (let i = 0; i < 8; i += 1) {
23835
- if (existsSync10(join21(dir, "package.json")) && existsSync10(join21(dir, "souls"))) {
23836
- return dir;
23837
- }
23838
- const parent = dirname8(dir);
23839
- if (parent === dir) break;
23840
- dir = parent;
23841
- }
23842
- return fileURLToPath3(new URL("..", moduleUrl));
23843
- }
23844
- var packageRootUrl2, MAIN_ROLE_SESSION_MATERIALS, GATEKEEPER_SESSION_MATERIALS;
23845
- var init_session_opening_materials = __esm({
23846
- "src/session-opening-materials.ts"() {
23847
- "use strict";
23848
- init_packaged_role_registry();
23849
- packageRootUrl2 = pathToFileURL2(resolvePackageRootDir() + "/").href;
23850
- MAIN_ROLE_SESSION_MATERIALS = {
23851
- ...Object.fromEntries(
23852
- PUBLIC_ROLE_RECORDS.map((record4) => [record4.role, record4.sessionMaterials])
23853
- )
23854
- };
23855
- GATEKEEPER_SESSION_MATERIALS = {
23856
- // #639: single authority — the public gatekeeper record owns the province list.
23857
- gatekeeper: PUBLIC_ROLE_RECORDS.find((entry) => entry.role === "gatekeeper").sessionMaterials,
23858
- inspector: INSPECTOR_SESSION_MATERIALS,
23859
- notary: NOTARY_SESSION_MATERIALS
23860
- };
23861
- }
23862
- });
23863
-
23864
- // src/navigator-session-contracts.ts
23865
- var navigatorProviderFailureSchema;
23866
- var init_navigator_session_contracts = __esm({
23867
- "src/navigator-session-contracts.ts"() {
23868
- "use strict";
23869
- init_build();
23870
- init_value2();
23871
- init_auditor_dossier_tool();
23872
- init_institutional_resolution();
23873
- navigatorProviderFailureSchema = typebox_exports.Object({
23874
- source: typebox_exports.Union([
23875
- typebox_exports.Literal("context"),
23876
- typebox_exports.Literal("session"),
23877
- typebox_exports.Literal("model"),
23878
- typebox_exports.Literal("thinking"),
23879
- typebox_exports.Literal("auth"),
23880
- typebox_exports.Literal("quota"),
23881
- typebox_exports.Literal("transport"),
23882
- typebox_exports.Literal("unknown")
23883
- ]),
23884
- cause: typebox_exports.Union([
23885
- typebox_exports.Literal("context"),
23886
- typebox_exports.Literal("session"),
23887
- typebox_exports.Literal("model"),
23888
- typebox_exports.Literal("thinking"),
23889
- typebox_exports.Literal("auth"),
23890
- typebox_exports.Literal("quota"),
23891
- typebox_exports.Literal("transport"),
23892
- typebox_exports.Literal("unknown")
23893
- ])
23894
- }, { additionalProperties: false });
23895
- }
23896
- });
23897
-
23898
- // src/receipt-delivery-policy.ts
23899
- function isRecord13(value) {
23900
- return typeof value === "object" && value !== null && !Array.isArray(value);
23901
- }
23902
- function parseNoReceiptLifecycleFacts(input) {
23903
- if (!isRecord13(input) || typeof input.terminalToolCalled !== "boolean" || input.deliveryTurns !== RECEIPT_DELIVERY_TURN_LIMIT || input.sessionCompletion !== "settled-without-accepted-receipt" || input.acceptedReceipt !== false || typeof input.runPointer !== "string" || input.runPointer.trim() === "" || typeof input.attemptPointer !== "string" || input.attemptPointer.trim() === "" || !Array.isArray(input.rejectedReceipts) || !input.rejectedReceipts.every((item) => isRecord13(item) && typeof item.reason === "string")) {
23904
- throw new TypeError("malformed no-receipt lifecycle facts");
23905
- }
23906
- return {
23907
- terminalToolCalled: input.terminalToolCalled,
23908
- rejectedReceipts: input.rejectedReceipts.map((item) => ({
23909
- reason: item.reason,
23910
- diagnosticAvailable: item.reason.trim() !== ""
23911
- })),
23912
- deliveryTurns: RECEIPT_DELIVERY_TURN_LIMIT,
23913
- sessionCompletion: "settled-without-accepted-receipt",
23914
- runPointer: input.runPointer,
23915
- attemptPointer: input.attemptPointer,
23916
- acceptedReceipt: false
23917
- };
23918
- }
23919
- var RECEIPT_DELIVERY_TURN_LIMIT, NO_RECEIPT_LIFECYCLE_ENTRY_TYPE;
23920
- var init_receipt_delivery_policy = __esm({
23921
- "src/receipt-delivery-policy.ts"() {
23922
- "use strict";
23923
- RECEIPT_DELIVERY_TURN_LIMIT = 2;
23924
- NO_RECEIPT_LIFECYCLE_ENTRY_TYPE = "ak-no-receipt-lifecycle";
23925
- }
23926
- });
23927
-
23928
- // src/upstream-error-testimony.ts
23929
- function isNonSuccessHttpStatus(status) {
23930
- return typeof status === "number" && (status < 200 || status >= 300);
23931
- }
23932
- function hasUpstreamErrorTestimony(input) {
23933
- if (isNonSuccessHttpStatus(input.httpStatus)) return true;
23934
- return Array.isArray(input.diagnostics) && input.diagnostics.length > 0;
23935
- }
23936
- function projectConfirmedRemotePayload(input) {
23937
- return {
23938
- ...input.body === void 0 ? {} : { body: input.body },
23939
- ...input.code === void 0 ? {} : { code: input.code },
23940
- ...input.errno === void 0 ? {} : { errno: input.errno }
23941
- };
23942
- }
23943
- var init_upstream_error_testimony = __esm({
23944
- "src/upstream-error-testimony.ts"() {
23778
+ });
23779
+
23780
+ // src/auditor-dossier-tool.ts
23781
+ var init_auditor_dossier_tool = __esm({
23782
+ "src/auditor-dossier-tool.ts"() {
23945
23783
  "use strict";
23784
+ init_build();
23946
23785
  }
23947
23786
  });
23948
23787
 
23949
- // src/evidence-child-executor.ts
23950
- var init_evidence_child_executor = __esm({
23951
- "src/evidence-child-executor.ts"() {
23788
+ // src/shape-unreadable-failure.ts
23789
+ function stampShapeUnreadableDetails(candidate) {
23790
+ return {
23791
+ [SHAPE_UNREADABLE_KEY]: true,
23792
+ candidate,
23793
+ acceptedReceipt: false
23794
+ };
23795
+ }
23796
+ var SHAPE_UNREADABLE_KEY;
23797
+ var init_shape_unreadable_failure = __esm({
23798
+ "src/shape-unreadable-failure.ts"() {
23952
23799
  "use strict";
23953
- init_compliance_transport();
23954
- init_auditor_dossier_tool();
23955
- init_sitian_facade();
23956
- init_engine_detour_tool();
23957
- init_engine_detour();
23958
- init_engine_material();
23959
- init_session_opening_materials();
23960
- init_config2();
23961
- init_institutional_resolution();
23962
- init_navigator_session_contracts();
23963
- init_receipt_delivery_policy();
23964
- init_typed_provider_http();
23965
- init_upstream_error_testimony();
23800
+ SHAPE_UNREADABLE_KEY = "shapeUnreadable";
23966
23801
  }
23967
23802
  });
23968
23803
 
23969
23804
  // src/compliance-transport.ts
23970
- function createComplianceDecisionTool(name, description) {
23971
- return { name, description, parameters: complianceDecisionSchema, async execute(_id, params) {
23972
- return { content: [{ type: "text", text: "\u5BA1\u8BA1\u51B3\u8BAE\u5DF2\u6536" }], details: params, terminate: true };
23973
- } };
23974
- }
23975
23805
  var nonblank2, decisionGateSchema, complianceDecisionSchema, AUDITOR_PARENT_ATTEMPT_BINDING_ENTRY_TYPE, AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE;
23976
23806
  var init_compliance_transport = __esm({
23977
23807
  "src/compliance-transport.ts"() {
23978
23808
  "use strict";
23979
23809
  init_build();
23980
- init_evidence_child_executor();
23981
23810
  init_auditor_dossier_tool();
23982
- init_sitian_facade();
23811
+ init_shape_unreadable_failure();
23983
23812
  nonblank2 = typebox_exports.String({ minLength: 1, pattern: "\\S" });
23984
23813
  decisionGateSchema = typebox_exports.Object({ question: nonblank2, options: typebox_exports.Array(nonblank2, { minItems: 1 }) }, { additionalProperties: false });
23985
23814
  complianceDecisionSchema = typebox_exports.Object({ status: typebox_exports.Unknown({ description: "pass | revise | escalate \u2014 \u5F62\u72B6\u6307\u5F15\uFF0C\u975E schema \u95F8" }), violations: typebox_exports.Array(nonblank2, { description: "\u89C2\u5BDF\u5230\u7684\u5408\u89C4\u8FDD\u89C4" }), conflicts: typebox_exports.Array(nonblank2, { description: "\u672A\u51B3\u6743\u5A01\u6216\u6267\u884C\u51B2\u7A81" }), decisionGate: typebox_exports.Union([decisionGateSchema, typebox_exports.Null()], { description: "\u5347\u7EA7\u95EE\u9898\u4E0E\u53EF\u9009\u9009\u9879" }) }, { additionalProperties: true, required: [] });
@@ -23989,12 +23818,12 @@ var init_compliance_transport = __esm({
23989
23818
  });
23990
23819
 
23991
23820
  // src/ledger-session-read.ts
23992
- import { readFile as readFile12 } from "node:fs/promises";
23821
+ import { readFile as readFile11 } from "node:fs/promises";
23993
23822
  function isRecord14(value) {
23994
23823
  return typeof value === "object" && value !== null && !Array.isArray(value);
23995
23824
  }
23996
23825
  async function readLedgerSessionJsonl(path) {
23997
- const text = await readFile12(path, "utf8");
23826
+ const text = await readFile11(path, "utf8");
23998
23827
  const lines = text.split("\n");
23999
23828
  const rows = [];
24000
23829
  for (let index = 0; index < lines.length; index += 1) {
@@ -24169,7 +23998,7 @@ var init_ledger_session_read = __esm({
24169
23998
 
24170
23999
  // src/analyst-gate-cycles-read.ts
24171
24000
  import { readdir as readdir3 } from "node:fs/promises";
24172
- import { join as join22 } from "node:path";
24001
+ import { join as join19 } from "node:path";
24173
24002
  function isRecord15(value) {
24174
24003
  return typeof value === "object" && value !== null && !Array.isArray(value);
24175
24004
  }
@@ -24395,6 +24224,26 @@ function pairGateRounds(volumes) {
24395
24224
  }
24396
24225
  return rounds.sort((a, b) => a.officerStartedAt.localeCompare(b.officerStartedAt)).map((round, index) => ({ ...round, roundIndex: index + 1 }));
24397
24226
  }
24227
+ async function resolveOfficerSessionFromPointerFile(pointerPath) {
24228
+ const { readFile: readFile21 } = await import("node:fs/promises");
24229
+ let raw;
24230
+ try {
24231
+ raw = JSON.parse(await readFile21(pointerPath, "utf8"));
24232
+ } catch (error) {
24233
+ throw new Error(
24234
+ `direct officer run pointer unreadable in ${pointerPath}: ${error instanceof Error ? error.message : String(error)}`,
24235
+ { cause: error }
24236
+ );
24237
+ }
24238
+ if (!isRecord15(raw) || raw.kind !== "direct-officer-run-pointer" || raw.version !== 1) {
24239
+ throw new Error(`direct officer run pointer has unknown shape in ${pointerPath}`);
24240
+ }
24241
+ const sessionFile = raw.sessionFile;
24242
+ if (typeof sessionFile !== "string" || sessionFile.trim() === "") {
24243
+ throw new Error(`direct officer run pointer missing sessionFile in ${pointerPath}`);
24244
+ }
24245
+ return sessionFile;
24246
+ }
24398
24247
  async function readAnalystGateCyclesFromAuditorRoles(auditorRolesDirectory, options = {}) {
24399
24248
  const directories = typeof auditorRolesDirectory === "string" ? [auditorRolesDirectory] : auditorRolesDirectory;
24400
24249
  const volumes = [];
@@ -24402,13 +24251,18 @@ async function readAnalystGateCyclesFromAuditorRoles(auditorRolesDirectory, opti
24402
24251
  let names;
24403
24252
  try {
24404
24253
  const entries = await readdir3(directory, { withFileTypes: true });
24405
- names = entries.filter((e) => e.isFile() && e.name.endsWith(".jsonl")).map((e) => e.name).sort();
24254
+ names = entries.filter(
24255
+ (e) => e.isFile() && (e.name.endsWith(".jsonl") || e.name.endsWith(".pointer.json"))
24256
+ ).map((e) => e.name).sort();
24406
24257
  } catch (error) {
24407
24258
  if (isMissingDirectoryError(error)) continue;
24408
24259
  throw error;
24409
24260
  }
24410
24261
  for (const name of names) {
24411
- const classified = await classifyAuditorVolume(join22(directory, name));
24262
+ const path = join19(directory, name);
24263
+ const sessionPath = name.endsWith(".pointer.json") ? await resolveOfficerSessionFromPointerFile(path) : path;
24264
+ if (sessionPath === void 0) continue;
24265
+ const classified = await classifyAuditorVolume(sessionPath);
24412
24266
  for (const volume of classified) {
24413
24267
  if (options.parentSessionFile !== void 0 && volume.parentSessionFile !== void 0 && volume.parentSessionFile !== options.parentSessionFile) {
24414
24268
  continue;
@@ -24442,31 +24296,23 @@ var init_analyst_gate_cycles_read = __esm({
24442
24296
  });
24443
24297
 
24444
24298
  // src/gatekeeper-role.ts
24445
- var officerDecisionSchema, MISSING_ARGUMENTS_SUBMISSION;
24299
+ var MISSING_ARGUMENTS_SUBMISSION;
24446
24300
  var init_gatekeeper_role = __esm({
24447
24301
  "src/gatekeeper-role.ts"() {
24448
24302
  "use strict";
24449
- init_build();
24450
24303
  init_auditor_dossier_tool();
24451
- init_evidence_child_executor();
24452
- init_open_tool_schema();
24453
- init_session_opening_materials();
24454
24304
  init_submission_errors();
24455
24305
  init_inspector_contracts();
24456
24306
  init_gatekeeper_output();
24307
+ init_shape_unreadable_failure();
24457
24308
  init_submission_errors();
24458
- officerDecisionSchema = openToolObject(typebox_exports.Object({
24459
- status: typebox_exports.Unknown({ description: "pass | bounce | escalate \u2014 \u5F62\u72B6\u6307\u5F15\uFF0C\u975E schema \u95F8" }),
24460
- reason: typebox_exports.Optional(typebox_exports.Unknown({ description: "status \u4E3A escalate \u65F6\u7684\u7406\u7531" })),
24461
- findings: typebox_exports.Unknown({ description: "string[] findings\uFF0C\u968F pass\u3001bounce \u6216 escalate \u7559\u5B58" })
24462
- }));
24463
24309
  MISSING_ARGUMENTS_SUBMISSION = Object.freeze({ missing: "arguments" });
24464
24310
  }
24465
24311
  });
24466
24312
 
24467
24313
  // src/run-terminal-artifacts.ts
24468
- import { readdir as readdir4, readFile as readFile13 } from "node:fs/promises";
24469
- import { basename as basename7, dirname as dirname9, join as join23 } from "node:path";
24314
+ import { readdir as readdir4, readFile as readFile12 } from "node:fs/promises";
24315
+ import { basename as basename7, dirname as dirname8, join as join20 } from "node:path";
24470
24316
  function isMissingPathError2(error) {
24471
24317
  return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
24472
24318
  }
@@ -24497,7 +24343,7 @@ function readUsableTerminalArtifactBody(body) {
24497
24343
  async function readTerminalArtifactAtPath(path, file) {
24498
24344
  let raw;
24499
24345
  try {
24500
- raw = await readFile13(path, "utf8");
24346
+ raw = await readFile12(path, "utf8");
24501
24347
  } catch (error) {
24502
24348
  if (isMissingPathError2(error)) return void 0;
24503
24349
  return {
@@ -24541,7 +24387,7 @@ async function listUniqueErrorFallbackPaths(directories) {
24541
24387
  }
24542
24388
  for (const name of names.sort((a, b) => a.localeCompare(b))) {
24543
24389
  if (!UNIQUE_ERROR_FALLBACK_NAME.test(name)) continue;
24544
- found.push(join23(dir, name));
24390
+ found.push(join20(dir, name));
24545
24391
  }
24546
24392
  }
24547
24393
  return found;
@@ -24557,14 +24403,14 @@ function presentUniqueFallbackBoundToRun(body, expectedRunId) {
24557
24403
  return typeof body.runId === "string" && body.runId === expectedRunId;
24558
24404
  }
24559
24405
  async function readRunTerminalArtifact(runDirectory) {
24560
- const artifactsDir = join23(runDirectory, "artifacts");
24406
+ const artifactsDir = join20(runDirectory, "artifacts");
24561
24407
  for (const file of RUN_TERMINAL_ARTIFACT_FILES) {
24562
- const path = join23(artifactsDir, file);
24408
+ const path = join20(artifactsDir, file);
24563
24409
  const read3 = await readTerminalArtifactAtPath(path, file);
24564
24410
  if (read3 !== void 0) return read3;
24565
24411
  }
24566
24412
  for (const relative3 of RUN_TERMINAL_ERROR_FALLBACK_RELATIVE_PATHS) {
24567
- const path = join23(runDirectory, relative3);
24413
+ const path = join20(runDirectory, relative3);
24568
24414
  const read3 = await readTerminalArtifactAtPath(path, "error.json");
24569
24415
  if (read3 !== void 0) return read3;
24570
24416
  }
@@ -24573,7 +24419,7 @@ async function readRunTerminalArtifact(runDirectory) {
24573
24419
  if (read3 !== void 0) return read3;
24574
24420
  }
24575
24421
  const expectedRunId = runIdFromRunDirectory(runDirectory);
24576
- for (const path of await listUniqueErrorFallbackPaths([dirname9(runDirectory)])) {
24422
+ for (const path of await listUniqueErrorFallbackPaths([dirname8(runDirectory)])) {
24577
24423
  const read3 = await readTerminalArtifactAtPath(path, "error.json");
24578
24424
  if (read3 === void 0) continue;
24579
24425
  if (read3.status === "present") {
@@ -24702,11 +24548,112 @@ var init_submission_ledger = __esm({
24702
24548
  }
24703
24549
  });
24704
24550
 
24551
+ // src/session-opening-materials.ts
24552
+ import { existsSync as existsSync9 } from "node:fs";
24553
+ import { readFile as readFile13 } from "node:fs/promises";
24554
+ import { dirname as dirname9, join as join21 } from "node:path";
24555
+ import { fileURLToPath as fileURLToPath2, pathToFileURL as pathToFileURL2 } from "node:url";
24556
+ function resolvePackageRootDir(moduleUrl = import.meta.url) {
24557
+ let dir = dirname9(fileURLToPath2(moduleUrl));
24558
+ for (let i = 0; i < 8; i += 1) {
24559
+ if (existsSync9(join21(dir, "package.json")) && existsSync9(join21(dir, "souls"))) {
24560
+ return dir;
24561
+ }
24562
+ const parent = dirname9(dir);
24563
+ if (parent === dir) break;
24564
+ dir = parent;
24565
+ }
24566
+ return fileURLToPath2(new URL("..", moduleUrl));
24567
+ }
24568
+ async function readPackageMaterial(relativePath) {
24569
+ return readFile13(fileURLToPath2(new URL(relativePath, packageRootUrl)), "utf8");
24570
+ }
24571
+ async function joinPackageMaterials(relativePaths) {
24572
+ const chunks = [];
24573
+ for (const relativePath of relativePaths) {
24574
+ chunks.push(await readPackageMaterial(relativePath));
24575
+ }
24576
+ return chunks.join("\n\n");
24577
+ }
24578
+ var packageRootUrl, MAIN_ROLE_SESSION_MATERIALS, GATEKEEPER_SESSION_MATERIALS;
24579
+ var init_session_opening_materials = __esm({
24580
+ "src/session-opening-materials.ts"() {
24581
+ "use strict";
24582
+ init_packaged_role_registry();
24583
+ packageRootUrl = pathToFileURL2(resolvePackageRootDir() + "/").href;
24584
+ MAIN_ROLE_SESSION_MATERIALS = {
24585
+ ...Object.fromEntries(
24586
+ PUBLIC_ROLE_RECORDS.map((record4) => [record4.role, record4.sessionMaterials])
24587
+ )
24588
+ };
24589
+ GATEKEEPER_SESSION_MATERIALS = {
24590
+ // #639: single authority — the public gatekeeper record owns the province list.
24591
+ gatekeeper: PUBLIC_ROLE_RECORDS.find((entry) => entry.role === "gatekeeper").sessionMaterials,
24592
+ inspector: INSPECTOR_SESSION_MATERIALS,
24593
+ notary: NOTARY_SESSION_MATERIALS
24594
+ };
24595
+ }
24596
+ });
24597
+
24705
24598
  // src/auditor-soul.ts
24599
+ var auditor_soul_exports = {};
24600
+ __export(auditor_soul_exports, {
24601
+ AK_ROLE_AUDITOR_SOURCE_RUN_ENV: () => AK_ROLE_AUDITOR_SOURCE_RUN_ENV,
24602
+ AK_ROLE_AUDITOR_SUBJECT_ENV: () => AK_ROLE_AUDITOR_SUBJECT_ENV,
24603
+ AUDITOR_SESSION_MATERIALS: () => AUDITOR_SESSION_MATERIALS,
24604
+ AUDITOR_SOUL_ROLES: () => AUDITOR_SOUL_ROLES,
24605
+ isAuditorSoulRole: () => isAuditorSoulRole,
24606
+ loadAuditorSoul: () => loadAuditorSoul,
24607
+ loadAuditorSoulFromSubjectInput: () => loadAuditorSoulFromSubjectInput,
24608
+ resolveAuditorSubject: () => resolveAuditorSubject
24609
+ });
24610
+ function auditorSoulRelativePath(role) {
24611
+ return `souls/${role}-auditor.md`;
24612
+ }
24613
+ function isAuditorSoulRole(value) {
24614
+ return value === "judge" || value === "doctor";
24615
+ }
24616
+ function resolveAuditorSubject(raw) {
24617
+ const value = typeof raw === "string" && raw.trim() !== "" ? raw.trim() : typeof process.env[AK_ROLE_AUDITOR_SUBJECT_ENV] === "string" ? process.env[AK_ROLE_AUDITOR_SUBJECT_ENV].trim() : "";
24618
+ if (!isAuditorSoulRole(value)) {
24619
+ throw new Error(
24620
+ `auditor subject must be judge|doctor (input --subject / ${AK_ROLE_AUDITOR_SUBJECT_ENV}), got ${value === "" ? "(missing)" : value}`
24621
+ );
24622
+ }
24623
+ return value;
24624
+ }
24625
+ async function loadAuditorSoul(role) {
24626
+ const materials = AUDITOR_SESSION_MATERIALS[role];
24627
+ const soulPath = auditorSoulRelativePath(role);
24628
+ const soul = await readPackageMaterial(soulPath);
24629
+ if (soul.trim().length === 0) {
24630
+ throw new Error(`The ${role} auditor Soul is blank`);
24631
+ }
24632
+ return joinPackageMaterials(materials);
24633
+ }
24634
+ async function loadAuditorSoulFromSubjectInput(raw) {
24635
+ return loadAuditorSoul(resolveAuditorSubject(raw));
24636
+ }
24637
+ var AUDITOR_SOUL_ROLES, AK_ROLE_AUDITOR_SUBJECT_ENV, AK_ROLE_AUDITOR_SOURCE_RUN_ENV, AUDITOR_SESSION_MATERIALS;
24706
24638
  var init_auditor_soul = __esm({
24707
24639
  "src/auditor-soul.ts"() {
24708
24640
  "use strict";
24709
24641
  init_session_opening_materials();
24642
+ AUDITOR_SOUL_ROLES = [
24643
+ "judge",
24644
+ "doctor"
24645
+ ];
24646
+ AK_ROLE_AUDITOR_SUBJECT_ENV = "AK_ROLE_AUDITOR_SUBJECT";
24647
+ AK_ROLE_AUDITOR_SOURCE_RUN_ENV = "AK_ROLE_AUDITOR_SOURCE_RUN";
24648
+ AUDITOR_SESSION_MATERIALS = {
24649
+ judge: [
24650
+ "CLAUDE.md",
24651
+ "souls/judge-auditor.md",
24652
+ "souls/audit-law.md",
24653
+ "souls/quality-law.md"
24654
+ ],
24655
+ doctor: ["CLAUDE.md", "souls/doctor-auditor.md"]
24656
+ };
24710
24657
  }
24711
24658
  });
24712
24659
 
@@ -24719,36 +24666,43 @@ var init_dossier_resolution = __esm({
24719
24666
  });
24720
24667
 
24721
24668
  // src/doctor-auditor.ts
24722
- var DOCTOR_AUDIT_TOOL_NAME, tool;
24723
24669
  var init_doctor_auditor = __esm({
24724
24670
  "src/doctor-auditor.ts"() {
24725
24671
  "use strict";
24726
24672
  init_auditor_dossier_tool();
24727
- init_auditor_soul();
24728
24673
  init_compliance_transport();
24729
24674
  init_dossier_resolution();
24730
- DOCTOR_AUDIT_TOOL_NAME = "ak_doctor_audit_decision";
24731
- tool = createComplianceDecisionTool(
24732
- DOCTOR_AUDIT_TOOL_NAME,
24733
- "\u63D0\u4EA4 typed pass/revise/escalate \u51B3\u8BAE\uFF08\u592A\u533B\u7F72\u5BA1\u5211\uFF09\u3002"
24734
- );
24735
24675
  }
24736
24676
  });
24737
24677
 
24738
24678
  // src/judge-auditor.ts
24739
- var JUDGE_AUDIT_TOOL_NAME, auditDecisionTool;
24740
24679
  var init_judge_auditor = __esm({
24741
24680
  "src/judge-auditor.ts"() {
24742
24681
  "use strict";
24743
24682
  init_compliance_transport();
24744
24683
  init_auditor_dossier_tool();
24745
- init_auditor_soul();
24746
24684
  init_dossier_resolution();
24747
- JUDGE_AUDIT_TOOL_NAME = "ak_soul_audit_decision";
24748
- auditDecisionTool = createComplianceDecisionTool(
24749
- JUDGE_AUDIT_TOOL_NAME,
24750
- "\u63D0\u4EA4 typed pass/revise/escalate \u51B3\u8BAE\uFF08\u5927\u7406\u5BFA\u5BA1\u5211\uFF09\u3002"
24751
- );
24685
+ }
24686
+ });
24687
+
24688
+ // src/upstream-error-testimony.ts
24689
+ function isNonSuccessHttpStatus(status) {
24690
+ return typeof status === "number" && (status < 200 || status >= 300);
24691
+ }
24692
+ function hasUpstreamErrorTestimony(input) {
24693
+ if (isNonSuccessHttpStatus(input.httpStatus)) return true;
24694
+ return Array.isArray(input.diagnostics) && input.diagnostics.length > 0;
24695
+ }
24696
+ function projectConfirmedRemotePayload(input) {
24697
+ return {
24698
+ ...input.body === void 0 ? {} : { body: input.body },
24699
+ ...input.code === void 0 ? {} : { code: input.code },
24700
+ ...input.errno === void 0 ? {} : { errno: input.errno }
24701
+ };
24702
+ }
24703
+ var init_upstream_error_testimony = __esm({
24704
+ "src/upstream-error-testimony.ts"() {
24705
+ "use strict";
24752
24706
  }
24753
24707
  });
24754
24708
 
@@ -24851,12 +24805,12 @@ var init_reviewer_dispatch = __esm({
24851
24805
 
24852
24806
  // src/public-cli/reviewer-dispatch-rejection.ts
24853
24807
  import { readFile as readFile14, unlink as unlink3 } from "node:fs/promises";
24854
- import { join as join24 } from "node:path";
24808
+ import { join as join22 } from "node:path";
24855
24809
  function isReviewerPreflightViolation(value) {
24856
24810
  return typeof value === "string" && REVIEWER_PREFLIGHT_VIOLATIONS.includes(value);
24857
24811
  }
24858
24812
  function reviewerDispatchRejectionPath(runDirectory) {
24859
- return join24(runDirectory, REVIEWER_DISPATCH_REJECTION_FILE);
24813
+ return join22(runDirectory, REVIEWER_DISPATCH_REJECTION_FILE);
24860
24814
  }
24861
24815
  async function clearReviewerDispatchRejection(runDirectory) {
24862
24816
  try {
@@ -25077,6 +25031,36 @@ var init_navigator_invocation_identity = __esm({
25077
25031
  }
25078
25032
  });
25079
25033
 
25034
+ // src/receipt-delivery-policy.ts
25035
+ function isRecord17(value) {
25036
+ return typeof value === "object" && value !== null && !Array.isArray(value);
25037
+ }
25038
+ function parseNoReceiptLifecycleFacts(input) {
25039
+ if (!isRecord17(input) || typeof input.terminalToolCalled !== "boolean" || input.deliveryTurns !== RECEIPT_DELIVERY_TURN_LIMIT || input.sessionCompletion !== "settled-without-accepted-receipt" || input.acceptedReceipt !== false || typeof input.runPointer !== "string" || input.runPointer.trim() === "" || typeof input.attemptPointer !== "string" || input.attemptPointer.trim() === "" || !Array.isArray(input.rejectedReceipts) || !input.rejectedReceipts.every((item) => isRecord17(item) && typeof item.reason === "string")) {
25040
+ throw new TypeError("malformed no-receipt lifecycle facts");
25041
+ }
25042
+ return {
25043
+ terminalToolCalled: input.terminalToolCalled,
25044
+ rejectedReceipts: input.rejectedReceipts.map((item) => ({
25045
+ reason: item.reason,
25046
+ diagnosticAvailable: item.reason.trim() !== ""
25047
+ })),
25048
+ deliveryTurns: RECEIPT_DELIVERY_TURN_LIMIT,
25049
+ sessionCompletion: "settled-without-accepted-receipt",
25050
+ runPointer: input.runPointer,
25051
+ attemptPointer: input.attemptPointer,
25052
+ acceptedReceipt: false
25053
+ };
25054
+ }
25055
+ var RECEIPT_DELIVERY_TURN_LIMIT, NO_RECEIPT_LIFECYCLE_ENTRY_TYPE;
25056
+ var init_receipt_delivery_policy = __esm({
25057
+ "src/receipt-delivery-policy.ts"() {
25058
+ "use strict";
25059
+ RECEIPT_DELIVERY_TURN_LIMIT = 2;
25060
+ NO_RECEIPT_LIFECYCLE_ENTRY_TYPE = "ak-no-receipt-lifecycle";
25061
+ }
25062
+ });
25063
+
25080
25064
  // src/public-command-renderer.ts
25081
25065
  function isPublicCallableRole2(role) {
25082
25066
  return PUBLIC_CALLABLE_ROLES3.has(role);
@@ -25237,8 +25221,8 @@ var init_terminal = __esm({
25237
25221
 
25238
25222
  // src/public-cli/settlement.ts
25239
25223
  import { randomUUID as randomUUID3 } from "node:crypto";
25240
- import { appendFile as appendFile2, readFile as readFile15, readdir as readdir5, writeFile as writeFile7 } from "node:fs/promises";
25241
- import { dirname as dirname10, join as join25 } from "node:path";
25224
+ import { appendFile as appendFile2, readFile as readFile15, readdir as readdir5, writeFile as writeFile6 } from "node:fs/promises";
25225
+ import { dirname as dirname10, join as join23 } from "node:path";
25242
25226
  function sealedLedgerHome(admitted) {
25243
25227
  return homeFromRunDirectory(admitted.runDirectory);
25244
25228
  }
@@ -25618,7 +25602,7 @@ async function readSitianRetainedAuditorProviderStop(sessionFile) {
25618
25602
  const { records: records2 } = await readSitianRecords(recordFile);
25619
25603
  for (let i = records2.length - 1; i >= 0; i -= 1) {
25620
25604
  const payload = records2[i]?.payload;
25621
- if (!isRecord17(payload) || !isRecord17(payload.response)) continue;
25605
+ if (!isRecord18(payload) || !isRecord18(payload.response)) continue;
25622
25606
  if (typeof payload.type === "string") continue;
25623
25607
  const stop = sessionProviderStopFromAssistant(payload.response);
25624
25608
  if (stop !== void 0) return stop;
@@ -25639,7 +25623,7 @@ async function readSessionProviderStop(sessionFile) {
25639
25623
  }
25640
25624
  }
25641
25625
  async function readBoundEvidenceChildKnownFailure(sessionFile) {
25642
- const childDirectory = join25(dirname10(sessionFile), "evidence-children");
25626
+ const childDirectory = join23(dirname10(sessionFile), "evidence-children");
25643
25627
  let names;
25644
25628
  try {
25645
25629
  names = await readdir5(childDirectory);
@@ -25650,12 +25634,12 @@ async function readBoundEvidenceChildKnownFailure(sessionFile) {
25650
25634
  for (const file of names.filter((name) => name.endsWith(".jsonl")).sort().reverse()) {
25651
25635
  let entries;
25652
25636
  try {
25653
- entries = await readBoundSessionEntries(join25(childDirectory, file));
25637
+ entries = await readBoundSessionEntries(join23(childDirectory, file));
25654
25638
  } catch (error) {
25655
25639
  throw sessionReadFailure(error, "failed to read discovered evidence-child session");
25656
25640
  }
25657
25641
  const header = entries.find((entry) => entry.type === "session");
25658
- if (!isRecord17(header) || header.parentSession !== sessionFile) continue;
25642
+ if (!isRecord18(header) || header.parentSession !== sessionFile) continue;
25659
25643
  const stop = extractSessionProviderStop(entries);
25660
25644
  if (stop === void 0) continue;
25661
25645
  const primary = knownFailureFromProviderStop(stop);
@@ -25687,12 +25671,12 @@ async function loadBoundAuditorVolumes(sessionFile) {
25687
25671
  return firstLine === RESUME_ENVELOPE;
25688
25672
  };
25689
25673
  const isResumeEnvelope = (msg) => {
25690
- if (!isRecord17(msg) || msg.role !== "user") return false;
25674
+ if (!isRecord18(msg) || msg.role !== "user") return false;
25691
25675
  const text = typeof msg.text === "string" ? msg.text : typeof msg.content === "string" ? msg.content : void 0;
25692
25676
  if (isResumeEnvelopeBytes(text)) return true;
25693
25677
  const content = msg.content;
25694
25678
  if (Array.isArray(content)) {
25695
- return content.some((p) => isRecord17(p) && (isResumeEnvelopeBytes(p.text) || isResumeEnvelopeBytes(p.content)));
25679
+ return content.some((p) => isRecord18(p) && (isResumeEnvelopeBytes(p.text) || isResumeEnvelopeBytes(p.content)));
25696
25680
  }
25697
25681
  return false;
25698
25682
  };
@@ -25704,7 +25688,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
25704
25688
  latestParentUserIndex = i;
25705
25689
  break;
25706
25690
  }
25707
- const childDirectories = [join25(dirname10(sessionFile), "auditor-roles")];
25691
+ const childDirectories = [join23(dirname10(sessionFile), "auditor-roles")];
25708
25692
  const valid = [];
25709
25693
  let sawAnyDirectory = false;
25710
25694
  for (const childDirectory of childDirectories) {
@@ -25719,12 +25703,12 @@ async function loadBoundAuditorVolumes(sessionFile) {
25719
25703
  for (const file of names.filter((name) => name.endsWith(".jsonl")).sort().reverse()) {
25720
25704
  let entries;
25721
25705
  try {
25722
- entries = await readBoundSessionEntries(join25(childDirectory, file));
25706
+ entries = await readBoundSessionEntries(join23(childDirectory, file));
25723
25707
  } catch (error) {
25724
25708
  throw sessionReadFailure(error, "failed to read discovered auditor session");
25725
25709
  }
25726
25710
  const header = entries.find((entry) => entry.type === "session");
25727
- if (!isRecord17(header)) continue;
25711
+ if (!isRecord18(header)) continue;
25728
25712
  const bindingIndexes = [];
25729
25713
  for (let i = 0; i < entries.length; i += 1) {
25730
25714
  const entry = entries[i];
@@ -25738,7 +25722,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
25738
25722
  end: idx + 1 < bindingIndexes.length ? bindingIndexes[idx + 1] : entries.length
25739
25723
  })) : [{ entry: void 0, start: 0, end: entries.length }];
25740
25724
  for (const { entry: bindingEntry, start, end } of bindingPasses) {
25741
- const bindingParent = bindingEntry !== void 0 && isRecord17(bindingEntry.data) && isRecord17(bindingEntry.data.parent) ? bindingEntry.data.parent : void 0;
25725
+ const bindingParent = bindingEntry !== void 0 && isRecord18(bindingEntry.data) && isRecord18(bindingEntry.data.parent) ? bindingEntry.data.parent : void 0;
25742
25726
  const attemptEntryId = typeof bindingParent?.attemptEntryId === "string" ? bindingParent.attemptEntryId : void 0;
25743
25727
  const attemptEntryIndex = attemptEntryId === void 0 ? -1 : parentEntries.findIndex((entry) => entry.id === attemptEntryId);
25744
25728
  const boundSessionFile = typeof bindingParent?.sessionFile === "string" ? bindingParent.sessionFile : typeof header.parentSession === "string" ? header.parentSession : void 0;
@@ -25765,11 +25749,11 @@ function complianceFailureFromAuditorVolumes(volumes) {
25765
25749
  if (stop === void 0) continue;
25766
25750
  for (let i = entries.length - 1; i >= 0; i -= 1) {
25767
25751
  const entry = entries[i];
25768
- if (entry?.type !== "custom" || entry.customType !== AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE || !isRecord17(entry.data)) continue;
25769
- const parent = isRecord17(entry.data.parent) ? entry.data.parent : void 0;
25770
- const failure = isRecord17(entry.data.failure) ? entry.data.failure : void 0;
25752
+ if (entry?.type !== "custom" || entry.customType !== AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE || !isRecord18(entry.data)) continue;
25753
+ const parent = isRecord18(entry.data.parent) ? entry.data.parent : void 0;
25754
+ const failure = isRecord18(entry.data.failure) ? entry.data.failure : void 0;
25771
25755
  if (parent?.sessionId !== parentId || parent.sessionFile !== sessionFile || parent.attemptEntryId !== attemptEntryId || failure?.cause !== "provider" && failure?.cause !== "unrecognized") continue;
25772
- const identity = isRecord17(failure.identity) ? failure.identity : void 0;
25756
+ const identity = isRecord18(failure.identity) ? failure.identity : void 0;
25773
25757
  return {
25774
25758
  cause: failure.cause === "provider" ? "provider" : "unrecognized",
25775
25759
  ...identity === void 0 ? {} : { identity: {
@@ -25777,7 +25761,7 @@ function complianceFailureFromAuditorVolumes(volumes) {
25777
25761
  ...typeof identity.code === "string" || typeof identity.code === "number" ? { code: identity.code } : {}
25778
25762
  } },
25779
25763
  ...typeof failure.diagnostic === "string" ? { diagnostic: failure.diagnostic } : {},
25780
- ...isRecord17(failure.details) ? { details: failure.details } : {}
25764
+ ...isRecord18(failure.details) ? { details: failure.details } : {}
25781
25765
  };
25782
25766
  }
25783
25767
  }
@@ -25824,11 +25808,11 @@ function typedFailedTerminatingToolKnownFailure(entries) {
25824
25808
  if (classification.kind !== "infrastructure") continue;
25825
25809
  if (typeof message.toolCallId !== "string" || typeof message.toolName !== "string") continue;
25826
25810
  if (boundRoleToolCallForResult(attemptEntries, i, message, message.toolName) === void 0) continue;
25827
- const textPart = Array.isArray(message.content) ? message.content.find((part) => isRecord17(part) && part.type === "text" && typeof part.text === "string") : void 0;
25828
- const diagnostic = isRecord17(textPart) ? textPart.text : void 0;
25829
- const details = isRecord17(message.details) ? message.details : classification.fact;
25811
+ const textPart = Array.isArray(message.content) ? message.content.find((part) => isRecord18(part) && part.type === "text" && typeof part.text === "string") : void 0;
25812
+ const diagnostic = isRecord18(textPart) ? textPart.text : void 0;
25813
+ const details = isRecord18(message.details) ? message.details : classification.fact;
25830
25814
  return {
25831
- cause: "output",
25815
+ cause: "activation",
25832
25816
  identity: { name: message.toolName, code: message.toolCallId },
25833
25817
  ...typeof diagnostic === "string" && diagnostic.trim() !== "" ? { diagnostic } : {},
25834
25818
  details
@@ -25984,7 +25968,7 @@ function controlledFailureInputFromResolution(resolution) {
25984
25968
  } : {}
25985
25969
  };
25986
25970
  }
25987
- function isRecord17(value) {
25971
+ function isRecord18(value) {
25988
25972
  return typeof value === "object" && value !== null && !Array.isArray(value);
25989
25973
  }
25990
25974
  function safelyRead(object, key) {
@@ -26003,11 +25987,19 @@ function auditNoReceiptDecisiveFact(candidate) {
26003
25987
  return {};
26004
25988
  }
26005
25989
  }
25990
+ function auditUnreadableDecisiveFact(candidate) {
25991
+ const projected = safelyRead(candidate, "auditUnreadable");
25992
+ if (!projected.readable || projected.value === void 0) return {};
25993
+ if (typeof projected.value !== "object" || projected.value === null || Array.isArray(projected.value)) {
25994
+ return { auditUnreadable: projected.value };
25995
+ }
25996
+ return { auditUnreadable: projected.value };
25997
+ }
26006
25998
  function countersignDecisiveFacts(verdict, countersignStatus) {
26007
25999
  const facts = { countersignStatus };
26008
26000
  if (countersignStatus === "continue") {
26009
26001
  const fix = safelyRead(verdict, "fix");
26010
- if (fix.readable && isRecord17(fix.value)) {
26002
+ if (fix.readable && isRecord18(fix.value)) {
26011
26003
  const summary = safelyRead(fix.value, "summary");
26012
26004
  if (summary.readable && typeof summary.value === "string") {
26013
26005
  facts.fixSummary = summary.value;
@@ -26016,7 +26008,7 @@ function countersignDecisiveFacts(verdict, countersignStatus) {
26016
26008
  }
26017
26009
  if (countersignStatus === "escalate") {
26018
26010
  const gate = safelyRead(verdict, "decisionGate");
26019
- if (gate.readable && isRecord17(gate.value)) {
26011
+ if (gate.readable && isRecord18(gate.value)) {
26020
26012
  const question = safelyRead(gate.value, "question");
26021
26013
  const options = safelyRead(gate.value, "options");
26022
26014
  if (question.readable && typeof question.value === "string") {
@@ -26036,12 +26028,13 @@ function countersignDecisiveFacts(verdict, countersignStatus) {
26036
26028
  function judgeDecisiveFacts(verdict, judgeStatus) {
26037
26029
  const facts = {
26038
26030
  judgeStatus,
26039
- ...auditNoReceiptDecisiveFact(verdict)
26031
+ ...auditNoReceiptDecisiveFact(verdict),
26032
+ ...auditUnreadableDecisiveFact(verdict)
26040
26033
  };
26041
26034
  const statusBase = judgeStatus;
26042
26035
  if (statusBase === "continue") {
26043
26036
  const fix = safelyRead(verdict, "fix");
26044
- if (fix.readable && isRecord17(fix.value)) {
26037
+ if (fix.readable && isRecord18(fix.value)) {
26045
26038
  const summary = safelyRead(fix.value, "summary");
26046
26039
  if (summary.readable && typeof summary.value === "string") {
26047
26040
  facts.fixSummary = summary.value;
@@ -26051,7 +26044,7 @@ function judgeDecisiveFacts(verdict, judgeStatus) {
26051
26044
  if (classes.readable && Array.isArray(classes.value)) {
26052
26045
  try {
26053
26046
  facts.classes = classes.value.map((entry) => {
26054
- if (!isRecord17(entry)) throw new Error("unreadable Judge class");
26047
+ if (!isRecord18(entry)) throw new Error("unreadable Judge class");
26055
26048
  return {
26056
26049
  name: entry.name,
26057
26050
  owner: entry.owner,
@@ -26066,7 +26059,7 @@ function judgeDecisiveFacts(verdict, judgeStatus) {
26066
26059
  }
26067
26060
  if (statusBase === "escalate") {
26068
26061
  const gate = safelyRead(verdict, "decisionGate");
26069
- if (gate.readable && isRecord17(gate.value)) {
26062
+ if (gate.readable && isRecord18(gate.value)) {
26070
26063
  const question = safelyRead(gate.value, "question");
26071
26064
  const options = safelyRead(gate.value, "options");
26072
26065
  if (question.readable && typeof question.value === "string") {
@@ -26112,7 +26105,7 @@ function fixerDecisiveFacts(output) {
26112
26105
  facts.reason = reason.value;
26113
26106
  }
26114
26107
  const blockerRead = safelyRead(candidate, "blocker");
26115
- if (statusBase === "refused" && blockerRead.readable && isRecord17(blockerRead.value)) {
26108
+ if (statusBase === "refused" && blockerRead.readable && isRecord18(blockerRead.value)) {
26116
26109
  const cause = safelyRead(blockerRead.value, "cause");
26117
26110
  if (cause.readable && typeof cause.value === "string") facts.blockerCause = cause.value;
26118
26111
  const prerequisiteId = safelyRead(blockerRead.value, "prerequisiteId");
@@ -26124,13 +26117,13 @@ function fixerDecisiveFacts(output) {
26124
26117
  const blockers = [];
26125
26118
  try {
26126
26119
  for (const entry of classResults.value) {
26127
- if (!isRecord17(entry)) throw new Error("unreadable class result");
26120
+ if (!isRecord18(entry)) throw new Error("unreadable class result");
26128
26121
  const name = safelyRead(entry, "name");
26129
26122
  const disposition = safelyRead(entry, "disposition");
26130
26123
  if (!name.readable || !disposition.readable) throw new Error("unreadable class result");
26131
26124
  rows.push({ name: name.value, disposition: disposition.value });
26132
26125
  const blocker = safelyRead(entry, "blocker");
26133
- if (disposition.value === "refused" && blocker.readable && isRecord17(blocker.value)) blockers.push(blocker.value);
26126
+ if (disposition.value === "refused" && blocker.readable && isRecord18(blocker.value)) blockers.push(blocker.value);
26134
26127
  }
26135
26128
  facts.classResultCount = rows.length;
26136
26129
  facts.classDispositions = rows;
@@ -26163,7 +26156,7 @@ function collectorDecisiveFacts(receipt) {
26163
26156
  if (groups.readable && Array.isArray(groups.value)) {
26164
26157
  try {
26165
26158
  facts.groups = groups.value.map((group) => {
26166
- if (!isRecord17(group)) throw new Error("unreadable Collector group");
26159
+ if (!isRecord18(group)) throw new Error("unreadable Collector group");
26167
26160
  const identity = safelyRead(group, "identity");
26168
26161
  const attendance = safelyRead(group, "attendance");
26169
26162
  const materials = safelyRead(group, "materials");
@@ -26186,7 +26179,10 @@ function collectorDecisiveFacts(receipt) {
26186
26179
  function doctorDecisiveFacts(output) {
26187
26180
  const candidate = output;
26188
26181
  const status = safelyRead(candidate, "status");
26189
- const facts = { ...auditNoReceiptDecisiveFact(candidate) };
26182
+ const facts = {
26183
+ ...auditNoReceiptDecisiveFact(candidate),
26184
+ ...auditUnreadableDecisiveFact(candidate)
26185
+ };
26190
26186
  if (status.readable && typeof status.value === "string") facts.doctorStatus = status.value;
26191
26187
  const statusBase = status.readable && typeof status.value === "string" ? status.value : void 0;
26192
26188
  if (statusBase === "refused") {
@@ -26197,7 +26193,7 @@ function doctorDecisiveFacts(output) {
26197
26193
  return facts;
26198
26194
  }
26199
26195
  const caseValue = safelyRead(candidate, "case");
26200
- if (caseValue.readable && isRecord17(caseValue.value)) {
26196
+ if (caseValue.readable && isRecord18(caseValue.value)) {
26201
26197
  const issueNumber = safelyRead(caseValue.value, "issueNumber");
26202
26198
  const runsPath = safelyRead(caseValue.value, "runsPath");
26203
26199
  if (issueNumber.readable && issueNumber.value !== void 0) facts.issueNumber = issueNumber.value;
@@ -26208,7 +26204,7 @@ function doctorDecisiveFacts(output) {
26208
26204
  return facts;
26209
26205
  }
26210
26206
  function reviewerAxes(value) {
26211
- if (!isRecord17(value)) return [];
26207
+ if (!isRecord18(value)) return [];
26212
26208
  return ["standards", "spec"].filter((axis) => {
26213
26209
  const projected = safelyRead(value, axis);
26214
26210
  return projected.readable && projected.value !== void 0;
@@ -26342,7 +26338,7 @@ function boundRoleToolCallForResult(entries, resultIndex, message, outputToolNam
26342
26338
  const candidateMessage = entries[index]?.message;
26343
26339
  if (candidateMessage?.role === "assistant" && Array.isArray(candidateMessage.content)) {
26344
26340
  for (const part of candidateMessage.content) {
26345
- if (!isRecord17(part) || part.type !== "toolCall" || part.id !== callId) {
26341
+ if (!isRecord18(part) || part.type !== "toolCall" || part.id !== callId) {
26346
26342
  continue;
26347
26343
  }
26348
26344
  if (part.name !== outputToolName) return void 0;
@@ -26414,7 +26410,7 @@ function parseNavigatorAttendanceDetails(details) {
26414
26410
  const advisoryDiagnostic = typeof details.routePlaybookReadFailure === "string" ? { advisoryDiagnostic: details.routePlaybookReadFailure } : {};
26415
26411
  if (disposition === "recommendation") {
26416
26412
  const next = details.next;
26417
- if (!isRecord17(next) || typeof next.role !== "string") {
26413
+ if (!isRecord18(next) || typeof next.role !== "string") {
26418
26414
  return {
26419
26415
  disposition: "unavailable",
26420
26416
  source: "unknown",
@@ -26422,7 +26418,7 @@ function parseNavigatorAttendanceDetails(details) {
26422
26418
  };
26423
26419
  }
26424
26420
  const reason = typeof details.reason === "string" ? details.reason : "";
26425
- const route = Array.isArray(details.route) ? details.route.filter(isRecord17).map((target) => ({
26421
+ const route = Array.isArray(details.route) ? details.route.filter(isRecord18).map((target) => ({
26426
26422
  role: String(target.role),
26427
26423
  phase: navigatorPhaseValue(target.phase)
26428
26424
  })) : void 0;
@@ -26485,8 +26481,8 @@ function projectTerminalGateFact(rounds) {
26485
26481
  };
26486
26482
  }
26487
26483
  async function extractGateFactFromSessionDirectory(sessionDirectory, options = {}) {
26488
- const directories = [join25(sessionDirectory, "auditor-roles")];
26489
- const parentSessionFile = options.parentSessionFile ?? join25(sessionDirectory, "session.jsonl");
26484
+ const directories = [join23(sessionDirectory, "auditor-roles")];
26485
+ const parentSessionFile = options.parentSessionFile ?? join23(sessionDirectory, "session.jsonl");
26490
26486
  const rounds = await readAnalystGateCyclesFromAuditorRoles(directories, {
26491
26487
  parentSessionFile
26492
26488
  });
@@ -26494,7 +26490,7 @@ async function extractGateFactFromSessionDirectory(sessionDirectory, options = {
26494
26490
  }
26495
26491
  async function withOptionalGateProjection(base, sessionDirectory, gateContext = {}) {
26496
26492
  const secondaryEvidence = base.roleOutcome.kind === "failure" ? base.roleOutcome.decisiveFacts.secondaryEvidence : void 0;
26497
- if (isRecord17(secondaryEvidence) && secondaryEvidence.kind === "role_infrastructure_failure" && (secondaryEvidence.stage === "gatekeeper" || secondaryEvidence.stage === "inspector" || secondaryEvidence.stage === "notary")) return base;
26493
+ if (isRecord18(secondaryEvidence) && secondaryEvidence.kind === "role_infrastructure_failure" && (secondaryEvidence.stage === "gatekeeper" || secondaryEvidence.stage === "inspector" || secondaryEvidence.stage === "notary")) return base;
26498
26494
  const gate = await extractGateFactFromSessionDirectory(sessionDirectory, gateContext);
26499
26495
  return gate === void 0 ? base : { ...base, gate };
26500
26496
  }
@@ -26534,7 +26530,7 @@ function extractNavigatorFact(entries) {
26534
26530
  const entry = entries[i];
26535
26531
  if (entry?.type === "custom_message" && entry.customType === "ak-navigator-attendance") {
26536
26532
  const details = entry.message?.details ?? entry.details;
26537
- if (!isRecord17(details)) {
26533
+ if (!isRecord18(details)) {
26538
26534
  return {
26539
26535
  disposition: "unavailable",
26540
26536
  source: "unknown",
@@ -26584,9 +26580,9 @@ async function extractNavigatorFactFromAdmittedSession(sessionFile) {
26584
26580
  async function publishJudgeArtifacts(admitted, roleOutcome, coordinates) {
26585
26581
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
26586
26582
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
26587
- const reportPath = join25(artifactsDir, "report.json");
26588
- const evidencePath = join25(artifactsDir, "evidence.json");
26589
- await writeFile7(
26583
+ const reportPath = join23(artifactsDir, "report.json");
26584
+ const evidencePath = join23(artifactsDir, "evidence.json");
26585
+ await writeFile6(
26590
26586
  reportPath,
26591
26587
  `${JSON.stringify(
26592
26588
  {
@@ -26600,7 +26596,7 @@ async function publishJudgeArtifacts(admitted, roleOutcome, coordinates) {
26600
26596
  `,
26601
26597
  "utf8"
26602
26598
  );
26603
- await writeFile7(
26599
+ await writeFile6(
26604
26600
  evidencePath,
26605
26601
  `${JSON.stringify(
26606
26602
  {
@@ -26629,9 +26625,9 @@ async function publishJudgeArtifacts(admitted, roleOutcome, coordinates) {
26629
26625
  async function publishCoderArtifacts(admitted, roleOutcome, coordinates, options = {}) {
26630
26626
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
26631
26627
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
26632
- const reportPath = join25(artifactsDir, "report.json");
26633
- const evidencePath = join25(artifactsDir, "evidence.json");
26634
- await writeFile7(
26628
+ const reportPath = join23(artifactsDir, "report.json");
26629
+ const evidencePath = join23(artifactsDir, "evidence.json");
26630
+ await writeFile6(
26635
26631
  reportPath,
26636
26632
  `${JSON.stringify(
26637
26633
  {
@@ -26647,7 +26643,7 @@ async function publishCoderArtifacts(admitted, roleOutcome, coordinates, options
26647
26643
  `,
26648
26644
  "utf8"
26649
26645
  );
26650
- await writeFile7(
26646
+ await writeFile6(
26651
26647
  evidencePath,
26652
26648
  `${JSON.stringify(
26653
26649
  {
@@ -26789,9 +26785,9 @@ function extractFixerMethodInvocations(entries, options) {
26789
26785
  async function publishFixerArtifacts(admitted, roleOutcome, coordinates, options) {
26790
26786
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
26791
26787
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
26792
- const reportPath = join25(artifactsDir, "report.json");
26793
- const evidencePath = join25(artifactsDir, "evidence.json");
26794
- await writeFile7(
26788
+ const reportPath = join23(artifactsDir, "report.json");
26789
+ const evidencePath = join23(artifactsDir, "evidence.json");
26790
+ await writeFile6(
26795
26791
  reportPath,
26796
26792
  `${JSON.stringify(
26797
26793
  {
@@ -26807,7 +26803,7 @@ async function publishFixerArtifacts(admitted, roleOutcome, coordinates, options
26807
26803
  `,
26808
26804
  "utf8"
26809
26805
  );
26810
- await writeFile7(
26806
+ await writeFile6(
26811
26807
  evidencePath,
26812
26808
  `${JSON.stringify(
26813
26809
  {
@@ -26889,9 +26885,9 @@ async function settleLawfulFixerTerminalResult(admitted, authority, options) {
26889
26885
  async function publishCollectorArtifacts(admitted, roleOutcome, coordinates, options = {}) {
26890
26886
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
26891
26887
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
26892
- const reportPath = join25(artifactsDir, "report.json");
26893
- const evidencePath = join25(artifactsDir, "evidence.json");
26894
- await writeFile7(
26888
+ const reportPath = join23(artifactsDir, "report.json");
26889
+ const evidencePath = join23(artifactsDir, "evidence.json");
26890
+ await writeFile6(
26895
26891
  reportPath,
26896
26892
  `${JSON.stringify(
26897
26893
  {
@@ -26906,7 +26902,7 @@ async function publishCollectorArtifacts(admitted, roleOutcome, coordinates, opt
26906
26902
  `,
26907
26903
  "utf8"
26908
26904
  );
26909
- await writeFile7(
26905
+ await writeFile6(
26910
26906
  evidencePath,
26911
26907
  `${JSON.stringify(
26912
26908
  {
@@ -26949,7 +26945,7 @@ async function settleLawfulCollectorTerminalResult(admitted, authority) {
26949
26945
  const residual = boundErroredToolCandidate(entries, index, message, COLLECTOR_WAIT_TOOL);
26950
26946
  if (residual === void 0) continue;
26951
26947
  const candidate = residual.candidate;
26952
- const duration = isRecord17(candidate) ? candidate.durationMs : void 0;
26948
+ const duration = isRecord18(candidate) ? candidate.durationMs : void 0;
26953
26949
  if (Number.isSafeInteger(duration) && duration >= 1 && duration <= 9e5) {
26954
26950
  continue;
26955
26951
  }
@@ -26997,9 +26993,9 @@ async function trySettleCollectorTerminalResult(admitted, authority) {
26997
26993
  async function publishDoctorArtifacts(admitted, roleOutcome, coordinates, options = {}) {
26998
26994
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
26999
26995
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
27000
- const reportPath = join25(artifactsDir, "report.json");
27001
- const evidencePath = join25(artifactsDir, "evidence.json");
27002
- await writeFile7(
26996
+ const reportPath = join23(artifactsDir, "report.json");
26997
+ const evidencePath = join23(artifactsDir, "evidence.json");
26998
+ await writeFile6(
27003
26999
  reportPath,
27004
27000
  `${JSON.stringify(
27005
27001
  {
@@ -27014,7 +27010,7 @@ async function publishDoctorArtifacts(admitted, roleOutcome, coordinates, option
27014
27010
  `,
27015
27011
  "utf8"
27016
27012
  );
27017
- await writeFile7(
27013
+ await writeFile6(
27018
27014
  evidencePath,
27019
27015
  `${JSON.stringify(
27020
27016
  {
@@ -27143,7 +27139,7 @@ async function settleLawfulSeatAcceptedTerminalResult(admitted, authority, spec,
27143
27139
  return settleFailureTerminalResult(admitted, {
27144
27140
  cause: "output",
27145
27141
  diagnostic: residual.diagnostic,
27146
- details: { candidate: residual.candidate, acceptedReceipt: false }
27142
+ details: stampShapeUnreadableDetails(residual.candidate)
27147
27143
  }, authority);
27148
27144
  }
27149
27145
  if (acceptedNonUsable === void 0 && message.toolName === spec.toolName && isAcceptedPackagedRoleTerminalResult(message)) {
@@ -27156,7 +27152,7 @@ async function settleLawfulSeatAcceptedTerminalResult(admitted, authority, spec,
27156
27152
  return settleFailureTerminalResult(admitted, {
27157
27153
  cause: "output",
27158
27154
  diagnostic: spec.nonUsableDiagnostic,
27159
- details: { candidate: acceptedNonUsable, acceptedReceipt: false }
27155
+ details: stampShapeUnreadableDetails(acceptedNonUsable)
27160
27156
  }, authority);
27161
27157
  }
27162
27158
  return void 0;
@@ -27167,7 +27163,7 @@ async function settleLawfulSeatAcceptedTerminalResult(admitted, authority, spec,
27167
27163
  {
27168
27164
  cause: "output",
27169
27165
  diagnostic: spec.nonUsableDiagnostic,
27170
- details: { candidate: roleOutcome.decisiveFacts, acceptedReceipt: false }
27166
+ details: stampShapeUnreadableDetails(roleOutcome.decisiveFacts)
27171
27167
  },
27172
27168
  authority
27173
27169
  );
@@ -27257,6 +27253,27 @@ async function settleLawfulGleanerLeftTerminalResult(admitted, authority, scope)
27257
27253
  async function trySettleGleanerLeftTerminalResult(admitted, authority, scope) {
27258
27254
  return settleLawfulGleanerLeftTerminalResult(admitted, authority, scope);
27259
27255
  }
27256
+ async function settleLawfulDiaristTerminalResult(admitted, authority, scope) {
27257
+ return settleLawfulSeatAcceptedTerminalResult(admitted, authority, {
27258
+ role: "diarist",
27259
+ toolName: DIARIST_OUTPUT_TOOL_NAME,
27260
+ nonUsableDiagnostic: "\u8D77\u5C45\u90CE\u56DE\u6267\u65E0\u663E\u5F0F completed",
27261
+ tryAcceptDetails: tryAcceptWithValidator(validateRecordedDiaristOutput),
27262
+ projectAccepted: (sealed) => {
27263
+ const output = validateRecordedDiaristOutput(sealed.decisiveFacts);
27264
+ const accepted = {
27265
+ kind: "accepted",
27266
+ role: "diarist",
27267
+ status: sealed.status,
27268
+ decisiveFacts: diaristDecisiveFacts(output)
27269
+ };
27270
+ return accepted;
27271
+ }
27272
+ }, scope);
27273
+ }
27274
+ async function trySettleDiaristTerminalResult(admitted, authority, scope) {
27275
+ return settleLawfulDiaristTerminalResult(admitted, authority, scope);
27276
+ }
27260
27277
  async function settleLawfulInspectorTerminalResult(admitted, authority, scope) {
27261
27278
  return settleLawfulSeatAcceptedTerminalResult(admitted, authority, {
27262
27279
  role: "inspector",
@@ -27320,6 +27337,53 @@ async function settleLawfulNavigatorTerminalResult(admitted, authority, scope) {
27320
27337
  async function trySettleNavigatorTerminalResult(admitted, authority, scope) {
27321
27338
  return settleLawfulNavigatorTerminalResult(admitted, authority, scope);
27322
27339
  }
27340
+ async function settleLawfulAuditorTerminalResult(admitted, authority, scope) {
27341
+ return settleLawfulSeatAcceptedTerminalResult(admitted, authority, {
27342
+ role: "auditor",
27343
+ toolName: AUDITOR_OUTPUT_TOOL_NAME,
27344
+ nonUsableDiagnostic: "\u5BA1\u5211\u9662\u56DE\u6267\u65E0\u663E\u5F0F pass/revise/escalate",
27345
+ // Only pass/revise/escalate are lawful releases. Unreadable mystery status
27346
+ // fails closed with candidate retained for parent ComplianceCandidateUnreadableError.
27347
+ tryAcceptDetails: (details) => projectLawfulAuditorOutput(details) !== void 0,
27348
+ projectAccepted: (sealed) => {
27349
+ const lawful = projectLawfulAuditorOutput(sealed.decisiveFacts);
27350
+ if (lawful === void 0) {
27351
+ throw new Error("auditor projectAccepted requires lawful pass/revise/escalate");
27352
+ }
27353
+ const accepted = {
27354
+ kind: "accepted",
27355
+ role: "auditor",
27356
+ status: lawful.status,
27357
+ decisiveFacts: auditorDecisiveFacts(lawful)
27358
+ };
27359
+ return accepted;
27360
+ }
27361
+ }, scope);
27362
+ }
27363
+ async function trySettleAuditorTerminalResult(admitted, authority, scope) {
27364
+ return settleLawfulAuditorTerminalResult(admitted, authority, scope);
27365
+ }
27366
+ async function settleLawfulEvidenceChildTerminalResult(admitted, authority, scope) {
27367
+ return settleLawfulSeatAcceptedTerminalResult(admitted, authority, {
27368
+ role: "evidence-child",
27369
+ toolName: EVIDENCE_CHILD_OUTPUT_TOOL_NAME,
27370
+ nonUsableDiagnostic: "\u53D6\u8BC1\u56DE\u6267\u65E0\u62A5\u544A\u6B63\u6587",
27371
+ tryAcceptDetails: tryAcceptWithValidator(validateRecordedEvidenceChildOutput),
27372
+ projectAccepted: (sealed) => {
27373
+ const output = validateRecordedEvidenceChildOutput(sealed.decisiveFacts);
27374
+ const accepted = {
27375
+ kind: "accepted",
27376
+ role: "evidence-child",
27377
+ status: "report",
27378
+ decisiveFacts: evidenceChildDecisiveFacts(output)
27379
+ };
27380
+ return accepted;
27381
+ }
27382
+ }, scope);
27383
+ }
27384
+ async function trySettleEvidenceChildTerminalResult(admitted, authority, scope) {
27385
+ return settleLawfulEvidenceChildTerminalResult(admitted, authority, scope);
27386
+ }
27323
27387
  async function trySettleCoderTerminalResult(admitted, authority, options = {}) {
27324
27388
  return settleLawfulCoderTerminalResult(admitted, authority, options);
27325
27389
  }
@@ -27345,9 +27409,9 @@ function extractReviewerMethodInvocations(entries, options) {
27345
27409
  async function publishReviewerArtifacts(admitted, roleOutcome, coordinates, options) {
27346
27410
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
27347
27411
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
27348
- const reportPath = join25(artifactsDir, "report.json");
27349
- const evidencePath = join25(artifactsDir, "evidence.json");
27350
- await writeFile7(
27412
+ const reportPath = join23(artifactsDir, "report.json");
27413
+ const evidencePath = join23(artifactsDir, "evidence.json");
27414
+ await writeFile6(
27351
27415
  reportPath,
27352
27416
  `${JSON.stringify(
27353
27417
  {
@@ -27362,7 +27426,7 @@ async function publishReviewerArtifacts(admitted, roleOutcome, coordinates, opti
27362
27426
  `,
27363
27427
  "utf8"
27364
27428
  );
27365
- await writeFile7(
27429
+ await writeFile6(
27366
27430
  evidencePath,
27367
27431
  `${JSON.stringify(
27368
27432
  {
@@ -27473,9 +27537,9 @@ function extractMergerMethodInvocations(entries, options) {
27473
27537
  async function publishMergerArtifacts(admitted, roleOutcome, coordinates, options) {
27474
27538
  await appendRunAttemptHistory({ role: admitted.role, runId: admitted.runId, sessionFile: coordinates.sessionFile }, roleOutcome);
27475
27539
  const artifactsDir = await ensureRunArtifactsDir(admitted.runDirectory);
27476
- const reportPath = join25(artifactsDir, "report.json");
27477
- const evidencePath = join25(artifactsDir, "evidence.json");
27478
- await writeFile7(
27540
+ const reportPath = join23(artifactsDir, "report.json");
27541
+ const evidencePath = join23(artifactsDir, "evidence.json");
27542
+ await writeFile6(
27479
27543
  reportPath,
27480
27544
  `${JSON.stringify(
27481
27545
  {
@@ -27490,7 +27554,7 @@ async function publishMergerArtifacts(admitted, roleOutcome, coordinates, option
27490
27554
  `,
27491
27555
  "utf8"
27492
27556
  );
27493
- await writeFile7(
27557
+ await writeFile6(
27494
27558
  evidencePath,
27495
27559
  `${JSON.stringify(
27496
27560
  {
@@ -27541,7 +27605,7 @@ async function settleLawfulMergerTerminalResult(admitted, authority, options) {
27541
27605
  if (message?.role !== "toolResult") continue;
27542
27606
  const residual = boundErroredToolCandidate(entries, index, message, MERGER_OUTPUT_TOOL_NAME);
27543
27607
  if (residual === void 0) continue;
27544
- const attemptId = isRecord17(residual.candidate) ? safelyRead(residual.candidate, "attemptId") : { readable: true, value: void 0 };
27608
+ const attemptId = isRecord18(residual.candidate) ? safelyRead(residual.candidate, "attemptId") : { readable: true, value: void 0 };
27545
27609
  if (!attemptId.readable || attemptId.value !== admitted.runId) continue;
27546
27610
  try {
27547
27611
  validateMergerOutput(residual.candidate, admitted.runId);
@@ -27623,7 +27687,7 @@ function uniqueFailureFallbackDirs(runDirectory, baseDir) {
27623
27687
  return dirs;
27624
27688
  }
27625
27689
  async function resolveFailureArtifactsBase(runDirectory) {
27626
- const artifactsDir = join25(runDirectory, "artifacts");
27690
+ const artifactsDir = join23(runDirectory, "artifacts");
27627
27691
  try {
27628
27692
  await ensureRunArtifactsDir(runDirectory);
27629
27693
  return { baseDir: artifactsDir };
@@ -27639,13 +27703,13 @@ async function writeFailureJsonRetainingCause(preferredCandidates, uniqueFallbac
27639
27703
  const candidates = [
27640
27704
  ...preferredCandidates,
27641
27705
  // One unique name per fallback dir — collisions on fixed names cannot exhaust this.
27642
- ...uniqueFallbackDirs.map((dir) => join25(dir, `${stem}.${randomUUID3()}.json`))
27706
+ ...uniqueFallbackDirs.map((dir) => join23(dir, `${stem}.${randomUUID3()}.json`))
27643
27707
  ];
27644
27708
  for (let i = 0; i < candidates.length; i += 1) {
27645
27709
  const path = candidates[i];
27646
27710
  const payload = issues.length === 0 ? basePayload : { ...basePayload, publicationIssues: issues };
27647
27711
  try {
27648
- await writeFile7(
27712
+ await writeFile6(
27649
27713
  path,
27650
27714
  `${JSON.stringify(payload, null, 2)}
27651
27715
  `,
@@ -27684,26 +27748,26 @@ async function publishFailureArtifacts(admitted, failure, authority) {
27684
27748
  } catch (error) {
27685
27749
  priorIssues.push(publicationAttemptFromError(sessionFile, error));
27686
27750
  }
27687
- const underArtifacts = baseDir === join25(admitted.runDirectory, "artifacts");
27751
+ const underArtifacts = baseDir === join23(admitted.runDirectory, "artifacts");
27688
27752
  const uniqueFallbackDirs = uniqueFailureFallbackDirs(
27689
27753
  admitted.runDirectory,
27690
27754
  baseDir
27691
27755
  );
27692
27756
  const errorCandidates = underArtifacts ? [
27693
- join25(baseDir, "error.json"),
27694
- join25(baseDir, "error.settlement.json"),
27695
- join25(admitted.runDirectory, "error.settlement.json")
27757
+ join23(baseDir, "error.json"),
27758
+ join23(baseDir, "error.settlement.json"),
27759
+ join23(admitted.runDirectory, "error.settlement.json")
27696
27760
  ] : [
27697
- join25(baseDir, "error.settlement.json"),
27698
- join25(baseDir, "error.json")
27761
+ join23(baseDir, "error.settlement.json"),
27762
+ join23(baseDir, "error.json")
27699
27763
  ];
27700
27764
  const evidenceCandidates = underArtifacts ? [
27701
- join25(baseDir, "evidence.json"),
27702
- join25(baseDir, "evidence.settlement.json"),
27703
- join25(admitted.runDirectory, "evidence.settlement.json")
27765
+ join23(baseDir, "evidence.json"),
27766
+ join23(baseDir, "evidence.settlement.json"),
27767
+ join23(admitted.runDirectory, "evidence.settlement.json")
27704
27768
  ] : [
27705
- join25(baseDir, "evidence.settlement.json"),
27706
- join25(baseDir, "evidence.json")
27769
+ join23(baseDir, "evidence.settlement.json"),
27770
+ join23(baseDir, "evidence.json")
27707
27771
  ];
27708
27772
  const errorPayloadBase = {
27709
27773
  kind: "error",
@@ -27899,6 +27963,7 @@ var init_settlement = __esm({
27899
27963
  init_auditor_soul();
27900
27964
  init_doctor_auditor();
27901
27965
  init_judge_auditor();
27966
+ init_shape_unreadable_failure();
27902
27967
  init_known_failure();
27903
27968
  init_reviewer_dispatch_rejection();
27904
27969
  init_run_lifecycle();
@@ -27915,9 +27980,12 @@ var init_settlement = __esm({
27915
27980
  init_notary_contracts();
27916
27981
  init_countersign_contracts();
27917
27982
  init_gleaner_left_contracts();
27983
+ init_diarist_contracts();
27918
27984
  init_inspector_contracts();
27919
27985
  init_gatekeeper_output();
27920
27986
  init_navigator_output();
27987
+ init_auditor_output();
27988
+ init_evidence_child_output();
27921
27989
  init_method_skill();
27922
27990
  init_navigator_invocation_identity();
27923
27991
  init_receipt_delivery_policy();
@@ -27975,7 +28043,7 @@ var init_turn_request = __esm({
27975
28043
 
27976
28044
  // src/host-transition-prior-native.ts
27977
28045
  import { access as access2, readdir as readdir6 } from "node:fs/promises";
27978
- import { dirname as dirname11, join as join26 } from "node:path";
28046
+ import { dirname as dirname11, join as join24 } from "node:path";
27979
28047
  function isEnoent2(error) {
27980
28048
  return typeof error === "object" && error !== null && error.code === "ENOENT";
27981
28049
  }
@@ -28000,7 +28068,7 @@ async function listSitianRecordPaths(sessionParent) {
28000
28068
  const recordPaths = [];
28001
28069
  for (const entry of entries) {
28002
28070
  if (!entry.isDirectory()) continue;
28003
- const recordFile = join26(sessionRoot, entry.name, "records.jsonl");
28071
+ const recordFile = join24(sessionRoot, entry.name, "records.jsonl");
28004
28072
  try {
28005
28073
  await access2(recordFile);
28006
28074
  recordPaths.push(recordFile);
@@ -28070,7 +28138,7 @@ var init_public_run_credentials = __esm({
28070
28138
  import { constants as fsConstants } from "node:fs";
28071
28139
  import { randomUUID as randomUUID4 } from "node:crypto";
28072
28140
  import { lstat as lstat5, mkdir as mkdir4, open as open2 } from "node:fs/promises";
28073
- import { join as join27 } from "node:path";
28141
+ import { join as join25 } from "node:path";
28074
28142
  function presentTerminal(terminal, io) {
28075
28143
  if (terminal.roleOutcome.kind === "failure" || terminal.roleOutcome.kind === "no_receipt") {
28076
28144
  presentFailureTerminal(terminal, io);
@@ -28089,7 +28157,7 @@ async function finalizeExceptionRunBestEffort(runDirectory, io) {
28089
28157
  }
28090
28158
  }
28091
28159
  function runArtifactsDirectory(runDirectory) {
28092
- return join27(runDirectory, "artifacts");
28160
+ return join25(runDirectory, "artifacts");
28093
28161
  }
28094
28162
  async function ensureRealArtifactsDirectory(runDirectory) {
28095
28163
  const runStat = await lstat5(runDirectory);
@@ -28172,7 +28240,7 @@ function jsonSafeReplacer() {
28172
28240
  }
28173
28241
  async function retainDispatchError(admitted, principalAuthority, sessionAppender, attempt, error) {
28174
28242
  const artifactsDir = await ensureRealArtifactsDirectory(admitted.runDirectory);
28175
- const filePath = join27(
28243
+ const filePath = join25(
28176
28244
  artifactsDir,
28177
28245
  `dispatch-error-attempt-${attempt}-${randomUUID4()}.json`
28178
28246
  );
@@ -28420,11 +28488,11 @@ var init_auto_resume = __esm({
28420
28488
 
28421
28489
  // src/public-cli/post-admission.ts
28422
28490
  import { randomUUID as randomUUID5 } from "node:crypto";
28423
- import { readFile as readFile16, writeFile as writeFile8 } from "node:fs/promises";
28424
- import { isAbsolute as isAbsolute6, join as join28, resolve as resolve9 } from "node:path";
28491
+ import { readFile as readFile16, writeFile as writeFile7 } from "node:fs/promises";
28492
+ import { isAbsolute as isAbsolute6, join as join26, resolve as resolve9 } from "node:path";
28425
28493
  async function readInvocationHost(runDirectory) {
28426
28494
  try {
28427
- const raw = JSON.parse(await readFile16(join28(runDirectory, "invocation.json"), "utf8"));
28495
+ const raw = JSON.parse(await readFile16(join26(runDirectory, "invocation.json"), "utf8"));
28428
28496
  return typeof raw.host === "string" && raw.host.trim() !== "" ? raw.host : void 0;
28429
28497
  } catch (error) {
28430
28498
  if (error.code === "ENOENT") return void 0;
@@ -28507,7 +28575,7 @@ async function dispatchPostAdmissionTurn(input) {
28507
28575
  liveHost,
28508
28576
  piSessionFile: principalCoordinates.sessionFile
28509
28577
  }) : void 0;
28510
- turnRequest = request;
28578
+ turnRequest = env.signal === void 0 ? request : { ...request, signal: env.signal };
28511
28579
  if (hostTransition !== void 0) {
28512
28580
  turnRequest = { ...turnRequest, hostTransition };
28513
28581
  }
@@ -28563,8 +28631,8 @@ async function dispatchPostAdmissionTurn(input) {
28563
28631
  );
28564
28632
  }
28565
28633
  try {
28566
- await writeFile8(
28567
- join28(admitted.runDirectory, "stderr.log"),
28634
+ await writeFile7(
28635
+ join26(admitted.runDirectory, "stderr.log"),
28568
28636
  result2.stderr,
28569
28637
  "utf8"
28570
28638
  );
@@ -28676,7 +28744,7 @@ function resumeTurnRequestProjectionOptions(admitted, request, env, summonsPrepa
28676
28744
  }
28677
28745
  function isAlreadyFrozenSummonsAttachment(runDirectory, attachmentPath) {
28678
28746
  const absolute = isAbsolute6(attachmentPath) ? attachmentPath : resolve9(attachmentPath);
28679
- return pathContainedIn(join28(runDirectory, "attachments"), absolute);
28747
+ return pathContainedIn(join26(runDirectory, "attachments"), absolute);
28680
28748
  }
28681
28749
  async function prepareSummonsResumeMaterials(runDirectory, summons) {
28682
28750
  if (summons === void 0) return void 0;
@@ -29176,13 +29244,50 @@ function buildInstructionSeatTurnRequest(admitted, options) {
29176
29244
  options
29177
29245
  );
29178
29246
  }
29179
- function instructionSeatAdapters() {
29247
+ function instructionSeatAdapters(options) {
29180
29248
  return {
29181
- trySettle: (admitted, authority, scope) => admitted.role === "gatekeeper" ? trySettleGatekeeperTerminalResult(admitted, authority, scope) : trySettleNavigatorTerminalResult(admitted, authority, scope),
29249
+ trySettle: (admitted, authority, scope) => {
29250
+ switch (admitted.role) {
29251
+ case "gatekeeper":
29252
+ return trySettleGatekeeperTerminalResult(admitted, authority, scope);
29253
+ case "navigator":
29254
+ return trySettleNavigatorTerminalResult(admitted, authority, scope);
29255
+ case "auditor":
29256
+ return trySettleAuditorTerminalResult(admitted, authority, scope);
29257
+ case "evidence-child":
29258
+ return trySettleEvidenceChildTerminalResult(admitted, authority, scope);
29259
+ }
29260
+ },
29182
29261
  // Accepted receipts and failure terminals both present via shared path.
29183
- shouldPresentSettled: () => true
29262
+ shouldPresentSettled: () => true,
29263
+ // #675 / #357 T2: failInfrastructure abort after engine-detour tool failure must not
29264
+ // wash the durable toolResult diagnostic (same seam as reviewer-run / judge-run).
29265
+ resolveRunnerKnownFailure: async ({
29266
+ result: result2,
29267
+ sessionFile
29268
+ }) => {
29269
+ const infrastructureFailure = await readEngineDetourInfrastructureFailure(sessionFile);
29270
+ return infrastructureFailure === void 0 ? result2.knownFailure : {
29271
+ cause: infrastructureFailure.cause,
29272
+ diagnostic: infrastructureFailure.diagnostic,
29273
+ ...infrastructureFailure.identity === void 0 ? {} : { identity: infrastructureFailure.identity }
29274
+ };
29275
+ },
29276
+ ...options?.beforeDispatch === void 0 ? {} : { beforeDispatch: options.beforeDispatch }
29184
29277
  };
29185
29278
  }
29279
+ async function admitInstructionSeat(role, options) {
29280
+ switch (role) {
29281
+ case "gatekeeper":
29282
+ return admitGatekeeperInvocation(options);
29283
+ case "navigator":
29284
+ return admitNavigatorInvocation(options);
29285
+ case "auditor":
29286
+ return admitAuditorInvocation(options);
29287
+ case "evidence-child":
29288
+ return admitEvidenceChildInvocation(options);
29289
+ }
29290
+ }
29186
29291
  async function runPublicInstructionSeatResume(request, env, io) {
29187
29292
  return await runPostAdmissionSeatResume({
29188
29293
  request,
@@ -29193,19 +29298,136 @@ async function runPublicInstructionSeatResume(request, env, io) {
29193
29298
  effective.runId,
29194
29299
  env.principalAuthority
29195
29300
  ),
29196
- buildTurnRequest: (admitted, effective) => buildInstructionSeatTurnRequest(
29197
- admitted,
29198
- resumeTurnRequestProjectionOptions(admitted, effective, env)
29199
- ),
29301
+ buildTurnRequest: async (admitted, effective) => {
29302
+ const summonsPrepared = await prepareSummonsResumeMaterials(
29303
+ admitted.runDirectory,
29304
+ effective.summons
29305
+ );
29306
+ return buildInstructionSeatTurnRequest(
29307
+ admitted,
29308
+ resumeTurnRequestProjectionOptions(
29309
+ admitted,
29310
+ effective,
29311
+ env,
29312
+ summonsPrepared
29313
+ )
29314
+ );
29315
+ },
29200
29316
  adapters: instructionSeatAdapters(),
29201
29317
  ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
29202
29318
  });
29203
29319
  }
29320
+ async function withAuditorSoulEnv(options) {
29321
+ if (options.subject === void 0 && options.sourceRunDirectory === void 0) {
29322
+ return options.run();
29323
+ }
29324
+ const { AK_ROLE_AUDITOR_SUBJECT_ENV: AK_ROLE_AUDITOR_SUBJECT_ENV2, AK_ROLE_AUDITOR_SOURCE_RUN_ENV: AK_ROLE_AUDITOR_SOURCE_RUN_ENV2 } = await Promise.resolve().then(() => (init_auditor_soul(), auditor_soul_exports));
29325
+ const priorSubject = process.env[AK_ROLE_AUDITOR_SUBJECT_ENV2];
29326
+ const priorSource = process.env[AK_ROLE_AUDITOR_SOURCE_RUN_ENV2];
29327
+ if (options.subject !== void 0) {
29328
+ process.env[AK_ROLE_AUDITOR_SUBJECT_ENV2] = options.subject;
29329
+ }
29330
+ if (options.sourceRunDirectory !== void 0) {
29331
+ process.env[AK_ROLE_AUDITOR_SOURCE_RUN_ENV2] = options.sourceRunDirectory;
29332
+ }
29333
+ try {
29334
+ return await options.run();
29335
+ } finally {
29336
+ if (options.subject !== void 0) {
29337
+ if (priorSubject === void 0) delete process.env[AK_ROLE_AUDITOR_SUBJECT_ENV2];
29338
+ else process.env[AK_ROLE_AUDITOR_SUBJECT_ENV2] = priorSubject;
29339
+ }
29340
+ if (options.sourceRunDirectory !== void 0) {
29341
+ if (priorSource === void 0) delete process.env[AK_ROLE_AUDITOR_SOURCE_RUN_ENV2];
29342
+ else process.env[AK_ROLE_AUDITOR_SOURCE_RUN_ENV2] = priorSource;
29343
+ }
29344
+ }
29345
+ }
29204
29346
  async function runPublicInstructionSeat(argv, env, io, role, parseArgv2) {
29347
+ let parsed;
29348
+ try {
29349
+ parsed = parseArgv2(argv);
29350
+ } catch (error) {
29351
+ if (error instanceof CliUsageError) {
29352
+ presentStructuralRejection(error, io);
29353
+ return { exitCode: 2 };
29354
+ }
29355
+ throw error;
29356
+ }
29357
+ let auditorSubject;
29358
+ let auditorSourceRun;
29359
+ let auditorSourceTicket;
29360
+ let ticketProbe;
29361
+ const projectRoot = parsed.project ?? env.cwd;
29362
+ if (role === "auditor") {
29363
+ if (parsed.subject !== "judge" && parsed.subject !== "doctor") {
29364
+ presentStructuralRejection(
29365
+ new CliUsageError("auditor --subject requires judge|doctor"),
29366
+ io
29367
+ );
29368
+ return { exitCode: 2 };
29369
+ }
29370
+ auditorSubject = parsed.subject;
29371
+ const source = typeof parsed.sourceRun === "string" ? parsed.sourceRun.trim() : "";
29372
+ if (source === "") {
29373
+ presentStructuralRejection(
29374
+ new CliUsageError("auditor --source-run requires a run locator"),
29375
+ io
29376
+ );
29377
+ return { exitCode: 2 };
29378
+ }
29379
+ try {
29380
+ const { resolveNotarySourceRunLocator: resolveNotarySourceRunLocator2 } = await Promise.resolve().then(() => (init_notary_source_run(), notary_source_run_exports));
29381
+ const resolved = await resolveNotarySourceRunLocator2({
29382
+ projectRoot,
29383
+ sourceRun: source,
29384
+ home: env.home
29385
+ });
29386
+ auditorSourceRun = resolved.runDirectory;
29387
+ auditorSourceTicket = await readRunTicketNumber(resolved.runDirectory);
29388
+ } catch (error) {
29389
+ presentStructuralRejection(
29390
+ new CliUsageError(error instanceof Error ? error.message : String(error)),
29391
+ io
29392
+ );
29393
+ return { exitCode: 2 };
29394
+ }
29395
+ } else {
29396
+ ticketProbe = await probeInstructionTicket(
29397
+ parsed.instruction,
29398
+ projectRoot,
29399
+ env
29400
+ );
29401
+ }
29402
+ const probedTicketNumber = auditorSourceTicket ?? (ticketProbe === void 0 ? void 0 : ticketNumberFromProbe(ticketProbe));
29403
+ if (probedTicketNumber !== void 0) {
29404
+ const summons = {
29405
+ instruction: parsed.instruction,
29406
+ instructionEmpty: parsed.instruction.trim() === "",
29407
+ attachmentPaths: parsed.attachmentPaths
29408
+ };
29409
+ const resumed = await withAuditorSoulEnv({
29410
+ ...auditorSubject === void 0 ? {} : { subject: auditorSubject },
29411
+ ...auditorSourceRun === void 0 ? {} : { sourceRunDirectory: auditorSourceRun },
29412
+ run: () => tryResumeSameTicketSeatRun({
29413
+ home: env.home,
29414
+ projectRoot,
29415
+ role,
29416
+ ticketNumber: probedTicketNumber,
29417
+ freshSummons: env.freshSummons,
29418
+ summons,
29419
+ resume: (runId, materials) => runPublicInstructionSeatResume(
29420
+ { runId, ...materials === void 0 ? {} : { summons: materials } },
29421
+ env,
29422
+ io
29423
+ )
29424
+ })
29425
+ });
29426
+ if (resumed !== void 0) return resumed;
29427
+ }
29205
29428
  let admitted;
29206
29429
  try {
29207
- const parsed = parseArgv2(argv);
29208
- const options = {
29430
+ admitted = await admitInstructionSeat(role, {
29209
29431
  home: env.home,
29210
29432
  principalAuthority: env.principalAuthority,
29211
29433
  cwd: env.cwd,
@@ -29215,8 +29437,7 @@ async function runPublicInstructionSeat(argv, env, io, role, parseArgv2) {
29215
29437
  ...env.createRunId === void 0 ? {} : { createRunId: env.createRunId },
29216
29438
  ...env.model === void 0 ? {} : { model: env.model },
29217
29439
  ...env.correlationId === void 0 ? {} : { correlationId: env.correlationId }
29218
- };
29219
- admitted = role === "gatekeeper" ? await admitGatekeeperInvocation(options) : await admitNavigatorInvocation(options);
29440
+ });
29220
29441
  } catch (error) {
29221
29442
  if (error instanceof CliUsageError) {
29222
29443
  presentStructuralRejection(error, io);
@@ -29224,43 +29445,59 @@ async function runPublicInstructionSeat(argv, env, io, role, parseArgv2) {
29224
29445
  }
29225
29446
  throw error;
29226
29447
  }
29227
- await markRunAdmitted(admitted, env.principalAuthority);
29228
- const turnRequest = buildInstructionSeatTurnRequest(admitted, {
29229
- packageRoot: env.packageRoot,
29230
- home: env.home,
29231
- agentDir: env.agentDir,
29232
- ...env.model === void 0 ? {} : { model: env.model },
29233
- ...env.engine === void 0 ? {} : { engine: env.engine },
29234
- ...env.timeoutMs === void 0 ? {} : { timeoutMs: env.timeoutMs },
29235
- ...env.correlationId === void 0 || env.correlationId.trim() === "" ? {} : { correlationId: env.correlationId },
29236
- continuation: {
29237
- kind: "initial",
29238
- prompt: buildInstructionTransportPrompt(
29448
+ return await withAuditorSoulEnv({
29449
+ ...auditorSubject === void 0 ? {} : { subject: auditorSubject },
29450
+ ...auditorSourceRun === void 0 ? {} : { sourceRunDirectory: auditorSourceRun },
29451
+ run: async () => {
29452
+ await markRunAdmitted(admitted, env.principalAuthority);
29453
+ const turnRequest = buildInstructionSeatTurnRequest(admitted, {
29454
+ packageRoot: env.packageRoot,
29455
+ home: env.home,
29456
+ agentDir: env.agentDir,
29457
+ ...env.model === void 0 ? {} : { model: env.model },
29458
+ ...env.engine === void 0 ? {} : { engine: env.engine },
29459
+ ...env.timeoutMs === void 0 ? {} : { timeoutMs: env.timeoutMs },
29460
+ ...env.correlationId === void 0 || env.correlationId.trim() === "" ? {} : { correlationId: env.correlationId },
29461
+ continuation: {
29462
+ kind: "initial",
29463
+ prompt: buildInstructionTransportPrompt(
29464
+ admitted,
29465
+ engineSessionMaterialFromOptions({
29466
+ ...env.engine === void 0 ? {} : { engine: env.engine },
29467
+ packageRoot: env.packageRoot
29468
+ })
29469
+ )
29470
+ }
29471
+ });
29472
+ return await runPostAdmissionOneShot({
29239
29473
  admitted,
29240
- engineSessionMaterialFromOptions({
29241
- ...env.engine === void 0 ? {} : { engine: env.engine },
29242
- packageRoot: env.packageRoot
29243
- })
29244
- )
29474
+ env,
29475
+ io,
29476
+ request: turnRequest,
29477
+ adapters: instructionSeatAdapters({
29478
+ beforeDispatch: async (admittedSeat) => {
29479
+ if (auditorSourceTicket !== void 0) {
29480
+ await bindAdmittedTicketNumber(admittedSeat, auditorSourceTicket);
29481
+ } else if (ticketProbe !== void 0) {
29482
+ await applyInstructionTicketProbe(admittedSeat, ticketProbe);
29483
+ }
29484
+ }
29485
+ }),
29486
+ ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
29487
+ });
29245
29488
  }
29246
29489
  });
29247
- return await runPostAdmissionOneShot({
29248
- admitted,
29249
- env,
29250
- io,
29251
- request: turnRequest,
29252
- adapters: instructionSeatAdapters(),
29253
- ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
29254
- });
29255
29490
  }
29256
29491
  var init_instruction_seat_run = __esm({
29257
29492
  "src/public-cli/instruction-seat-run.ts"() {
29258
29493
  "use strict";
29259
29494
  init_engine_material();
29495
+ init_run_ticket_number();
29260
29496
  init_cli_errors();
29261
29497
  init_invocation();
29262
29498
  init_post_admission();
29263
29499
  init_run_lifecycle();
29500
+ init_seat_ticket_binding();
29264
29501
  init_settlement();
29265
29502
  init_turn_request();
29266
29503
  }
@@ -29479,7 +29716,6 @@ async function runPublicCountersign(argv, env, io, parseCountersignArgv2) {
29479
29716
  turnRequest,
29480
29717
  buildCountersignTurnRequest(admitted2, turnProjection)
29481
29718
  );
29482
- await runCountersignDiaristStation(admitted2, env);
29483
29719
  }
29484
29720
  }),
29485
29721
  ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
@@ -29518,97 +29754,219 @@ async function runPublicCountersignResume(request, env, io) {
29518
29754
  )
29519
29755
  );
29520
29756
  },
29521
- adapters: countersignAdapters({
29522
- beforeDispatch: async (admitted) => {
29523
- await runCountersignDiaristStation(admitted, env);
29524
- }
29525
- }),
29757
+ adapters: countersignAdapters(),
29526
29758
  ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
29527
29759
  });
29528
29760
  }
29529
- async function runCountersignDiaristStation(admitted, env) {
29761
+ var init_countersign_run = __esm({
29762
+ "src/public-cli/countersign-run.ts"() {
29763
+ "use strict";
29764
+ init_engine_material();
29765
+ init_cli_errors();
29766
+ init_invocation();
29767
+ init_seat_ticket_binding();
29768
+ init_post_admission();
29769
+ init_run_lifecycle();
29770
+ init_settlement();
29771
+ init_turn_request();
29772
+ }
29773
+ });
29774
+
29775
+ // src/public-cli/diarist-run.ts
29776
+ import { existsSync as existsSync10 } from "node:fs";
29777
+ import { writeFile as writeFile8 } from "node:fs/promises";
29778
+ import { join as join27 } from "node:path";
29779
+ function withDiaristCatalogPath(prompt, sourcesPath) {
29780
+ if (sourcesPath === void 0 || sourcesPath.trim() === "") return prompt;
29781
+ return `${prompt}
29782
+
29783
+ \u5DF2\u51BB\u7ED3\u6765\u6E90\u6587\u4EF6\uFF08\u8DEF\u5F84\uFF09\uFF1A
29784
+ - ${sourcesPath}`;
29785
+ }
29786
+ function buildDiaristTurnRequest(admitted, options, sourcesPath) {
29787
+ const continuation = sourcesPath === void 0 ? options.continuation : {
29788
+ ...options.continuation,
29789
+ prompt: withDiaristCatalogPath(options.continuation.prompt, sourcesPath)
29790
+ };
29791
+ return projectRoleTurnRequest(
29792
+ admitted,
29793
+ {
29794
+ activation: {
29795
+ role: "diarist",
29796
+ ...sourcesPath === void 0 ? {} : { sourcesPath }
29797
+ }
29798
+ },
29799
+ { ...options, continuation }
29800
+ );
29801
+ }
29802
+ async function freezeDiaristSourceCatalog(admitted, env) {
29530
29803
  if (admitted.ticketNumber === void 0) return void 0;
29531
- const issueFace = await loadBoundIssueFace(admitted);
29532
- const home = tryHomeFromAkRolesPath(admitted.runDirectory);
29533
- const result2 = await runDiarist({
29804
+ const path = join27(admitted.runDirectory, DIARIST_SOURCE_CATALOG_FILE);
29805
+ if (existsSync10(path)) {
29806
+ const identity = await readRoleRunIdentity(admitted.runDirectory);
29807
+ if (identity !== void 0 && identity.state !== "terminal") return path;
29808
+ }
29809
+ const issueFace = await loadDiaristIssueFace({
29810
+ ticketNumber: admitted.ticketNumber,
29811
+ projectRoot: admitted.projectRoot,
29812
+ home: env.home
29813
+ });
29814
+ const catalog = await prepareDiaristSourceCatalog({
29534
29815
  ticketNumber: admitted.ticketNumber,
29535
29816
  cwd: admitted.projectRoot,
29536
- ...home === void 0 ? {} : { home },
29817
+ home: env.home,
29537
29818
  issueFace,
29538
- sessionCwds: [admitted.projectRoot, env.cwd],
29539
- ...env.packageRoot === void 0 ? {} : { packageRoot: env.packageRoot }
29819
+ sessionCwds: [admitted.projectRoot, env.cwd]
29540
29820
  });
29541
- return result2;
29821
+ await writeFile8(path, serializeDiaristSourceCatalog(catalog), "utf8");
29822
+ return path;
29542
29823
  }
29543
- function persistIssueSourceFailure(admitted, ticketNumber, error) {
29544
- const home = tryHomeFromAkRolesPath(admitted.runDirectory);
29545
- appendIssueSourceFailureDiagnostic({
29546
- ticketNumber,
29547
- cwd: admitted.projectRoot,
29548
- ...home === void 0 ? {} : { home },
29549
- cause: error.message,
29550
- reason: error.reason
29551
- });
29552
- throw error;
29824
+ function diaristAdapters(options) {
29825
+ return {
29826
+ trySettle: (admitted, authority, scope) => trySettleDiaristTerminalResult(admitted, authority, scope),
29827
+ shouldPresentSettled: () => true,
29828
+ ...options?.beforeDispatch === void 0 ? {} : { beforeDispatch: options.beforeDispatch }
29829
+ };
29553
29830
  }
29554
- async function loadBoundIssueFace(admitted) {
29555
- const ticketNumber = admitted.ticketNumber;
29556
- if (ticketNumber === void 0) {
29557
- throw new Error("loadBoundIssueFace requires a bound ticketNumber");
29831
+ async function runPublicDiarist(argv, env, io, parseDiaristArgv2) {
29832
+ let parsed;
29833
+ try {
29834
+ parsed = parseDiaristArgv2(argv);
29835
+ } catch (error) {
29836
+ if (error instanceof CliUsageError) {
29837
+ presentStructuralRejection(error, io);
29838
+ return { exitCode: 2 };
29839
+ }
29840
+ throw error;
29558
29841
  }
29559
- const origin = resolveDiaristGithubOrigin(admitted.projectRoot);
29560
- if (origin === void 0) {
29561
- persistIssueSourceFailure(
29562
- admitted,
29563
- ticketNumber,
29564
- new DiaristIssueSourceError(
29565
- "origin-unresolved",
29566
- `bound ticket #${ticketNumber} issue face requires a resolvable github.com origin remote`
29842
+ const projectRoot = parsed.project ?? env.cwd;
29843
+ const ticketProbe = await probeInstructionTicket(
29844
+ parsed.instruction,
29845
+ projectRoot,
29846
+ env
29847
+ );
29848
+ const probedTicketNumber = ticketNumberFromProbe(ticketProbe);
29849
+ if (probedTicketNumber !== void 0) {
29850
+ const summons = {
29851
+ instruction: parsed.instruction,
29852
+ instructionEmpty: parsed.instruction.trim() === "",
29853
+ attachmentPaths: parsed.attachmentPaths
29854
+ };
29855
+ const resumed = await tryResumeSameTicketSeatRun({
29856
+ home: env.home,
29857
+ projectRoot,
29858
+ role: "diarist",
29859
+ ticketNumber: probedTicketNumber,
29860
+ freshSummons: env.freshSummons,
29861
+ summons,
29862
+ resume: (runId, materials) => runPublicDiaristResume(
29863
+ { runId, ...materials === void 0 ? {} : { summons: materials } },
29864
+ env,
29865
+ io
29567
29866
  )
29568
- );
29867
+ });
29868
+ if (resumed !== void 0) return resumed;
29569
29869
  }
29570
- const fetcher = createDiaristIssueFaceFetcher();
29571
- let face;
29870
+ let admitted;
29572
29871
  try {
29573
- face = await fetcher({
29574
- owner: origin.owner,
29575
- repo: origin.repo,
29576
- ticketNumber
29872
+ admitted = await admitDiaristInvocation({
29873
+ home: env.home,
29874
+ principalAuthority: env.principalAuthority,
29875
+ cwd: env.cwd,
29876
+ instruction: parsed.instruction,
29877
+ attachmentPaths: parsed.attachmentPaths,
29878
+ ...parsed.project === void 0 ? {} : { project: parsed.project },
29879
+ ...env.createRunId === void 0 ? {} : { createRunId: env.createRunId },
29880
+ ...env.model === void 0 ? {} : { model: env.model },
29881
+ ...env.correlationId === void 0 ? {} : { correlationId: env.correlationId }
29577
29882
  });
29578
29883
  } catch (error) {
29579
- const typed = error instanceof DiaristIssueSourceError ? error : new DiaristIssueSourceError(
29580
- "issue-unavailable",
29581
- `issue face fetch failed for ${origin.owner}/${origin.repo}#${ticketNumber}`,
29582
- { cause: error }
29583
- );
29584
- persistIssueSourceFailure(admitted, ticketNumber, typed);
29884
+ if (error instanceof CliUsageError) {
29885
+ presentStructuralRejection(error, io);
29886
+ return { exitCode: 2 };
29887
+ }
29888
+ throw error;
29585
29889
  }
29586
- if (face === void 0) {
29587
- persistIssueSourceFailure(
29588
- admitted,
29589
- ticketNumber,
29590
- new DiaristIssueSourceError(
29591
- "issue-unavailable",
29592
- `issue face unavailable for ${origin.owner}/${origin.repo}#${ticketNumber}`
29890
+ await markRunAdmitted(admitted, env.principalAuthority);
29891
+ const turnProjection = {
29892
+ packageRoot: env.packageRoot,
29893
+ home: env.home,
29894
+ agentDir: env.agentDir,
29895
+ ...env.model === void 0 ? {} : { model: env.model },
29896
+ ...env.engine === void 0 ? {} : { engine: env.engine },
29897
+ ...env.timeoutMs === void 0 ? {} : { timeoutMs: env.timeoutMs },
29898
+ ...env.correlationId === void 0 || env.correlationId.trim() === "" ? {} : { correlationId: env.correlationId },
29899
+ continuation: {
29900
+ kind: "initial",
29901
+ prompt: buildInstructionTransportPrompt(
29902
+ admitted,
29903
+ engineSessionMaterialFromOptions({
29904
+ ...env.engine === void 0 ? {} : { engine: env.engine },
29905
+ packageRoot: env.packageRoot
29906
+ })
29593
29907
  )
29594
- );
29595
- }
29596
- return face;
29908
+ }
29909
+ };
29910
+ const turnRequest = buildDiaristTurnRequest(admitted, turnProjection);
29911
+ return await runPostAdmissionOneShot({
29912
+ admitted,
29913
+ env,
29914
+ io,
29915
+ request: turnRequest,
29916
+ adapters: diaristAdapters({
29917
+ beforeDispatch: async (admittedSeat) => {
29918
+ await applyInstructionTicketProbe(admittedSeat, ticketProbe);
29919
+ const sourcesPath = await freezeDiaristSourceCatalog(admittedSeat, env);
29920
+ Object.assign(
29921
+ turnRequest,
29922
+ buildDiaristTurnRequest(admittedSeat, turnProjection, sourcesPath)
29923
+ );
29924
+ }
29925
+ }),
29926
+ ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
29927
+ });
29597
29928
  }
29598
- var init_countersign_run = __esm({
29599
- "src/public-cli/countersign-run.ts"() {
29929
+ async function runPublicDiaristResume(request, env, io) {
29930
+ return await runPostAdmissionSeatResume({
29931
+ request,
29932
+ env,
29933
+ io,
29934
+ load: (effective) => loadResumableDiaristRun(env.home, effective.runId, env.principalAuthority),
29935
+ buildTurnRequest: async (admitted, effective) => {
29936
+ const summonsPrepared = await prepareSummonsResumeMaterials(
29937
+ admitted.runDirectory,
29938
+ effective.summons
29939
+ );
29940
+ const sourcesPath = await freezeDiaristSourceCatalog(admitted, env);
29941
+ return buildDiaristTurnRequest(
29942
+ admitted,
29943
+ resumeTurnRequestProjectionOptions(
29944
+ admitted,
29945
+ effective,
29946
+ env,
29947
+ summonsPrepared
29948
+ ),
29949
+ sourcesPath
29950
+ );
29951
+ },
29952
+ adapters: diaristAdapters(),
29953
+ ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
29954
+ });
29955
+ }
29956
+ var DIARIST_SOURCE_CATALOG_FILE;
29957
+ var init_diarist_run = __esm({
29958
+ "src/public-cli/diarist-run.ts"() {
29600
29959
  "use strict";
29601
29960
  init_diarist();
29602
- init_ticket_provenance();
29603
29961
  init_engine_material();
29604
29962
  init_cli_errors();
29605
29963
  init_invocation();
29606
29964
  init_seat_ticket_binding();
29607
- init_activation_ledger_topology();
29608
29965
  init_post_admission();
29609
29966
  init_run_lifecycle();
29610
29967
  init_settlement();
29611
29968
  init_turn_request();
29969
+ DIARIST_SOURCE_CATALOG_FILE = "diarist-sources.json";
29612
29970
  }
29613
29971
  });
29614
29972
 
@@ -30426,7 +30784,7 @@ var init_judge_run = __esm({
30426
30784
 
30427
30785
  // src/public-cli/merger-run.ts
30428
30786
  import { mkdir as mkdir5, writeFile as writeFile9 } from "node:fs/promises";
30429
- import { join as join29, resolve as resolve10 } from "node:path";
30787
+ import { join as join28, resolve as resolve10 } from "node:path";
30430
30788
  function mergerMethods(packageRoot2) {
30431
30789
  return [
30432
30790
  {
@@ -30492,8 +30850,8 @@ async function admitMergerShellForActivationFailure(options) {
30492
30850
  expectedConflictPaths: [],
30493
30851
  resolutionScope: []
30494
30852
  };
30495
- const admittedRequestPath = join29(runDirectory, "admitted-request.json");
30496
- const mergerInputPath = join29(runDirectory, "merger-input.json");
30853
+ const admittedRequestPath = join28(runDirectory, "admitted-request.json");
30854
+ const mergerInputPath = join28(runDirectory, "merger-input.json");
30497
30855
  await writeFile9(
30498
30856
  admittedRequestPath,
30499
30857
  `${JSON.stringify(
@@ -30933,10 +31291,10 @@ var init_analyst_book_key = __esm({
30933
31291
  // src/atomic-write.ts
30934
31292
  import { randomUUID as randomUUID6 } from "node:crypto";
30935
31293
  import { rename, rm as rm2, writeFile as writeFile10 } from "node:fs/promises";
30936
- import { dirname as dirname12, join as join30 } from "node:path";
31294
+ import { dirname as dirname12, join as join29 } from "node:path";
30937
31295
  async function writeFileAtomically(destination, contents) {
30938
31296
  const parent = dirname12(destination);
30939
- const temporary = join30(parent, `.atomic-write-${randomUUID6()}.tmp`);
31297
+ const temporary = join29(parent, `.atomic-write-${randomUUID6()}.tmp`);
30940
31298
  try {
30941
31299
  await writeFile10(temporary, contents);
30942
31300
  await rename(temporary, destination);
@@ -30953,7 +31311,7 @@ var init_atomic_write = __esm({
30953
31311
 
30954
31312
  // src/analyst-index.ts
30955
31313
  import { open as open3, readFile as readFile17, unlink as unlink4 } from "node:fs/promises";
30956
- import { dirname as dirname13, join as join31 } from "node:path";
31314
+ import { dirname as dirname13, join as join30 } from "node:path";
30957
31315
  function sleep(ms) {
30958
31316
  return new Promise((resolve12) => {
30959
31317
  setTimeout(resolve12, ms);
@@ -30962,7 +31320,7 @@ function sleep(ms) {
30962
31320
  async function withAnalystLibraryIndexLock(ledgerHome, fn) {
30963
31321
  const indexPath = analystLibraryIndexPath(ledgerHome);
30964
31322
  ensureRealDirectoryTree(ledgerHome, dirname13(indexPath));
30965
- const lockPath = join31(dirname13(indexPath), LIBRARY_INDEX_LOCK_NAME);
31323
+ const lockPath = join30(dirname13(indexPath), LIBRARY_INDEX_LOCK_NAME);
30966
31324
  assertLedgerFileInsideHome(lockPath, ledgerHome);
30967
31325
  const startedAt = Date.now();
30968
31326
  while (true) {
@@ -30989,7 +31347,7 @@ async function withAnalystLibraryIndexLock(ledgerHome, fn) {
30989
31347
  }
30990
31348
  }
30991
31349
  function analystLibraryIndexPath(ledgerHome) {
30992
- return join31(ledgerHome, "analyst", "library-index.json");
31350
+ return join30(ledgerHome, "analyst", "library-index.json");
30993
31351
  }
30994
31352
  function rowFromIssueMetricsPage(page) {
30995
31353
  return {
@@ -31285,22 +31643,22 @@ var init_analyst_cohort = __esm({
31285
31643
 
31286
31644
  // src/analyst-ledger.ts
31287
31645
  import { readdir as readdir7, readFile as readFile18 } from "node:fs/promises";
31288
- import { join as join32 } from "node:path";
31646
+ import { join as join31 } from "node:path";
31289
31647
  function isMissingPathError5(error) {
31290
31648
  return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
31291
31649
  }
31292
31650
  function errorText3(error) {
31293
31651
  return error instanceof Error ? error.message : String(error);
31294
31652
  }
31295
- function isRecord18(value) {
31653
+ function isRecord19(value) {
31296
31654
  return typeof value === "object" && value !== null && !Array.isArray(value);
31297
31655
  }
31298
31656
  async function readExistingRunLifecycleState(runDirectory) {
31299
31657
  try {
31300
31658
  const raw = JSON.parse(
31301
- await readFile18(join32(runDirectory, "run-state.json"), "utf8")
31659
+ await readFile18(join31(runDirectory, "run-state.json"), "utf8")
31302
31660
  );
31303
- if (!isRecord18(raw) || typeof raw.state !== "string") return void 0;
31661
+ if (!isRecord19(raw) || typeof raw.state !== "string") return void 0;
31304
31662
  return raw.state;
31305
31663
  } catch {
31306
31664
  return void 0;
@@ -31330,13 +31688,13 @@ async function listLedgerBookNames(booksRoot) {
31330
31688
  async function readInvocationScopeFields(runDirectory) {
31331
31689
  let raw;
31332
31690
  try {
31333
- raw = await readFile18(join32(runDirectory, "invocation.json"), "utf8");
31691
+ raw = await readFile18(join31(runDirectory, "invocation.json"), "utf8");
31334
31692
  } catch (error) {
31335
31693
  if (isMissingPathError5(error)) return void 0;
31336
31694
  throw error;
31337
31695
  }
31338
31696
  const parsed = JSON.parse(raw);
31339
- if (!isRecord18(parsed)) return void 0;
31697
+ if (!isRecord19(parsed)) return void 0;
31340
31698
  if (typeof parsed.projectRoot !== "string" || parsed.projectRoot.trim() === "") {
31341
31699
  return void 0;
31342
31700
  }
@@ -31362,15 +31720,15 @@ function decideIssueScope(input) {
31362
31720
  }
31363
31721
  async function resolveSessionFile(runDirectory) {
31364
31722
  try {
31365
- const raw = await readFile18(join32(runDirectory, "invocation.json"), "utf8");
31723
+ const raw = await readFile18(join31(runDirectory, "invocation.json"), "utf8");
31366
31724
  const parsed = JSON.parse(raw);
31367
- if (isRecord18(parsed) && typeof parsed.sessionFile === "string" && parsed.sessionFile.trim() !== "") {
31725
+ if (isRecord19(parsed) && typeof parsed.sessionFile === "string" && parsed.sessionFile.trim() !== "") {
31368
31726
  return parsed.sessionFile;
31369
31727
  }
31370
31728
  } catch (error) {
31371
31729
  if (!isMissingPathError5(error)) throw error;
31372
31730
  }
31373
- return join32(runDirectory, "session", "session.jsonl");
31731
+ return join31(runDirectory, "session", "session.jsonl");
31374
31732
  }
31375
31733
  function attributeSessionRowsForRun(input) {
31376
31734
  if (pathContainedIn(input.runDirectory, input.sessionFile)) {
@@ -31542,9 +31900,9 @@ async function classifyScopedRun(input) {
31542
31900
  }
31543
31901
  let gateCycles;
31544
31902
  try {
31545
- const parentSessionFile = join32(input.runDirectory, "session", "session.jsonl");
31903
+ const parentSessionFile = join31(input.runDirectory, "session", "session.jsonl");
31546
31904
  gateCycles = await readAnalystGateCyclesFromAuditorRoles(
31547
- join32(input.runDirectory, "session", "auditor-roles"),
31905
+ join31(input.runDirectory, "session", "auditor-roles"),
31548
31906
  { parentSessionFile }
31549
31907
  );
31550
31908
  } catch (error) {
@@ -31577,7 +31935,7 @@ async function classifyScopedRun(input) {
31577
31935
  async function scanAnalystIssueRuns(input) {
31578
31936
  const ledgerHome = resolveActivationLedgerHome(input.home);
31579
31937
  const scopeTicketNumber = input.ticketNumber;
31580
- const booksRoot = join32(ledgerHome, "books");
31938
+ const booksRoot = join31(ledgerHome, "books");
31581
31939
  let wholeBook = false;
31582
31940
  let scopeRootIdentity;
31583
31941
  let bookNames;
@@ -31609,7 +31967,7 @@ async function scanAnalystIssueRuns(input) {
31609
31967
  const unreadable = [];
31610
31968
  const scopeConflicts = [];
31611
31969
  for (const book of bookNames) {
31612
- const runsDir = join32(booksRoot, book, "runs");
31970
+ const runsDir = join31(booksRoot, book, "runs");
31613
31971
  let runNames;
31614
31972
  try {
31615
31973
  const entries = await readdir7(runsDir, { withFileTypes: true });
@@ -31621,7 +31979,7 @@ async function scanAnalystIssueRuns(input) {
31621
31979
  for (const runName of runNames) {
31622
31980
  const parsed = parseRunDirectoryName2(runName);
31623
31981
  if (parsed === void 0) continue;
31624
- const runDirectory = join32(runsDir, runName);
31982
+ const runDirectory = join31(runsDir, runName);
31625
31983
  let scopeFields;
31626
31984
  try {
31627
31985
  scopeFields = await readInvocationScopeFields(runDirectory);
@@ -31669,7 +32027,7 @@ var init_analyst_ledger = __esm({
31669
32027
  });
31670
32028
 
31671
32029
  // src/analyst-metric-families/acceptance-success-rework.ts
31672
- function isRecord19(value) {
32030
+ function isRecord20(value) {
31673
32031
  return typeof value === "object" && value !== null && !Array.isArray(value);
31674
32032
  }
31675
32033
  function wallMsFromSpan(span) {
@@ -31678,21 +32036,21 @@ function wallMsFromSpan(span) {
31678
32036
  function findCollectorGroups(body) {
31679
32037
  if (Array.isArray(body.groups)) return body.groups;
31680
32038
  const receipt = body.receipt;
31681
- if (isRecord19(receipt) && Array.isArray(receipt.groups)) return receipt.groups;
32039
+ if (isRecord20(receipt) && Array.isArray(receipt.groups)) return receipt.groups;
31682
32040
  const outcome = body.outcome;
31683
- if (isRecord19(outcome)) {
32041
+ if (isRecord20(outcome)) {
31684
32042
  const facts = outcome.decisiveFacts;
31685
- if (isRecord19(facts) && Array.isArray(facts.groups)) return facts.groups;
32043
+ if (isRecord20(facts) && Array.isArray(facts.groups)) return facts.groups;
31686
32044
  }
31687
32045
  return void 0;
31688
32046
  }
31689
32047
  function extractStatus(body) {
31690
32048
  const outcome = body.outcome;
31691
- if (isRecord19(outcome) && typeof outcome.status === "string" && outcome.status.trim() !== "") {
32049
+ if (isRecord20(outcome) && typeof outcome.status === "string" && outcome.status.trim() !== "") {
31692
32050
  return outcome.status;
31693
32051
  }
31694
32052
  const receipt = body.receipt;
31695
- if (isRecord19(receipt) && typeof receipt.status === "string" && receipt.status.trim() !== "") {
32053
+ if (isRecord20(receipt) && typeof receipt.status === "string" && receipt.status.trim() !== "") {
31696
32054
  return receipt.status;
31697
32055
  }
31698
32056
  if (typeof body.status === "string" && body.status.trim() !== "") {
@@ -32049,18 +32407,18 @@ function closedTools(intervals) {
32049
32407
  function clipToolsToFrame(tools, frameStartMs, frameEndMs) {
32050
32408
  if (frameEndMs <= frameStartMs) return [];
32051
32409
  const out = [];
32052
- for (const tool2 of tools) {
32053
- const startMs = Math.max(tool2.startMs, frameStartMs);
32054
- const endMs = Math.min(tool2.endMs, frameEndMs);
32410
+ for (const tool of tools) {
32411
+ const startMs = Math.max(tool.startMs, frameStartMs);
32412
+ const endMs = Math.min(tool.endMs, frameEndMs);
32055
32413
  if (endMs <= startMs) continue;
32056
32414
  out.push({
32057
- toolCallId: tool2.toolCallId,
32058
- toolName: tool2.toolName,
32415
+ toolCallId: tool.toolCallId,
32416
+ toolName: tool.toolName,
32059
32417
  startMs,
32060
32418
  endMs,
32061
- startedAt: startMs === tool2.startMs ? tool2.startedAt : toIso(startMs),
32062
- endedAt: endMs === tool2.endMs ? tool2.endedAt : toIso(endMs),
32063
- ...tool2.command !== void 0 ? { command: tool2.command } : {}
32419
+ startedAt: startMs === tool.startMs ? tool.startedAt : toIso(startMs),
32420
+ endedAt: endMs === tool.endMs ? tool.endedAt : toIso(endMs),
32421
+ ...tool.command !== void 0 ? { command: tool.command } : {}
32064
32422
  });
32065
32423
  }
32066
32424
  return out;
@@ -32099,19 +32457,19 @@ function modelMaximalIntervals(frameStartMs, frameEndMs, toolUnion) {
32099
32457
  }
32100
32458
  return gaps;
32101
32459
  }
32102
- function toolAction(tool2) {
32460
+ function toolAction(tool) {
32103
32461
  const action = {
32104
32462
  kind: "tool",
32105
- toolCallId: tool2.toolCallId,
32106
- toolName: tool2.toolName,
32107
- durationMs: tool2.endMs - tool2.startMs,
32108
- startedAt: tool2.startedAt,
32109
- endedAt: tool2.endedAt
32463
+ toolCallId: tool.toolCallId,
32464
+ toolName: tool.toolName,
32465
+ durationMs: tool.endMs - tool.startMs,
32466
+ startedAt: tool.startedAt,
32467
+ endedAt: tool.endedAt
32110
32468
  };
32111
- if (tool2.toolName === "bash" && tool2.command !== void 0) {
32469
+ if (tool.toolName === "bash" && tool.command !== void 0) {
32112
32470
  return {
32113
32471
  ...action,
32114
- commandSummary: tool2.command
32472
+ commandSummary: tool.command
32115
32473
  };
32116
32474
  }
32117
32475
  return action;
@@ -32317,21 +32675,21 @@ var init_leg_wall_clock = __esm({
32317
32675
  });
32318
32676
 
32319
32677
  // src/analyst-metric-families/round-timeline.ts
32320
- function isRecord20(value) {
32678
+ function isRecord21(value) {
32321
32679
  return typeof value === "object" && value !== null && !Array.isArray(value);
32322
32680
  }
32323
32681
  function wallMsFromSpan2(startedAt, endedAt) {
32324
32682
  return Date.parse(endedAt) - Date.parse(startedAt);
32325
32683
  }
32326
32684
  function readOutcomeStatus(body) {
32327
- if (!isRecord20(body.outcome)) return void 0;
32685
+ if (!isRecord21(body.outcome)) return void 0;
32328
32686
  const status = body.outcome.status;
32329
32687
  if (typeof status !== "string" || status.trim() === "") return void 0;
32330
32688
  return status;
32331
32689
  }
32332
32690
  function readClassCount(body) {
32333
- if (!isRecord20(body.outcome)) return void 0;
32334
- if (!isRecord20(body.outcome.decisiveFacts)) return void 0;
32691
+ if (!isRecord21(body.outcome)) return void 0;
32692
+ if (!isRecord21(body.outcome.decisiveFacts)) return void 0;
32335
32693
  const classCount = body.outcome.decisiveFacts.classCount;
32336
32694
  if (typeof classCount !== "number" || !Number.isFinite(classCount)) {
32337
32695
  return void 0;
@@ -32475,7 +32833,7 @@ var init_analyst_metric_family = __esm({
32475
32833
 
32476
32834
  // src/analyst-page.ts
32477
32835
  import { createHash as createHash7 } from "node:crypto";
32478
- import { dirname as dirname14, join as join33 } from "node:path";
32836
+ import { dirname as dirname14, join as join32 } from "node:path";
32479
32837
  function analystIssuePageKey(address) {
32480
32838
  const parts = ["book", address.bookKey];
32481
32839
  if (address.issueNumber !== void 0) {
@@ -32486,7 +32844,7 @@ function analystIssuePageKey(address) {
32486
32844
  return createHash7("sha256").update(parts.join("\0")).digest("hex").slice(0, 32);
32487
32845
  }
32488
32846
  function analystIssuePagePath(ledgerHome, address) {
32489
- return join33(ledgerHome, "analyst", "issues", `${analystIssuePageKey(address)}.json`);
32847
+ return join32(ledgerHome, "analyst", "issues", `${analystIssuePageKey(address)}.json`);
32490
32848
  }
32491
32849
  function analystIssuePageAddressFromPage(page) {
32492
32850
  return {
@@ -33019,7 +33377,7 @@ __export(cli_exports, {
33019
33377
  runAkRole: () => runAkRole
33020
33378
  });
33021
33379
  import { realpath as realpath6 } from "node:fs/promises";
33022
- import { join as join34 } from "node:path";
33380
+ import { join as join33 } from "node:path";
33023
33381
  function takePublicGlobalFlag(argv, index, options) {
33024
33382
  const tokens = argv.slice(index);
33025
33383
  const taken = options.takeDashed(tokens);
@@ -33151,7 +33509,7 @@ function resolveHome(env) {
33151
33509
  return env.home ?? packageMachineHome();
33152
33510
  }
33153
33511
  function resolveAgentDir(env, home) {
33154
- return env.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? join34(home, ".pi", "agent");
33512
+ return env.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? join33(home, ".pi", "agent");
33155
33513
  }
33156
33514
  function parseThinking(value) {
33157
33515
  return value;
@@ -33773,6 +34131,28 @@ async function runAkRole(argv, env) {
33773
34131
  ...result2.terminal === void 0 ? {} : { terminal: result2.terminal }
33774
34132
  };
33775
34133
  }
34134
+ if (parsed.command === "diarist") {
34135
+ const agentDir = resolveAgentDir(env, home);
34136
+ const cwd = env.cwd ?? process.cwd();
34137
+ const config = await loadAndValidateConfig(home, env.packageRoot);
34138
+ const credentials = env.credentials ?? await loadCredentialProviders(agentDir);
34139
+ const seat = resolveEffectiveSeat(
34140
+ config,
34141
+ "diarist",
34142
+ credentials,
34143
+ invocationFromParsed(parsed)
34144
+ );
34145
+ const result2 = await runPublicDiarist(
34146
+ parsed.args,
34147
+ createRoleEnvironment(env, { role: "diarist", home, agentDir, cwd, credentials, seat, config }),
34148
+ io,
34149
+ PUBLIC_ROLE_ARGV.diarist.parse
34150
+ );
34151
+ return {
34152
+ exitCode: result2.exitCode,
34153
+ ...result2.terminal === void 0 ? {} : { terminal: result2.terminal }
34154
+ };
34155
+ }
33776
34156
  if (parsed.command === "coder") {
33777
34157
  const agentDir = resolveAgentDir(env, home);
33778
34158
  const cwd = env.cwd ?? process.cwd();
@@ -33949,7 +34329,7 @@ async function runAkRole(argv, env) {
33949
34329
  ...result2.terminal === void 0 ? {} : { terminal: result2.terminal }
33950
34330
  };
33951
34331
  }
33952
- if (parsed.command === "gatekeeper" || parsed.command === "navigator") {
34332
+ if (parsed.command === "gatekeeper" || parsed.command === "navigator" || parsed.command === "auditor" || parsed.command === "evidence-child") {
33953
34333
  const agentDir = resolveAgentDir(env, home);
33954
34334
  const cwd = env.cwd ?? process.cwd();
33955
34335
  const config = await loadAndValidateConfig(home, env.packageRoot);
@@ -33965,7 +34345,7 @@ async function runAkRole(argv, env) {
33965
34345
  createRoleEnvironment(env, { role: parsed.command, home, agentDir, cwd, credentials, seat, config }),
33966
34346
  io,
33967
34347
  parsed.command,
33968
- parsed.command === "gatekeeper" ? PUBLIC_ROLE_ARGV.gatekeeper.parse : PUBLIC_ROLE_ARGV.navigator.parse
34348
+ PUBLIC_ROLE_ARGV[parsed.command].parse
33969
34349
  );
33970
34350
  return {
33971
34351
  exitCode: result2.exitCode,
@@ -34021,6 +34401,7 @@ var init_cli = __esm({
34021
34401
  init_instruction_seat_run();
34022
34402
  init_collector_run();
34023
34403
  init_countersign_run();
34404
+ init_diarist_run();
34024
34405
  init_gleaner_left_run();
34025
34406
  init_doctor_run();
34026
34407
  init_fixer_run();
@@ -34048,7 +34429,10 @@ var init_cli = __esm({
34048
34429
  notary: { seat: "notary", run: runPublicNotaryResume },
34049
34430
  inspector: { seat: "inspector", run: runPublicInspectorResume },
34050
34431
  gatekeeper: { seat: "gatekeeper", run: runPublicInstructionSeatResume },
34051
- navigator: { seat: "navigator", run: runPublicInstructionSeatResume }
34432
+ navigator: { seat: "navigator", run: runPublicInstructionSeatResume },
34433
+ auditor: { seat: "auditor", run: runPublicInstructionSeatResume },
34434
+ "evidence-child": { seat: "evidence-child", run: runPublicInstructionSeatResume },
34435
+ diarist: { seat: "diarist", run: runPublicDiaristResume }
34052
34436
  };
34053
34437
  PUBLIC_ROLE_ARGV = {
34054
34438
  judge: { parse: parseJudgeArgv, options: optionsForOwner("judge") },
@@ -34064,6 +34448,9 @@ var init_cli = __esm({
34064
34448
  reviewer: { parse: parseReviewerArgv, options: optionsForOwner("reviewer") },
34065
34449
  gatekeeper: { parse: parseGatekeeperArgv, options: optionsForOwner("gatekeeper") },
34066
34450
  navigator: { parse: parseNavigatorArgv, options: optionsForOwner("navigator") },
34451
+ auditor: { parse: parseAuditorArgv, options: optionsForOwner("auditor") },
34452
+ "evidence-child": { parse: parseEvidenceChildArgv, options: optionsForOwner("evidence-child") },
34453
+ diarist: { parse: parseDiaristArgv, options: optionsForOwner("diarist") },
34067
34454
  /** Deterministic analysis seat (#336) — argv parse only; no LLM admission. */
34068
34455
  analyst: { parse: parseAnalystArgv, options: optionsForOwner("analyst") }
34069
34456
  };
@@ -34080,8 +34467,8 @@ var init_cli = __esm({
34080
34467
 
34081
34468
  // src/public-cli/main.ts
34082
34469
  import { existsSync as existsSync11 } from "node:fs";
34083
- import { dirname as dirname15, join as join35 } from "node:path";
34084
- import { fileURLToPath as fileURLToPath4 } from "node:url";
34470
+ import { dirname as dirname15, join as join34 } from "node:path";
34471
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
34085
34472
 
34086
34473
  // src/public-cli/host-pi-runtime.ts
34087
34474
  import { existsSync, lstatSync, mkdirSync, realpathSync, rmSync, symlinkSync } from "node:fs";
@@ -34167,10 +34554,10 @@ function linkPackage(packageRoot2, name, targetDir) {
34167
34554
  }
34168
34555
 
34169
34556
  // src/public-cli/main.ts
34170
- var here = dirname15(fileURLToPath4(import.meta.url));
34557
+ var here = dirname15(fileURLToPath3(import.meta.url));
34171
34558
  function resolvePackageRoot(binDir) {
34172
- const canonical = join35(binDir, "..", "..");
34173
- if (existsSync11(join35(canonical, "package.json"))) {
34559
+ const canonical = join34(binDir, "..", "..");
34560
+ if (existsSync11(join34(canonical, "package.json"))) {
34174
34561
  return canonical;
34175
34562
  }
34176
34563
  return binDir;