@akagilnc/pi-workflow-roles 0.1.5015 → 0.1.5063

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 (95) hide show
  1. package/README.md +2 -2
  2. package/README.zh-CN.md +2 -2
  3. package/THIRD_PARTY_NOTICES.md +8 -8
  4. package/dist/acp-host/production-host.js +525 -978
  5. package/dist/headless-host/description.js +0 -2
  6. package/dist/headless-host/production-host.js +528 -1014
  7. package/dist/host-descriptions.js +2 -3
  8. package/dist/migrate-book-topology.js +7 -12
  9. package/dist/packaged-role-registry.js +20 -18
  10. package/dist/pi/role-turn-host.js +3 -27
  11. package/dist/public-cli/cli.js +23 -2
  12. package/dist/public-cli/countersign-run.js +13 -8
  13. package/dist/public-cli/instruction-seat-run.js +75 -107
  14. package/dist/public-cli/invocation.js +13 -32
  15. package/dist/public-cli/machine-method-skills.js +150 -0
  16. package/dist/public-cli/main.js +549 -679
  17. package/dist/public-cli/post-admission.js +10 -5
  18. package/dist/public-cli/registry.js +2 -1
  19. package/dist/public-cli/run-lifecycle.js +12 -15
  20. package/dist/public-cli/seat-ticket-binding.js +5 -8
  21. package/dist/public-cli/settlement.js +12 -99
  22. package/dist/public-cli/turn-request.js +16 -8
  23. package/dist/public-role-summons.js +8 -3
  24. package/package.json +5 -1
  25. package/resources/countersign-ticket-issue.md +5 -0
  26. package/resources/diarist-collect.md +1 -0
  27. package/resources/secretariat-ticket-identity.md +15 -0
  28. package/scripts/build-package.mjs +1 -6
  29. package/src/headless-host/description.ts +0 -3
  30. package/src/headless-host/role-turn-host.ts +2 -23
  31. package/src/host-contracts.ts +2 -23
  32. package/src/host-descriptions.ts +2 -3
  33. package/src/packaged-role-registry.ts +17 -16
  34. package/src/pi/adapter.ts +0 -27
  35. package/src/pi/role-turn-host.ts +3 -31
  36. package/src/public-cli/cli.ts +24 -2
  37. package/src/public-cli/countersign-run.ts +17 -10
  38. package/src/public-cli/instruction-seat-run.ts +75 -105
  39. package/src/public-cli/invocation.ts +10 -38
  40. package/src/public-cli/machine-method-skills.ts +153 -0
  41. package/src/public-cli/post-admission.ts +12 -6
  42. package/src/public-cli/registry.ts +1 -0
  43. package/src/public-cli/run-lifecycle.ts +12 -13
  44. package/src/public-cli/seat-ticket-binding.ts +5 -8
  45. package/src/public-cli/settlement.ts +6 -138
  46. package/src/public-cli/turn-request.ts +24 -16
  47. package/src/public-role-summons.ts +16 -3
  48. package/src/reviewer-role.ts +1 -12
  49. package/src/role-envelope.ts +0 -13
  50. package/src/role-runtime-dependencies.ts +0 -13
  51. package/src/role-runtime.ts +4 -56
  52. package/src/worker-role.ts +1 -81
  53. package/dist/method-host-plugin/.claude-plugin/plugin.json +0 -5
  54. package/dist/method-host-plugin/skills/ak-cross-m-review/CONTEXT.md +0 -48
  55. package/dist/method-host-plugin/skills/ak-cross-m-review/LICENSE +0 -21
  56. package/dist/method-host-plugin/skills/ak-cross-m-review/SKILL.md +0 -170
  57. package/dist/method-host-plugin/skills/ak-cross-m-review/prompts/cmr-completeness.md +0 -118
  58. package/dist/method-host-plugin/skills/ak-cross-m-review/prompts/cmr-reviewer.md +0 -128
  59. package/dist/method-host-plugin/skills/ak-cross-m-review/provenance.json +0 -41
  60. package/dist/method-host-plugin/skills/diagnosing-bugs/SKILL.md +0 -134
  61. package/dist/method-host-plugin/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  62. package/dist/method-host-plugin/skills/diagnosing-bugs/provenance.json +0 -31
  63. package/dist/method-host-plugin/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -41
  64. package/dist/method-host-plugin/skills/resolving-merge-conflicts/SKILL.md +0 -14
  65. package/dist/method-host-plugin/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  66. package/dist/method-host-plugin/skills/resolving-merge-conflicts/provenance.json +0 -26
  67. package/dist/method-host-plugin/skills/tdd/SKILL.md +0 -38
  68. package/dist/method-host-plugin/skills/tdd/agents/openai.yaml +0 -3
  69. package/dist/method-host-plugin/skills/tdd/mocking.md +0 -59
  70. package/dist/method-host-plugin/skills/tdd/provenance.json +0 -36
  71. package/dist/method-host-plugin/skills/tdd/tests.md +0 -77
  72. package/dist/package-resources/method-skill.js +0 -259
  73. package/resources/method-host-plugin/.claude-plugin/plugin.json +0 -5
  74. package/resources/methods/ak-cross-m-review/CONTEXT.md +0 -48
  75. package/resources/methods/ak-cross-m-review/LICENSE +0 -21
  76. package/resources/methods/ak-cross-m-review/SKILL.md +0 -170
  77. package/resources/methods/ak-cross-m-review/prompts/cmr-completeness.md +0 -118
  78. package/resources/methods/ak-cross-m-review/prompts/cmr-reviewer.md +0 -128
  79. package/resources/methods/ak-cross-m-review/provenance.json +0 -41
  80. package/resources/methods/diagnosing-bugs/SKILL.md +0 -134
  81. package/resources/methods/diagnosing-bugs/agents/openai.yaml +0 -3
  82. package/resources/methods/diagnosing-bugs/provenance.json +0 -31
  83. package/resources/methods/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -41
  84. package/resources/methods/resolving-merge-conflicts/SKILL.md +0 -14
  85. package/resources/methods/resolving-merge-conflicts/agents/openai.yaml +0 -3
  86. package/resources/methods/resolving-merge-conflicts/provenance.json +0 -26
  87. package/resources/methods/tdd/SKILL.md +0 -38
  88. package/resources/methods/tdd/agents/openai.yaml +0 -3
  89. package/resources/methods/tdd/mocking.md +0 -59
  90. package/resources/methods/tdd/provenance.json +0 -36
  91. package/resources/methods/tdd/tests.md +0 -77
  92. package/src/canonical-skill-binding.ts +0 -118
  93. package/src/host-native-method.ts +0 -185
  94. package/src/package-resources/method-skill-binding.ts +0 -60
  95. package/src/package-resources/method-skill.ts +0 -363
