@akagilnc/pi-workflow-roles 0.1.4444 → 0.1.4503

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 (50) hide show
  1. package/README.md +2 -0
  2. package/README.zh-CN.md +2 -0
  3. package/dist/acp-host/description.js +2 -3
  4. package/dist/acp-host/production-host.js +512 -288
  5. package/dist/auditor-soul.js +8 -1
  6. package/dist/headless-host/description.js +3 -3
  7. package/dist/headless-host/production-host.js +519 -257
  8. package/dist/host-descriptions.js +3 -18
  9. package/dist/method-host-plugin/.claude-plugin/plugin.json +5 -0
  10. package/dist/method-host-plugin/skills/ak-cross-m-review/CONTEXT.md +48 -0
  11. package/dist/method-host-plugin/skills/ak-cross-m-review/LICENSE +21 -0
  12. package/dist/method-host-plugin/skills/ak-cross-m-review/SKILL.md +170 -0
  13. package/dist/method-host-plugin/skills/ak-cross-m-review/prompts/cmr-completeness.md +118 -0
  14. package/dist/method-host-plugin/skills/ak-cross-m-review/prompts/cmr-reviewer.md +128 -0
  15. package/dist/method-host-plugin/skills/ak-cross-m-review/provenance.json +41 -0
  16. package/dist/method-host-plugin/skills/diagnosing-bugs/SKILL.md +134 -0
  17. package/dist/method-host-plugin/skills/diagnosing-bugs/agents/openai.yaml +3 -0
  18. package/dist/method-host-plugin/skills/diagnosing-bugs/provenance.json +31 -0
  19. package/dist/method-host-plugin/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +41 -0
  20. package/dist/method-host-plugin/skills/resolving-merge-conflicts/SKILL.md +14 -0
  21. package/dist/method-host-plugin/skills/resolving-merge-conflicts/agents/openai.yaml +3 -0
  22. package/dist/method-host-plugin/skills/resolving-merge-conflicts/provenance.json +26 -0
  23. package/dist/method-host-plugin/skills/tdd/SKILL.md +38 -0
  24. package/dist/method-host-plugin/skills/tdd/agents/openai.yaml +3 -0
  25. package/dist/method-host-plugin/skills/tdd/mocking.md +59 -0
  26. package/dist/method-host-plugin/skills/tdd/provenance.json +36 -0
  27. package/dist/method-host-plugin/skills/tdd/tests.md +77 -0
  28. package/dist/public-cli/countersign-run.js +214 -155
  29. package/dist/public-cli/diarist-run.js +4 -1
  30. package/dist/public-cli/invocation.js +129 -21
  31. package/dist/public-cli/main.js +386 -202
  32. package/dist/session-opening-materials.js +17 -5
  33. package/extensions/role-runtime.ts +16 -6
  34. package/package.json +1 -1
  35. package/resources/method-host-plugin/.claude-plugin/plugin.json +5 -0
  36. package/scripts/build-package.mjs +6 -1
  37. package/src/acp-host/description.ts +2 -4
  38. package/src/acp-host/production-host.ts +0 -1
  39. package/src/auditor-soul.ts +10 -1
  40. package/src/headless-host/description.ts +4 -3
  41. package/src/headless-host/role-turn-host.ts +27 -4
  42. package/src/host-descriptions.ts +3 -23
  43. package/src/host-native-method.ts +67 -0
  44. package/src/public-cli/countersign-run.ts +326 -218
  45. package/src/public-cli/diarist-run.ts +4 -0
  46. package/src/public-cli/invocation.ts +205 -23
  47. package/src/role-envelope.ts +17 -47
  48. package/src/role-runtime-dependencies.ts +17 -2
  49. package/src/role-runtime.ts +12 -7
  50. package/src/session-opening-materials.ts +27 -11
@@ -15308,13 +15308,10 @@ function assertRegisteredHostName(host) {
15308
15308
  }
15309
15309
  throw new Error(`unregistered host: ${host}`);
15310
15310
  }