@@ -15308,7 +15308,7 @@ __export(packaged_role_registry_exports, {
15308
15308
  packagedEmitsAuthorityRefs: () => packagedEmitsAuthorityRefs,
15309
15309
  packagedGateStageLabel: () => packagedGateStageLabel,
15310
15310
  packagedGateSummon: () => packagedGateSummon,
15311
- packagedMethodLoadFailureCause: () => packagedMethodLoadFailureCause,
15311
+ packagedMethodSkillNames: () => packagedMethodSkillNames,
15312
15312
  packagedModelParent: () => packagedModelParent,
15313
15313
  packagedNavigatorSubject: () => packagedNavigatorSubject,
15314
15314
  packagedProjectsTargetBindRejection: () => packagedProjectsTargetBindRejection,
@@ -15330,6 +15330,18 @@ __export(packaged_role_registry_exports, {
15330
15330
  function packagedRoleMetadata(role) {
15331
15331
  return PACKAGED_ROLE_REGISTRY.find((entry) => entry.role === role);
15332
15332
  }
15333
+ function packagedMethodSkillNames() {
15334
+ const names = [];
15335
+ for (const record4 of PACKAGED_ROLE_REGISTRY) {
15336
+ if ("methodSkills" in record4 && record4.methodSkills !== void 0) {
15337
+ for (const name of record4.methodSkills) if (!names.includes(name)) names.push(name);
15338
+ }
15339
+ if ("applyMethod" in record4 && record4.applyMethod !== void 0 && !names.includes(record4.applyMethod)) {
15340
+ names.push(record4.applyMethod);
15341
+ }
15342
+ }
15343
+ return names;
15344
+ }
15333
15345
  function isOfficerReviewSeat(role) {
15334
15346
  const record4 = packagedRoleMetadata(role);
15335
15347
  return record4 !== void 0 && "reviewOfficer" in record4 && record4.reviewOfficer === true;
@@ -15364,11 +15376,6 @@ function packagedRolePhaseFlag(role) {
15364
15376
  function packagedRoleOutputTool(role) {
15365
15377
  return packagedRoleMetadata(role)?.outputTool;
15366
15378
  }
15367
- function packagedMethodLoadFailureCause(role) {
15368
- const record4 = packagedRoleMetadata(role);
15369
- if (record4 === void 0 || !("methodLoadFailureCause" in record4)) return void 0;
15370
- return record4.methodLoadFailureCause;
15371
- }
15372
15379
  function packagedBindsBoardTicket(role) {
15373
15380
  const record4 = packagedRoleMetadata(role);
15374
15381
  return record4?.sameParent === "board-ticket";
@@ -15571,8 +15578,7 @@ var init_packaged_role_registry = __esm({
15571
15578
  { key: "packetPath" },
15572
15579
  { key: "prerequisitesPath", omitUndefined: true },
15573
15580
  { key: "prerequisites" }
15574
- ],
15575
- method: "observed"
15581
+ ]
15576
15582
  },
15577
15583
  boardPlacement: "marshal",
15578
15584
  activationFlags: [
@@ -15598,7 +15604,6 @@ var init_packaged_role_registry = __esm({
15598
15604
  worker: true,
15599
15605
  applyMethod: "tdd",
15600
15606
  /** Method-material load failure keeps the activation cause (not reviewer/fixer). */
15601
- methodLoadFailureCause: "activation",
15602
15607
  boardPlacement: "coder",
15603
15608
  phases: ["plan", "apply"],
15604
15609
  outputTool: CODER_OUTPUT_TOOL_NAME,
@@ -15609,8 +15614,7 @@ var init_packaged_role_registry = __esm({
15609
15614
  leaves: [
15610
15615
  { key: "phase" },
15611
15616
  { key: "taskPath" }
15612
- ],
15613
- method: "optional"
15617
+ ]
15614
15618
  },
15615
15619
  activationFlags: [
15616
15620
  { field: "taskPath", flag: "ak-coder-task", binds: "input" },
@@ -15651,8 +15655,7 @@ var init_packaged_role_registry = __esm({
15651
15655
  { key: "lens" },
15652
15656
  { key: "authorityRefs", copyArray: true },
15653
15657
  { key: "callerProvenance", callerProvenance: true }
15654
- ],
15655
- method: "observed"
15658
+ ]
15656
15659
  },
15657
15660
  /** Frozen base/lens/authority become the initial prompt; instruction follows. */
15658
15661
  transportPrompt: "skill-args",
@@ -15751,7 +15754,6 @@ var init_packaged_role_registry = __esm({
15751
15754
  methodSkills: ["resolving-merge-conflicts"],
15752
15755
  settleMethod: "resolving-merge-conflicts",
15753
15756
  /** Method-material load failure keeps the activation cause (not reviewer/fixer). */
15754
- methodLoadFailureCause: "activation",
15755
15757
  phases: [null],
15756
15758
  outputTool: MERGER_OUTPUT_TOOL_NAME,
15757
15759
  settlement: "residual",
@@ -15763,8 +15765,7 @@ var init_packaged_role_registry = __esm({
15763
15765
  leaves: [
15764
15766
  { key: "mergerInputPath" },
15765
15767
  { key: "derived" }
15766
- ],
15767
- method: "observed"
15768
+ ]
15768
15769
  },
15769
15770
  activationFlags: [
15770
15771
  { field: "inputPath", from: "mergerInputPath", flag: "ak-merger-input", binds: "input" }
@@ -15831,7 +15832,7 @@ var init_packaged_role_registry = __esm({
15831
15832
  activationStage: "load-and-install",
15832
15833
  receiptStatusKey: "status",
15833
15834
  // #924: 公用《票面法》三席同装
15834
- sessionMaterials: ["CLAUDE.md", "souls/countersign.md", "souls/ticket-law.md"]
15835
+ sessionMaterials: ["CLAUDE.md", "souls/countersign.md", "souls/ticket-law.md", "resources/countersign-ticket-issue.md"]
15835
15836
  },
15836
15837
  {
15837
15838
  role: "secretariat",
@@ -15839,7 +15840,7 @@ var init_packaged_role_registry = __esm({
15839
15840
  presentSettled: "always",
15840
15841
  summonResume: false,
15841
15842
  admission: "instruction",
15842
- sameParent: "court-diarist",
15843
+ sameParent: "none",
15843
15844
  phases: [null],
15844
15845
  outputTool: SECRETARIAT_OUTPUT_TOOL_NAME,
15845
15846
  settlement: "accepted",
@@ -15855,6 +15856,7 @@ var init_packaged_role_registry = __esm({
15855
15856
  "CLAUDE.md",
15856
15857
  "souls/secretariat.md",
15857
15858
  "souls/ticket-law.md",
15859
+ "resources/secretariat-ticket-identity.md",
15858
15860
  "souls/countersign.md",
15859
15861
  "souls/notary.md"
15860
15862
  ]
@@ -16057,7 +16059,8 @@ var init_registry2 = __esm({
16057
16059
  "config",
16058
16060
  "help",
16059
16061
  "resume",
16060
- "new"
16062
+ "new",
16063
+ "setup"
16061
16064
  ];
16062
16065
  PUBLIC_DETERMINISTIC_COMMANDS = ["analyst"];
16063
16066
  }
@@ -16911,6 +16914,150 @@ var init_cli_errors = __esm({
16911
16914
  }
16912
16915
  });
16913
16916
 
16917
+ // src/public-cli/machine-method-skills.ts
16918
+ import { accessSync, constants, statSync as statSync2 } from "node:fs";
16919
+ import { lstat as lstat2, mkdir as mkdir2, symlink } from "node:fs/promises";
16920
+ import { join as join9 } from "node:path";
16921
+ import { spawnSync } from "node:child_process";
16922
+ function skillRoot(home) {
16923
+ return join9(home, ".agents/skills");
16924
+ }
16925
+ function installedMethodSkillPath(home, name) {
16926
+ return installedSkillPath(skillRoot(home), name);
16927
+ }
16928
+ function installedSkillPath(root, name) {
16929
+ const path = join9(root, name, "SKILL.md");
16930
+ try {
16931
+ if (!statSync2(path).isFile()) return void 0;
16932
+ accessSync(path, constants.R_OK);
16933
+ return path;
16934
+ } catch (error) {
16935
+ const code = error.code;
16936
+ if (code === "ENOENT" || code === "ENOTDIR" || code === "EACCES" || code === "EPERM" || code === "ELOOP") return void 0;
16937
+ throw error;
16938
+ }
16939
+ }
16940
+ function linkedSkillRoot(home, host) {
16941
+ if (host === "claude" || host === "claude-code") {
16942
+ return join9(process.env.CLAUDE_CONFIG_DIR?.trim() || join9(home, ".claude"), "skills");
16943
+ }
16944
+ if (host === "hermes") return join9(home, ".hermes/skills");
16945
+ return void 0;
16946
+ }
16947
+ async function occupied(path) {
16948
+ try {
16949
+ await lstat2(path);
16950
+ return true;
16951
+ } catch (error) {
16952
+ if (error.code !== "ENOENT") throw error;
16953
+ return false;
16954
+ }
16955
+ }
16956
+ function warnOccupied(path, stdout) {
16957
+ stdout(`Warning: ${path} is already occupied; left untouched.
16958
+ `);
16959
+ }
16960
+ async function warnMissingMethodSkills(home, host, role, skills, stdout) {
16961
+ const missing = [];
16962
+ const linkedRoot = linkedSkillRoot(home, host);
16963
+ for (const skill of skills) {
16964
+ if (installedMethodSkillPath(home, skill) === void 0 || linkedRoot !== void 0 && installedSkillPath(linkedRoot, skill) === void 0) missing.push(skill);
16965
+ }
16966
+ for (const skill of missing) {
16967
+ stdout(`Warning: required machine Skill "${skill}" is missing for ${role}; its method guidance may be unavailable and reduce work quality. Run \`ak-role setup\` to install required Skills.
16968
+ `);
16969
+ }
16970
+ }
16971
+ function runSkillsCli(args, home) {
16972
+ const result = spawnSync("npx", ["--yes", "skills", ...args], {
16973
+ stdio: "inherit",
16974
+ env: { ...process.env, HOME: home }
16975
+ });
16976
+ if (result.error !== void 0) throw result.error;
16977
+ return result.status === 0;
16978
+ }
16979
+ function addSkills(source, skills, home) {
16980
+ if (skills.length === 0) return true;
16981
+ return runSkillsCli([
16982
+ "add",
16983
+ source,
16984
+ ...skills.flatMap((skill) => ["--skill", skill]),
16985
+ "--agent",
16986
+ "codex",
16987
+ "--global",
16988
+ "--yes"
16989
+ ], home);
16990
+ }
16991
+ function updateRequiredSkills(home) {
16992
+ const names = packagedMethodSkillNames();
16993
+ if (names.length === 0) return true;
16994
+ return runSkillsCli(["update", "-g", "-y", ...names], home);
16995
+ }
16996
+ async function runMachineSkillSetup(home, stdout) {
16997
+ const canonical = skillRoot(home);
16998
+ const missingBySource = /* @__PURE__ */ new Map();
16999
+ let unsourced = false;
17000
+ for (const name of packagedMethodSkillNames()) {
17001
+ const path = join9(canonical, name);
17002
+ if (await occupied(path)) {
17003
+ warnOccupied(path, stdout);
17004
+ continue;
17005
+ }
17006
+ const source = SKILL_SOURCE[name];
17007
+ if (source === void 0) {
17008
+ unsourced = true;
17009
+ stdout(`Warning: required machine Skill "${name}" has no install source; setup did not install it.
17010
+ `);
17011
+ continue;
17012
+ }
17013
+ const missing = missingBySource.get(source) ?? [];
17014
+ missing.push(name);
17015
+ missingBySource.set(source, missing);
17016
+ }
17017
+ for (const [source, missing] of missingBySource) {
17018
+ if (!addSkills(source, missing, home)) return 1;
17019
+ }
17020
+ if (unsourced) return 1;
17021
+ for (const host of ["claude-code", "hermes"]) {
17022
+ const root = linkedSkillRoot(home, host);
17023
+ const binaryFromHome = host === "claude-code" ? HEADLESS_HOST_DESCRIPTIONS.claude.binaryFromHome : HOST_DESCRIPTIONS.hermes.binaryFromHome;
17024
+ try {
17025
+ accessSync(join9(home, ...binaryFromHome), constants.X_OK);
17026
+ } catch (error) {
17027
+ if (["ENOENT", "ENOTDIR", "EACCES"].includes(error.code ?? "")) continue;
17028
+ throw error;
17029
+ }
17030
+ for (const name of packagedMethodSkillNames()) {
17031
+ const target = join9(canonical, name);
17032
+ if (installedMethodSkillPath(home, name) === void 0) continue;
17033
+ const link = join9(root, name);
17034
+ if (await occupied(link)) {
17035
+ warnOccupied(link, stdout);
17036
+ continue;
17037
+ }
17038
+ await mkdir2(root, { recursive: true });
17039
+ await symlink(target, link, "dir");
17040
+ }
17041
+ }
17042
+ if (!updateRequiredSkills(home)) return 1;
17043
+ stdout("Machine method Skills setup finished. Existing same-name Skills were left untouched.\n");
17044
+ return 0;
17045
+ }
17046
+ var SKILL_SOURCE;
17047
+ var init_machine_method_skills = __esm({
17048
+ "src/public-cli/machine-method-skills.ts"() {
17049
+ "use strict";
17050
+ init_host_descriptions();
17051
+ init_packaged_role_registry();
17052
+ SKILL_SOURCE = {
17053
+ tdd: "mattpocock/skills",
17054
+ "diagnosing-bugs": "mattpocock/skills",
17055
+ "resolving-merge-conflicts": "mattpocock/skills",
17056
+ "ak-cross-m-review": "Akagilnc/ak-cross-m-review"
17057
+ };
17058
+ }
17059
+ });
17060
+
16914
17061
  // src/host-contracts.ts
16915
17062
  var ExplicitInternalActivationError;
16916
17063
  var init_host_contracts = __esm({
@@ -17031,7 +17178,7 @@ import {
17031
17178
  unlinkSync,
17032
17179
  writeFileSync
17033
17180
  } from "node:fs";
17034
- import { dirname as dirname5, join as join9 } from "node:path";
17181
+ import { dirname as dirname5, join as join10 } from "node:path";
17035
17182
  function isRecord2(value) {
17036
17183
  return typeof value === "object" && value !== null && !Array.isArray(value);
17037
17184
  }
@@ -17189,8 +17336,8 @@ function resolveSitianVolumeCategory(kind) {
17189
17336
  return kind;
17190
17337
  }
17191
17338
  function ticketProvenanceUnderBookPaths(ledgerHome, bookKey, ticketId) {
17192
- const sessionDir = join9(activationBookDirectory(ledgerHome, bookKey), ticketId);
17193
- return { sessionDir, recordFile: join9(sessionDir, SITIAN_RECORDS_LEAF) };
17339
+ const sessionDir = join10(activationBookDirectory(ledgerHome, bookKey), ticketId);
17340
+ return { sessionDir, recordFile: join10(sessionDir, SITIAN_RECORDS_LEAF) };
17194
17341
  }
17195
17342
  function resolveSitianRecordPathInLedger(input, ledgerHome) {
17196
17343
  const category = resolveSitianVolumeCategory(input.kind);
@@ -17207,13 +17354,13 @@ function resolveSitianRecordPathInLedger(input, ledgerHome) {
17207
17354
  recordFile = paths.recordFile;
17208
17355
  } else if (category === "ticket-provenance" && input.runDirectory !== void 0) {
17209
17356
  sessionDir = input.runDirectory;
17210
- recordFile = join9(sessionDir, SITIAN_RECORDS_LEAF);
17357
+ recordFile = join10(sessionDir, SITIAN_RECORDS_LEAF);
17211
17358
  } else {
17212
17359
  if (input.sessionParent === void 0 || input.sessionParent.length === 0 || !physicallyContainedIn(ledgerHome, input.sessionParent)) {
17213
17360
  throw new Error("Sitian record ownership requires a parent session inside the ledger home");
17214
17361
  }
17215
- sessionDir = join9(dirname5(input.sessionParent), category);
17216
- recordFile = join9(sessionDir, SITIAN_RECORDS_LEAF);
17362
+ sessionDir = join10(dirname5(input.sessionParent), category);
17363
+ recordFile = join10(sessionDir, SITIAN_RECORDS_LEAF);
17217
17364
  }
17218
17365
  if (!physicallyContainedIn(ledgerHome, sessionDir)) {
17219
17366
  throw new Error("Sitian record ownership requires a directory inside the ledger home");
@@ -17222,7 +17369,7 @@ function resolveSitianRecordPathInLedger(input, ledgerHome) {
17222
17369
  }
17223
17370
  function projectTicketRecordsPathShape() {
17224
17371
  const { recordFile } = ticketProvenanceUnderBookPaths(
17225
- join9("~", ".ak-roles"),
17372
+ join10("~", ".ak-roles"),
17226
17373
  "<\u7C3F>",
17227
17374
  "<\u7968\u53F7>"
17228
17375
  );
@@ -17348,7 +17495,6 @@ var role_turn_host_exports = {};
17348
17495
  __export(role_turn_host_exports, {
17349
17496
  EXPLICIT_INTERNAL_LOAD_PROBE_ARGS: () => EXPLICIT_INTERNAL_LOAD_PROBE_ARGS,
17350
17497
  appendPiSessionCustomEntry: () => appendPiSessionCustomEntry,
17351
- applyPiNativeSkillInvocation: () => applyPiNativeSkillInvocation,
17352
17498
  buildExplicitInternalActivationArgs: () => buildExplicitInternalActivationArgs,
17353
17499
  buildPiTurnExtraArgs: () => buildPiTurnExtraArgs,
17354
17500
  createDefaultPiSpawnRunner: () => createDefaultPiSpawnRunner,
@@ -17356,14 +17502,14 @@ __export(role_turn_host_exports, {
17356
17502
  resolveInternalRoleEntrypoint: () => resolveInternalRoleEntrypoint
17357
17503
  });
17358
17504
  import { execFile, spawn as spawn2 } from "node:child_process";
17359
- import { constants } from "node:fs";
17505
+ import { constants as constants2 } from "node:fs";
17360
17506
  import { access, appendFile, readFile as readFile5, realpath } from "node:fs/promises";
17361
- import { basename as basename3, delimiter as delimiter2, dirname as dirname6, isAbsolute as isAbsolute3, join as join10, resolve as resolve3 } from "node:path";
17507
+ import { delimiter as delimiter2, dirname as dirname6, isAbsolute as isAbsolute3, join as join11, resolve as resolve3 } from "node:path";
17362
17508
  import { platform } from "node:process";
17363
17509
  import { promisify } from "node:util";
17364
17510
  import { randomUUID as randomUUID2 } from "node:crypto";
17365
17511
  function resolveInternalRoleEntrypoint(packageRoot2) {
17366
- return join10(packageRoot2, INTERNAL_ROLE_ENTRYPOINT_RELATIVE2);
17512
+ return join11(packageRoot2, INTERNAL_ROLE_ENTRYPOINT_RELATIVE2);
17367
17513
  }
17368
17514
  function buildExplicitInternalActivationArgs(selectedRoleEntry, extraArgs = []) {
17369
17515
  return ["--no-extensions", "-e", selectedRoleEntry, ...extraArgs];
@@ -17391,24 +17537,11 @@ function buildMethodArgs(methods) {
17391
17537
  const skillArgs = [];
17392
17538
  for (const method of methods) {
17393
17539
  if (method.kind === "skill") {
17394
- skillArgs.push("--skill", method.path);
17540
+ skillArgs.push("--skill", dirname6(method.path));
17395
17541
  }
17396
17542
  }
17397
17543
  return skillArgs;
17398
17544
  }
17399
- function applyPiNativeSkillInvocation(methods, prompt) {
17400
- const skills = methods.filter((method) => method.kind === "skill");
17401
- if (skills.length !== 1) return prompt;
17402
- const name = basename3(dirname6(skills[0].path));
17403
- if (name.length === 0) return prompt;
17404
- const token = `/skill:${name}`;
17405
- const trimmed = prompt.trimStart();
17406
- if (trimmed === token || trimmed.startsWith(`${token} `) || trimmed.startsWith(`${token}
17407
- `)) {
17408
- return prompt;
17409
- }
17410
- return prompt.length === 0 ? token : `${token} ${prompt}`;
17411
- }
17412
17545
  function buildPiTurnExtraArgs(request, authority, extraPiArgs = []) {
17413
17546
  const { sessionFile, sessionDirectory } = authority.decode(request.principal);
17414
17547
  return [
@@ -17440,14 +17573,14 @@ function piUserDialogueBody(request) {
17440
17573
  const _exhaustive = request.continuation;
17441
17574
  return _exhaustive;
17442
17575
  })();
17443
- return request.continuation.kind === "resume" ? rawPrompt : applyPiNativeSkillInvocation(request.methods, rawPrompt);
17576
+ return rawPrompt;
17444
17577
  }
17445
17578
  async function resolveSelectedPi(command, cwd, env) {
17446
17579
  const searchPath = env.PATH ?? (platform === "win32" ? process.env.PATH ?? "" : "/usr/bin:/bin");
17447
17580
  const candidates = isAbsolute3(command) || command.includes("/") ? [resolve3(cwd, command)] : searchPath.split(delimiter2).map((dir) => resolve3(cwd, dir, command));
17448
17581
  for (const candidate of candidates) {
17449
17582
  try {
17450
- await access(candidate, constants.X_OK);
17583
+ await access(candidate, constants2.X_OK);
17451
17584
  } catch (error) {
17452
17585
  const code = error.code;
17453
17586
  if (code === "ENOENT" || code === "ENOTDIR" || code === "EACCES") continue;
@@ -17705,7 +17838,7 @@ __export(run_terminal_artifacts_exports, {
17705
17838
  runIdFromRunDirectory: () => runIdFromRunDirectory
17706
17839
  });
17707
17840
  import { readdir as readdir2, readFile as readFile6 } from "node:fs/promises";
17708
- import { basename as basename4, dirname as dirname7, join as join11 } from "node:path";
17841
+ import { basename as basename3, dirname as dirname7, join as join12 } from "node:path";
17709
17842
  function isMissingPathError2(error) {
17710
17843
  return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
17711
17844
  }
@@ -17780,13 +17913,13 @@ async function listUniqueErrorFallbackPaths(directories) {
17780
17913
  }
17781
17914
  for (const name of names.sort((a, b) => a.localeCompare(b))) {
17782
17915
  if (!UNIQUE_ERROR_FALLBACK_NAME.test(name)) continue;
17783
- found.push(join11(dir, name));
17916
+ found.push(join12(dir, name));
17784
17917
  }
17785
17918
  }
17786
17919
  return found;
17787
17920
  }
17788
17921
  function runIdFromRunDirectory(runDirectory) {
17789
- const name = basename4(runDirectory);
17922
+ const name = basename3(runDirectory);
17790
17923
  const at = name.lastIndexOf("@");
17791
17924
  if (at <= 0 || at === name.length - 1) return void 0;
17792
17925
  return name.slice(0, at);
@@ -17826,11 +17959,11 @@ async function readRunTerminalArtifact(runDirectory) {
17826
17959
  unreadable.push(read);
17827
17960
  };
17828
17961
  for (const file of RUN_TERMINAL_ARTIFACT_FILES) {
17829
- consider(await readTerminalArtifactAtPath(join11(artifactsDir, file), file));
17962
+ consider(await readTerminalArtifactAtPath(join12(artifactsDir, file), file));
17830
17963
  }
17831
17964
  for (const relative3 of RUN_TERMINAL_ERROR_FALLBACK_RELATIVE_PATHS) {
17832
17965
  consider(
17833
- await readTerminalArtifactAtPath(join11(runDirectory, relative3), "error.json")
17966
+ await readTerminalArtifactAtPath(join12(runDirectory, relative3), "error.json")
17834
17967
  );
17835
17968
  }
17836
17969
  for (const path of await listSeamOwnedUniqueErrorFacePaths(runDirectory)) {
@@ -17848,7 +17981,7 @@ async function readRunTerminalArtifact(runDirectory) {
17848
17981
  return { status: "absent" };
17849
17982
  }
17850
17983
  function isUniqueErrorFallbackName(name) {
17851
- return UNIQUE_ERROR_FALLBACK_NAME.test(basename4(name));
17984
+ return UNIQUE_ERROR_FALLBACK_NAME.test(basename3(name));
17852
17985
  }
17853
17986
  var RUN_TERMINAL_ARTIFACT_FILES, RUN_TERMINAL_ERROR_FALLBACK_RELATIVE_PATHS, UNIQUE_ERROR_FALLBACK_NAME;
17854
17987
  var init_run_terminal_artifacts = __esm({
@@ -18006,7 +18139,7 @@ var init_compliance_transport = __esm({
18006
18139
  });
18007
18140
 
18008
18141
  // src/role-run-relocation.ts
18009
- import { join as join12, sep as sep2 } from "node:path";
18142
+ import { join as join13, sep as sep2 } from "node:path";
18010
18143
  function rewriteRunDirectoryPathValue(value, oldRunDirectory, newRunDirectory) {
18011
18144
  if (typeof value !== "string") return value;
18012
18145
  if (value === oldRunDirectory) return newRunDirectory;
@@ -18804,7 +18937,7 @@ var init_session_dialogue = __esm({
18804
18937
 
18805
18938
  // src/ticket-provenance.ts
18806
18939
  import { readFile as readFile10, unlink } from "node:fs/promises";
18807
- import { basename as basename5, dirname as dirname9, join as join13, resolve as resolve6 } from "node:path";
18940
+ import { basename as basename4, dirname as dirname9, join as join14, resolve as resolve6 } from "node:path";
18808
18941
  function ticketProvenanceSubject(ticketNumber) {
18809
18942
  if (!isSafePositiveTicketNumber(ticketNumber)) {
18810
18943
  throw new Error(
@@ -18830,7 +18963,7 @@ function resolveTicketProvenanceVolume(ticketNumber, cwd, home) {
18830
18963
  return { recordFile: path.recordFile, volumeDir: path.sessionDir };
18831
18964
  }
18832
18965
  async function rehomeUnboundTicketProvenance(runDirectory, ticketNumber, cwd, home) {
18833
- const source = join13(runDirectory, "records.jsonl");
18966
+ const source = join14(runDirectory, "records.jsonl");
18834
18967
  let content;
18835
18968
  try {
18836
18969
  content = await readFile10(source, "utf8");
@@ -18881,9 +19014,9 @@ var init_uuidv7 = __esm({
18881
19014
 
18882
19015
  // src/typed-provider-http.ts
18883
19016
  import { readFile as readFile11, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
18884
- import { join as join14 } from "node:path";
19017
+ import { join as join15 } from "node:path";
18885
19018
  function typedProviderHttpPath(runDirectory) {
18886
- return join14(runDirectory, TYPED_HTTP_FILE);
19019
+ return join15(runDirectory, TYPED_HTTP_FILE);
18887
19020
  }
18888
19021
  async function clearTypedProviderHttpObservation(runDirectory) {
18889
19022
  try {
@@ -18895,6 +19028,22 @@ async function clearTypedProviderHttpObservation(runDirectory) {
18895
19028
  throw error;
18896
19029
  }
18897
19030
  }
19031
+ async function recordTypedProviderHttpStatus(runDirectory, observation) {
19032
+ if (observation.httpStatus >= 200 && observation.httpStatus < 300) {
19033
+ await clearTypedProviderHttpObservation(runDirectory);
19034
+ return;
19035
+ }
19036
+ const body = {
19037
+ httpStatus: observation.httpStatus,
19038
+ provider: observation.provider
19039
+ };
19040
+ await writeFile2(
19041
+ typedProviderHttpPath(runDirectory),
19042
+ `${JSON.stringify(body)}
19043
+ `,
19044
+ "utf8"
19045
+ );
19046
+ }
18898
19047
  async function readLatestTypedProviderHttpObservation(runDirectory) {
18899
19048
  let text;
18900
19049
  try {
@@ -18927,8 +19076,43 @@ var init_typed_provider_http = __esm({
18927
19076
  });
18928
19077
 
18929
19078
  // src/public-cli/run-lifecycle.ts
18930
- import { chmod, lstat as lstat2, open, readdir as readdir4, readFile as readFile12, unlink as unlink3, writeFile as writeFile3 } from "node:fs/promises";
18931
- import { basename as basename6, join as join15 } from "node:path";
19079
+ var run_lifecycle_exports = {};
19080
+ __export(run_lifecycle_exports, {
19081
+ AUTO_RESUME_LIMIT: () => AUTO_RESUME_LIMIT,
19082
+ GATE_DOSSIER_POINTER_PREFIX: () => GATE_DOSSIER_POINTER_PREFIX,
19083
+ RESUME_TRANSPORT_ENVELOPE: () => RESUME_TRANSPORT_ENVELOPE,
19084
+ RunWriterLeaseHeldError: () => RunWriterLeaseHeldError,
19085
+ V1_RESUMABLE_PROVIDERS: () => V1_RESUMABLE_PROVIDERS,
19086
+ acquireRunWriterLease: () => acquireRunWriterLease,
19087
+ autopsyWriterLock: () => autopsyWriterLock,
19088
+ buildAutoResumeContinuationPrompt: () => buildAutoResumeContinuationPrompt,
19089
+ clearCurrentCourt: () => clearCurrentCourt,
19090
+ clearTypedProviderHttpObservation: () => clearTypedProviderHttpObservation,
19091
+ describeErrorIdentity: () => describeErrorIdentity,
19092
+ findLatestRunIdForSeatTicket: () => findLatestRunIdForSeatTicket,
19093
+ findRunDirectoryById: () => findRunDirectoryById,
19094
+ isDurablePrincipalAvailable: () => isDurablePrincipalAvailable,
19095
+ isV1ResumableProvider: () => isV1ResumableProvider,
19096
+ loadResumablePublicRole: () => loadResumablePublicRole,
19097
+ markRunAdmitted: () => markRunAdmitted,
19098
+ markRunResumable: () => markRunResumable,
19099
+ markRunRunning: () => markRunRunning,
19100
+ markRunTerminal: () => markRunTerminal,
19101
+ parentRunPathFromGatePointerInstruction: () => parentRunPathFromGatePointerInstruction,
19102
+ peekRoleRunRole: () => peekRoleRunRole,
19103
+ readCurrentCourt: () => readCurrentCourt,
19104
+ readLatestTypedProviderHttpObservation: () => readLatestTypedProviderHttpObservation,
19105
+ readRoleRunIdentity: () => readRoleRunIdentity,
19106
+ readRoleRunState: () => readRoleRunState,
19107
+ readRunParentPath: () => readRunParentPath,
19108
+ readTypedHttp429Observation: () => readTypedHttp429Observation,
19109
+ recordCurrentCourt: () => recordCurrentCourt,
19110
+ recordTypedProviderHttpStatus: () => recordTypedProviderHttpStatus,
19111
+ renderResumeCommand: () => renderResumeCommand,
19112
+ writeRoleRunState: () => writeRoleRunState
19113
+ });
19114
+ import { chmod, lstat as lstat3, open, readdir as readdir4, readFile as readFile12, unlink as unlink3, writeFile as writeFile3 } from "node:fs/promises";
19115
+ import { basename as basename5, join as join16 } from "node:path";
18932
19116
  function buildAutoResumeContinuationPrompt(options) {
18933
19117
  return appendEngineSessionMaterial(
18934
19118
  [RESUME_TRANSPORT_ENVELOPE],
@@ -18954,7 +19138,7 @@ function renderResumeCommand(runId) {
18954
19138
  async function writeRoleRunState(runDirectory, record4) {
18955
19139
  const payload = { ...record4, runDirectory };
18956
19140
  await writeFile3(
18957
- join15(runDirectory, RUN_STATE_FILE),
19141
+ join16(runDirectory, RUN_STATE_FILE),
18958
19142
  `${JSON.stringify(payload, null, 2)}
18959
19143
  `,
18960
19144
  "utf8"
@@ -19004,7 +19188,7 @@ function parseCurrentCourtState(raw) {
19004
19188
  async function readRoleRunStateRaw(runDirectory) {
19005
19189
  let raw;
19006
19190
  try {
19007
- raw = JSON.parse(await readFile12(join15(runDirectory, RUN_STATE_FILE), "utf8"));
19191
+ raw = JSON.parse(await readFile12(join16(runDirectory, RUN_STATE_FILE), "utf8"));
19008
19192
  } catch (error) {
19009
19193
  if (errorCodeOf2(error) === "ENOENT") return void 0;
19010
19194
  throw error;
@@ -19098,7 +19282,7 @@ async function writeRoleRunStateDisk(runDirectory, disk) {
19098
19282
  ...disk.currentCourt === void 0 ? {} : { currentCourt: disk.currentCourt }
19099
19283
  };
19100
19284
  await writeFile3(
19101
- join15(runDirectory, RUN_STATE_FILE),
19285
+ join16(runDirectory, RUN_STATE_FILE),
19102
19286
  `${JSON.stringify(payload, null, 2)}
19103
19287
  `,
19104
19288
  "utf8"
@@ -19127,6 +19311,11 @@ function materializeRoleRunFromDisk(disk, authority) {
19127
19311
  return void 0;
19128
19312
  }
19129
19313
  }
19314
+ async function readRoleRunState(runDirectory, authority) {
19315
+ const disk = await readRoleRunStateDisk(runDirectory);
19316
+ if (disk === void 0) return void 0;
19317
+ return materializeRoleRunFromDisk(disk, authority)?.run;
19318
+ }
19130
19319
  async function readRoleRunIdentity(runDirectory) {
19131
19320
  const raw = await readRoleRunStateRaw(runDirectory);
19132
19321
  return raw === void 0 ? void 0 : parseRoleRunIdentity(raw, runDirectory);
@@ -19319,7 +19508,7 @@ async function createWriterLease(lockPath, runDirectory, reportCleanupFailure) {
19319
19508
  },
19320
19509
  relocate(nextRunDirectory) {
19321
19510
  currentRunDirectory = nextRunDirectory;
19322
- currentLockPath = join15(nextRunDirectory, WRITER_LOCK_FILE);
19511
+ currentLockPath = join16(nextRunDirectory, WRITER_LOCK_FILE);
19323
19512
  },
19324
19513
  async release() {
19325
19514
  if (released) return;
@@ -19358,10 +19547,10 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
19358
19547
  };
19359
19548
  const reportReadFailure = (error) => {
19360
19549
  reportDiagnostic(
19361
- `writer lease lock read failed (holder liveness unverifiable; lock left in place) at ${join15(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
19550
+ `writer lease lock read failed (holder liveness unverifiable; lock left in place) at ${join16(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
19362
19551
  );
19363
19552
  };
19364
- const lockPath = join15(runDirectory, WRITER_LOCK_FILE);
19553
+ const lockPath = join16(runDirectory, WRITER_LOCK_FILE);
19365
19554
  let lastAutopsy = { verdict: "absent" };
19366
19555
  let lastReclaimFailure;
19367
19556
  for (let reclaimsLeft = WRITER_LEASE_RECLAIM_ROUNDS; ; reclaimsLeft -= 1) {
@@ -19416,7 +19605,7 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
19416
19605
  async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole) {
19417
19606
  if (runId.trim() === "") return void 0;
19418
19607
  const ledgerHome = resolveActivationLedgerHome(home);
19419
- const booksRoot = join15(ledgerHome, "books");
19608
+ const booksRoot = join16(ledgerHome, "books");
19420
19609
  let bookKeys;
19421
19610
  try {
19422
19611
  bookKeys = await readdir4(booksRoot);
@@ -19436,7 +19625,7 @@ async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole) {
19436
19625
  throw error;
19437
19626
  }
19438
19627
  for (const runDirectory of runDirectories) {
19439
- const entry = basename6(runDirectory);
19628
+ const entry = basename5(runDirectory);
19440
19629
  if (onlyRole === void 0 && (entry === `${runId}@judge` || entry.startsWith(`${runId}@`)) || entry === `${runId}@${onlyRole}`) {
19441
19630
  matches.push(runDirectory);
19442
19631
  }
@@ -19457,7 +19646,7 @@ async function readRunParentPath(runDirectory) {
19457
19646
  let raw;
19458
19647
  try {
19459
19648
  raw = JSON.parse(
19460
- await readFile12(join15(runDirectory, "admitted-request.json"), "utf8")
19649
+ await readFile12(join16(runDirectory, "admitted-request.json"), "utf8")
19461
19650
  );
19462
19651
  } catch (error) {
19463
19652
  if (errorCodeOf2(error) === "ENOENT") return void 0;
@@ -19478,9 +19667,9 @@ async function readRunParentPath(runDirectory) {
19478
19667
  async function runHasFormedSessionPrincipal(runDirectory) {
19479
19668
  const disk = await readRoleRunStateDisk(runDirectory);
19480
19669
  if (disk === void 0) return false;
19481
- const sessionFile = typeof disk.principalWire.sessionFile === "string" && disk.principalWire.sessionFile.trim() !== "" ? disk.principalWire.sessionFile : join15(disk.principalWire.sessionDirectory, "session.jsonl");
19670
+ const sessionFile = typeof disk.principalWire.sessionFile === "string" && disk.principalWire.sessionFile.trim() !== "" ? disk.principalWire.sessionFile : join16(disk.principalWire.sessionDirectory, "session.jsonl");
19482
19671
  try {
19483
- const stat2 = await lstat2(sessionFile);
19672
+ const stat2 = await lstat3(sessionFile);
19484
19673
  return stat2.isFile() && !stat2.isSymbolicLink();
19485
19674
  } catch (error) {
19486
19675
  if (errorCodeOf2(error) === "ENOENT") return false;
@@ -19496,7 +19685,7 @@ async function findLatestRunIdForSeatTicket(input) {
19496
19685
  let runDirectories;
19497
19686
  try {
19498
19687
  runDirectories = await listBookRunDirectories(
19499
- input.ticketNumber === void 0 ? bookDir : join15(bookDir, String(input.ticketNumber))
19688
+ input.ticketNumber === void 0 ? bookDir : join16(bookDir, String(input.ticketNumber))
19500
19689
  );
19501
19690
  } catch (error) {
19502
19691
  if (errorCodeOf2(error) === "ENOENT") return void 0;
@@ -19505,12 +19694,12 @@ async function findLatestRunIdForSeatTicket(input) {
19505
19694
  const suffix = `@${input.role}`;
19506
19695
  let best;
19507
19696
  for (const runDirectory of runDirectories) {
19508
- const entry = basename6(runDirectory);
19697
+ const entry = basename5(runDirectory);
19509
19698
  if (!entry.endsWith(suffix)) continue;
19510
19699
  const runId = entry.slice(0, entry.length - suffix.length);
19511
19700
  if (runId.length === 0) continue;
19512
19701
  const parentPath = await readRunParentPath(runDirectory);
19513
- if (parentPath !== input.parentRunPath) continue;
19702
+ if (parentPath !== input.parentRunPath && basename5(parentPath ?? "") !== basename5(input.parentRunPath)) continue;
19514
19703
  if (!await runHasFormedSessionPrincipal(runDirectory)) continue;
19515
19704
  if (best === void 0 || runId > best) best = runId;
19516
19705
  }
@@ -19572,7 +19761,7 @@ function restoredTicketFields(fields) {
19572
19761
  ...fields.courtTicketNumbers === void 0 ? {} : { courtTicketNumbers: fields.courtTicketNumbers }
19573
19762
  };
19574
19763
  }
19575
- async function loadResumableRunRecord(home, runId, authority) {
19764
+ async function loadResumableRunRecord(home, runId, authority, allowUnformedAdmitted = false) {
19576
19765
  const runDirectory = await findRunDirectoryById(home, runId);
19577
19766
  if (runDirectory === void 0) {
19578
19767
  throw new CliUsageError(`unknown role run id: ${runId}`);
@@ -19586,7 +19775,7 @@ async function loadResumableRunRecord(home, runId, authority) {
19586
19775
  throw new CliUsageError(`unknown role run id: ${runId}`);
19587
19776
  }
19588
19777
  const { run, principal } = materialized;
19589
- if (!await isDurablePrincipalAvailable(principal, authority)) {
19778
+ if (!(allowUnformedAdmitted && run.state === "admitted") && !await isDurablePrincipalAvailable(principal, authority)) {
19590
19779
  throw new CliUsageError(
19591
19780
  `role run Pi session principal is unavailable: ${runId}`
19592
19781
  );
@@ -19746,7 +19935,7 @@ async function loadResumableRunRecord(home, runId, authority) {
19746
19935
  let model;
19747
19936
  try {
19748
19937
  const invocationRaw = JSON.parse(
19749
- await readFile12(join15(run.runDirectory, "invocation.json"), "utf8")
19938
+ await readFile12(join16(run.runDirectory, "invocation.json"), "utf8")
19750
19939
  );
19751
19940
  if (invocationRaw !== null && typeof invocationRaw === "object" && !Array.isArray(invocationRaw)) {
19752
19941
  const rec = invocationRaw;
@@ -19785,7 +19974,7 @@ async function loadResumableRunRecord(home, runId, authority) {
19785
19974
  } else if (mergedSet.tickets !== void 0) {
19786
19975
  courtTicketNumbers = mergedSet.tickets;
19787
19976
  }
19788
- const sourceRunLeaf = basename6(sourceRunPath ?? "").split("@");
19977
+ const sourceRunLeaf = basename5(sourceRunPath ?? "").split("@");
19789
19978
  const referencedRunId = sourceRun?.runId ?? sourceRunLeaf[0];
19790
19979
  const referencedRole = sourceRun?.role ?? sourceRunLeaf[1];
19791
19980
  if (referencedRunId !== void 0 && referencedRunId !== "") {
@@ -19867,8 +20056,8 @@ async function peekRoleRunRole(home, runId) {
19867
20056
  const run = await readRoleRunIdentity(runDirectory);
19868
20057
  return run?.role;
19869
20058
  }
19870
- async function loadResumablePublicRole(home, runId, authority) {
19871
- const loaded = await loadResumableRunRecord(home, runId, authority);
20059
+ async function loadResumablePublicRole(home, runId, authority, allowUnformedAdmitted = false) {
20060
+ const loaded = await loadResumableRunRecord(home, runId, authority, allowUnformedAdmitted);
19872
20061
  return seatLoadedResult(loaded, admitResumedRole(loaded));
19873
20062
  }
19874
20063
  function admitResumedRole(loaded) {
@@ -20130,8 +20319,8 @@ var init_run_lifecycle = __esm({
20130
20319
  });
20131
20320
 
20132
20321
  // src/notary-source-run.ts
20133
- import { dirname as dirname10, isAbsolute as isAbsolute6, join as join16, resolve as resolve7, basename as basename7 } from "node:path";
20134
- import { lstat as lstat3, realpath as realpath3 } from "node:fs/promises";
20322
+ import { dirname as dirname10, isAbsolute as isAbsolute6, join as join17, resolve as resolve7, basename as basename6 } from "node:path";
20323
+ import { lstat as lstat4, realpath as realpath3 } from "node:fs/promises";
20135
20324
  async function readRetainedIdentity(runDirectory) {
20136
20325
  try {
20137
20326
  return await readRoleRunIdentity(runDirectory);
@@ -20159,7 +20348,7 @@ async function requireRunDirectory(candidate, display) {
20159
20348
  }
20160
20349
  let stat2;
20161
20350
  try {
20162
- stat2 = await lstat3(real);
20351
+ stat2 = await lstat4(real);
20163
20352
  } catch (error) {
20164
20353
  throw new NotarySourceRunError(
20165
20354
  `notary --source-run is not a readable run directory: ${display}`,
@@ -20171,10 +20360,10 @@ async function requireRunDirectory(candidate, display) {
20171
20360
  `notary --source-run must be a run directory: ${display}`
20172
20361
  );
20173
20362
  }
20174
- const identity = parseRunDirectoryName(basename7(real));
20363
+ const identity = parseRunDirectoryName(basename6(real));
20175
20364
  if (identity === void 0) {
20176
20365
  throw new NotarySourceRunError(
20177
- `notary --source-run must be named <runId>@<role>: ${basename7(real)}`
20366
+ `notary --source-run must be named <runId>@<role>: ${basename6(real)}`
20178
20367
  );
20179
20368
  }
20180
20369
  return real;
@@ -20187,16 +20376,16 @@ async function resolveNotarySourceRunLocator(options) {
20187
20376
  const ledgerHome = resolveActivationLedgerHome(options.home);
20188
20377
  const bookKey = resolveBookKeyFromGit(options.projectRoot);
20189
20378
  const bookDirectory = activationBookDirectory(ledgerHome, bookKey);
20190
- const bookRunsRoot = join16(bookDirectory, "runs");
20379
+ const bookRunsRoot = join17(bookDirectory, "runs");
20191
20380
  let candidate;
20192
20381
  const bare = parseRunDirectoryName(raw);
20193
20382
  if (bare !== void 0 && !raw.includes("/") && !raw.includes("\\")) {
20194
- candidate = await findRunDirectoryById(options.home, bare.runId, bookKey, bare.role) ?? join16(bookRunsRoot, `${bare.runId}@${bare.role}`);
20383
+ candidate = await findRunDirectoryById(options.home, bare.runId, bookKey, bare.role) ?? join17(bookRunsRoot, `${bare.runId}@${bare.role}`);
20195
20384
  } else {
20196
20385
  candidate = isAbsolute6(raw) ? raw : resolve7(options.projectRoot, raw);
20197
- const identity2 = parseRunDirectoryName(basename7(candidate));
20386
+ const identity2 = parseRunDirectoryName(basename6(candidate));
20198
20387
  const subjectDirectory = dirname10(dirname10(candidate));
20199
- const isLegacyUnboundLocator = identity2 !== void 0 && basename7(dirname10(candidate)) === "runs" && basename7(subjectDirectory) === "unbound" && resolve7(dirname10(subjectDirectory)) === resolve7(bookDirectory);
20388
+ const isLegacyUnboundLocator = identity2 !== void 0 && basename6(dirname10(candidate)) === "runs" && basename6(subjectDirectory) === "unbound" && resolve7(dirname10(subjectDirectory)) === resolve7(bookDirectory);
20200
20389
  if (isLegacyUnboundLocator) {
20201
20390
  candidate = await findRunDirectoryById(
20202
20391
  options.home,
@@ -20207,11 +20396,11 @@ async function resolveNotarySourceRunLocator(options) {
20207
20396
  }
20208
20397
  }
20209
20398
  const real = await requireRunDirectory(candidate, raw);
20210
- const identity = parseRunDirectoryName(basename7(real));
20399
+ const identity = parseRunDirectoryName(basename6(real));
20211
20400
  const bookIdentity = physicalPathIdentity(bookDirectory);
20212
20401
  const parentIdentity = physicalPathIdentity(dirname10(real));
20213
20402
  const subjectBookIdentity = physicalPathIdentity(dirname10(dirname10(dirname10(real))));
20214
- if (parentIdentity !== physicalPathIdentity(bookRunsRoot) && !(basename7(dirname10(real)) === "runs" && subjectBookIdentity === bookIdentity)) {
20403
+ if (parentIdentity !== physicalPathIdentity(bookRunsRoot) && !(basename6(dirname10(real)) === "runs" && subjectBookIdentity === bookIdentity)) {
20215
20404
  throw new NotarySourceRunError(
20216
20405
  "notary --source-run must resolve to a retained run under the project machine-ledger book"
20217
20406
  );
@@ -21313,7 +21502,7 @@ var init_option_definitions = __esm({
21313
21502
  import { execFileSync as execFileSync3 } from "node:child_process";
21314
21503
  import { existsSync as existsSync5 } from "node:fs";
21315
21504
  import {
21316
- lstat as lstat4,
21505
+ lstat as lstat5,
21317
21506
  mkdtemp,
21318
21507
  readFile as readFile13,
21319
21508
  realpath as realpath4,
@@ -21322,7 +21511,7 @@ import {
21322
21511
  writeFile as writeFile4
21323
21512
  } from "node:fs/promises";
21324
21513
  import { tmpdir } from "node:os";
21325
- import { basename as basename8, dirname as dirname11, isAbsolute as isAbsolute7, join as join17, resolve as resolve8, sep as sep4 } from "node:path";
21514
+ import { basename as basename7, dirname as dirname11, isAbsolute as isAbsolute7, join as join18, resolve as resolve8, sep as sep4 } from "node:path";
21326
21515
  function issueAdmissionPlacement(authority, request) {
21327
21516
  const ledgerHome = resolveActivationLedgerHome(request.home);
21328
21517
  const bookKey = resolveBookKeyFromGit(request.cwd);
@@ -21376,14 +21565,14 @@ async function writeRoleInvocationLedger(source, role, effectiveModel) {
21376
21565
  ...effectiveModelLedgerFields(effectiveModel)
21377
21566
  };
21378
21567
  await writeFile4(
21379
- join17(source.runDirectory, "invocation.json"),
21568
+ join18(source.runDirectory, "invocation.json"),
21380
21569
  `${JSON.stringify(identity, null, 2)}
21381
21570
  `,
21382
21571
  "utf8"
21383
21572
  );
21384
21573
  }
21385
21574
  async function recordEffectiveInvocationModel(runDirectory, model, engine, host, engineModel) {
21386
- const ledgerPath = join17(runDirectory, "invocation.json");
21575
+ const ledgerPath = join18(runDirectory, "invocation.json");
21387
21576
  const current = JSON.parse(await readFile13(ledgerPath, "utf8"));
21388
21577
  const next = { ...current };
21389
21578
  if (model !== void 0) {
@@ -21416,7 +21605,7 @@ async function recordEffectiveInvocationModel(runDirectory, model, engine, host,
21416
21605
  );
21417
21606
  }
21418
21607
  async function mergeInvocationIdentityPage(runDirectory, fields) {
21419
- const ledgerPath = join17(runDirectory, "invocation.json");
21608
+ const ledgerPath = join18(runDirectory, "invocation.json");
21420
21609
  const current = JSON.parse(await readFile13(ledgerPath, "utf8"));
21421
21610
  await writeFile4(
21422
21611
  ledgerPath,
@@ -21448,12 +21637,7 @@ async function persistAdmittedSourceRunPath(admitted, sourceRunPath) {
21448
21637
  );
21449
21638
  }
21450
21639
  async function bindAdmittedTicketNumber(admitted, ticketNumber) {
21451
- if (admitted.ticketNumber !== void 0) {
21452
- if (admitted.ticketNumber === ticketNumber) return;
21453
- throw new Error(
21454
- `bindAdmittedTicketNumber refuses to replace existing ticket #${admitted.ticketNumber} with #${ticketNumber}`
21455
- );
21456
- }
21640
+ if (admitted.ticketNumber === ticketNumber) return;
21457
21641
  await bindTicketNumberOnRunDirectory(admitted.runDirectory, ticketNumber);
21458
21642
  admitted.ticketNumber = ticketNumber;
21459
21643
  }
@@ -21536,7 +21720,8 @@ async function relocateAdmittedRunToTicket(admitted, authority, heldLease) {
21536
21720
  const childRunIds = parentPage.childDiaristRunIds;
21537
21721
  for (const childRunId of Array.isArray(childRunIds) ? childRunIds : []) {
21538
21722
  if (typeof childRunId !== "string") continue;
21539
- const childDirectory = join17(dirname11(oldRunDirectory), `${childRunId}@diarist`);
21723
+ const childDirectory = join18(dirname11(oldRunDirectory), `${childRunId}@diarist`);
21724
+ if (!existsSync5(childDirectory)) continue;
21540
21725
  const childTarget = roleRunPlacement(ledgerHome, {
21541
21726
  bookKey: admitted.bookKey,
21542
21727
  subject: { ticketNumber: admitted.ticketNumber },
@@ -21544,7 +21729,6 @@ async function relocateAdmittedRunToTicket(admitted, authority, heldLease) {
21544
21729
  role: "diarist"
21545
21730
  });
21546
21731
  authority.seal(childTarget);
21547
- if (!existsSync5(childDirectory) && existsSync5(childTarget.runDirectory)) continue;
21548
21732
  await bindTicketNumberOnRunDirectory(childDirectory, admitted.ticketNumber);
21549
21733
  await rehomeUnboundTicketProvenance(childDirectory, admitted.ticketNumber, admitted.projectRoot, homeFromRunDirectory(oldRunDirectory));
21550
21734
  ensureRoleRunDirectory(ledgerHome, dirname11(childTarget.runDirectory));
@@ -21593,26 +21777,9 @@ async function bindTicketNumberOnRunDirectory(runDirectory, ticketNumber) {
21593
21777
  ticketNumber,
21594
21778
  "bindTicketNumberOnRunDirectory"
21595
21779
  );
21596
- const admittedPath = join17(runDirectory, "admitted-request.json");
21597
- const invocationPath = join17(runDirectory, "invocation.json");
21780
+ const admittedPath = join18(runDirectory, "admitted-request.json");
21598
21781
  const admitted = JSON.parse(await readFile13(admittedPath, "utf8"));
21599
- const existing = admitted.ticketNumber;
21600
- if (typeof existing === "number") {
21601
- if (existing === ticketNumber) return;
21602
- throw new Error(
21603
- `bindTicketNumberOnRunDirectory refuses to replace existing ticket #${existing} with #${ticketNumber}`
21604
- );
21605
- }
21606
- if (existsSync5(invocationPath)) {
21607
- const invocation = JSON.parse(
21608
- await readFile13(invocationPath, "utf8")
21609
- );
21610
- if (typeof invocation.ticketNumber === "number" && invocation.ticketNumber !== ticketNumber) {
21611
- throw new Error(
21612
- `bindTicketNumberOnRunDirectory refuses to replace invocation ticket #${invocation.ticketNumber} with #${ticketNumber}`
21613
- );
21614
- }
21615
- }
21782
+ if (admitted.ticketNumber === ticketNumber) return;
21616
21783
  await writeFile4(
21617
21784
  admittedPath,
21618
21785
  `${JSON.stringify({ ...admitted, ticketNumber }, null, 2)}
@@ -21630,7 +21797,7 @@ async function recordLaunchedPiIdentity(runDirectory, identity) {
21630
21797
  async function observeLaunchedRolePackageIdentity(packageRoot2, selectedRoleEntry) {
21631
21798
  const rolePackageRoot = packageRoot2;
21632
21799
  const raw = JSON.parse(
21633
- await readFile13(join17(rolePackageRoot, "package.json"), "utf8")
21800
+ await readFile13(join18(rolePackageRoot, "package.json"), "utf8")
21634
21801
  );
21635
21802
  if (typeof raw.version !== "string" || raw.version.trim() === "") {
21636
21803
  throw new Error(
@@ -21904,7 +22071,7 @@ async function readRegularFileAttachment(sourcePath) {
21904
22071
  const absolute = isAbsolute7(sourcePath) ? sourcePath : resolve8(sourcePath);
21905
22072
  let st;
21906
22073
  try {
21907
- st = await lstat4(absolute);
22074
+ st = await lstat5(absolute);
21908
22075
  } catch (error) {
21909
22076
  throw new CliUsageError(
21910
22077
  `attachment is not a readable regular file: ${sourcePath}`,
@@ -21930,13 +22097,13 @@ async function removePreparedAttachmentDirectory(stagingDirectory) {
21930
22097
  }
21931
22098
  async function withPreparedAttachments(attachmentPaths, use) {
21932
22099
  if (attachmentPaths.length === 0) return await use([]);
21933
- const stagingDirectory = await mkdtemp(join17(tmpdir(), "ak-role-attachments-"));
22100
+ const stagingDirectory = await mkdtemp(join18(tmpdir(), "ak-role-attachments-"));
21934
22101
  const prepared = [];
21935
22102
  let result;
21936
22103
  try {
21937
22104
  for (let index = 0; index < attachmentPaths.length; index += 1) {
21938
22105
  const { absolute, bytes } = await readRegularFileAttachment(attachmentPaths[index]);
21939
- const snapshotPath = join17(stagingDirectory, String(index).padStart(6, "0"));
22106
+ const snapshotPath = join18(stagingDirectory, String(index).padStart(6, "0"));
21940
22107
  await writeFile4(snapshotPath, bytes);
21941
22108
  prepared.push({ absolute, snapshotPath });
21942
22109
  }
@@ -21957,9 +22124,9 @@ async function withPreparedAttachments(attachmentPaths, use) {
21957
22124
  return result;
21958
22125
  }
21959
22126
  async function freezeAttachmentBytes(provenancePath, bytes, destinationDir, index) {
21960
- const frozenPath = join17(
22127
+ const frozenPath = join18(
21961
22128
  destinationDir,
21962
- `${String(index).padStart(2, "0")}-${basename8(provenancePath)}`
22129
+ `${String(index).padStart(2, "0")}-${basename7(provenancePath)}`
21963
22130
  );
21964
22131
  await writeFile4(frozenPath, bytes);
21965
22132
  return {
@@ -22000,14 +22167,14 @@ async function freezeAttachments(attachmentPaths, attachmentsDirectory) {
22000
22167
  async function freezeAttachmentsIntoRun(attachmentPaths, runDirectory, summonsKey = `s-${Date.now().toString(36)}`) {
22001
22168
  if (attachmentPaths.length === 0) return [];
22002
22169
  const ledgerHome = resolveActivationLedgerHome(homeFromRunDirectory(runDirectory));
22003
- const attachmentsDirectory = join17(runDirectory, "attachments", summonsKey);
22170
+ const attachmentsDirectory = join18(runDirectory, "attachments", summonsKey);
22004
22171
  ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
22005
22172
  return freezeAttachments(attachmentPaths, attachmentsDirectory);
22006
22173
  }
22007
22174
  async function freezePreparedAttachmentsIntoRun(prepared, runDirectory, summonsKey) {
22008
22175
  if (prepared.length === 0) return [];
22009
22176
  const ledgerHome = resolveActivationLedgerHome(homeFromRunDirectory(runDirectory));
22010
- const attachmentsDirectory = summonsKey === void 0 ? join17(runDirectory, "attachments") : join17(runDirectory, "attachments", summonsKey);
22177
+ const attachmentsDirectory = summonsKey === void 0 ? join18(runDirectory, "attachments") : join18(runDirectory, "attachments", summonsKey);
22011
22178
  ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
22012
22179
  const attachments = [];
22013
22180
  for (let index = 0; index < prepared.length; index += 1) {
@@ -22084,7 +22251,7 @@ async function admitPublicRole(role, parsed, env, override) {
22084
22251
  attachmentPaths,
22085
22252
  ...project,
22086
22253
  placedFields: async (placed) => {
22087
- const taskPath = join17(placed.runDirectory, "task.md");
22254
+ const taskPath = join18(placed.runDirectory, "task.md");
22088
22255
  await writeFile4(taskPath, instruction, "utf8");
22089
22256
  return { phase, taskPath };
22090
22257
  }
@@ -22130,7 +22297,7 @@ async function admitPublicRole(role, parsed, env, override) {
22130
22297
  placedFields: async (placed) => {
22131
22298
  let prerequisitesPath;
22132
22299
  if (prerequisitesSource !== void 0) {
22133
- prerequisitesPath = join17(placed.runDirectory, "prerequisites.json");
22300
+ prerequisitesPath = join18(placed.runDirectory, "prerequisites.json");
22134
22301
  await writeFile4(
22135
22302
  prerequisitesPath,
22136
22303
  `${JSON.stringify(prerequisites, null, 2)}
@@ -22138,7 +22305,7 @@ async function admitPublicRole(role, parsed, env, override) {
22138
22305
  "utf8"
22139
22306
  );
22140
22307
  }
22141
- const packetPath = join17(placed.runDirectory, "fix-packet.md");
22308
+ const packetPath = join18(placed.runDirectory, "fix-packet.md");
22142
22309
  await writeFile4(packetPath, instruction, "utf8");
22143
22310
  return {
22144
22311
  phase,
@@ -22202,7 +22369,7 @@ async function admitPublicRole(role, parsed, env, override) {
22202
22369
  const prNumber = target.kind === "bound" ? target.prNumber : void 0;
22203
22370
  let requestManifestPath;
22204
22371
  if (manifestCanonicalJson !== void 0) {
22205
- requestManifestPath = join17(placed.runDirectory, "request-manifest.json");
22372
+ requestManifestPath = join18(placed.runDirectory, "request-manifest.json");
22206
22373
  await writeFile4(requestManifestPath, manifestCanonicalJson, "utf8");
22207
22374
  }
22208
22375
  return {
@@ -22393,7 +22560,7 @@ async function admitPublicRole(role, parsed, env, override) {
22393
22560
  resolutionScope: [...derived.resolutionScope],
22394
22561
  authorizedChecks: []
22395
22562
  });
22396
- const mergerInputPath = join17(placed.runDirectory, "merger-input.json");
22563
+ const mergerInputPath = join18(placed.runDirectory, "merger-input.json");
22397
22564
  await writeFile4(
22398
22565
  mergerInputPath,
22399
22566
  `${JSON.stringify(mergerInput, null, 2)}
@@ -22467,7 +22634,7 @@ function persistedAttachmentRefs(attachments) {
22467
22634
  }));
22468
22635
  }
22469
22636
  async function persistPlacedAdmission(admitted, placed, model) {
22470
- const admittedRequestPath = join17(placed.runDirectory, "admitted-request.json");
22637
+ const admittedRequestPath = join18(placed.runDirectory, "admitted-request.json");
22471
22638
  await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
22472
22639
  sessionDirectory: placed.sessionDirectory,
22473
22640
  sessionFile: placed.sessionFile
@@ -22520,7 +22687,7 @@ async function admitStandardMaterialInvocation(role, options) {
22520
22687
  attachments: persistedAttachmentRefs(placed.attachments),
22521
22688
  ...placed.ticketFields
22522
22689
  };
22523
- const admittedRequestPath = defer ? join17(placed.runDirectory, "admitted-request.json") : await persistPlacedAdmission(admitted, placed, options.model);
22690
+ const admittedRequestPath = defer ? join18(placed.runDirectory, "admitted-request.json") : await persistPlacedAdmission(admitted, placed, options.model);
22524
22691
  return {
22525
22692
  role,
22526
22693
  runId: placed.runId,
@@ -22595,7 +22762,7 @@ async function materializeCountersignInvocation(admitted, options) {
22595
22762
  });
22596
22763
  const placement = placed;
22597
22764
  admitted.runDirectory = placement.runDirectory;
22598
- admitted.admittedRequestPath = join17(
22765
+ admitted.admittedRequestPath = join18(
22599
22766
  placement.runDirectory,
22600
22767
  "admitted-request.json"
22601
22768
  );
@@ -22691,7 +22858,7 @@ function parseDoctorIssueNumber(raw) {
22691
22858
  }
22692
22859
  async function resolveDoctorCaseRunsPath(options) {
22693
22860
  const ledgerHome = resolveActivationLedgerHome(options.home);
22694
- const defaultRuns = join17(
22861
+ const defaultRuns = join18(
22695
22862
  activationBookDirectory(ledgerHome, options.bookKey),
22696
22863
  String(options.issueNumber),
22697
22864
  "runs"
@@ -23014,15 +23181,15 @@ var init_invocation = __esm({
23014
23181
 
23015
23182
  // src/public-cli/load-production-acp-host.ts
23016
23183
  import { existsSync as existsSync6 } from "node:fs";
23017
- import { join as join18 } from "node:path";
23184
+ import { join as join19 } from "node:path";
23018
23185
  import { pathToFileURL } from "node:url";
23019
23186
  async function loadProductionAcpHostFactory(packageRoot2, host) {
23020
23187
  const description = lookupHostDescription(host);
23021
23188
  if (description === void 0) {
23022
23189
  throw new Error(`unregistered host: ${host}`);
23023
23190
  }
23024
- const built = join18(packageRoot2, "dist/acp-host/production-host.js");
23025
- const source = join18(packageRoot2, "src/acp-host/production-host.ts");
23191
+ const built = join19(packageRoot2, "dist/acp-host/production-host.js");
23192
+ const source = join19(packageRoot2, "src/acp-host/production-host.ts");
23026
23193
  const target = existsSync6(built) ? built : source;
23027
23194
  const href = pathToFileURL(target).href;
23028
23195
  const mod = await import(href);
@@ -23038,15 +23205,15 @@ var init_load_production_acp_host = __esm({
23038
23205
 
23039
23206
  // src/public-cli/load-production-headless-host.ts
23040
23207
  import { existsSync as existsSync7 } from "node:fs";
23041
- import { join as join19 } from "node:path";
23208
+ import { join as join20 } from "node:path";
23042
23209
  import { pathToFileURL as pathToFileURL2 } from "node:url";
23043
23210
  async function loadProductionHeadlessHostFactory(packageRoot2, host) {
23044
23211
  const description = lookupHeadlessHostDescription(host);
23045
23212
  if (description === void 0) {
23046
23213
  throw new Error(`unregistered headless host: ${host}`);
23047
23214
  }
23048
- const built = join19(packageRoot2, "dist/headless-host/production-host.js");
23049
- const source = join19(packageRoot2, "src/headless-host/production-host.ts");
23215
+ const built = join20(packageRoot2, "dist/headless-host/production-host.js");
23216
+ const source = join20(packageRoot2, "src/headless-host/production-host.ts");
23050
23217
  const target = existsSync7(built) ? built : source;
23051
23218
  const href = pathToFileURL2(target).href;
23052
23219
  const mod = await import(href);
@@ -23171,246 +23338,9 @@ var init_role_turn_host_resolution = __esm({
23171
23338
  }
23172
23339
  });
23173
23340
 
23174
- // src/package-resources/method-skill.ts
23175
- import { createHash as createHash4 } from "node:crypto";
23176
- import { readFile as readFile14, realpath as realpath5 } from "node:fs/promises";
23177
- import { join as join20 } from "node:path";
23178
- function gitBlobOid(bytes) {
23179
- const body = typeof bytes === "string" ? Buffer.from(bytes, "utf8") : Buffer.from(bytes);
23180
- const header = Buffer.from(`blob ${body.byteLength}\0`, "utf8");
23181
- return createHash4("sha1").update(header).update(body).digest("hex");
23182
- }
23183
- function stripSkillFrontmatter(content) {
23184
- if (!content.startsWith("---")) return content;
23185
- const end = content.indexOf("\n---", 3);
23186
- if (end === -1) return content;
23187
- const after = content.slice(end + "\n---".length);
23188
- return after.replace(/^\r?\n/, "");
23189
- }
23190
- function packagedMethodSkillRelativeDirectory(name) {
23191
- return `${METHOD_SKILL_RELATIVE_ROOT}/${name}`;
23192
- }
23193
- function resolvePackagedMethodSkillRoot(packageRoot2, name) {
23194
- return join20(packageRoot2, packagedMethodSkillRelativeDirectory(name));
23195
- }
23196
- function resolvePackagedMethodSkillPath(packageRoot2, name) {
23197
- return join20(resolvePackagedMethodSkillRoot(packageRoot2, name), "SKILL.md");
23198
- }
23199
- function isRecord6(value) {
23200
- return typeof value === "object" && value !== null && !Array.isArray(value);
23201
- }
23202
- function parseProvenance(raw, expectedName) {
23203
- if (!isRecord6(raw)) {
23204
- throw new Error(`Packaged method provenance must be an object for ${expectedName}`);
23205
- }
23206
- if (raw.name !== expectedName) {
23207
- throw new Error(
23208
- `Packaged method provenance name mismatch: expected ${expectedName}, got ${String(raw.name)}`
23209
- );
23210
- }
23211
- if (raw.kind !== "role-method-skill") {
23212
- throw new Error(`Packaged method provenance kind must be role-method-skill`);
23213
- }
23214
- if (typeof raw.packageAdaptation !== "string" || raw.packageAdaptation.trim() === "") {
23215
- throw new Error(`Packaged method provenance packageAdaptation must be nonblank`);
23216
- }
23217
- if (!isRecord6(raw.upstream)) {
23218
- throw new Error(`Packaged method provenance upstream must be an object`);
23219
- }
23220
- const upstream = raw.upstream;
23221
- for (const key of [
23222
- "repository",
23223
- "path",
23224
- "license",
23225
- "copyright",
23226
- "attribution"
23227
- ]) {
23228
- if (typeof upstream[key] !== "string" || upstream[key].trim() === "") {
23229
- throw new Error(`Packaged method provenance upstream.${key} must be nonblank`);
23230
- }
23231
- }
23232
- if (typeof upstream.commit !== "string" || !GIT_COMMIT_RE.test(upstream.commit)) {
23233
- throw new Error(
23234
- `Packaged method provenance upstream.commit must be a 40-char lowercase git object id`
23235
- );
23236
- }
23237
- const tag = typeof upstream.tag === "string" && upstream.tag.trim() !== "" ? upstream.tag.trim() : void 0;
23238
- const version = typeof upstream.version === "string" && upstream.version.trim() !== "" ? upstream.version.trim() : void 0;
23239
- if (tag === void 0 && version === void 0) {
23240
- throw new Error(
23241
- `Packaged method provenance upstream must include nonblank tag or version`
23242
- );
23243
- }
23244
- if (!isRecord6(raw.files)) {
23245
- throw new Error(`Packaged method provenance files must be an object`);
23246
- }
23247
- const files = {};
23248
- for (const [rel, entry] of Object.entries(raw.files)) {
23249
- if (!isRecord6(entry)) {
23250
- throw new Error(`Packaged method provenance file entry must be an object: ${rel}`);
23251
- }
23252
- if (typeof entry.sha256 !== "string" || !SHA256_RE.test(entry.sha256)) {
23253
- throw new Error(`Packaged method provenance file sha256 invalid: ${rel}`);
23254
- }
23255
- if (typeof entry.byteLength !== "number" || !Number.isInteger(entry.byteLength) || entry.byteLength < 0) {
23256
- throw new Error(`Packaged method provenance file byteLength invalid: ${rel}`);
23257
- }
23258
- if (typeof entry.gitBlob !== "string" || !GIT_BLOB_RE.test(entry.gitBlob)) {
23259
- throw new Error(
23260
- `Packaged method provenance file gitBlob must be a 40-char lowercase git object id: ${rel}`
23261
- );
23262
- }
23263
- files[rel] = {
23264
- sha256: entry.sha256,
23265
- byteLength: entry.byteLength,
23266
- gitBlob: entry.gitBlob
23267
- };
23268
- }
23269
- if (files["SKILL.md"] === void 0) {
23270
- throw new Error(`Packaged method provenance must include SKILL.md`);
23271
- }
23272
- return Object.freeze({
23273
- name: expectedName,
23274
- kind: "role-method-skill",
23275
- packageAdaptation: raw.packageAdaptation,
23276
- upstream: Object.freeze({
23277
- repository: upstream.repository,
23278
- path: upstream.path,
23279
- commit: upstream.commit,
23280
- ...tag === void 0 ? {} : { tag },
23281
- ...version === void 0 ? {} : { version },
23282
- license: upstream.license,
23283
- copyright: upstream.copyright,
23284
- attribution: upstream.attribution
23285
- }),
23286
- files: Object.freeze(files)
23287
- });
23288
- }
23289
- async function loadPackagedMethodSkillMaterial(packageRoot2, name) {
23290
- const rootDirectory = resolvePackagedMethodSkillRoot(packageRoot2, name);
23291
- const skillPathConfigured = join20(rootDirectory, "SKILL.md");
23292
- const provenancePath = join20(rootDirectory, "provenance.json");
23293
- let provenanceRaw;
23294
- try {
23295
- provenanceRaw = await readFile14(provenancePath, "utf8");
23296
- } catch (error) {
23297
- throw new PackagedMethodSkillUnavailableError(name, provenancePath, error);
23298
- }
23299
- let provenanceJson;
23300
- try {
23301
- provenanceJson = JSON.parse(provenanceRaw);
23302
- } catch (error) {
23303
- throw new Error(`Packaged method provenance is not valid JSON at ${provenancePath}`, {
23304
- cause: error
23305
- });
23306
- }
23307
- const provenance = parseProvenance(provenanceJson, name);
23308
- for (const [rel, expected] of Object.entries(provenance.files)) {
23309
- const absolute = join20(rootDirectory, rel);
23310
- let bytes;
23311
- try {
23312
- bytes = await readFile14(absolute);
23313
- } catch (error) {
23314
- throw new PackagedMethodSkillUnavailableError(name, absolute, error);
23315
- }
23316
- const actualSha = sha256Hex(bytes);
23317
- const actualBlob = gitBlobOid(bytes);
23318
- if (actualSha !== expected.sha256 || bytes.byteLength !== expected.byteLength || actualBlob !== expected.gitBlob) {
23319
- throw new Error(
23320
- `Packaged method file digest mismatch for ${name}/${rel}: expected sha256=${expected.sha256} byteLength=${expected.byteLength} gitBlob=${expected.gitBlob}, got sha256=${actualSha} byteLength=${bytes.byteLength} gitBlob=${actualBlob}`
23321
- );
23322
- }
23323
- }
23324
- let skillPath;
23325
- let raw;
23326
- try {
23327
- skillPath = await realpath5(skillPathConfigured);
23328
- raw = await readFile14(skillPath, "utf8");
23329
- } catch (error) {
23330
- throw new PackagedMethodSkillUnavailableError(name, skillPathConfigured, error);
23331
- }
23332
- const body = stripSkillFrontmatter(raw).trim();
23333
- if (body.length === 0) {
23334
- throw new Error(`Canonical ${name} Skill is empty at ${skillPath}`);
23335
- }
23336
- const companionRelativePaths = REQUIRED_COMPANIONS[name].filter(
23337
- (rel) => provenance.files[rel] !== void 0
23338
- );
23339
- for (const rel of REQUIRED_COMPANIONS[name]) {
23340
- if (provenance.files[rel] === void 0) {
23341
- throw new Error(
23342
- `Packaged method ${name} missing required companion in provenance: ${rel}`
23343
- );
23344
- }
23345
- }
23346
- return Object.freeze({
23347
- name,
23348
- rootDirectory,
23349
- skillPath,
23350
- raw,
23351
- body,
23352
- provenance,
23353
- companionRelativePaths: Object.freeze([...companionRelativePaths])
23354
- });
23355
- }
23356
- function observePackagedMethodSkillInvocation(text, expected) {
23357
- if (!text.startsWith('<skill name="')) return void 0;
23358
- const nameStart = '<skill name="'.length;
23359
- const nameEnd = text.indexOf('"', nameStart);
23360
- if (nameEnd <= nameStart) return void 0;
23361
- const name = text.slice(nameStart, nameEnd);
23362
- if (name !== expected.name) return void 0;
23363
- const locationMarker = '" location="';
23364
- if (!text.startsWith(locationMarker, nameEnd)) return void 0;
23365
- const locationStart = nameEnd + locationMarker.length;
23366
- const locationEnd = text.indexOf('"', locationStart);
23367
- if (locationEnd <= locationStart) return void 0;
23368
- const location = text.slice(locationStart, locationEnd);
23369
- const openTail = ">\n";
23370
- if (!text.startsWith(openTail, locationEnd + 1)) return void 0;
23371
- const closeTag = "\n</skill>";
23372
- const closeAt = text.indexOf(closeTag, locationEnd + 1 + openTail.length);
23373
- if (closeAt === -1) return void 0;
23374
- const afterClose = text.slice(closeAt + closeTag.length);
23375
- if (afterClose.length > 0 && !afterClose.startsWith("\n")) return void 0;
23376
- if (!expected.allowedLocations.includes(location)) return void 0;
23377
- return Object.freeze({ name: expected.name, location });
23378
- }
23379
- var PackagedMethodSkillUnavailableError, METHOD_SKILL_RELATIVE_ROOT, GIT_COMMIT_RE, GIT_BLOB_RE, SHA256_RE, REQUIRED_COMPANIONS;
23380
- var init_method_skill = __esm({
23381
- "src/package-resources/method-skill.ts"() {
23382
- "use strict";
23383
- init_sha256();
23384
- PackagedMethodSkillUnavailableError = class extends Error {
23385
- constructor(skillName, path, cause) {
23386
- super(`Canonical ${skillName} Skill is unavailable at ${path}`, { cause });
23387
- this.skillName = skillName;
23388
- this.name = "CanonicalSkillUnavailableError";
23389
- }
23390
- skillName;
23391
- code = "canonical-skill-unavailable";
23392
- };
23393
- METHOD_SKILL_RELATIVE_ROOT = "resources/methods";
23394
- GIT_COMMIT_RE = /^[0-9a-f]{40}$/;
23395
- GIT_BLOB_RE = /^[0-9a-f]{40}$/;
23396
- SHA256_RE = /^[0-9a-f]{64}$/;
23397
- REQUIRED_COMPANIONS = {
23398
- tdd: ["tests.md", "mocking.md", "agents/openai.yaml"],
23399
- "diagnosing-bugs": ["agents/openai.yaml", "scripts/hitl-loop.template.sh"],
23400
- "ak-cross-m-review": [
23401
- "CONTEXT.md",
23402
- "LICENSE",
23403
- "prompts/cmr-completeness.md",
23404
- "prompts/cmr-reviewer.md"
23405
- ],
23406
- "resolving-merge-conflicts": ["agents/openai.yaml"]
23407
- };
23408
- }
23409
- });
23410
-
23411
23341
  // src/session-opening-materials.ts
23412
23342
  import { existsSync as existsSync8 } from "node:fs";
23413
- import { readFile as readFile15 } from "node:fs/promises";
23343
+ import { readFile as readFile14 } from "node:fs/promises";
23414
23344
  import { dirname as dirname12, join as join21 } from "node:path";
23415
23345
  import { fileURLToPath, pathToFileURL as pathToFileURL3 } from "node:url";
23416
23346
  function resolvePackageRootDir(moduleUrl = import.meta.url) {
@@ -23426,7 +23356,7 @@ function resolvePackageRootDir(moduleUrl = import.meta.url) {
23426
23356
  return fileURLToPath(new URL("..", moduleUrl));
23427
23357
  }
23428
23358
  async function readPackageMaterial(relativePath) {
23429
- return readFile15(fileURLToPath(new URL(relativePath, packageRootUrl)), "utf8");
23359
+ return readFile14(fileURLToPath(new URL(relativePath, packageRootUrl)), "utf8");
23430
23360
  }
23431
23361
  async function joinPackageMaterials(relativePaths) {
23432
23362
  const chunks = [];
@@ -23728,7 +23658,7 @@ var init_submission_ledger = __esm({
23728
23658
  });
23729
23659
 
23730
23660
  // src/session-identity.ts
23731
- import { mkdir as mkdir2, readFile as readFile16, rename as rename2, writeFile as writeFile5 } from "node:fs/promises";
23661
+ import { mkdir as mkdir3, readFile as readFile15, rename as rename2, writeFile as writeFile5 } from "node:fs/promises";
23732
23662
  import { dirname as dirname13, join as join23 } from "node:path";
23733
23663
  function createSessionIdentityAuthority(authority, sessionBindingFile) {
23734
23664
  const bindingPath = (principal) => join23(authority.decode(principal).sessionDirectory, sessionBindingFile);
@@ -23738,7 +23668,7 @@ function createSessionIdentityAuthority(authority, sessionBindingFile) {
23738
23668
  },
23739
23669
  async load(principal) {
23740
23670
  try {
23741
- const value = JSON.parse(await readFile16(bindingPath(principal), "utf8"));
23671
+ const value = JSON.parse(await readFile15(bindingPath(principal), "utf8"));
23742
23672
  if (typeof value !== "object" || value === null || typeof value.sessionId !== "string") {
23743
23673
  throw new Error("durable session binding is invalid");
23744
23674
  }
@@ -23750,7 +23680,7 @@ function createSessionIdentityAuthority(authority, sessionBindingFile) {
23750
23680
  },
23751
23681
  async bind(principal, sessionId) {
23752
23682
  const target = bindingPath(principal);
23753
- await mkdir2(dirname13(target), { recursive: true });
23683
+ await mkdir3(dirname13(target), { recursive: true });
23754
23684
  const temporary = `${target}.${process.pid}.tmp`;
23755
23685
  await writeFile5(temporary, `${JSON.stringify({ sessionId })}
23756
23686
  `, { encoding: "utf8", mode: 384 });
@@ -23783,7 +23713,7 @@ var init_session_identity = __esm({
23783
23713
  });
23784
23714
 
23785
23715
  // src/public-cli/case-dossier-delivery.ts
23786
- import { mkdtemp as mkdtemp2, readFile as readFile17, rm as rm2, writeFile as writeFile6 } from "node:fs/promises";
23716
+ import { mkdtemp as mkdtemp2, readFile as readFile16, rm as rm2, writeFile as writeFile6 } from "node:fs/promises";
23787
23717
  import { tmpdir as tmpdir2 } from "node:os";
23788
23718
  import { join as join24 } from "node:path";
23789
23719
  async function projectCaseDossierPointerSection(input) {
@@ -23844,11 +23774,11 @@ var init_case_dossier_delivery = __esm({
23844
23774
  import { randomUUID as randomUUID3 } from "node:crypto";
23845
23775
  import { readFileSync as readFileSync3 } from "node:fs";
23846
23776
  import { dirname as dirname14, join as join25 } from "node:path";
23847
- function isRecord7(value) {
23777
+ function isRecord6(value) {
23848
23778
  return typeof value === "object" && value !== null && !Array.isArray(value);
23849
23779
  }
23850
23780
  function callFactFromSitianPayload(payload, pointer) {
23851
- if (!isRecord7(payload)) return void 0;
23781
+ if (!isRecord6(payload)) return void 0;
23852
23782
  if (payload.tool !== ENGINE_DETOUR_TOOL_NAME) return void 0;
23853
23783
  if (typeof payload.toolCallId !== "string" || payload.toolCallId.length === 0) {
23854
23784
  return void 0;
@@ -23865,11 +23795,11 @@ function callFactFromSitianPayload(payload, pointer) {
23865
23795
  };
23866
23796
  }
23867
23797
  function invocationScopeIdOfRecord(record4) {
23868
- if (isRecord7(record4.subject)) {
23798
+ if (isRecord6(record4.subject)) {
23869
23799
  const fromSubject = record4.subject.invocationScopeId;
23870
23800
  if (typeof fromSubject === "string" && fromSubject.length > 0) return fromSubject;
23871
23801
  }
23872
- if (isRecord7(record4.payload)) {
23802
+ if (isRecord6(record4.payload)) {
23873
23803
  const fromPayload = record4.payload.invocationScopeId;
23874
23804
  if (typeof fromPayload === "string" && fromPayload.length > 0) return fromPayload;
23875
23805
  }
@@ -23929,7 +23859,7 @@ function readInvocationRecord(runDirectory) {
23929
23859
  const raw = JSON.parse(
23930
23860
  readFileSync3(join25(runDirectory, "invocation.json"), "utf8")
23931
23861
  );
23932
- return isRecord7(raw) ? raw : void 0;
23862
+ return isRecord6(raw) ? raw : void 0;
23933
23863
  } catch (error) {
23934
23864
  if (error?.code === "ENOENT") return void 0;
23935
23865
  throw error;
@@ -23947,7 +23877,7 @@ function readInvocationSelectedHost(runDirectory) {
23947
23877
  }
23948
23878
  function withEngineDetourToolUsageFact(outcome, usage) {
23949
23879
  if (usage === void 0) return outcome;
23950
- const prior = isRecord7(outcome.decisiveFacts) ? outcome.decisiveFacts : {};
23880
+ const prior = isRecord6(outcome.decisiveFacts) ? outcome.decisiveFacts : {};
23951
23881
  return {
23952
23882
  ...outcome,
23953
23883
  decisiveFacts: {
@@ -24101,7 +24031,7 @@ var init_process_cancel = __esm({
24101
24031
  // src/analyst-gate-cycles-read.ts
24102
24032
  import { readdir as readdir6 } from "node:fs/promises";
24103
24033
  import { join as join27 } from "node:path";
24104
- function isRecord8(value) {
24034
+ function isRecord7(value) {
24105
24035
  return typeof value === "object" && value !== null && !Array.isArray(value);
24106
24036
  }
24107
24037
  function isParentAttemptBindingRow(row) {
@@ -24131,7 +24061,7 @@ function isGateTerminatingToolName(toolName) {
24131
24061
  function acceptedGateReceiptIds(rows) {
24132
24062
  const accepted = /* @__PURE__ */ new Set();
24133
24063
  for (const row of rows) {
24134
- const message = isRecord8(row.message) ? row.message : void 0;
24064
+ const message = isRecord7(row.message) ? row.message : void 0;
24135
24065
  if (message?.role !== "toolResult") continue;
24136
24066
  if (typeof message.toolCallId !== "string" || message.toolCallId.length === 0) continue;
24137
24067
  if (message.isError === false) accepted.add(message.toolCallId);
@@ -24166,7 +24096,7 @@ function nearestAttemptBindingBefore(rows, beforeIndex) {
24166
24096
  for (let i = beforeIndex - 1; i >= 0; i -= 1) {
24167
24097
  const row = rows[i];
24168
24098
  if (!isParentAttemptBindingRow(row)) continue;
24169
- if (!isRecord8(row.data) || !isRecord8(row.data.parent)) continue;
24099
+ if (!isRecord7(row.data) || !isRecord7(row.data.parent)) continue;
24170
24100
  const id = row.data.parent.attemptEntryId;
24171
24101
  const sessionFile = row.data.parent.sessionFile;
24172
24102
  return {
@@ -24181,10 +24111,10 @@ function extractAllAcceptedGateToolCalls(rows) {
24181
24111
  const out = [];
24182
24112
  for (let rowIndex = 0; rowIndex < rows.length; rowIndex += 1) {
24183
24113
  const row = rows[rowIndex];
24184
- const message = isRecord8(row.message) ? row.message : void 0;
24114
+ const message = isRecord7(row.message) ? row.message : void 0;
24185
24115
  if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
24186
24116
  for (const part of message.content) {
24187
- if (!isRecord8(part) || part.type !== "toolCall") continue;
24117
+ if (!isRecord7(part) || part.type !== "toolCall") continue;
24188
24118
  if (typeof part.id !== "string" || part.id.length === 0) continue;
24189
24119
  if (typeof part.name !== "string" || part.name.length === 0) continue;
24190
24120
  if (!isGateTerminatingToolName(part.name)) continue;
@@ -24192,7 +24122,7 @@ function extractAllAcceptedGateToolCalls(rows) {
24192
24122
  const binding = nearestAttemptBindingBefore(rows, rowIndex);
24193
24123
  out.push({
24194
24124
  toolName: part.name,
24195
- args: isRecord8(part.arguments) ? part.arguments : void 0,
24125
+ args: isRecord7(part.arguments) ? part.arguments : void 0,
24196
24126
  accepted: true,
24197
24127
  rowIndex,
24198
24128
  ...binding
@@ -24315,17 +24245,17 @@ function pairGateRounds(volumes) {
24315
24245
  return rounds.sort((a, b) => a.officerStartedAt.localeCompare(b.officerStartedAt)).map((round, index) => ({ ...round, roundIndex: index + 1 }));
24316
24246
  }
24317
24247
  async function resolveOfficerSessionFromPointerFile(pointerPath) {
24318
- const { readFile: readFile23 } = await import("node:fs/promises");
24248
+ const { readFile: readFile22 } = await import("node:fs/promises");
24319
24249
  let raw;
24320
24250
  try {
24321
- raw = JSON.parse(await readFile23(pointerPath, "utf8"));
24251
+ raw = JSON.parse(await readFile22(pointerPath, "utf8"));
24322
24252
  } catch (error) {
24323
24253
  throw new Error(
24324
24254
  `direct officer run pointer unreadable in ${pointerPath}: ${error instanceof Error ? error.message : String(error)}`,
24325
24255
  { cause: error }
24326
24256
  );
24327
24257
  }
24328
- if (!isRecord8(raw) || raw.kind !== "direct-officer-run-pointer" || raw.version !== 1) {
24258
+ if (!isRecord7(raw) || raw.kind !== "direct-officer-run-pointer" || raw.version !== 1) {
24329
24259
  throw new Error(`direct officer run pointer has unknown shape in ${pointerPath}`);
24330
24260
  }
24331
24261
  const sessionFile = raw.sessionFile;
@@ -24588,11 +24518,11 @@ var init_navigator_invocation_identity = __esm({
24588
24518
  });
24589
24519
 
24590
24520
  // src/receipt-delivery-policy.ts
24591
- function isRecord9(value) {
24521
+ function isRecord8(value) {
24592
24522
  return typeof value === "object" && value !== null && !Array.isArray(value);
24593
24523
  }
24594
24524
  function parseNoReceiptLifecycleFacts(input) {
24595
- if (!isRecord9(input) || typeof input.terminalToolCalled !== "boolean" || input.deliveryTurns !== RECEIPT_DELIVERY_TURN_LIMIT || input.sessionCompletion !== "settled-without-accepted-receipt" || input.acceptedReceipt !== false || typeof input.runPointer !== "string" || input.runPointer.trim() === "" || typeof input.attemptPointer !== "string" || input.attemptPointer.trim() === "" || !Array.isArray(input.rejectedReceipts) || !input.rejectedReceipts.every((item) => isRecord9(item) && typeof item.reason === "string")) {
24525
+ if (!isRecord8(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) => isRecord8(item) && typeof item.reason === "string")) {
24596
24526
  throw new TypeError("malformed no-receipt lifecycle facts");
24597
24527
  }
24598
24528
  return {
@@ -24658,7 +24588,6 @@ __export(settlement_exports, {
24658
24588
  formatTerminalResult: () => formatTerminalResult,
24659
24589
  inspectJudgeSession: () => inspectJudgeSession,
24660
24590
  isLawfulTypedTerminalOutcome: () => isLawfulTypedTerminalOutcome,
24661
- observedMethodSkillOptions: () => observedMethodSkillOptions,
24662
24591
  presentControlledFailure: () => presentControlledFailure,
24663
24592
  presentFailureTerminal: () => presentFailureTerminal,
24664
24593
  presentStructuralRejection: () => presentStructuralRejection,
@@ -24685,7 +24614,7 @@ __export(settlement_exports, {
24685
24614
  withSubmissions: () => withSubmissions
24686
24615
  });
24687
24616
  import { randomUUID as randomUUID4 } from "node:crypto";
24688
- import { appendFile as appendFile2, readFile as readFile18, readdir as readdir7, rm as rm3, writeFile as writeFile7 } from "node:fs/promises";
24617
+ import { appendFile as appendFile2, readFile as readFile17, readdir as readdir7, rm as rm3, writeFile as writeFile7 } from "node:fs/promises";
24689
24618
  import { dirname as dirname16, join as join28 } from "node:path";
24690
24619
  function sealedLedgerHome(admitted) {
24691
24620
  return homeFromRunDirectory(admitted.runDirectory);
@@ -24843,7 +24772,7 @@ function presentControlledFailure(failure, io) {
24843
24772
  }
24844
24773
  async function inspectJudgeSession(sessionFile) {
24845
24774
  try {
24846
- await readFile18(sessionFile, "utf8");
24775
+ await readFile17(sessionFile, "utf8");
24847
24776
  return { state: "present" };
24848
24777
  } catch (error) {
24849
24778
  if (isMissingPathError4(error)) return { state: "missing" };
@@ -25083,7 +25012,7 @@ function sessionReadFailure(error, fallbackMessage) {
25083
25012
  return failed;
25084
25013
  }
25085
25014
  async function readBoundSessionEntries(sessionFile) {
25086
- const text = await readFile18(sessionFile, "utf8");
25015
+ const text = await readFile17(sessionFile, "utf8");
25087
25016
  const entries = [];
25088
25017
  for (const line2 of text.trim().split("\n").filter(Boolean)) {
25089
25018
  try {
@@ -25149,7 +25078,7 @@ async function readSitianRetainedAuditorProviderStop(sessionFile) {
25149
25078
  const { records } = await readSitianRecords(recordFile);
25150
25079
  for (let i = records.length - 1; i >= 0; i -= 1) {
25151
25080
  const payload = records[i]?.payload;
25152
- if (!isRecord10(payload) || !isRecord10(payload.response)) continue;
25081
+ if (!isRecord9(payload) || !isRecord9(payload.response)) continue;
25153
25082
  if (typeof payload.type === "string") continue;
25154
25083
  const stop = sessionProviderStopFromAssistant(payload.response);
25155
25084
  if (stop !== void 0) return stop;
@@ -25199,7 +25128,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
25199
25128
  throw sessionReadFailure(error, "failed to read discovered auditor session");
25200
25129
  }
25201
25130
  const header = entries.find((entry) => entry.type === "session");
25202
- if (!isRecord10(header)) continue;
25131
+ if (!isRecord9(header)) continue;
25203
25132
  const bindingIndexes = [];
25204
25133
  for (let i = 0; i < entries.length; i += 1) {
25205
25134
  const entry = entries[i];
@@ -25213,7 +25142,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
25213
25142
  end: idx + 1 < bindingIndexes.length ? bindingIndexes[idx + 1] : entries.length
25214
25143
  })) : [{ entry: void 0, start: 0, end: entries.length }];
25215
25144
  for (const { entry: bindingEntry, start, end } of bindingPasses) {
25216
- const bindingParent = bindingEntry !== void 0 && isRecord10(bindingEntry.data) && isRecord10(bindingEntry.data.parent) ? bindingEntry.data.parent : void 0;
25145
+ const bindingParent = bindingEntry !== void 0 && isRecord9(bindingEntry.data) && isRecord9(bindingEntry.data.parent) ? bindingEntry.data.parent : void 0;
25217
25146
  const attemptEntryId = typeof bindingParent?.attemptEntryId === "string" ? bindingParent.attemptEntryId : void 0;
25218
25147
  const boundSessionFile = typeof bindingParent?.sessionFile === "string" ? bindingParent.sessionFile : typeof header.parentSession === "string" ? header.parentSession : void 0;
25219
25148
  if (boundSessionFile !== sessionFile) continue;
@@ -25237,12 +25166,12 @@ function complianceFailureFromAuditorVolumes(volumes) {
25237
25166
  if (stop === void 0) continue;
25238
25167
  for (let i = entries.length - 1; i >= 0; i -= 1) {
25239
25168
  const entry = entries[i];
25240
- if (entry?.type !== "custom" || entry.customType !== AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE || !isRecord10(entry.data)) continue;
25241
- const parent = isRecord10(entry.data.parent) ? entry.data.parent : void 0;
25242
- const failure = isRecord10(entry.data.failure) ? entry.data.failure : void 0;
25169
+ if (entry?.type !== "custom" || entry.customType !== AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE || !isRecord9(entry.data)) continue;
25170
+ const parent = isRecord9(entry.data.parent) ? entry.data.parent : void 0;
25171
+ const failure = isRecord9(entry.data.failure) ? entry.data.failure : void 0;
25243
25172
  if (parent?.sessionId !== parentId || parent.sessionFile !== sessionFile || parent.attemptEntryId !== attemptEntryId) continue;
25244
25173
  if (failure === void 0) continue;
25245
- const identity = isRecord10(failure.identity) ? failure.identity : void 0;
25174
+ const identity = isRecord9(failure.identity) ? failure.identity : void 0;
25246
25175
  const typedCause = failure.cause === "provider" || failure.cause === "activation" || failure.cause === "session" || failure.cause === "output" || failure.cause === "timeout" ? failure.cause : void 0;
25247
25176
  return {
25248
25177
  ...typedCause === void 0 ? {} : { cause: typedCause },
@@ -25251,7 +25180,7 @@ function complianceFailureFromAuditorVolumes(volumes) {
25251
25180
  ...typeof identity.code === "string" || typeof identity.code === "number" ? { code: identity.code } : {}
25252
25181
  } },
25253
25182
  ...typeof failure.diagnostic === "string" ? { diagnostic: failure.diagnostic } : {},
25254
- ...isRecord10(failure.details) ? { details: failure.details } : {}
25183
+ ...isRecord9(failure.details) ? { details: failure.details } : {}
25255
25184
  };
25256
25185
  }
25257
25186
  }
@@ -25298,9 +25227,9 @@ function typedFailedTerminatingToolKnownFailure(entries) {
25298
25227
  if (classification.kind !== "infrastructure") continue;
25299
25228
  if (typeof message.toolCallId !== "string" || typeof message.toolName !== "string") continue;
25300
25229
  if (boundRoleToolCallForResult(attemptEntries, i, message, message.toolName) === void 0) continue;
25301
- const textPart = Array.isArray(message.content) ? message.content.find((part) => isRecord10(part) && part.type === "text" && typeof part.text === "string") : void 0;
25302
- const diagnostic = isRecord10(textPart) ? textPart.text : void 0;
25303
- const details = isRecord10(message.details) ? message.details : classification.fact;
25230
+ const textPart = Array.isArray(message.content) ? message.content.find((part) => isRecord9(part) && part.type === "text" && typeof part.text === "string") : void 0;
25231
+ const diagnostic = isRecord9(textPart) ? textPart.text : void 0;
25232
+ const details = isRecord9(message.details) ? message.details : classification.fact;
25304
25233
  return {
25305
25234
  cause: "activation",
25306
25235
  identity: { name: message.toolName, code: message.toolCallId },
@@ -25437,7 +25366,7 @@ function controlledFailureInputFromResolution(resolution) {
25437
25366
  } : {}
25438
25367
  };
25439
25368
  }
25440
- function isRecord10(value) {
25369
+ function isRecord9(value) {
25441
25370
  return typeof value === "object" && value !== null && !Array.isArray(value);
25442
25371
  }
25443
25372
  function toolResultText(message) {
@@ -25462,7 +25391,7 @@ function extractCollectorTargetBindRejection(entries) {
25462
25391
  const diagnostic = toolResultText(message);
25463
25392
  if (diagnostic.length === 0) return void 0;
25464
25393
  const details = message.details;
25465
- const code = isRecord10(details) && typeof details.code === "string" && details.code.trim() !== "" ? details.code : void 0;
25394
+ const code = isRecord9(details) && typeof details.code === "string" && details.code.trim() !== "" ? details.code : void 0;
25466
25395
  return code === void 0 ? { diagnostic } : { diagnostic, code };
25467
25396
  }
25468
25397
  return void 0;
@@ -25563,7 +25492,7 @@ function boundRoleToolCallForResult(entries, resultIndex, message, outputToolNam
25563
25492
  const candidateMessage = entries[index]?.message;
25564
25493
  if (candidateMessage?.role === "assistant" && Array.isArray(candidateMessage.content)) {
25565
25494
  for (const part of candidateMessage.content) {
25566
- if (!isRecord10(part) || part.type !== "toolCall" || part.id !== callId) {
25495
+ if (!isRecord9(part) || part.type !== "toolCall" || part.id !== callId) {
25567
25496
  continue;
25568
25497
  }
25569
25498
  if (part.name !== outputToolName) return void 0;
@@ -25634,7 +25563,7 @@ function parseNavigatorAttendanceDetails(details) {
25634
25563
  if (typeof details.prose === "string" && details.prose.trim() !== "") {
25635
25564
  prose = details.prose;
25636
25565
  } else {
25637
- const next = isRecord10(details.next) && typeof details.next.role === "string" ? details.next.role : void 0;
25566
+ const next = isRecord9(details.next) && typeof details.next.role === "string" ? details.next.role : void 0;
25638
25567
  const reason = typeof details.reason === "string" && details.reason.trim() !== "" ? details.reason : void 0;
25639
25568
  const command = typeof details.command === "string" && details.command.trim() !== "" ? details.command : void 0;
25640
25569
  if (reason !== void 0 && next !== void 0) {
@@ -25743,7 +25672,7 @@ function detourGateContext(admitted, scope) {
25743
25672
  }
25744
25673
  async function withOptionalGateProjection(base, sessionDirectory, gateContext = {}) {
25745
25674
  const secondaryEvidence = base.roleOutcome.kind === "failure" ? base.roleOutcome.decisiveFacts.secondaryEvidence : void 0;
25746
- const skipGate = isRecord10(secondaryEvidence) && secondaryEvidence.kind === "role_infrastructure_failure" && packagedSkipsGateOnInfrastructureStage(secondaryEvidence.stage);
25675
+ const skipGate = isRecord9(secondaryEvidence) && secondaryEvidence.kind === "role_infrastructure_failure" && packagedSkipsGateOnInfrastructureStage(secondaryEvidence.stage);
25747
25676
  let next = base;
25748
25677
  if (!skipGate) {
25749
25678
  const gate = await extractGateFactFromSessionDirectory(sessionDirectory, gateContext);
@@ -25787,7 +25716,7 @@ function extractNavigatorFact(entries) {
25787
25716
  const entry = entries[i];
25788
25717
  if (entry?.type === "custom_message" && entry.customType === "ak-navigator-attendance") {
25789
25718
  const details = entry.message?.details ?? entry.details;
25790
- if (!isRecord10(details)) {
25719
+ if (!isRecord9(details)) {
25791
25720
  return {
25792
25721
  disposition: "unavailable",
25793
25722
  source: "unknown",
@@ -25896,8 +25825,8 @@ async function publishAcceptedTerminalArtifacts(admitted, roleOutcome, coordinat
25896
25825
  { kind: "evidence", path: evidencePath }
25897
25826
  ];
25898
25827
  }
25899
- async function publishSeatAcceptedArtifacts(admitted, roleOutcome, coordinates, entries = [], options = {}) {
25900
- return publishDeclaredSeatArtifacts(admitted, roleOutcome, coordinates, entries, options);
25828
+ async function publishSeatAcceptedArtifacts(admitted, roleOutcome, coordinates, entries = []) {
25829
+ return publishDeclaredSeatArtifacts(admitted, roleOutcome, coordinates, entries);
25901
25830
  }
25902
25831
  async function readLawfulSettlementEntries(sessionFile) {
25903
25832
  try {
@@ -25938,7 +25867,7 @@ async function settleSealedAcceptedOrToolResidual(admitted, authority, scope, ro
25938
25867
  const residual = boundErroredToolCandidate(entries, index, message, residualToolName);
25939
25868
  if (residual === void 0) continue;
25940
25869
  const candidate = residual.candidate;
25941
- const details = isRecord10(candidate) ? candidate : { candidate };
25870
+ const details = isRecord9(candidate) ? candidate : { candidate };
25942
25871
  const failed = await settleFailureTerminalResult(
25943
25872
  admitted,
25944
25873
  {
@@ -25969,7 +25898,7 @@ async function settleSealedAcceptedOrToolResidual(admitted, authority, scope, ro
25969
25898
  scope
25970
25899
  );
25971
25900
  }
25972
- async function settleSeat(admitted, authority, scope, options) {
25901
+ async function settleSeat(admitted, authority, scope) {
25973
25902
  const record4 = packagedRoleMetadata(admitted.role);
25974
25903
  if (record4 === void 0) {
25975
25904
  throw new Error(`no settlement for ${admitted.role}`);
@@ -25977,7 +25906,7 @@ async function settleSeat(admitted, authority, scope, options) {
25977
25906
  if (record4.settlement === "accepted") {
25978
25907
  return trySettleAcceptedSeatTerminalResult(admitted, authority, scope);
25979
25908
  }
25980
- const publish = (roleOutcome, coordinates, entries) => publishDeclaredSeatArtifacts(admitted, roleOutcome, coordinates, entries, options);
25909
+ const publish = (roleOutcome, coordinates, entries) => publishDeclaredSeatArtifacts(admitted, roleOutcome, coordinates, entries);
25981
25910
  if (record4.settlement === "residual") {
25982
25911
  return settleSealedAcceptedOrToolResidual(
25983
25912
  admitted,
@@ -25992,11 +25921,11 @@ async function settleSeat(admitted, authority, scope, options) {
25992
25921
  const accept = "sealedAcceptedOnly" in record4 && record4.sealedAcceptedOnly === true ? (roleOutcome) => roleOutcome.role === admitted.role && roleOutcome.kind === "accepted" : void 0;
25993
25922
  return settleSealedLedgerTerminal(admitted, authority, scope, publish, accept);
25994
25923
  }
25995
- async function trySettleSeatTerminalResult(admitted, authority, options = {}, scope) {
25996
- return settleSeat(admitted, authority, scope, options);
25924
+ async function trySettleSeatTerminalResult(admitted, authority, scope) {
25925
+ return settleSeat(admitted, authority, scope);
25997
25926
  }
25998
- async function settleSeatTerminalResult(admitted, authority, options = {}, scope) {
25999
- const settled = await settleSeat(admitted, authority, scope, options);
25927
+ async function settleSeatTerminalResult(admitted, authority, scope) {
25928
+ const settled = await settleSeat(admitted, authority, scope);
26000
25929
  if (settled === void 0) {
26001
25930
  const label = admitted.role.charAt(0).toUpperCase() + admitted.role.slice(1);
26002
25931
  throw new Error(
@@ -26005,41 +25934,6 @@ async function settleSeatTerminalResult(admitted, authority, options = {}, scope
26005
25934
  }
26006
25935
  return settled;
26007
25936
  }
26008
- function sessionMessageText(message) {
26009
- if (message === void 0) return "";
26010
- if (typeof message.content === "string") return message.content;
26011
- if (!Array.isArray(message.content)) return "";
26012
- const parts = [];
26013
- for (const part of message.content) {
26014
- if (typeof part === "object" && part !== null && !Array.isArray(part) && part.type === "text" && typeof part.text === "string") {
26015
- parts.push(part.text);
26016
- }
26017
- }
26018
- return parts.join("\n");
26019
- }
26020
- function observedMethodSkillOptions(packageRoot2, material) {
26021
- return {
26022
- methodProvenance: material.provenance,
26023
- methodSkillPath: material.skillPath,
26024
- methodSkillConfiguredPath: resolvePackagedMethodSkillPath(packageRoot2, material.name)
26025
- };
26026
- }
26027
- function extractObservedMethodInvocations(entries, options) {
26028
- const observed = [];
26029
- for (const entry of entries) {
26030
- if (entry?.type !== "message") continue;
26031
- const message = entry.message;
26032
- if (message?.role !== "user") continue;
26033
- const text = sessionMessageText(message);
26034
- if (text.length === 0) continue;
26035
- const hit = observePackagedMethodSkillInvocation(text, {
26036
- name: options.name,
26037
- allowedLocations: options.allowedLocations
26038
- });
26039
- if (hit !== void 0) observed.push(hit);
26040
- }
26041
- return Object.freeze(observed);
26042
- }
26043
25937
  function extractDoctorCandidateFacts(entries) {
26044
25938
  const scanStart = currentAttemptStartIndex(entries);
26045
25939
  for (let i = entries.length - 1; i >= scanStart; i -= 1) {
@@ -26048,7 +25942,7 @@ function extractDoctorCandidateFacts(entries) {
26048
25942
  continue;
26049
25943
  }
26050
25944
  const data = entry.data;
26051
- if (!isRecord10(data)) return {};
25945
+ if (!isRecord9(data)) return {};
26052
25946
  return {
26053
25947
  ...data.cost === void 0 ? {} : { cost: data.cost },
26054
25948
  ...data.auditNoReceipt === void 0 ? {} : { auditNoReceipt: data.auditNoReceipt }
@@ -26092,25 +25986,7 @@ function doctorReportFacts(face, roleOutcome, entries) {
26092
25986
  ...facts.auditNoReceipt === void 0 ? {} : { auditNoReceipt: facts.auditNoReceipt }
26093
25987
  };
26094
25988
  }
26095
- function observedMethodTail(face, entries, options) {
26096
- if (face.method === void 0) return {};
26097
- if (face.method === "optional") {
26098
- return options.methodProvenance === void 0 ? {} : { methodProvenance: options.methodProvenance };
26099
- }
26100
- if (options.methodProvenance === void 0 || options.methodSkillPath === void 0 || options.methodSkillConfiguredPath === void 0) {
26101
- throw new Error("observed method publication is missing packaged method coordinates");
26102
- }
26103
- const methodInvocations = extractObservedMethodInvocations(entries, {
26104
- name: options.methodProvenance.name,
26105
- allowedLocations: [options.methodSkillPath, options.methodSkillConfiguredPath]
26106
- });
26107
- return {
26108
- methodProvenance: options.methodProvenance,
26109
- methodInvocationObserved: methodInvocations.length > 0,
26110
- methodInvocations
26111
- };
26112
- }
26113
- async function publishDeclaredSeatArtifacts(admitted, roleOutcome, coordinates, entries, options = {}) {
25989
+ async function publishDeclaredSeatArtifacts(admitted, roleOutcome, coordinates, entries) {
26114
25990
  const face = seatArtifactFace(admitted.role);
26115
25991
  const phase = face.reportPhase === true ? { phase: readAdmittedPath(admitted, "phase") } : {};
26116
25992
  return publishAcceptedTerminalArtifacts(admitted, roleOutcome, coordinates, {
@@ -26128,8 +26004,7 @@ async function publishDeclaredSeatArtifacts(admitted, roleOutcome, coordinates,
26128
26004
  sessionDirectory: coordinates.sessionDirectory,
26129
26005
  sessionFile: coordinates.sessionFile,
26130
26006
  admittedRequestPath: admitted.admittedRequestPath,
26131
- attachments: acceptedArtifactAttachmentRefs(admitted.attachments),
26132
- ...observedMethodTail(face, entries, options)
26007
+ attachments: acceptedArtifactAttachmentRefs(admitted.attachments)
26133
26008
  }
26134
26009
  });
26135
26010
  }
@@ -26152,7 +26027,7 @@ async function settleLawfulSeatAcceptedTerminalResult(admitted, authority, spec,
26152
26027
  let residual;
26153
26028
  for (let index = entries.length - 1; index >= scanStart; index -= 1) {
26154
26029
  const entry = entries[index];
26155
- if (entry?.type === "custom" && entry.customType === "ak-role-submission-closure" && isRecord10(entry.data) && entry.data.toolName === spec.toolName && classifyPackagedRoleTerminalResult(entry.data).kind === "accepted") {
26030
+ if (entry?.type === "custom" && entry.customType === "ak-role-submission-closure" && isRecord9(entry.data) && entry.data.toolName === spec.toolName && classifyPackagedRoleTerminalResult(entry.data).kind === "accepted") {
26156
26031
  thisAttemptHasSeatSuccess = true;
26157
26032
  }
26158
26033
  const message = entries[index]?.message;
@@ -26192,7 +26067,7 @@ async function settleLawfulSeatAcceptedTerminalResult(admitted, authority, spec,
26192
26067
  );
26193
26068
  }
26194
26069
  if (residual !== void 0) {
26195
- const details = isRecord10(residual.candidate) ? residual.candidate : { candidate: residual.candidate };
26070
+ const details = isRecord9(residual.candidate) ? residual.candidate : { candidate: residual.candidate };
26196
26071
  const failed = await settleFailureTerminalResult(
26197
26072
  admitted,
26198
26073
  {
@@ -26222,11 +26097,8 @@ async function trySettleAcceptedSeatTerminalResult(admitted, authority, scope) {
26222
26097
  }
26223
26098
  return applySecretariatCountersignTerminal(admitted, authority, settled);
26224
26099
  }
26225
- async function trySettlePublicSeat(admitted, authority, scope, material, packageRoot2) {
26226
- const face = seatArtifactFace(admitted.role);
26227
- if (face.method === "observed" && material === void 0) return void 0;
26228
- const options = face.method === "observed" && material !== void 0 ? observedMethodSkillOptions(packageRoot2, material) : face.method === "optional" && material !== void 0 ? { methodProvenance: material.provenance } : {};
26229
- return settleSeat(admitted, authority, scope, options);
26100
+ async function trySettlePublicSeat(admitted, authority, scope) {
26101
+ return settleSeat(admitted, authority, scope);
26230
26102
  }
26231
26103
  function countersignTerminalFromEntries(entries) {
26232
26104
  for (let index = entries.length - 1; index >= 0; index -= 1) {
@@ -26245,7 +26117,7 @@ function countersignTerminalFromEntries(entries) {
26245
26117
  return void 0;
26246
26118
  }
26247
26119
  function withCountersignTerminalFact(roleOutcome, officer) {
26248
- const prior = roleOutcome.decisiveFacts !== void 0 && isRecord10(roleOutcome.decisiveFacts) ? roleOutcome.decisiveFacts : {};
26120
+ const prior = roleOutcome.decisiveFacts !== void 0 && isRecord9(roleOutcome.decisiveFacts) ? roleOutcome.decisiveFacts : {};
26249
26121
  return {
26250
26122
  ...roleOutcome,
26251
26123
  decisiveFacts: {
@@ -26258,7 +26130,7 @@ function acceptedSecretariatDefinesOfficerProjection(roleOutcome) {
26258
26130
  const payloads = roleOutcome.payloads ?? [];
26259
26131
  for (let index = payloads.length - 1; index >= 0; index -= 1) {
26260
26132
  const payload = payloads[index];
26261
- if (!isRecord10(payload)) continue;
26133
+ if (!isRecord9(payload)) continue;
26262
26134
  const status = payload.secretariatStatus;
26263
26135
  if (typeof status !== "string") continue;
26264
26136
  return status === "converged";
@@ -26640,7 +26512,6 @@ var init_settlement = __esm({
26640
26512
  init_reviewer_output();
26641
26513
  init_packaged_role_registry();
26642
26514
  init_secretariat_contracts();
26643
- init_method_skill();
26644
26515
  init_navigator_invocation_identity();
26645
26516
  init_receipt_delivery_policy();
26646
26517
  init_role_run_placement();
@@ -26689,7 +26560,7 @@ var init_settlement = __esm({
26689
26560
  // src/public-cli/auto-resume.ts
26690
26561
  import { constants as fsConstants2 } from "node:fs";
26691
26562
  import { randomUUID as randomUUID5 } from "node:crypto";
26692
- import { lstat as lstat6, mkdir as mkdir3, open as open2 } from "node:fs/promises";
26563
+ import { lstat as lstat7, mkdir as mkdir4, open as open2 } from "node:fs/promises";
26693
26564
  import { join as join29 } from "node:path";
26694
26565
  async function persistReturnedRunState(admitted, authority, options) {
26695
26566
  if (options?.lawful === true) {
@@ -26726,20 +26597,20 @@ async function finalizeExceptionRunBestEffort(runDirectory, io) {
26726
26597
  }
26727
26598
  }
26728
26599
  async function ensureRealArtifactsDirectory(runDirectory) {
26729
- const runStat = await lstat6(runDirectory);
26600
+ const runStat = await lstat7(runDirectory);
26730
26601
  if (runStat.isSymbolicLink() || !runStat.isDirectory()) {
26731
26602
  throw new Error("run artifact retention: run directory is not a real directory");
26732
26603
  }
26733
26604
  const artifactsDir = roleRunArtifactsDirectory(runDirectory);
26734
26605
  try {
26735
- const existing = await lstat6(artifactsDir);
26606
+ const existing = await lstat7(artifactsDir);
26736
26607
  if (existing.isSymbolicLink() || !existing.isDirectory()) {
26737
26608
  throw new Error("run artifact retention: artifacts path is not a real directory");
26738
26609
  }
26739
26610
  } catch (error) {
26740
26611
  if (!isMissingPathError5(error)) throw error;
26741
- await mkdir3(artifactsDir, { recursive: true });
26742
- const created = await lstat6(artifactsDir);
26612
+ await mkdir4(artifactsDir, { recursive: true });
26613
+ const created = await lstat7(artifactsDir);
26743
26614
  if (created.isSymbolicLink() || !created.isDirectory()) {
26744
26615
  throw new Error("run artifact retention: artifacts directory is not a real directory");
26745
26616
  }
@@ -27121,8 +26992,9 @@ function withOnceSuccessfulBeforeDispatch(adapters) {
27121
26992
  ...adapters,
27122
26993
  beforeDispatch: async (admitted, lease) => {
27123
26994
  if (succeeded) return;
27124
- await hook(admitted, lease);
26995
+ const result = await hook(admitted, lease);
27125
26996
  succeeded = true;
26997
+ return result;
27126
26998
  }
27127
26999
  };
27128
27000
  }
@@ -27157,30 +27029,6 @@ async function recordBestEffortPostDispatchDiagnostic(admitted, env, diagnostic,
27157
27029
  } catch {
27158
27030
  }
27159
27031
  }
27160
- async function resolveResumeMethodMaterialAdapters(input) {
27161
- if (input.shouldLoad === false) {
27162
- return { kind: "continue", adapters: input.emptyAdapters };
27163
- }
27164
- try {
27165
- const material = await input.loadMaterial();
27166
- return { kind: "continue", adapters: input.adaptersWith(material) };
27167
- } catch (error) {
27168
- const terminal = await presentControlledFailure2(
27169
- input.admitted,
27170
- {
27171
- timedOut: false,
27172
- code: null,
27173
- stderr: "",
27174
- thrown: error,
27175
- ...input.knownCause === void 0 ? {} : { knownCause: input.knownCause }
27176
- },
27177
- input.emptyAdapters,
27178
- input.authority,
27179
- input.io
27180
- );
27181
- return { kind: "terminal", ...terminal };
27182
- }
27183
- }
27184
27032
  async function presentControlledFailure2(admitted, failureInput, adapters, authority, io, persistRunState = true) {
27185
27033
  const hasThrown = Object.hasOwn(failureInput, "thrown");
27186
27034
  const resumeObservation = await resolveControlledFailureResumeObservation({
@@ -27384,7 +27232,10 @@ async function dispatchPostAdmissionTurn(input) {
27384
27232
  await clearTypedProviderHttpObservation(admitted.runDirectory);
27385
27233
  if (adapters.beforeDispatch !== void 0) {
27386
27234
  try {
27387
- await adapters.beforeDispatch(admitted, lease);
27235
+ const paused = await adapters.beforeDispatch(admitted, lease);
27236
+ if (paused !== void 0) {
27237
+ return { exitCode: 0, admitted, terminal: paused, skipAutoResume: true };
27238
+ }
27388
27239
  } catch (error) {
27389
27240
  const settled2 = await presentControlledFailure2(
27390
27241
  admitted,
@@ -27696,6 +27547,7 @@ function resumeTurnRequestProjectionOptions(admitted, request, env, summonsPrepa
27696
27547
  return {
27697
27548
  packageRoot: env.packageRoot,
27698
27549
  home: env.home,
27550
+ ...env.host === void 0 ? {} : { host: env.host },
27699
27551
  agentDir: env.agentDir,
27700
27552
  ...env.model === void 0 ? {} : { model: env.model },
27701
27553
  ...pickEngineAxis(env),
@@ -27714,6 +27566,7 @@ function roleTurnOptions(env, admitted, continuation) {
27714
27566
  return {
27715
27567
  packageRoot: env.packageRoot,
27716
27568
  home: env.home,
27569
+ ...env.host === void 0 ? {} : { host: env.host },
27717
27570
  agentDir: env.agentDir,
27718
27571
  ...env.model === void 0 ? {} : { model: env.model },
27719
27572
  ...pickEngineAxis(env),
@@ -28127,7 +27980,7 @@ function activationForAdmitted(admitted) {
28127
27980
  }
28128
27981
  return activation;
28129
27982
  }
28130
- function methodBindings(admitted, packageRoot2) {
27983
+ function requiredMethodSkills(admitted) {
28131
27984
  const record4 = packagedRoleMetadata(admitted.role);
28132
27985
  const names = [];
28133
27986
  if (record4 !== void 0 && "methodSkills" in record4 && record4.methodSkills !== void 0) {
@@ -28135,23 +27988,30 @@ function methodBindings(admitted, packageRoot2) {
28135
27988
  }
28136
27989
  const apply = packagedSettleSkill(admitted);
28137
27990
  if (apply !== void 0 && !names.includes(apply)) names.push(apply);
28138
- return names.map((name) => ({
28139
- kind: "skill",
28140
- path: resolvePackagedMethodSkillPath(packageRoot2, name)
28141
- }));
27991
+ return names;
27992
+ }
27993
+ function methodBindings(admitted, home, host) {
27994
+ if (host !== void 0 && host !== "pi") return [];
27995
+ return requiredMethodSkills(admitted).flatMap((name) => {
27996
+ const path = installedMethodSkillPath(home, name);
27997
+ return path === void 0 ? [] : [{
27998
+ kind: "skill",
27999
+ path
28000
+ }];
28001
+ });
28142
28002
  }
28143
- function admittedSeatTurnDetails(admitted, packageRoot2) {
28003
+ function admittedSeatTurnDetails(admitted, home, host) {
28144
28004
  return {
28145
28005
  activation: activationForAdmitted(admitted),
28146
- methods: methodBindings(admitted, packageRoot2)
28006
+ methods: methodBindings(admitted, home, host)
28147
28007
  };
28148
28008
  }
28149
28009
  var init_turn_request = __esm({
28150
28010
  "src/public-cli/turn-request.ts"() {
28151
28011
  "use strict";
28152
28012
  init_engine_material();
28153
- init_method_skill();
28154
28013
  init_packaged_role_registry();
28014
+ init_machine_method_skills();
28155
28015
  init_run_lifecycle();
28156
28016
  }
28157
28017
  });
@@ -28167,7 +28027,7 @@ __export(public_role_summons_exports, {
28167
28027
  });
28168
28028
  import { execFile as execFile3 } from "node:child_process";
28169
28029
  import { existsSync as existsSync9 } from "node:fs";
28170
- import { realpath as realpath6 } from "node:fs/promises";
28030
+ import { realpath as realpath5 } from "node:fs/promises";
28171
28031
  import { join as join31 } from "node:path";
28172
28032
  import { promisify as promisify3 } from "node:util";
28173
28033
  function createCapturingIo() {
@@ -28438,7 +28298,10 @@ async function summonPublicRole(options) {
28438
28298
  result = stepped.ok;
28439
28299
  }
28440
28300
  const stderr = captured?.stderrText();
28441
- const runDirectory = result.admitted?.runDirectory;
28301
+ const runDirectory = result.terminal !== void 0 && result.terminal.roleOutcome.role !== options.role && typeof result.terminal.runId === "string" ? await (await Promise.resolve().then(() => (init_run_lifecycle(), run_lifecycle_exports))).findRunDirectoryById(
28302
+ home,
28303
+ result.terminal.runId
28304
+ ) : result.admitted?.runDirectory;
28442
28305
  return {
28443
28306
  exitCode: result.exitCode,
28444
28307
  ...result.terminal === void 0 ? {} : { terminal: result.terminal },
@@ -28453,8 +28316,8 @@ function withReviewerLens(argv2, lens) {
28453
28316
  return [...argv2.slice(0, separator), "--lens", lens, ...argv2.slice(separator)];
28454
28317
  }
28455
28318
  async function resolveReviewerGitToplevel(projectRoot) {
28456
- const callerProjectRoot = await realpath6(projectRoot);
28457
- return await realpath6((await execFileAsync3(
28319
+ const callerProjectRoot = await realpath5(projectRoot);
28320
+ return await realpath5((await execFileAsync3(
28458
28321
  "git",
28459
28322
  ["rev-parse", "--show-toplevel"],
28460
28323
  { cwd: callerProjectRoot }
@@ -28642,8 +28505,10 @@ async function summonGateOfficer(options) {
28642
28505
  `countersign gate summon requires parent runId from sourceRunDirectory: ${options.sourceRunDirectory}`
28643
28506
  );
28644
28507
  }
28645
- const { readBoardTicketNumber: readBoardTicketNumber2 } = await Promise.resolve().then(() => (init_run_ticket_number(), run_ticket_number_exports));
28508
+ const { isSafePositiveTicketNumber: isSafePositiveTicketNumber2, readBoardTicketNumber: readBoardTicketNumber2 } = await Promise.resolve().then(() => (init_run_ticket_number(), run_ticket_number_exports));
28646
28509
  const parentTicket = await readBoardTicketNumber2(options.sourceRunDirectory);
28510
+ const submittedTicket = options.submission !== null && typeof options.submission === "object" && !Array.isArray(options.submission) ? options.submission.ticketNumber : void 0;
28511
+ const courtTicket = isSafePositiveTicketNumber2(submittedTicket) ? submittedTicket : parentTicket;
28647
28512
  const instruction = options.reask ?? gateReviewInstruction ?? "";
28648
28513
  return summonPublicRole({
28649
28514
  role: options.officer,
@@ -28651,7 +28516,7 @@ async function summonGateOfficer(options) {
28651
28516
  ...common,
28652
28517
  correlationId,
28653
28518
  parentRunPath: options.sourceRunDirectory,
28654
- ...parentTicket === void 0 ? {} : { boundTicketNumber: parentTicket }
28519
+ ...courtTicket === void 0 ? {} : { boundTicketNumber: courtTicket }
28655
28520
  });
28656
28521
  }
28657
28522
  return summonPublicRole({
@@ -28671,16 +28536,11 @@ var init_public_role_summons = __esm({
28671
28536
  });
28672
28537
 
28673
28538
  // src/public-cli/countersign-run.ts
28674
- var countersign_run_exports = {};
28675
- __export(countersign_run_exports, {
28676
- invokeCourtDiarist: () => invokeCourtDiarist,
28677
- runCountersignCourtDiaristStation: () => runCountersignCourtDiaristStation
28678
- });
28679
- function isRecord11(value) {
28539
+ function isRecord10(value) {
28680
28540
  return typeof value === "object" && value !== null && !Array.isArray(value);
28681
28541
  }
28682
28542
  function isEscalatePayload(payload) {
28683
- if (!isRecord11(payload)) return false;
28543
+ if (!isRecord10(payload)) return false;
28684
28544
  return payload.status === "escalate";
28685
28545
  }
28686
28546
  function courtDiaristPayloadRows(roleOutcome, submissions) {
@@ -28775,7 +28635,8 @@ async function invokeCourtDiarist(input, env, io) {
28775
28635
  kind: "escalate",
28776
28636
  diagnostic: courtDiaristEscalateDiagnostic(roleOutcome, submissions)
28777
28637
  },
28778
- ...result.admitted === void 0 ? {} : { admitted: result.admitted }
28638
+ ...result.admitted === void 0 ? {} : { admitted: result.admitted },
28639
+ ...result.terminal === void 0 ? {} : { terminal: result.terminal }
28779
28640
  };
28780
28641
  }
28781
28642
  if (result.exitCode !== 0) {
@@ -28809,7 +28670,7 @@ async function invokeCourtDiarist(input, env, io) {
28809
28670
  ...result.admitted === void 0 ? {} : { admitted: result.admitted }
28810
28671
  };
28811
28672
  }
28812
- async function runCountersignCourtDiaristStation(admitted, env, io) {
28673
+ async function runCountersignCourtDiaristStation(admitted, env, io, afterTicketNumber) {
28813
28674
  if (env.runCourtDiaristStation !== void 0) {
28814
28675
  await env.runCourtDiaristStation(admitted);
28815
28676
  return;
@@ -28826,7 +28687,8 @@ async function runCountersignCourtDiaristStation(admitted, env, io) {
28826
28687
  } else {
28827
28688
  refreshTickets = [admitted.ticketNumber];
28828
28689
  }
28829
- for (const ticketNumber of refreshTickets) {
28690
+ const completedIndex = afterTicketNumber === void 0 ? -1 : refreshTickets.indexOf(afterTicketNumber);
28691
+ for (const ticketNumber of refreshTickets.slice(completedIndex + 1)) {
28830
28692
  const outcome = await invokeCourtDiarist(
28831
28693
  {
28832
28694
  instruction: `\u6574\u7406 #${ticketNumber} \u7684\u672C\u6848\u4F9D\u636E\u3002`,
@@ -28839,14 +28701,17 @@ async function runCountersignCourtDiaristStation(admitted, env, io) {
28839
28701
  env,
28840
28702
  io
28841
28703
  );
28842
- if (outcome.identity.kind === "escalate") {
28843
- throw new StationChildExhaustedError(outcome.identity.diagnostic);
28844
- }
28845
28704
  if (outcome.failedWithoutEscalate !== void 0) {
28846
28705
  throw new StationChildExhaustedError(
28847
28706
  outcome.failedWithoutEscalate.diagnostic
28848
28707
  );
28849
28708
  }
28709
+ if (outcome.identity.kind === "escalate" && outcome.terminal !== void 0) {
28710
+ return {
28711
+ terminal: outcome.terminal,
28712
+ ...outcome.admitted === void 0 ? {} : { childRunId: outcome.admitted.runId }
28713
+ };
28714
+ }
28850
28715
  }
28851
28716
  }
28852
28717
  var init_countersign_run = __esm({
@@ -28863,6 +28728,7 @@ var init_countersign_run = __esm({
28863
28728
  var instruction_seat_run_exports = {};
28864
28729
  __export(instruction_seat_run_exports, {
28865
28730
  buildInstructionSeatTurnRequest: () => buildInstructionSeatTurnRequest,
28731
+ continueParentAfterChild: () => continueParentAfterChild,
28866
28732
  runPublicInstructionSeat: () => runPublicInstructionSeat,
28867
28733
  runPublicInstructionSeatResume: () => runPublicInstructionSeatResume
28868
28734
  });
@@ -28877,7 +28743,7 @@ function roleRecord(role) {
28877
28743
  function buildInstructionSeatTurnRequest(admitted, options) {
28878
28744
  return projectRoleTurnRequest(
28879
28745
  admitted,
28880
- admittedSeatTurnDetails(admitted, options.packageRoot),
28746
+ admittedSeatTurnDetails(admitted, options.home, options.host),
28881
28747
  options
28882
28748
  );
28883
28749
  }
@@ -28910,11 +28776,11 @@ async function bindAndRelocateDiarist(admitted, authority, lease) {
28910
28776
  }
28911
28777
  await relocateAdmittedRunToTicket(admitted, authority, lease);
28912
28778
  }
28913
- function seatAdapters(admitted, env, material) {
28779
+ function seatAdapters(admitted, env) {
28914
28780
  const record4 = roleRecord(admitted.role);
28915
28781
  const present = "presentSettled" in record4 ? record4.presentSettled : "default";
28916
28782
  return {
28917
- trySettle: (seat, authority, scope) => trySettlePublicSeat(seat, authority, scope, material, env.packageRoot),
28783
+ trySettle: (seat, authority, scope) => trySettlePublicSeat(seat, authority, scope),
28918
28784
  ...present === "always" ? { shouldPresentSettled: () => true } : {},
28919
28785
  ...present === "typed" ? { shouldPresentSettled: (terminal) => isLawfulTypedTerminalOutcome(terminal.roleOutcome) } : {},
28920
28786
  ...infraFailure(admitted.role),
@@ -28966,23 +28832,8 @@ async function withAuditorSoulEnv(options) {
28966
28832
  }
28967
28833
  async function dispatchAdmitted(admitted, env, io) {
28968
28834
  const record4 = roleRecord(admitted.role);
28969
- let material;
28970
- const skill = packagedSettleSkill(admitted);
28971
- if (skill !== void 0) {
28972
- try {
28973
- material = await loadPackagedMethodSkillMaterial(env.packageRoot, skill);
28974
- } catch (error) {
28975
- const knownCause = packagedMethodLoadFailureCause(admitted.role);
28976
- return await presentControlledFailure2(admitted, {
28977
- timedOut: false,
28978
- code: null,
28979
- stderr: "",
28980
- thrown: error,
28981
- ...knownCause === void 0 ? {} : { knownCause }
28982
- }, seatAdapters(admitted, env), env.principalAuthority, io);
28983
- }
28984
- }
28985
- const adapters = seatAdapters(admitted, env, material);
28835
+ await warnMissingMethodSkills(env.home, env.host, admitted.role, requiredMethodSkills(admitted), io.stdout);
28836
+ const adapters = seatAdapters(admitted, env);
28986
28837
  const execute = async (activeEnv) => {
28987
28838
  const auto = "inCallAutoResume" in record4 && record4.inCallAutoResume === true;
28988
28839
  if (auto) {
@@ -29088,7 +28939,7 @@ async function runCountersignBody(parsed, env, io) {
29088
28939
  projectRoot: resolve10(parsed.project ?? env.cwd),
29089
28940
  role: "countersign",
29090
28941
  parentRunPath: gateParentRunPath,
29091
- ...env.boundTicketNumber === void 0 ? {} : { ticketNumber: env.boundTicketNumber },
28942
+ ...isSafePositiveTicketNumber(env.boundTicketNumber) ? { ticketNumber: env.boundTicketNumber } : {},
29092
28943
  freshSummons: env.freshSummons,
29093
28944
  summons: {
29094
28945
  sourceRunPath: gateParentRunPath,
@@ -29125,14 +28976,16 @@ async function runCountersignBody(parsed, env, io) {
29125
28976
  let typedTicket;
29126
28977
  let typedCourtTicketNumbers;
29127
28978
  let identityDiaristRan = false;
29128
- let unboundDiaristRunId;
29129
- if (env.runCourtDiaristStation === void 0) {
28979
+ let childDiaristRunId;
28980
+ let pausedDiaristTerminal;
28981
+ if (gateParentRunPath === void 0 && env.runCourtDiaristStation === void 0) {
29130
28982
  let outcome;
29131
28983
  try {
29132
28984
  outcome = await invokeCourtDiarist({
29133
28985
  instruction: parsed.instruction ?? "",
29134
28986
  projectRoot: admitted.projectRoot,
29135
28987
  failureLabel: "unbound summons",
28988
+ correlationId: admitted.runId,
29136
28989
  ...env.boundTicketNumber === void 0 ? {} : { boundTicketNumber: env.boundTicketNumber }
29137
28990
  }, env, io);
29138
28991
  } catch (error) {
@@ -29148,15 +29001,16 @@ async function runCountersignBody(parsed, env, io) {
29148
29001
  }, seatAdapters(admitted, env), env.principalAuthority, io);
29149
29002
  }
29150
29003
  identityDiaristRan = true;
29004
+ if (outcome.identity.kind === "escalate") pausedDiaristTerminal = outcome.terminal;
29151
29005
  if (outcome.admitted?.runDirectory.includes(`${sep5}unbound${sep5}runs${sep5}`)) {
29152
- unboundDiaristRunId = outcome.admitted.runId;
29006
+ childDiaristRunId = outcome.admitted.runId;
29153
29007
  }
29154
- if (outcome.identity.kind === "escalate" || outcome.failedWithoutEscalate !== void 0) {
29155
- const diagnostic = outcome.identity.kind === "escalate" ? outcome.identity.diagnostic : outcome.failedWithoutEscalate?.diagnostic ?? "";
29008
+ if (outcome.failedWithoutEscalate !== void 0) {
29009
+ const diagnostic = outcome.failedWithoutEscalate.diagnostic;
29156
29010
  await materializeAdmission(
29157
29011
  isSafePositiveTicketNumber(env.boundTicketNumber) ? env.boundTicketNumber : void 0
29158
29012
  );
29159
- if (unboundDiaristRunId !== void 0) await recordChildDiaristRun(admitted, unboundDiaristRunId);
29013
+ if (childDiaristRunId !== void 0) await recordChildDiaristRun(admitted, childDiaristRunId);
29160
29014
  await markRunAdmitted(admitted, env.principalAuthority);
29161
29015
  return await presentControlledFailure2(admitted, {
29162
29016
  timedOut: false,
@@ -29166,16 +29020,18 @@ async function runCountersignBody(parsed, env, io) {
29166
29020
  }, seatAdapters(admitted, env), env.principalAuthority, io);
29167
29021
  }
29168
29022
  if (outcome.identity.kind === "ticket") {
29169
- typedTicket = isSafePositiveTicketNumber(env.boundTicketNumber) ? env.boundTicketNumber : outcome.identity.ticketNumber;
29023
+ typedTicket = outcome.identity.ticketNumber;
29170
29024
  typedCourtTicketNumbers = outcome.identity.courtTicketNumbers;
29171
- } else if (isSafePositiveTicketNumber(env.boundTicketNumber)) {
29172
- typedTicket = env.boundTicketNumber;
29173
29025
  }
29174
29026
  }
29175
29027
  await materializeAdmission(typedTicket);
29176
29028
  await markRunAdmitted(admitted, env.principalAuthority);
29177
- if (unboundDiaristRunId !== void 0) {
29178
- await recordChildDiaristRun(admitted, unboundDiaristRunId);
29029
+ if (childDiaristRunId !== void 0) {
29030
+ await recordChildDiaristRun(admitted, childDiaristRunId);
29031
+ }
29032
+ if (pausedDiaristTerminal !== void 0) {
29033
+ io.stdout(formatTerminalResult(pausedDiaristTerminal));
29034
+ return { exitCode: 0, admitted, terminal: pausedDiaristTerminal };
29179
29035
  }
29180
29036
  if (gateParentRunPath !== void 0) {
29181
29037
  await persistAdmittedSourceRunPath(admitted, gateParentRunPath);
@@ -29225,7 +29081,11 @@ async function runCountersignBody(parsed, env, io) {
29225
29081
  beforeDispatch: async (admittedSeat, lease) => {
29226
29082
  if (!packagedAdmitsCountersign(admittedSeat.role)) return;
29227
29083
  if (!identityDiaristRan || typedTicket !== void 0) {
29228
- await runCountersignCourtDiaristStation(admittedSeat, env, io);
29084
+ const refresh = await runCountersignCourtDiaristStation(admittedSeat, env, io);
29085
+ if (refresh !== void 0) {
29086
+ io.stdout(formatTerminalResult(refresh.terminal));
29087
+ return refresh.terminal;
29088
+ }
29229
29089
  }
29230
29090
  await relocateAdmittedRunToTicket(admittedSeat, env.principalAuthority, lease);
29231
29091
  Object.assign(turnRequest, buildInstructionSeatTurnRequest(admittedSeat, turnProjection));
@@ -29302,7 +29162,6 @@ async function runPublicInstructionSeat(argv2, env, io, role, parseArgv2) {
29302
29162
  projectRoot,
29303
29163
  role,
29304
29164
  parentRunPath: sourceDirectory,
29305
- ...auditorTicket === void 0 ? {} : { ticketNumber: auditorTicket },
29306
29165
  freshSummons: env.freshSummons,
29307
29166
  summons,
29308
29167
  resume: (runId, materials) => runPublicInstructionSeatResume(
@@ -29328,7 +29187,6 @@ async function runPublicInstructionSeat(argv2, env, io, role, parseArgv2) {
29328
29187
  projectRoot,
29329
29188
  role,
29330
29189
  parentRunPath,
29331
- ...env.boundTicketNumber === void 0 ? {} : { ticketNumber: env.boundTicketNumber },
29332
29190
  freshSummons: env.freshSummons,
29333
29191
  summons,
29334
29192
  resume: (runId, materials) => runPublicInstructionSeatResume(
@@ -29356,7 +29214,6 @@ async function runPublicInstructionSeat(argv2, env, io, role, parseArgv2) {
29356
29214
  throw error;
29357
29215
  }
29358
29216
  const resumeInstruction = env.reviewReask ?? env.gateReviewInstruction;
29359
- const knownTicket = await readBoardTicketNumber(source.runDirectory) ?? env.boundTicketNumber;
29360
29217
  const summons = {
29361
29218
  sourceRunPath: source.runDirectory,
29362
29219
  sourceRun: source,
@@ -29367,7 +29224,6 @@ async function runPublicInstructionSeat(argv2, env, io, role, parseArgv2) {
29367
29224
  projectRoot,
29368
29225
  role,
29369
29226
  parentRunPath: source.runDirectory,
29370
- ...knownTicket === void 0 ? {} : { ticketNumber: knownTicket },
29371
29227
  freshSummons: env.freshSummons,
29372
29228
  summons,
29373
29229
  resume: (runId, materials) => runPublicInstructionSeatResume(
@@ -29404,50 +29260,38 @@ async function runPublicInstructionSeat(argv2, env, io, role, parseArgv2) {
29404
29260
  }
29405
29261
  const runAdmitted = async () => {
29406
29262
  await markRunAdmitted(admitted, env.principalAuthority);
29407
- if (record4.sameParent === "court-diarist") {
29408
- const { invokeCourtDiarist: invokeCourtDiarist2 } = await Promise.resolve().then(() => (init_countersign_run(), countersign_run_exports));
29409
- const outcome = await invokeCourtDiarist2({
29410
- instruction: parsed.instruction ?? "",
29411
- projectRoot: admitted.projectRoot,
29412
- failureLabel: "secretariat unbound summons",
29413
- attachmentPaths: admitted.attachments.map((attachment) => attachment.frozenPath),
29414
- correlationId: admitted.runId
29415
- }, {
29416
- cwd: env.cwd,
29417
- home: env.home,
29418
- agentDir: env.agentDir,
29419
- packageRoot: env.packageRoot,
29420
- ...env.credentials === void 0 ? {} : { credentials: env.credentials },
29421
- ...env.signal === void 0 ? {} : { signal: env.signal },
29422
- ...env.hostAdapters === void 0 ? {} : { hostAdapters: env.hostAdapters }
29423
- }, io);
29263
+ if (role === "secretariat") {
29264
+ let outcome;
29265
+ try {
29266
+ outcome = await invokeCourtDiarist({
29267
+ instruction: parsed.instruction ?? "",
29268
+ projectRoot: admitted.projectRoot,
29269
+ failureLabel: "secretariat unbound summons",
29270
+ attachmentPaths: admitted.attachments.map((attachment) => attachment.frozenPath),
29271
+ correlationId: admitted.runId
29272
+ }, env, io);
29273
+ } catch (error) {
29274
+ return await presentControlledFailure2(admitted, {
29275
+ timedOut: false,
29276
+ code: null,
29277
+ stderr: "",
29278
+ thrown: error
29279
+ }, seatAdapters(admitted, env), env.principalAuthority, io);
29280
+ }
29424
29281
  if (outcome.admitted?.runDirectory.includes(`${sep5}unbound${sep5}runs${sep5}`)) {
29425
29282
  await recordChildDiaristRun(admitted, outcome.admitted.runId);
29426
29283
  }
29427
- if (outcome.identity.kind === "escalate" || outcome.failedWithoutEscalate !== void 0) {
29428
- const diagnostic = outcome.identity.kind === "escalate" ? outcome.identity.diagnostic : outcome.failedWithoutEscalate?.diagnostic ?? "";
29284
+ if (outcome.failedWithoutEscalate !== void 0) {
29429
29285
  return await presentControlledFailure2(admitted, {
29430
29286
  timedOut: false,
29431
29287
  code: null,
29432
29288
  stderr: "",
29433
- thrown: new Error(diagnostic)
29289
+ thrown: new Error(outcome.failedWithoutEscalate.diagnostic)
29434
29290
  }, seatAdapters(admitted, env), env.principalAuthority, io);
29435
29291
  }
29436
- if (outcome.identity.kind === "ticket") {
29437
- try {
29438
- if (outcome.admitted === void 0) throw new Error("court diarist ticket has no admitted run");
29439
- await bindAdmittedTicketNumber(outcome.admitted, outcome.identity.ticketNumber);
29440
- await relocateAdmittedRunToTicket(outcome.admitted, env.principalAuthority);
29441
- await bindAdmittedTicketNumber(admitted, outcome.identity.ticketNumber);
29442
- await relocateAdmittedRunToTicket(admitted, env.principalAuthority);
29443
- } catch (error) {
29444
- return await presentControlledFailure2(admitted, {
29445
- timedOut: false,
29446
- code: null,
29447
- stderr: "",
29448
- thrown: error
29449
- }, seatAdapters(admitted, env), env.principalAuthority, io);
29450
- }
29292
+ if (outcome.identity.kind === "escalate" && outcome.terminal !== void 0) {
29293
+ io.stdout(formatTerminalResult(outcome.terminal));
29294
+ return { exitCode: 0, admitted, terminal: outcome.terminal };
29451
29295
  }
29452
29296
  }
29453
29297
  return dispatchAdmitted(admitted, env, io);
@@ -29492,32 +29336,34 @@ async function runPublicInstructionSeatResume(request, env, io) {
29492
29336
  adapters: {
29493
29337
  trySettle: async () => void 0
29494
29338
  },
29495
- afterAdmittedLoad: (admitted) => {
29496
- const skill = packagedSettleSkill(admitted);
29497
- if (skill === void 0) {
29498
- return Promise.resolve({ kind: "continue", adapters: seatAdapters(admitted, env) });
29499
- }
29500
- const knownCause = packagedMethodLoadFailureCause(admitted.role);
29501
- return resolveResumeMethodMaterialAdapters({
29502
- admitted,
29503
- authority: env.principalAuthority,
29504
- io,
29505
- loadMaterial: () => loadPackagedMethodSkillMaterial(env.packageRoot, skill),
29506
- adaptersWith: (material) => seatAdapters(admitted, env, material),
29507
- emptyAdapters: seatAdapters(admitted, env),
29508
- ...knownCause === void 0 ? {} : { knownCause }
29509
- });
29339
+ afterAdmittedLoad: async (admitted) => {
29340
+ await warnMissingMethodSkills(env.home, env.host, admitted.role, requiredMethodSkills(admitted), io.stdout);
29341
+ return { kind: "continue", adapters: seatAdapters(admitted, env) };
29510
29342
  },
29511
29343
  ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
29512
29344
  });
29513
29345
  }
29346
+ async function continueParentAfterChild(parentRunId, child, env, io) {
29347
+ const loaded = await loadResumablePublicRole(env.home, parentRunId, env.principalAuthority, true);
29348
+ if (loaded.run.state !== "admitted") {
29349
+ return runPublicInstructionSeatResume({ runId: parentRunId }, env, io);
29350
+ }
29351
+ const admitted = loaded.admitted;
29352
+ if (admitted.role === "countersign" && admitted.ticketNumber !== void 0) {
29353
+ const refresh = await runCountersignCourtDiaristStation(admitted, env, io, child.ticketNumber);
29354
+ if (refresh !== void 0) {
29355
+ io.stdout(formatTerminalResult(refresh.terminal));
29356
+ return { exitCode: 0, admitted, terminal: refresh.terminal };
29357
+ }
29358
+ }
29359
+ return dispatchAdmitted(admitted, env, io);
29360
+ }
29514
29361
  var init_instruction_seat_run = __esm({
29515
29362
  "src/public-cli/instruction-seat-run.ts"() {
29516
29363
  "use strict";
29517
29364
  init_run_ticket_number();
29518
29365
  init_notary_source_run();
29519
29366
  init_engine_material();
29520
- init_method_skill();
29521
29367
  init_packaged_role_registry();
29522
29368
  init_auditor_soul();
29523
29369
  init_cli_errors();
@@ -29526,6 +29372,7 @@ var init_instruction_seat_run = __esm({
29526
29372
  init_run_lifecycle();
29527
29373
  init_seat_ticket_binding();
29528
29374
  init_settlement();
29375
+ init_machine_method_skills();
29529
29376
  init_terminal();
29530
29377
  init_turn_request();
29531
29378
  init_countersign_run();
@@ -29533,13 +29380,13 @@ var init_instruction_seat_run = __esm({
29533
29380
  });
29534
29381
 
29535
29382
  // src/analyst-book-key.ts
29536
- import { statSync as statSync2 } from "node:fs";
29383
+ import { statSync as statSync3 } from "node:fs";
29537
29384
  import { isAbsolute as isAbsolute9 } from "node:path";
29538
29385
  function resolveAnalystBookKey(projectRoot) {
29539
29386
  const identity = physicalPathIdentity(projectRoot);
29540
29387
  let stats;
29541
29388
  try {
29542
- stats = statSync2(identity);
29389
+ stats = statSync3(identity);
29543
29390
  } catch (error) {
29544
29391
  const code = errnoCode(error);
29545
29392
  if (code === "ENOENT" || code === "ENOTDIR") return `root:${identity}`;
@@ -29588,7 +29435,7 @@ var init_atomic_write = __esm({
29588
29435
  });
29589
29436
 
29590
29437
  // src/analyst-index.ts
29591
- import { open as open3, readFile as readFile19, unlink as unlink5 } from "node:fs/promises";
29438
+ import { open as open3, readFile as readFile18, unlink as unlink5 } from "node:fs/promises";
29592
29439
  import { dirname as dirname18, join as join33 } from "node:path";
29593
29440
  function sleep(ms) {
29594
29441
  return new Promise((resolve12) => {
@@ -29716,7 +29563,7 @@ async function readAnalystLibraryIndexPage(ledgerHome) {
29716
29563
  const path = analystLibraryIndexPath(ledgerHome);
29717
29564
  let raw;
29718
29565
  try {
29719
- raw = await readFile19(path, "utf8");
29566
+ raw = await readFile18(path, "utf8");
29720
29567
  } catch (error) {
29721
29568
  if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
29722
29569
  return void 0;
@@ -29920,15 +29767,15 @@ var init_analyst_cohort = __esm({
29920
29767
  });
29921
29768
 
29922
29769
  // src/analyst-ledger.ts
29923
- import { readdir as readdir8, readFile as readFile20 } from "node:fs/promises";
29924
- import { basename as basename9, join as join34 } from "node:path";
29770
+ import { readdir as readdir8, readFile as readFile19 } from "node:fs/promises";
29771
+ import { basename as basename8, join as join34 } from "node:path";
29925
29772
  function isMissingPathError6(error) {
29926
29773
  return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
29927
29774
  }
29928
29775
  function errorText3(error) {
29929
29776
  return error instanceof Error ? error.message : String(error);
29930
29777
  }
29931
- function isRecord12(value) {
29778
+ function isRecord11(value) {
29932
29779
  return typeof value === "object" && value !== null && !Array.isArray(value);
29933
29780
  }
29934
29781
  async function readExistingRunLifecycleState(runDirectory) {
@@ -29979,13 +29826,13 @@ async function listLedgerBookNames(booksRoot) {
29979
29826
  async function readInvocationScopeFields(runDirectory) {
29980
29827
  let raw;
29981
29828
  try {
29982
- raw = await readFile20(join34(runDirectory, "invocation.json"), "utf8");
29829
+ raw = await readFile19(join34(runDirectory, "invocation.json"), "utf8");
29983
29830
  } catch (error) {
29984
29831
  if (isMissingPathError6(error)) return void 0;
29985
29832
  throw error;
29986
29833
  }
29987
29834
  const parsed = JSON.parse(raw);
29988
- if (!isRecord12(parsed)) return void 0;
29835
+ if (!isRecord11(parsed)) return void 0;
29989
29836
  if (typeof parsed.projectRoot !== "string" || parsed.projectRoot.trim() === "") {
29990
29837
  return void 0;
29991
29838
  }
@@ -30012,9 +29859,9 @@ function decideIssueScope(input) {
30012
29859
  }
30013
29860
  async function resolveSessionFile(runDirectory) {
30014
29861
  try {
30015
- const raw = await readFile20(join34(runDirectory, "invocation.json"), "utf8");
29862
+ const raw = await readFile19(join34(runDirectory, "invocation.json"), "utf8");
30016
29863
  const parsed = JSON.parse(raw);
30017
- if (isRecord12(parsed) && typeof parsed.sessionFile === "string" && parsed.sessionFile.trim() !== "") {
29864
+ if (isRecord11(parsed) && typeof parsed.sessionFile === "string" && parsed.sessionFile.trim() !== "") {
30018
29865
  return parsed.sessionFile;
30019
29866
  }
30020
29867
  } catch (error) {
@@ -30291,7 +30138,7 @@ async function scanAnalystIssueRuns(input) {
30291
30138
  throw error;
30292
30139
  }
30293
30140
  for (const runDirectory of runDirectories) {
30294
- const runName = basename9(runDirectory);
30141
+ const runName = basename8(runDirectory);
30295
30142
  const parsed = parseRunDirectoryName2(runName);
30296
30143
  if (parsed === void 0) continue;
30297
30144
  let scopeFields;
@@ -30352,7 +30199,7 @@ var init_analyst_ledger = __esm({
30352
30199
  });
30353
30200
 
30354
30201
  // src/analyst-metric-families/acceptance-success-rework.ts
30355
- function isRecord13(value) {
30202
+ function isRecord12(value) {
30356
30203
  return typeof value === "object" && value !== null && !Array.isArray(value);
30357
30204
  }
30358
30205
  function wallMsFromSpan(span) {
@@ -30361,21 +30208,21 @@ function wallMsFromSpan(span) {
30361
30208
  function findCollectorGroups(body) {
30362
30209
  if (Array.isArray(body.groups)) return body.groups;
30363
30210
  const receipt = body.receipt;
30364
- if (isRecord13(receipt) && Array.isArray(receipt.groups)) return receipt.groups;
30211
+ if (isRecord12(receipt) && Array.isArray(receipt.groups)) return receipt.groups;
30365
30212
  const outcome = body.outcome;
30366
- if (isRecord13(outcome)) {
30213
+ if (isRecord12(outcome)) {
30367
30214
  const facts = outcome.decisiveFacts;
30368
- if (isRecord13(facts) && Array.isArray(facts.groups)) return facts.groups;
30215
+ if (isRecord12(facts) && Array.isArray(facts.groups)) return facts.groups;
30369
30216
  }
30370
30217
  return void 0;
30371
30218
  }
30372
30219
  function extractStatus(body) {
30373
30220
  const outcome = body.outcome;
30374
- if (isRecord13(outcome) && typeof outcome.status === "string" && outcome.status.trim() !== "") {
30221
+ if (isRecord12(outcome) && typeof outcome.status === "string" && outcome.status.trim() !== "") {
30375
30222
  return outcome.status;
30376
30223
  }
30377
30224
  const receipt = body.receipt;
30378
- if (isRecord13(receipt) && typeof receipt.status === "string" && receipt.status.trim() !== "") {
30225
+ if (isRecord12(receipt) && typeof receipt.status === "string" && receipt.status.trim() !== "") {
30379
30226
  return receipt.status;
30380
30227
  }
30381
30228
  if (typeof body.status === "string" && body.status.trim() !== "") {
@@ -31001,15 +30848,15 @@ var init_leg_wall_clock = __esm({
31001
30848
  });
31002
30849
 
31003
30850
  // src/analyst-metric-families/round-timeline.ts
31004
- function isRecord14(value) {
30851
+ function isRecord13(value) {
31005
30852
  return typeof value === "object" && value !== null && !Array.isArray(value);
31006
30853
  }
31007
30854
  function wallMsFromSpan2(startedAt, endedAt) {
31008
30855
  return Date.parse(endedAt) - Date.parse(startedAt);
31009
30856
  }
31010
30857
  function readClassCount(body) {
31011
- if (!isRecord14(body.outcome)) return void 0;
31012
- if (!isRecord14(body.outcome.decisiveFacts)) return void 0;
30858
+ if (!isRecord13(body.outcome)) return void 0;
30859
+ if (!isRecord13(body.outcome.decisiveFacts)) return void 0;
31013
30860
  const classCount = body.outcome.decisiveFacts.classCount;
31014
30861
  if (typeof classCount !== "number" || !Number.isFinite(classCount)) {
31015
30862
  return void 0;
@@ -31153,7 +31000,7 @@ var init_analyst_metric_family = __esm({
31153
31000
  });
31154
31001
 
31155
31002
  // src/analyst-page.ts
31156
- import { createHash as createHash5 } from "node:crypto";
31003
+ import { createHash as createHash4 } from "node:crypto";
31157
31004
  import { dirname as dirname19, join as join35 } from "node:path";
31158
31005
  function analystIssuePageKey(address) {
31159
31006
  const parts = ["book", address.bookKey];
@@ -31162,7 +31009,7 @@ function analystIssuePageKey(address) {
31162
31009
  } else if (address.scopeRootIdentity !== void 0) {
31163
31010
  parts.push("root", physicalPathIdentity(address.scopeRootIdentity));
31164
31011
  }
31165
- return createHash5("sha256").update(parts.join("\0")).digest("hex").slice(0, 32);
31012
+ return createHash4("sha256").update(parts.join("\0")).digest("hex").slice(0, 32);
31166
31013
  }
31167
31014
  function analystIssuePagePath(ledgerHome, address) {
31168
31015
  return join35(ledgerHome, "analyst", "issues", `${analystIssuePageKey(address)}.json`);
@@ -31301,7 +31148,7 @@ var init_analyst_page = __esm({
31301
31148
  });
31302
31149
 
31303
31150
  // src/analyst-entry.ts
31304
- import { readFile as readFile21 } from "node:fs/promises";
31151
+ import { readFile as readFile20 } from "node:fs/promises";
31305
31152
  function isMissingPathError7(error) {
31306
31153
  return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
31307
31154
  }
@@ -31331,7 +31178,7 @@ async function readOrComputeAnalystIssuePage(input, options) {
31331
31178
  ...issueNumber === void 0 && input.bookKey === void 0 ? { scopeRootIdentity: projectRoot } : {}
31332
31179
  });
31333
31180
  try {
31334
- const raw = await readFile21(pagePath, "utf8");
31181
+ const raw = await readFile20(pagePath, "utf8");
31335
31182
  const page = JSON.parse(raw);
31336
31183
  if (cachedPageMatchesRequestedScope(page, { bookKey, ...input })) {
31337
31184
  const ghostScan = await scanAnalystIssueRuns({
@@ -31432,7 +31279,7 @@ async function runAnalystModelGroupsMode(input, home) {
31432
31279
  scopeRootIdentity: projectRoot
31433
31280
  });
31434
31281
  try {
31435
- const raw = await readFile21(pagePath, "utf8");
31282
+ const raw = await readFile20(pagePath, "utf8");
31436
31283
  JSON.parse(raw);
31437
31284
  } catch (error) {
31438
31285
  if (!isMissingPathError7(error)) {
@@ -31531,7 +31378,7 @@ var init_analyst_entry = __esm({
31531
31378
  });
31532
31379
 
31533
31380
  // src/public-cli/analyst-run.ts
31534
- import { readFile as readFile22 } from "node:fs/promises";
31381
+ import { readFile as readFile21 } from "node:fs/promises";
31535
31382
  import { isAbsolute as isAbsolute10, resolve as resolve11 } from "node:path";
31536
31383
  function resolveAnalystIssueBookKeyFromCwd(cwd = process.cwd()) {
31537
31384
  try {
@@ -31584,7 +31431,7 @@ async function buildAnalystSweepModeInputFromAttachmentPaths(attachmentPaths) {
31584
31431
  const absolute = isAbsolute10(sourcePath) ? sourcePath : resolve11(sourcePath);
31585
31432
  let bytes;
31586
31433
  try {
31587
- bytes = await readFile22(absolute);
31434
+ bytes = await readFile21(absolute);
31588
31435
  } catch (error) {
31589
31436
  throw new CliUsageError(
31590
31437
  `analyst sweep attachment is not a readable regular file: ${sourcePath}`,
@@ -31704,7 +31551,7 @@ __export(cli_exports, {
31704
31551
  resolveInternalRoleEntrypoint: () => resolveInternalRoleEntrypoint,
31705
31552
  runAkRole: () => runAkRole
31706
31553
  });
31707
- import { realpath as realpath7 } from "node:fs/promises";
31554
+ import { realpath as realpath6 } from "node:fs/promises";
31708
31555
  import { join as join36 } from "node:path";
31709
31556
  function publicSeatArgv(owner) {
31710
31557
  return {
@@ -32379,7 +32226,7 @@ async function runAkRole(argv2, env) {
32379
32226
  try {
32380
32227
  env = {
32381
32228
  ...env,
32382
- packageRoot: await realpath7(env.packageRoot),
32229
+ packageRoot: await realpath6(env.packageRoot),
32383
32230
  principalAuthority: env.principalAuthority ?? piDurablePrincipalAuthority
32384
32231
  };
32385
32232
  let parsed = parseArgv(argv2);
@@ -32428,6 +32275,10 @@ async function runAkRole(argv2, env) {
32428
32275
  exitCode: await runConfigCommand(parsed.args, home, env.packageRoot, io)
32429
32276
  };
32430
32277
  }
32278
+ if (parsed.command === "setup") {
32279
+ if (parsed.args.length !== 0) throw new CliUsageError("setup takes no arguments");
32280
+ return { exitCode: await runMachineSkillSetup(home, io.stdout) };
32281
+ }
32431
32282
  if (parsed.command === "new") {
32432
32283
  const role = parsed.args[0];
32433
32284
  if (role === void 0) {
@@ -32470,7 +32321,24 @@ async function runAkRole(argv2, env) {
32470
32321
  }),
32471
32322
  io
32472
32323
  );
32473
- return cliResultFromRoleRun(result);
32324
+ let current = result;
32325
+ while (current.exitCode === 0 && current.admitted?.correlationId !== void 0 && current.terminal?.roleOutcome.kind === "accepted" && !courtDiaristEscalated(current.terminal.roleOutcome)) {
32326
+ const parentRunId = current.admitted.correlationId;
32327
+ const parentRole = await peekRoleRunRole(home, parentRunId);
32328
+ if (parentRole === void 0) break;
32329
+ const parentSeat = resolveEffectiveSeat(config, parentRole, credentials, invocationFromParsed(parsed));
32330
+ const parentEnv = createRoleEnvironment(env, {
32331
+ role: parentRole,
32332
+ home,
32333
+ agentDir,
32334
+ cwd,
32335
+ credentials,
32336
+ seat: parentSeat,
32337
+ config
32338
+ });
32339
+ current = await continueParentAfterChild(parentRunId, current.admitted, parentEnv, io);
32340
+ }
32341
+ return cliResultFromRoleRun(current);
32474
32342
  }
32475
32343
  if (parsed.command !== void 0 && isPublicCliSupportCommand(parsed.command)) {
32476
32344
  throw new CliUsageError(`unhandled support command: ${parsed.command}`);
@@ -32534,11 +32402,13 @@ var init_cli = __esm({
32534
32402
  init_packaged_role_registry();
32535
32403
  init_registry2();
32536
32404
  init_cli_errors();
32405
+ init_machine_method_skills();
32537
32406
  init_role_turn_host();
32538
32407
  init_role_turn_host_resolution();
32539
32408
  init_invocation();
32540
32409
  init_option_definitions();
32541
32410
  init_instruction_seat_run();
32411
+ init_countersign_run();
32542
32412
  init_analyst_run();
32543
32413
  init_run_lifecycle();
32544
32414
  init_registry2();