15311
- var PRIVATE_COMPAT_ENV, DEFAULT_ROLE_TURN_HOST, HOST_DESCRIPTIONS, HEADLESS_HOST_DESCRIPTIONS;
15311
+ var DEFAULT_ROLE_TURN_HOST, HOST_DESCRIPTIONS, HEADLESS_HOST_DESCRIPTIONS;
15312
15312
  var init_host_descriptions = __esm({
15313
15313
  "src/host-descriptions.ts"() {
15314
15314
  "use strict";
15315
- PRIVATE_COMPAT_ENV = Object.fromEntries(
15316
- ["CLAUDE", "CURSOR", "CODEX"].flatMap((vendor) => ["SKILLS", "RULES", "AGENTS", "MCPS", "HOOKS", "SESSIONS"].map((kind) => [`GROK_${vendor}_${kind}_ENABLED`, "false"]))
15317
- );
15318
15315
  DEFAULT_ROLE_TURN_HOST = "pi";
15319
15316
  HOST_DESCRIPTIONS = Object.freeze({
15320
15317
  /** Operator home `~/.grok`, native session/load resume, `agent [--model X] stdio`. */
@@ -15327,12 +15324,7 @@ var init_host_descriptions = __esm({
15327
15324
  }),
15328
15325
  modelPassing: "argv",
15329
15326
  boundResume: "session/load",
15330
- sessionBindingFile: "grok-acp-session.json",
15331
- childEnv: Object.freeze({
15332
- ...PRIVATE_COMPAT_ENV,
15333
- GROK_MEMORY: "0",
15334
- GROK_SUBAGENTS: "0"
15335
- })
15327
+ sessionBindingFile: "grok-acp-session.json"
15336
15328
  }),
15337
15329
  /**
15338
15330
  * Operator home `~/.hermes`, native session/load resume, `acp` subcommand.
@@ -15351,7 +15343,6 @@ var init_host_descriptions = __esm({
15351
15343
  modelPassing: "set_model",
15352
15344
  boundResume: "session/load",
15353
15345
  sessionBindingFile: "hermes-acp-session.json",
15354
- childEnv: Object.freeze({}),
15355
15346
  seatProfileSoul: Object.freeze({
15356
15347
  flag: "-p",
15357
15348
  namePrefix: "ak-",
@@ -15372,12 +15363,7 @@ var init_host_descriptions = __esm({
15372
15363
  // Intermediate assistant/tool/system events require verbose with stream-json.
15373
15364
  "--verbose",
15374
15365
  "--permission-mode",
15375
- "bypassPermissions",
15376
- // Empty sources: no user/project/local operator surface (envelope owns materials).
15377
- "--setting-sources",
15378
- "",
15379
- // With adapter-supplied --mcp-config only (AK relay); drops operator + claude.ai MCP.
15380
- "--strict-mcp-config"
15366
+ "bypassPermissions"
15381
15367
  ]),
15382
15368
  promptFlag: "-p",
15383
15369
  modelFlag: "--model",
@@ -20689,10 +20675,12 @@ __export(invocation_exports, {
20689
20675
  deriveMergerEnvelopeFromActiveMerge: () => deriveMergerEnvelopeFromActiveMerge,
20690
20676
  ensureRunArtifactsDir: () => ensureRunArtifactsDir,
20691
20677
  freezeAttachmentsIntoRun: () => freezeAttachmentsIntoRun,
20678
+ freezePreparedAttachmentsIntoRun: () => freezePreparedAttachmentsIntoRun,
20692
20679
  homeFromRunDirectory: () => homeFromRunDirectory,
20693
20680
  isReviewerLens: () => isReviewerLens,
20694
20681
  issueAdmissionPlacement: () => issueAdmissionPlacement,
20695
20682
  loadAdmittedJudgeRequest: () => loadAdmittedJudgeRequest,
20683
+ materializeCountersignInvocation: () => materializeCountersignInvocation,
20696
20684
  observeLaunchedRolePackageIdentity: () => observeLaunchedRolePackageIdentity,
20697
20685
  parseAnalystArgv: () => parseAnalystArgv,
20698
20686
  parseAnalystCohortIssueToken: () => parseAnalystCohortIssueToken,
@@ -20716,6 +20704,7 @@ __export(invocation_exports, {
20716
20704
  parseReviewerArgv: () => parseReviewerArgv,
20717
20705
  parseSecretariatArgv: () => parseSecretariatArgv,
20718
20706
  persistAdmittedSourceRunPath: () => persistAdmittedSourceRunPath,
20707
+ recordAdmittedCorrelation: () => recordAdmittedCorrelation,
20719
20708
  recordEffectiveInvocationModel: () => recordEffectiveInvocationModel,
20720
20709
  recordLaunchedPiIdentity: () => recordLaunchedPiIdentity,
20721
20710
  recordLaunchedRolePackageIdentity: () => recordLaunchedRolePackageIdentity,
@@ -20724,17 +20713,21 @@ __export(invocation_exports, {
20724
20713
  requireReviewerBaseRevision: () => requireReviewerBaseRevision,
20725
20714
  requireReviewerLens: () => requireReviewerLens,
20726
20715
  resolveDoctorCaseRunsPath: () => resolveDoctorCaseRunsPath,
20727
- resolveGitHubRemoteRepository: () => resolveGitHubRemoteRepository
20716
+ resolveGitHubRemoteRepository: () => resolveGitHubRemoteRepository,
20717
+ withPreparedAttachments: () => withPreparedAttachments
20728
20718
  });
20729
20719
  import { execFileSync as execFileSync3 } from "node:child_process";
20730
20720
  import { existsSync as existsSync6 } from "node:fs";
20731
20721
  import {
20732
20722
  lstat as lstat4,
20723
+ mkdtemp,
20733
20724
  readFile as readFile11,
20734
20725
  realpath as realpath4,
20735
20726
  rename,
20727
+ rm,
20736
20728
  writeFile as writeFile5
20737
20729
  } from "node:fs/promises";
20730
+ import { tmpdir } from "node:os";
20738
20731
  import { basename as basename6, dirname as dirname9, isAbsolute as isAbsolute7, join as join15, resolve as resolve7, sep as sep4 } from "node:path";
20739
20732
  function issueAdmissionPlacement(authority, request) {
20740
20733
  const ledgerHome = resolveActivationLedgerHome(request.home);
@@ -20745,7 +20738,7 @@ function issueAdmissionPlacement(authority, request) {
20745
20738
  runId: request.runId,
20746
20739
  role: request.role
20747
20740
  });
20748
- ensureRoleRunPlacement(ledgerHome, placement);
20741
+ if (request.materialize !== false) ensureRoleRunPlacement(ledgerHome, placement);
20749
20742
  return {
20750
20743
  principal: authority.seal(placement),
20751
20744
  ...placement,
@@ -20870,6 +20863,31 @@ async function bindAdmittedTicketNumber(admitted, ticketNumber) {
20870
20863
  await bindTicketNumberOnRunDirectory(admitted.runDirectory, ticketNumber);
20871
20864
  admitted.ticketNumber = ticketNumber;
20872
20865
  }
20866
+ async function recordAdmittedCorrelation(admitted, correlationId) {
20867
+ const current = JSON.parse(
20868
+ await readFile11(admitted.admittedRequestPath, "utf8")
20869
+ );
20870
+ const prior = [
20871
+ ...Array.isArray(current.correlationIds) ? current.correlationIds.filter(
20872
+ (value) => typeof value === "string" && value.trim() !== ""
20873
+ ) : [],
20874
+ ...typeof current.correlationId === "string" && current.correlationId.trim() !== "" ? [current.correlationId] : []
20875
+ ];
20876
+ const correlationIds = [.../* @__PURE__ */ new Set([...prior, correlationId])];
20877
+ await writeFile5(
20878
+ admitted.admittedRequestPath,
20879
+ `${JSON.stringify({ ...current, correlationId, correlationIds }, null, 2)}
20880
+ `,
20881
+ "utf8"
20882
+ );
20883
+ await mergeInvocationIdentityPage(admitted.runDirectory, {
20884
+ correlationId,
20885
+ correlationIds
20886
+ });
20887
+ const mutable = admitted;
20888
+ mutable.correlationId = correlationId;
20889
+ mutable.correlationIds = correlationIds;
20890
+ }
20873
20891
  async function bindCourtTicketNumbersOnAdmitted(admitted, courtTicketNumbers) {
20874
20892
  if (admitted.ticketNumber === void 0) {
20875
20893
  throw new Error(
@@ -21260,7 +21278,7 @@ function parseFixerArgv(args) {
21260
21278
  ...project === void 0 ? {} : { project }
21261
21279
  };
21262
21280
  }
21263
- async function freezeRegularFileAttachment(sourcePath, destinationDir, index) {
21281
+ async function readRegularFileAttachment(sourcePath) {
21264
21282
  const absolute = isAbsolute7(sourcePath) ? sourcePath : resolve7(sourcePath);
21265
21283
  let st;
21266
21284
  try {
@@ -21276,18 +21294,72 @@ async function freezeRegularFileAttachment(sourcePath, destinationDir, index) {
21276
21294
  `attachment must be a regular file (not a directory or symlink): ${sourcePath}`
21277
21295
  );
21278
21296
  }
21279
- const bytes = await readFile11(absolute);
21280
- const name = `${String(index).padStart(2, "0")}-${basename6(absolute)}`;
21281
- const frozenPath = join15(destinationDir, name);
21297
+ try {
21298
+ return { absolute, bytes: await readFile11(absolute) };
21299
+ } catch (error) {
21300
+ throw new CliUsageError(
21301
+ `attachment is not a readable regular file: ${sourcePath}`,
21302
+ { cause: error }
21303
+ );
21304
+ }
21305
+ }
21306
+ async function removePreparedAttachmentDirectory(stagingDirectory) {
21307
+ await rm(stagingDirectory, { recursive: true, force: true });
21308
+ }
21309
+ async function withPreparedAttachments(attachmentPaths, use) {
21310
+ if (attachmentPaths.length === 0) return await use([]);
21311
+ const stagingDirectory = await mkdtemp(join15(tmpdir(), "ak-role-attachments-"));
21312
+ const prepared = [];
21313
+ let result2;
21314
+ try {
21315
+ for (let index = 0; index < attachmentPaths.length; index += 1) {
21316
+ const { absolute, bytes } = await readRegularFileAttachment(attachmentPaths[index]);
21317
+ const snapshotPath = join15(stagingDirectory, String(index).padStart(6, "0"));
21318
+ await writeFile5(snapshotPath, bytes);
21319
+ prepared.push({ absolute, snapshotPath });
21320
+ }
21321
+ result2 = await use(prepared);
21322
+ } catch (primary) {
21323
+ try {
21324
+ await removePreparedAttachmentDirectory(stagingDirectory);
21325
+ } catch (cleanup) {
21326
+ throw new AggregateError(
21327
+ [primary, cleanup],
21328
+ "attachment snapshot operation failed and cleanup also failed",
21329
+ { cause: primary }
21330
+ );
21331
+ }
21332
+ throw primary;
21333
+ }
21334
+ await removePreparedAttachmentDirectory(stagingDirectory);
21335
+ return result2;
21336
+ }
21337
+ async function freezeAttachmentBytes(provenancePath, bytes, destinationDir, index) {
21338
+ const frozenPath = join15(
21339
+ destinationDir,
21340
+ `${String(index).padStart(2, "0")}-${basename6(provenancePath)}`
21341
+ );
21282
21342
  await writeFile5(frozenPath, bytes);
21283
21343
  return {
21284
- attachment: {
21285
- provenancePath: absolute,
21286
- frozenPath,
21287
- byteLength: bytes.byteLength,
21288
- sha256: sha256Hex(bytes),
21289
- mediaKind: "regular-file"
21290
- },
21344
+ provenancePath,
21345
+ frozenPath,
21346
+ byteLength: bytes.byteLength,
21347
+ sha256: sha256Hex(bytes),
21348
+ mediaKind: "regular-file"
21349
+ };
21350
+ }
21351
+ async function freezePreparedAttachment(prepared, destinationDir, index) {
21352
+ return freezeAttachmentBytes(
21353
+ prepared.absolute,
21354
+ await readFile11(prepared.snapshotPath),
21355
+ destinationDir,
21356
+ index
21357
+ );
21358
+ }
21359
+ async function freezeRegularFileAttachment(sourcePath, destinationDir, index) {
21360
+ const { absolute, bytes } = await readRegularFileAttachment(sourcePath);
21361
+ return {
21362
+ attachment: await freezeAttachmentBytes(absolute, bytes, destinationDir, index),
21291
21363
  body: bytes
21292
21364
  };
21293
21365
  }
@@ -21310,6 +21382,17 @@ async function freezeAttachmentsIntoRun(attachmentPaths, runDirectory, summonsKe
21310
21382
  ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
21311
21383
  return freezeAttachments(attachmentPaths, attachmentsDirectory);
21312
21384
  }
21385
+ async function freezePreparedAttachmentsIntoRun(prepared, runDirectory, summonsKey) {
21386
+ if (prepared.length === 0) return [];
21387
+ const ledgerHome = resolveActivationLedgerHome(homeFromRunDirectory(runDirectory));
21388
+ const attachmentsDirectory = summonsKey === void 0 ? join15(runDirectory, "attachments") : join15(runDirectory, "attachments", summonsKey);
21389
+ ensureRealDirectoryTree(ledgerHome, attachmentsDirectory);
21390
+ const attachments = [];
21391
+ for (let index = 0; index < prepared.length; index += 1) {
21392
+ attachments.push(await freezePreparedAttachment(prepared[index], attachmentsDirectory, index));
21393
+ }
21394
+ return attachments;
21395
+ }
21313
21396
  function ticketAdmissionFields(ticketNumber) {
21314
21397
  if (ticketNumber === void 0) return {};
21315
21398
  return {
@@ -21449,9 +21532,10 @@ async function admitCountersignInvocation(options) {
21449
21532
  runId,
21450
21533
  role: "countersign",
21451
21534
  subject: { unbound: true },
21452
- home: options.home
21535
+ home: options.home,
21536
+ materialize: options.deferPersistence !== true
21453
21537
  });
21454
- const attachments = await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
21538
+ const attachments = options.deferPersistence === true ? [] : await freezeAttachments(options.attachmentPaths, attachmentsDirectory);
21455
21539
  const instruction = options.instruction;
21456
21540
  const instructionEmpty = instruction.trim() === "";
21457
21541
  const admitted = {
@@ -21473,11 +21557,13 @@ async function admitCountersignInvocation(options) {
21473
21557
  }))
21474
21558
  };
21475
21559
  const admittedRequestPath = join15(runDirectory, "admitted-request.json");
21476
- await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
21477
- sessionDirectory,
21478
- sessionFile
21479
- });
21480
- await writeRoleInvocationLedger({ ...admitted, sessionDirectory, sessionFile }, admitted.role, options.model);
21560
+ if (options.deferPersistence !== true) {
21561
+ await writeAdmittedRequestPersistence(admittedRequestPath, admitted, {
21562
+ sessionDirectory,
21563
+ sessionFile
21564
+ });
21565
+ await writeRoleInvocationLedger({ ...admitted, sessionDirectory, sessionFile }, admitted.role, options.model);
21566
+ }
21481
21567
  return {
21482
21568
  role: "countersign",
21483
21569
  runId,
@@ -21492,6 +21578,29 @@ async function admitCountersignInvocation(options) {
21492
21578
  ...options.correlationId === void 0 ? {} : { correlationId: options.correlationId }
21493
21579
  };
21494
21580
  }
21581
+ async function materializeCountersignInvocation(admitted, options) {
21582
+ const placement = issueAdmissionPlacement(options.principalAuthority, {
21583
+ cwd: admitted.projectRoot,
21584
+ runId: admitted.runId,
21585
+ role: "countersign",
21586
+ subject: { unbound: true },
21587
+ home: options.home
21588
+ });
21589
+ const attachments = await freezePreparedAttachmentsIntoRun(
21590
+ options.preparedAttachments,
21591
+ admitted.runDirectory
21592
+ );
21593
+ admitted.attachments = attachments;
21594
+ await writeAdmittedRequestPersistence(admitted.admittedRequestPath, admitted, {
21595
+ sessionDirectory: placement.sessionDirectory,
21596
+ sessionFile: placement.sessionFile
21597
+ });
21598
+ await writeRoleInvocationLedger(
21599
+ { ...admitted, sessionDirectory: placement.sessionDirectory, sessionFile: placement.sessionFile },
21600
+ admitted.role,
21601
+ options.model
21602
+ );
21603
+ }
21495
21604
  function buildCountersignTransportPrompt(admitted, engineMaterial) {
21496
21605
  return buildInstructionTransportPrompt(admitted, engineMaterial);
21497
21606
  }
@@ -24252,9 +24361,7 @@ async function readPackageMaterial(relativePath) {
24252
24361
  }
24253
24362
  async function joinPackageMaterials(relativePaths) {
24254
24363
  const chunks = [];
24255
- for (const relativePath of relativePaths) {
24256
- chunks.push(await readPackageMaterial(relativePath));
24257
- }
24364
+ for (const relativePath of relativePaths) chunks.push(await readPackageMaterial(relativePath));
24258
24365
  return chunks.join("\n\n");
24259
24366
  }
24260
24367
  var packageRootUrl, MAIN_ROLE_SESSION_MATERIALS, GATEKEEPER_SESSION_MATERIALS;
@@ -24285,6 +24392,8 @@ __export(auditor_soul_exports, {
24285
24392
  AUDITOR_SESSION_MATERIALS: () => AUDITOR_SESSION_MATERIALS,
24286
24393
  AUDITOR_SOUL_ROLES: () => AUDITOR_SOUL_ROLES,
24287
24394
  isAuditorSoulRole: () => isAuditorSoulRole,
24395
+ loadAuditorReferenceMaterials: () => loadAuditorReferenceMaterials,
24396
+ loadAuditorReferenceMaterialsFromSubjectInput: () => loadAuditorReferenceMaterialsFromSubjectInput,
24288
24397
  loadAuditorSoul: () => loadAuditorSoul,
24289
24398
  loadAuditorSoulFromSubjectInput: () => loadAuditorSoulFromSubjectInput,
24290
24399
  resolveAuditorSubject: () => resolveAuditorSubject
@@ -24311,11 +24420,18 @@ async function loadAuditorSoul(role) {
24311
24420
  if (soul.trim().length === 0) {
24312
24421
  throw new Error(`The ${role} auditor Soul is blank`);
24313
24422
  }
24314
- return joinPackageMaterials(materials);
24423
+ return soul;
24424
+ }
24425
+ function loadAuditorReferenceMaterials(role) {
24426
+ const soulPath = auditorSoulRelativePath(role);
24427
+ return joinPackageMaterials(AUDITOR_SESSION_MATERIALS[role].filter((path) => path !== soulPath));
24315
24428
  }
24316
24429
  async function loadAuditorSoulFromSubjectInput(raw) {
24317
24430
  return loadAuditorSoul(resolveAuditorSubject(raw));
24318
24431
  }
24432
+ function loadAuditorReferenceMaterialsFromSubjectInput(raw) {
24433
+ return loadAuditorReferenceMaterials(resolveAuditorSubject(raw));
24434
+ }
24319
24435
  var AUDITOR_SOUL_ROLES, AK_ROLE_AUDITOR_SUBJECT_ENV, AK_ROLE_AUDITOR_SOURCE_RUN_ENV, AUDITOR_SESSION_MATERIALS;
24320
24436
  var init_auditor_soul = __esm({
24321
24437
  "src/auditor-soul.ts"() {
@@ -27552,8 +27668,8 @@ var init_ticket_provenance = __esm({
27552
27668
  });
27553
27669
 
27554
27670
  // src/public-cli/case-dossier-delivery.ts
27555
- import { mkdtemp, readFile as readFile18, rm, writeFile as writeFile8 } from "node:fs/promises";
27556
- import { tmpdir } from "node:os";
27671
+ import { mkdtemp as mkdtemp2, readFile as readFile18, rm as rm2, writeFile as writeFile8 } from "node:fs/promises";
27672
+ import { tmpdir as tmpdir2 } from "node:os";
27557
27673
  import { join as join26 } from "node:path";
27558
27674
  async function projectCaseDossierPointerSection(input) {
27559
27675
  if (input.ticketNumber === void 0) {
@@ -27581,7 +27697,7 @@ async function deliverCaseDossierAsAttachment(input) {
27581
27697
  projectRoot: input.projectRoot,
27582
27698
  home: input.home
27583
27699
  });
27584
- const stagingDir = await mkdtemp(join26(tmpdir(), "ak-case-dossier-"));
27700
+ const stagingDir = await mkdtemp2(join26(tmpdir2(), "ak-case-dossier-"));
27585
27701
  try {
27586
27702
  const stagingPath = join26(stagingDir, CASE_DOSSIER_ATTACH_FILE);
27587
27703
  await writeFile8(stagingPath, `${section}
@@ -27592,7 +27708,7 @@ async function deliverCaseDossierAsAttachment(input) {
27592
27708
  CASE_DOSSIER_ATTACH_KEY
27593
27709
  );
27594
27710
  } finally {
27595
- await rm(stagingDir, { recursive: true, force: true });
27711
+ await rm2(stagingDir, { recursive: true, force: true });
27596
27712
  }
27597
27713
  }
27598
27714
  var CASE_DOSSIER_SECTION_HEADING, UNBOUND_DOSSIER_PATH_HEADING, CASE_DOSSIER_ATTACH_KEY, CASE_DOSSIER_ATTACH_FILE;
@@ -30170,6 +30286,9 @@ function diaristAdapters(env) {
30170
30286
  shouldPresentSettled: () => true,
30171
30287
  // Resume interrupted state: board ticket already on pages, run still under unbound/.
30172
30288
  beforeDispatch: async (admitted, lease) => {
30289
+ if (env.correlationId !== void 0 && env.correlationId.trim() !== "") {
30290
+ await recordAdmittedCorrelation(admitted, env.correlationId);
30291
+ }
30173
30292
  await bindAndRelocateDiaristIfBoardBound(admitted, env.principalAuthority, lease);
30174
30293
  },
30175
30294
  // First post-turn assert: accept hook wrote board pages; relocate before lease release.
@@ -30721,7 +30840,8 @@ function courtDiaristEscalated(roleOutcome) {
30721
30840
  if (roleOutcome.kind === "audit_escalation") return true;
30722
30841
  if (roleOutcome.kind !== "accepted") return false;
30723
30842
  return (roleOutcome.payloads ?? []).some((payload) => {
30724
- if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return false;
30843
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload))
30844
+ return false;
30725
30845
  const record4 = payload;
30726
30846
  return record4.status === "escalate" || record4.countersignStatus === "escalate";
30727
30847
  });
@@ -30774,7 +30894,10 @@ async function invokeCourtDiarist(input, env, io) {
30774
30894
  }
30775
30895
  const asserted = result2.admitted?.ticketNumber;
30776
30896
  if (isSafePositiveTicketNumber(asserted)) {
30777
- const courtTicketNumbers = courtTicketNumbersFromOutcome(roleOutcome, asserted);
30897
+ const courtTicketNumbers = courtTicketNumbersFromOutcome(
30898
+ roleOutcome,
30899
+ asserted
30900
+ );
30778
30901
  return {
30779
30902
  identity: {
30780
30903
  kind: "ticket",
@@ -30823,7 +30946,9 @@ async function runCountersignCourtDiaristStation(admitted, env, io) {
30823
30946
  );
30824
30947
  }
30825
30948
  if (outcome.failedWithoutEscalate !== void 0) {
30826
- throw new StationChildExhaustedError(outcome.failedWithoutEscalate.diagnostic);
30949
+ throw new StationChildExhaustedError(
30950
+ outcome.failedWithoutEscalate.diagnostic
30951
+ );
30827
30952
  }
30828
30953
  }
30829
30954
  }
@@ -30849,7 +30974,8 @@ async function runPublicCountersign(argv, env, io, parseCountersignArgv2) {
30849
30974
  ...parsed.project === void 0 ? {} : { project: parsed.project },
30850
30975
  ...env.createRunId === void 0 ? {} : { createRunId: env.createRunId },
30851
30976
  ...env.model === void 0 ? {} : { model: env.model },
30852
- ...env.correlationId === void 0 ? {} : { correlationId: env.correlationId }
30977
+ ...env.correlationId === void 0 ? {} : { correlationId: env.correlationId },
30978
+ deferPersistence: true
30853
30979
  });
30854
30980
  } catch (error) {
30855
30981
  if (error instanceof CliUsageError) {
@@ -30858,160 +30984,216 @@ async function runPublicCountersign(argv, env, io, parseCountersignArgv2) {
30858
30984
  }
30859
30985
  throw error;
30860
30986
  }
30861
- await markRunAdmitted(admitted, env.principalAuthority);
30862
- let typedTicket;
30863
- let typedCourtTicketNumbers;
30864
- let identityDiaristRan = false;
30865
- if (env.runCourtDiaristStation === void 0) {
30866
- const outcome = await invokeCourtDiarist(
30867
- {
30868
- instruction: parsed.instruction,
30869
- projectRoot: admitted.projectRoot,
30870
- failureLabel: "unbound summons",
30871
- correlationId: admitted.runId
30872
- },
30873
- env,
30874
- io
30875
- );
30876
- identityDiaristRan = true;
30877
- if (outcome.identity.kind === "escalate") {
30878
- return await presentControlledFailure2(
30879
- admitted,
30880
- {
30881
- timedOut: false,
30882
- code: null,
30883
- stderr: "",
30884
- thrown: new Error(
30885
- "court diarist station escalated (cannot identify court target)"
30886
- )
30887
- },
30888
- countersignAdapters(),
30889
- env.principalAuthority,
30890
- io
30891
- );
30892
- }
30893
- if (outcome.failedWithoutEscalate !== void 0) {
30894
- return await presentControlledFailure2(
30895
- admitted,
30896
- {
30897
- timedOut: false,
30898
- code: null,
30899
- stderr: "",
30900
- thrown: new Error(outcome.failedWithoutEscalate.diagnostic)
30901
- },
30902
- countersignAdapters(),
30903
- env.principalAuthority,
30904
- io
30905
- );
30906
- }
30907
- if (outcome.identity.kind === "ticket") {
30908
- const assertedTicket = outcome.identity.ticketNumber;
30909
- typedTicket = assertedTicket;
30910
- typedCourtTicketNumbers = outcome.identity.courtTicketNumbers;
30911
- const summons = {
30912
- instruction: parsed.instruction,
30913
- instructionEmpty: parsed.instruction.trim() === "",
30914
- attachmentPaths: parsed.attachmentPaths
30915
- };
30916
- const resumed = await tryResumeSameTicketSeatRun({
30917
- home: env.home,
30918
- projectRoot: admitted.projectRoot,
30919
- role: "countersign",
30920
- ticketNumber: typedTicket,
30921
- freshSummons: env.freshSummons,
30922
- summons,
30923
- resume: async (runId, materials) => {
30924
- await bindAdmittedTicketNumber(admitted, assertedTicket);
30925
- await relocateAdmittedRunToTicket(admitted, env.principalAuthority);
30926
- await markRunTerminal(admitted.runDirectory);
30927
- return await runPublicCountersignResume(
30928
- {
30929
- runId,
30930
- ...materials === void 0 ? {} : { summons: materials }
30931
- },
30932
- {
30933
- ...env,
30934
- ...typedCourtTicketNumbers === void 0 ? {} : { pendingCourtTicketNumbers: typedCourtTicketNumbers }
30935
- },
30936
- io
30937
- );
30987
+ try {
30988
+ return await withPreparedAttachments(
30989
+ parsed.attachmentPaths,
30990
+ async (preparedAttachments) => {
30991
+ const materializeAdmission = async () => {
30992
+ await materializeCountersignInvocation(admitted, {
30993
+ home: env.home,
30994
+ principalAuthority: env.principalAuthority,
30995
+ preparedAttachments,
30996
+ ...env.model === void 0 ? {} : { model: env.model }
30997
+ });
30998
+ };
30999
+ let typedTicket;
31000
+ let typedCourtTicketNumbers;
31001
+ let identityDiaristRan = false;
31002
+ if (env.runCourtDiaristStation === void 0) {
31003
+ let outcome;
31004
+ try {
31005
+ outcome = await invokeCourtDiarist(
31006
+ {
31007
+ instruction: parsed.instruction,
31008
+ projectRoot: admitted.projectRoot,
31009
+ failureLabel: "unbound summons"
31010
+ },
31011
+ env,
31012
+ io
31013
+ );
31014
+ } catch (error) {
31015
+ await materializeAdmission();
31016
+ await markRunAdmitted(admitted, env.principalAuthority);
31017
+ return await presentControlledFailure2(
31018
+ admitted,
31019
+ { timedOut: false, code: null, stderr: "", thrown: error },
31020
+ countersignAdapters(),
31021
+ env.principalAuthority,
31022
+ io
31023
+ );
31024
+ }
31025
+ identityDiaristRan = true;
31026
+ if (outcome.identity.kind === "escalate") {
31027
+ await materializeAdmission();
31028
+ await markRunAdmitted(admitted, env.principalAuthority);
31029
+ return await presentControlledFailure2(
31030
+ admitted,
31031
+ {
31032
+ timedOut: false,
31033
+ code: null,
31034
+ stderr: "",
31035
+ thrown: new Error(
31036
+ "court diarist station escalated (cannot identify court target)"
31037
+ )
31038
+ },
31039
+ countersignAdapters(),
31040
+ env.principalAuthority,
31041
+ io
31042
+ );
31043
+ }
31044
+ if (outcome.failedWithoutEscalate !== void 0) {
31045
+ await materializeAdmission();
31046
+ await markRunAdmitted(admitted, env.principalAuthority);
31047
+ return await presentControlledFailure2(
31048
+ admitted,
31049
+ {
31050
+ timedOut: false,
31051
+ code: null,
31052
+ stderr: "",
31053
+ thrown: new Error(outcome.failedWithoutEscalate.diagnostic)
31054
+ },
31055
+ countersignAdapters(),
31056
+ env.principalAuthority,
31057
+ io
31058
+ );
31059
+ }
31060
+ if (outcome.identity.kind === "ticket") {
31061
+ const assertedTicket = outcome.identity.ticketNumber;
31062
+ typedTicket = assertedTicket;
31063
+ typedCourtTicketNumbers = outcome.identity.courtTicketNumbers;
31064
+ const summons = {
31065
+ instruction: parsed.instruction,
31066
+ instructionEmpty: parsed.instruction.trim() === ""
31067
+ };
31068
+ const resumed = await tryResumeSameTicketSeatRun({
31069
+ home: env.home,
31070
+ projectRoot: admitted.projectRoot,
31071
+ role: "countersign",
31072
+ ticketNumber: typedTicket,
31073
+ freshSummons: env.freshSummons,
31074
+ summons,
31075
+ resume: async (runId, materials) => {
31076
+ const retained = await loadResumableCountersignRun(
31077
+ env.home,
31078
+ runId,
31079
+ env.principalAuthority
31080
+ );
31081
+ if (retained.admitted === void 0) {
31082
+ throw new Error(
31083
+ `retained countersign run disappeared before resume: ${runId}`
31084
+ );
31085
+ }
31086
+ const frozenPaths = (await freezePreparedAttachmentsIntoRun(
31087
+ preparedAttachments,
31088
+ retained.admitted.runDirectory,
31089
+ `s-${Date.now().toString(36)}`
31090
+ )).map((attachment) => attachment.frozenPath);
31091
+ const preparedMaterials = {
31092
+ ...materials ?? {},
31093
+ ...frozenPaths.length === 0 ? {} : { attachmentPaths: frozenPaths }
31094
+ };
31095
+ return await runPublicCountersignResume(
31096
+ {
31097
+ runId,
31098
+ summons: preparedMaterials
31099
+ },
31100
+ {
31101
+ ...env,
31102
+ ...typedCourtTicketNumbers === void 0 ? {} : { pendingCourtTicketNumbers: typedCourtTicketNumbers }
31103
+ },
31104
+ io
31105
+ );
31106
+ }
31107
+ });
31108
+ if (resumed !== void 0) {
31109
+ return resumed;
31110
+ }
31111
+ }
30938
31112
  }
30939
- });
30940
- if (resumed !== void 0) {
30941
- return resumed;
30942
- }
30943
- }
30944
- }
30945
- if (identityDiaristRan && typedTicket !== void 0) {
30946
- try {
30947
- await bindAdmittedTicketNumber(admitted, typedTicket);
30948
- await relocateAdmittedRunToTicket(admitted, env.principalAuthority);
30949
- await bindCourtTicketNumbersOnAdmitted(
30950
- admitted,
30951
- typedCourtTicketNumbers ?? [typedTicket]
30952
- );
30953
- } catch (error) {
30954
- return await presentControlledFailure2(
30955
- admitted,
30956
- {
30957
- timedOut: false,
30958
- code: null,
30959
- stderr: "",
30960
- thrown: error
30961
- },
30962
- countersignAdapters(),
30963
- env.principalAuthority,
30964
- io
30965
- );
30966
- }
30967
- }
30968
- const turnProjection = {
30969
- packageRoot: env.packageRoot,
30970
- home: env.home,
30971
- agentDir: env.agentDir,
30972
- ...env.model === void 0 ? {} : { model: env.model },
30973
- ...pickEngineAxis(env),
30974
- ...env.timeoutMs === void 0 ? {} : { timeoutMs: env.timeoutMs },
30975
- ...env.correlationId === void 0 || env.correlationId.trim() === "" ? {} : { correlationId: env.correlationId },
30976
- continuation: {
30977
- kind: "initial",
30978
- prompt: buildCountersignTransportPrompt(
30979
- admitted,
30980
- engineSessionMaterialFromOptions({
30981
- ...pickEngineAxis(env),
30982
- packageRoot: env.packageRoot
30983
- })
30984
- )
30985
- }
30986
- };
30987
- const turnRequest = buildCountersignTurnRequest(admitted, turnProjection);
30988
- const result2 = await runPostAdmissionOneShot({
30989
- admitted,
30990
- env,
30991
- io,
30992
- request: turnRequest,
30993
- adapters: countersignAdapters({
30994
- beforeDispatch: async (admittedSeat, lease) => {
30995
- if (!identityDiaristRan) {
30996
- await runCountersignCourtDiaristStation(admittedSeat, env, io);
30997
- } else if (typedTicket !== void 0) {
30998
- await runCountersignCourtDiaristStation(admittedSeat, env, io);
31113
+ await materializeAdmission();
31114
+ await markRunAdmitted(admitted, env.principalAuthority);
31115
+ if (identityDiaristRan && typedTicket !== void 0) {
31116
+ try {
31117
+ await bindAdmittedTicketNumber(admitted, typedTicket);
31118
+ await relocateAdmittedRunToTicket(admitted, env.principalAuthority);
31119
+ await bindCourtTicketNumbersOnAdmitted(
31120
+ admitted,
31121
+ typedCourtTicketNumbers ?? [typedTicket]
31122
+ );
31123
+ } catch (error) {
31124
+ return await presentControlledFailure2(
31125
+ admitted,
31126
+ {
31127
+ timedOut: false,
31128
+ code: null,
31129
+ stderr: "",
31130
+ thrown: error
31131
+ },
31132
+ countersignAdapters(),
31133
+ env.principalAuthority,
31134
+ io
31135
+ );
31136
+ }
30999
31137
  }
31000
- await relocateAdmittedRunToTicket(
31001
- admittedSeat,
31002
- env.principalAuthority,
31003
- lease
31004
- );
31005
- Object.assign(
31006
- turnRequest,
31007
- buildCountersignTurnRequest(admittedSeat, turnProjection)
31138
+ const turnProjection = {
31139
+ packageRoot: env.packageRoot,
31140
+ home: env.home,
31141
+ agentDir: env.agentDir,
31142
+ ...env.model === void 0 ? {} : { model: env.model },
31143
+ ...pickEngineAxis(env),
31144
+ ...env.timeoutMs === void 0 ? {} : { timeoutMs: env.timeoutMs },
31145
+ ...env.correlationId === void 0 || env.correlationId.trim() === "" ? {} : { correlationId: env.correlationId },
31146
+ continuation: {
31147
+ kind: "initial",
31148
+ prompt: buildCountersignTransportPrompt(
31149
+ admitted,
31150
+ engineSessionMaterialFromOptions({
31151
+ ...pickEngineAxis(env),
31152
+ packageRoot: env.packageRoot
31153
+ })
31154
+ )
31155
+ }
31156
+ };
31157
+ const turnRequest = buildCountersignTurnRequest(
31158
+ admitted,
31159
+ turnProjection
31008
31160
  );
31161
+ const result2 = await runPostAdmissionOneShot({
31162
+ admitted,
31163
+ env,
31164
+ io,
31165
+ request: turnRequest,
31166
+ adapters: countersignAdapters({
31167
+ beforeDispatch: async (admittedSeat, lease) => {
31168
+ if (!identityDiaristRan) {
31169
+ await runCountersignCourtDiaristStation(admittedSeat, env, io);
31170
+ } else if (typedTicket !== void 0) {
31171
+ await runCountersignCourtDiaristStation(admittedSeat, env, io);
31172
+ }
31173
+ await relocateAdmittedRunToTicket(
31174
+ admittedSeat,
31175
+ env.principalAuthority,
31176
+ lease
31177
+ );
31178
+ Object.assign(
31179
+ turnRequest,
31180
+ buildCountersignTurnRequest(admittedSeat, turnProjection)
31181
+ );
31182
+ }
31183
+ }),
31184
+ ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
31185
+ });
31186
+ await relocateAdmittedRunToTicket(admitted, env.principalAuthority);
31187
+ return result2;
31009
31188
  }
31010
- }),
31011
- ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
31012
- });
31013
- await relocateAdmittedRunToTicket(admitted, env.principalAuthority);
31014
- return result2;
31189
+ );
31190
+ } catch (error) {
31191
+ if (error instanceof CliUsageError) {
31192
+ presentStructuralRejection(error, io);
31193
+ return { exitCode: 2 };
31194
+ }
31195
+ throw error;
31196
+ }
31015
31197
  }
31016
31198
  function countersignAdapters(options) {
31017
31199
  return {
@@ -31049,7 +31231,9 @@ async function runPublicCountersignResume(request, env, io) {
31049
31231
  adapters: countersignAdapters({
31050
31232
  beforeDispatch: async (admitted) => {
31051
31233
  if (admitted.courtTicketNumbersDamage !== void 0) {
31052
- throw new StationChildExhaustedError(admitted.courtTicketNumbersDamage);
31234
+ throw new StationChildExhaustedError(
31235
+ admitted.courtTicketNumbersDamage
31236
+ );
31053
31237
  }
31054
31238
  if (env.pendingCourtTicketNumbers !== void 0) {
31055
31239
  await bindCourtTicketNumbersOnAdmitted(
@@ -31923,7 +32107,7 @@ var init_analyst_book_key = __esm({
31923
32107
 
31924
32108
  // src/atomic-write.ts
31925
32109
  import { randomUUID as randomUUID7 } from "node:crypto";
31926
- import { rename as rename3, rm as rm2, writeFile as writeFile10 } from "node:fs/promises";
32110
+ import { rename as rename3, rm as rm3, writeFile as writeFile10 } from "node:fs/promises";
31927
32111
  import { dirname as dirname16, join as join31 } from "node:path";
31928
32112
  async function writeFileAtomically(destination, contents) {
31929
32113
  const parent = dirname16(destination);
@@ -31932,7 +32116,7 @@ async function writeFileAtomically(destination, contents) {
31932
32116
  await writeFile10(temporary, contents);
31933
32117
  await rename3(temporary, destination);
31934
32118
  } catch (error) {
31935
- await rm2(temporary, { force: true }).catch(() => void 0);
32119
+ await rm3(temporary, { force: true }).catch(() => void 0);
31936
32120
  throw error;
31937
32121
  }
31938
32122
  }