@akagilnc/pi-workflow-roles 0.1.3452 → 0.1.3471

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 (36) hide show
  1. package/CLAUDE.md +2 -0
  2. package/dist/evidence-child-executor.js +2 -11
  3. package/dist/grok/production-host.js +196 -205
  4. package/dist/pi/in-process-session.js +4 -0
  5. package/dist/public-cli/main.js +998 -920
  6. package/package.json +1 -1
  7. package/scripts/build-package.mjs +1 -3
  8. package/src/analyst-gate-cycles-read.ts +3 -21
  9. package/src/analyst-ledger.ts +11 -42
  10. package/src/archivist-record-entry.ts +5 -6
  11. package/src/evidence-child-executor.ts +5 -15
  12. package/src/grok/production-host.ts +3 -32
  13. package/src/grok/role-envelope.ts +10 -4
  14. package/src/host-contracts.ts +4 -11
  15. package/src/host-transition-prior-native.ts +3 -7
  16. package/src/ledger-session-read.ts +1 -17
  17. package/src/pi/in-process-session.ts +6 -2
  18. package/src/pi/role-turn-host.ts +9 -0
  19. package/src/public-cli/collector-run.ts +4 -4
  20. package/src/public-cli/countersign-run.ts +90 -20
  21. package/src/public-cli/doctor-run.ts +4 -4
  22. package/src/public-cli/gleaner-left-run.ts +9 -6
  23. package/src/public-cli/inspector-run.ts +95 -32
  24. package/src/public-cli/instruction-seat-run.ts +7 -6
  25. package/src/public-cli/invocation.ts +14 -8
  26. package/src/public-cli/judge-run.ts +4 -4
  27. package/src/public-cli/notary-run.ts +91 -30
  28. package/src/public-cli/post-admission.ts +424 -360
  29. package/src/public-cli/run-lifecycle.ts +205 -0
  30. package/src/public-cli/seat-ticket-binding.ts +136 -16
  31. package/src/public-cli/settlement.ts +74 -52
  32. package/src/run-ticket-number.ts +53 -0
  33. package/src/submission-ledger.ts +86 -18
  34. package/dist/ledger-session-read.js +0 -241
  35. package/dist/ticket-seat-memory.js +0 -244
  36. package/src/ticket-seat-memory.ts +0 -454
@@ -348,26 +348,6 @@ var init_activation_ledger_topology = __esm({
348
348
  }
349
349
  });
350
350
 
351
- // src/archivist-record-topology.ts
352
- import { createHash as createHash4 } from "node:crypto";
353
- import { join as join5 } from "node:path";
354
- function subjectKeyedRecordDirectory(input) {
355
- const ledgerHome = input.parentSessionFile !== void 0 && input.parentSessionFile.length > 0 ? resolveActivationLedgerHomeForPath(input.parentSessionFile) : resolveActivationLedgerHome(input.home);
356
- const digest = createHash4("sha256").update(input.subject).digest("hex").slice(0, 32);
357
- return join5(
358
- activationBookDirectory(ledgerHome, resolveBookKeyFromGit(input.cwd)),
359
- input.kind,
360
- digest
361
- );
362
- }
363
- var init_archivist_record_topology = __esm({
364
- "src/archivist-record-topology.ts"() {
365
- "use strict";
366
- init_activation_ledger_git();
367
- init_activation_ledger_topology();
368
- }
369
- });
370
-
371
351
  // src/upstream-error-testimony.ts
372
352
  function isNonSuccessHttpStatus(status) {
373
353
  return typeof status === "number" && (status < 200 || status >= 300);
@@ -389,6 +369,26 @@ var init_upstream_error_testimony = __esm({
389
369
  }
390
370
  });
391
371
 
372
+ // src/archivist-record-topology.ts
373
+ import { createHash as createHash4 } from "node:crypto";
374
+ import { join as join10 } from "node:path";
375
+ function subjectKeyedRecordDirectory(input) {
376
+ const ledgerHome = input.parentSessionFile !== void 0 && input.parentSessionFile.length > 0 ? resolveActivationLedgerHomeForPath(input.parentSessionFile) : resolveActivationLedgerHome(input.home);
377
+ const digest = createHash4("sha256").update(input.subject).digest("hex").slice(0, 32);
378
+ return join10(
379
+ activationBookDirectory(ledgerHome, resolveBookKeyFromGit(input.cwd)),
380
+ input.kind,
381
+ digest
382
+ );
383
+ }
384
+ var init_archivist_record_topology = __esm({
385
+ "src/archivist-record-topology.ts"() {
386
+ "use strict";
387
+ init_activation_ledger_git();
388
+ init_activation_ledger_topology();
389
+ }
390
+ });
391
+
392
392
  // src/archivist-record-entry.ts
393
393
  var archivist_record_entry_exports = {};
394
394
  __export(archivist_record_entry_exports, {
@@ -398,10 +398,10 @@ __export(archivist_record_entry_exports, {
398
398
  subjectKeyedRecordDirectory: () => subjectKeyedRecordDirectory
399
399
  });
400
400
  import { existsSync as existsSync5, readFileSync as readFileSync2, realpathSync as realpathSync2, writeFileSync as writeFileSync3 } from "node:fs";
401
- import { dirname as dirname8, resolve as resolve6, join as join12 } from "node:path";
401
+ import { dirname as dirname8, resolve as resolve6, join as join11 } from "node:path";
402
402
  import { SessionManager } from "@earendil-works/pi-coding-agent";
403
403
  function readCurrentSession(sessionDir) {
404
- const ledger = join12(sessionDir, CURRENT_SESSION_LEDGER);
404
+ const ledger = join11(sessionDir, CURRENT_SESSION_LEDGER);
405
405
  try {
406
406
  const value = JSON.parse(readFileSync2(ledger, "utf8"));
407
407
  if (typeof value !== "object" || value === null || typeof value.sessionFile !== "string" || value.sessionFile.length === 0) {
@@ -416,7 +416,7 @@ function readCurrentSession(sessionDir) {
416
416
  }
417
417
  }
418
418
  function writeCurrentSession(sessionDir, sessionFile) {
419
- const ledger = join12(sessionDir, CURRENT_SESSION_LEDGER);
419
+ const ledger = join11(sessionDir, CURRENT_SESSION_LEDGER);
420
420
  try {
421
421
  writeFileSync3(ledger, `${JSON.stringify({ sessionFile })}
422
422
  `, { flag: "wx" });
@@ -477,7 +477,7 @@ function createRecordSessionOpen(options) {
477
477
  return { session: SessionManager.inMemory(cwd), resumed: false };
478
478
  } else {
479
479
  const parentResolved = resolve6(parentFile);
480
- sessionDir = physicallyContainedIn(ledgerHome, parentResolved) ? join12(dirname8(parentResolved), options.kind) : join12(activationBookDirectory(ledgerHome, resolveBookKeyFromGit(cwd)), options.kind);
480
+ sessionDir = physicallyContainedIn(ledgerHome, parentResolved) ? join11(dirname8(parentResolved), options.kind) : join11(activationBookDirectory(ledgerHome, resolveBookKeyFromGit(cwd)), options.kind);
481
481
  parentSession = parentFile;
482
482
  }
483
483
  const nestAlreadyExists = existsSync5(sessionDir);
@@ -604,7 +604,7 @@ __export(in_process_session_exports, {
604
604
  });
605
605
  import { mkdtemp as mkdtemp2, rm as rm2 } from "node:fs/promises";
606
606
  import { tmpdir as tmpdir2 } from "node:os";
607
- import { join as join13 } from "node:path";
607
+ import { join as join12 } from "node:path";
608
608
  import {
609
609
  createAgentSession,
610
610
  DefaultResourceLoader,
@@ -727,7 +727,7 @@ async function openPiInstitutionalSession(options) {
727
727
  let scratchDir;
728
728
  let resolvedAgentDir = options.agentDir;
729
729
  if (resolvedAgentDir === void 0) {
730
- scratchDir = await mkdtemp2(join13(options.credentialScratchParent ?? tmpdir2(), "ak-institutional-"));
730
+ scratchDir = await mkdtemp2(join12(options.credentialScratchParent ?? tmpdir2(), "ak-institutional-"));
731
731
  resolvedAgentDir = scratchDir;
732
732
  }
733
733
  try {
@@ -1062,6 +1062,10 @@ async function openPiInstitutionalSession(options) {
1062
1062
  ...options.toolsAllowlist === void 0 ? {} : { tools: options.toolsAllowlist },
1063
1063
  ...customTools.length === 0 ? {} : { customTools }
1064
1064
  });
1065
+ await session.setModel(effectiveModel);
1066
+ if (options.selection.thinking !== void 0) {
1067
+ session.setThinkingLevel(options.selection.thinking);
1068
+ }
1065
1069
  const listeners = /* @__PURE__ */ new Set();
1066
1070
  const accumulatedUsage = emptyUsage();
1067
1071
  let lastEmittedAssistant;
@@ -1235,8 +1239,8 @@ var init_in_process_session = __esm({
1235
1239
  });
1236
1240
 
1237
1241
  // src/grok/production-host.ts
1238
- import { readFile as readFile16, rm as rm6, writeFile as writeFile11 } from "node:fs/promises";
1239
- import { join as join27 } from "node:path";
1242
+ import { readFile as readFile15, rm as rm6, writeFile as writeFile10 } from "node:fs/promises";
1243
+ import { join as join26 } from "node:path";
1240
1244
  import { fileURLToPath as fileURLToPath3 } from "node:url";
1241
1245
 
1242
1246
  // src/canonical-skill-binding.ts
@@ -3124,7 +3128,7 @@ import { Type as Type13 } from "typebox";
3124
3128
  // src/evidence-child-executor.ts
3125
3129
  import { mkdtemp as mkdtemp3, rm as rm3 } from "node:fs/promises";
3126
3130
  import { tmpdir as tmpdir3 } from "node:os";
3127
- import { join as join14 } from "node:path";
3131
+ import { join as join13 } from "node:path";
3128
3132
  import "@earendil-works/pi-ai";
3129
3133
 
3130
3134
  // src/sitian-appender.ts
@@ -3407,79 +3411,14 @@ function sitianReport(input) {
3407
3411
  return appendSitianRecord(input);
3408
3412
  }
3409
3413
 
3410
- // src/ticket-seat-memory.ts
3411
- import { readFile as readFile4, writeFile } from "node:fs/promises";
3412
- import { join as join6 } from "node:path";
3413
- init_activation_ledger_topology();
3414
- init_archivist_record_topology();
3415
- var TICKET_SEAT_MEMORY_KIND = "auditor-roles";
3416
- var TICKET_SEAT_MEMORY_SEATS = ["inspector", "notary", "auditor"];
3417
- function isTicketSeatMemorySeat(value) {
3418
- return TICKET_SEAT_MEMORY_SEATS.includes(value);
3419
- }
3420
- function isEnoent(error) {
3421
- return error instanceof Error && "code" in error && error.code === "ENOENT";
3422
- }
3423
- function ticketSeatMemorySubject(ticketNumber, seat) {
3424
- if (!Number.isSafeInteger(ticketNumber) || ticketNumber < 1) {
3425
- throw new Error(
3426
- `ticket-seat memory subject requires a positive ticket number, got ${String(ticketNumber)}`
3427
- );
3428
- }
3429
- return `${ticketNumber}:${seat}`;
3430
- }
3431
- async function readRunAdmittedPageFacts(runDirectory) {
3432
- try {
3433
- const raw = JSON.parse(
3434
- await readFile4(join6(runDirectory, "admitted-request.json"), "utf8")
3435
- );
3436
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
3437
- return {};
3438
- }
3439
- const record4 = raw;
3440
- const ticketNumber = record4.ticketNumber;
3441
- const projectRoot = record4.projectRoot;
3442
- return {
3443
- ...typeof ticketNumber === "number" && Number.isSafeInteger(ticketNumber) && ticketNumber >= 1 ? { ticketNumber } : {},
3444
- ...typeof projectRoot === "string" ? { projectRoot } : {}
3445
- };
3446
- } catch (error) {
3447
- if (isEnoent(error)) return {};
3448
- throw error;
3449
- }
3450
- }
3451
- async function readInvocationTicketNumber(runDirectory) {
3452
- try {
3453
- const raw = JSON.parse(
3454
- await readFile4(join6(runDirectory, "invocation.json"), "utf8")
3455
- );
3456
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
3457
- return void 0;
3458
- }
3459
- const ticketNumber = raw.ticketNumber;
3460
- if (typeof ticketNumber === "number" && Number.isSafeInteger(ticketNumber) && ticketNumber >= 1) {
3461
- return ticketNumber;
3462
- }
3463
- } catch (error) {
3464
- if (isEnoent(error)) return void 0;
3465
- throw error;
3466
- }
3467
- return void 0;
3468
- }
3469
- async function readRunTicketNumber(runDirectory) {
3470
- const admitted = await readRunAdmittedPageFacts(runDirectory);
3471
- if (admitted.ticketNumber !== void 0) return admitted.ticketNumber;
3472
- return readInvocationTicketNumber(runDirectory);
3473
- }
3474
-
3475
3414
  // src/engine-detour-tool.ts
3476
3415
  import { Type as Type11 } from "typebox";
3477
3416
 
3478
3417
  // src/engine-detour.ts
3479
3418
  import { spawn as spawn2 } from "node:child_process";
3480
- import { mkdtemp, rm, writeFile as writeFile2 } from "node:fs/promises";
3419
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3481
3420
  import { tmpdir } from "node:os";
3482
- import { join as join7 } from "node:path";
3421
+ import { join as join5 } from "node:path";
3483
3422
  var ENGINE_DETOUR_TOOL_NAME = "ak_engine_detour";
3484
3423
  var AK_ROLE_ENGINE_ENV = "AK_ROLE_ENGINE";
3485
3424
  var ENGINE_DETOUR_STAGED_PROMPT_TOKEN = "<<ak-engine-staged-prompt>>";
@@ -3570,12 +3509,12 @@ async function runEngineDetourOnce(input) {
3570
3509
  if (input.stagedPrompt === void 0) {
3571
3510
  return spawnEngineDetourOnce(input);
3572
3511
  }
3573
- const stagingDir = await mkdtemp(join7(tmpdir(), "ak-engine-detour-"));
3574
- const stagedPath = join7(stagingDir, "prompt.txt");
3512
+ const stagingDir = await mkdtemp(join5(tmpdir(), "ak-engine-detour-"));
3513
+ const stagedPath = join5(stagingDir, "prompt.txt");
3575
3514
  let result2;
3576
3515
  let runError;
3577
3516
  try {
3578
- await writeFile2(stagedPath, input.stagedPrompt, "utf8");
3517
+ await writeFile(stagedPath, input.stagedPrompt, "utf8");
3579
3518
  const argv = resolveArgvWithStagedPrompt(input.argv, stagedPath);
3580
3519
  result2 = await spawnEngineDetourOnce({
3581
3520
  argv,
@@ -3707,7 +3646,7 @@ function registerEngineDetourTool(roleHost, hostActions) {
3707
3646
 
3708
3647
  // src/package-resources/engine-material.ts
3709
3648
  import { existsSync as existsSync4, readdirSync } from "node:fs";
3710
- import { join as join8 } from "node:path";
3649
+ import { join as join6 } from "node:path";
3711
3650
  var ENGINE_MATERIAL_RELATIVE_ROOT = "resources/engines";
3712
3651
  function isEngineNameSyntax(name) {
3713
3652
  if (typeof name !== "string") return false;
@@ -3717,11 +3656,11 @@ function isEngineNameSyntax(name) {
3717
3656
  return true;
3718
3657
  }
3719
3658
  function resolveEngineMaterialDirectory(packageRoot) {
3720
- return join8(packageRoot, ENGINE_MATERIAL_RELATIVE_ROOT);
3659
+ return join6(packageRoot, ENGINE_MATERIAL_RELATIVE_ROOT);
3721
3660
  }
3722
3661
  function resolveEngineMaterialPath(packageRoot, name) {
3723
3662
  const legal = assertLegalEngineName(name);
3724
- return join8(resolveEngineMaterialDirectory(packageRoot), `${legal}.md`);
3663
+ return join6(resolveEngineMaterialDirectory(packageRoot), `${legal}.md`);
3725
3664
  }
3726
3665
  function assertLegalEngineName(name) {
3727
3666
  if (!isEngineNameSyntax(name)) {
@@ -3758,8 +3697,8 @@ function appendEngineSessionMaterial(lines, engineMaterial) {
3758
3697
  }
3759
3698
 
3760
3699
  // src/institutional-resolution.ts
3761
- import { readFile as readFile5, writeFile as writeFile3 } from "node:fs/promises";
3762
- import { join as join9 } from "node:path";
3700
+ import { readFile as readFile4, writeFile as writeFile2 } from "node:fs/promises";
3701
+ import { join as join7 } from "node:path";
3763
3702
 
3764
3703
  // src/public-cli/registry.ts
3765
3704
  var PUBLIC_CALLABLE_ROLES = PACKAGED_ROLE_REGISTRY.map(
@@ -3789,10 +3728,10 @@ function cleanSelection(model) {
3789
3728
  };
3790
3729
  }
3791
3730
  async function readInstitutionalSeatSelection(runDirectory, seat) {
3792
- const filePath = join9(runDirectory, INSTITUTIONAL_RESOLUTION_FILE);
3731
+ const filePath = join7(runDirectory, INSTITUTIONAL_RESOLUTION_FILE);
3793
3732
  let raw;
3794
3733
  try {
3795
- raw = await readFile5(filePath, "utf8");
3734
+ raw = await readFile4(filePath, "utf8");
3796
3735
  } catch (error) {
3797
3736
  throw new InstitutionalResolutionError(
3798
3737
  `institutional resolution page is missing at ${filePath}`,
@@ -3834,9 +3773,9 @@ async function readInstitutionalSeatSelection(runDirectory, seat) {
3834
3773
  }
3835
3774
 
3836
3775
  // src/navigator-session-contracts.ts
3837
- import { mkdir, readFile as readFile6, writeFile as writeFile4 } from "node:fs/promises";
3776
+ import { mkdir, readFile as readFile5, writeFile as writeFile3 } from "node:fs/promises";
3838
3777
  import { homedir as homedir2 } from "node:os";
3839
- import { dirname as dirname7, join as join10 } from "node:path";
3778
+ import { dirname as dirname7, join as join8 } from "node:path";
3840
3779
  import { Type as Type12 } from "typebox";
3841
3780
  import { Value as Value2 } from "typebox/value";
3842
3781
  var NAVIGATOR_PREPARE_TOOL_NAME = "ak_navigator_prepare";
@@ -3951,11 +3890,11 @@ var navigatorProviderFailureSchema = Type12.Object({
3951
3890
  ])
3952
3891
  }, { additionalProperties: false });
3953
3892
  function navigatorModelSettingPath() {
3954
- return join10(process.env.PI_CODING_AGENT_DIR ?? join10(homedir2(), ".pi", "agent"), "navigator-model.json");
3893
+ return join8(process.env.PI_CODING_AGENT_DIR ?? join8(homedir2(), ".pi", "agent"), "navigator-model.json");
3955
3894
  }
3956
3895
  async function readNavigatorModelSetting(path = navigatorModelSettingPath()) {
3957
3896
  try {
3958
- const raw = JSON.parse(await readFile6(path, "utf8"));
3897
+ const raw = JSON.parse(await readFile5(path, "utf8"));
3959
3898
  if (!exactRecord(raw) || typeof raw.model !== "string" || raw.model.trim() === "") {
3960
3899
  throw new Error("Navigator model setting is malformed");
3961
3900
  }
@@ -4078,11 +4017,11 @@ function createReceiptDeliveryPolicy() {
4078
4017
  }
4079
4018
 
4080
4019
  // src/typed-provider-http.ts
4081
- import { readFile as readFile7, unlink, writeFile as writeFile5 } from "node:fs/promises";
4082
- import { join as join11 } from "node:path";
4020
+ import { readFile as readFile6, unlink, writeFile as writeFile4 } from "node:fs/promises";
4021
+ import { join as join9 } from "node:path";
4083
4022
  var TYPED_HTTP_FILE = "typed-provider-http.json";
4084
4023
  function typedProviderHttpPath(runDirectory) {
4085
- return join11(runDirectory, TYPED_HTTP_FILE);
4024
+ return join9(runDirectory, TYPED_HTTP_FILE);
4086
4025
  }
4087
4026
  async function clearTypedProviderHttpObservation(runDirectory) {
4088
4027
  try {
@@ -4103,7 +4042,7 @@ async function recordTypedProviderHttpStatus(runDirectory, observation) {
4103
4042
  httpStatus: observation.httpStatus,
4104
4043
  provider: observation.provider
4105
4044
  };
4106
- await writeFile5(
4045
+ await writeFile4(
4107
4046
  typedProviderHttpPath(runDirectory),
4108
4047
  `${JSON.stringify(body)}
4109
4048
  `,
@@ -4124,7 +4063,7 @@ async function buildEvidenceChildSystemPrompt(engineMaterial) {
4124
4063
  return appendEngineSessionMaterial(materials, engineMaterial).join("\n");
4125
4064
  }
4126
4065
  async function withInProcessScratch(options, run) {
4127
- const scratch = await mkdtemp3(join14(options.parentDirectory ?? tmpdir3(), options.prefix));
4066
+ const scratch = await mkdtemp3(join13(options.parentDirectory ?? tmpdir3(), options.prefix));
4128
4067
  let failure2;
4129
4068
  try {
4130
4069
  return await run(scratch);
@@ -4359,7 +4298,6 @@ function auditorSeatKey(gateSeat) {
4359
4298
  return gateSeat ?? "auditor";
4360
4299
  }
4361
4300
  async function executeAuditorChild(options) {
4362
- const { createRecordSession: createRecordSession2 } = await Promise.resolve().then(() => (init_archivist_record_entry(), archivist_record_entry_exports));
4363
4301
  const runDirectory = options.runDirectory ?? auditorRunDirectory(options.context);
4364
4302
  if (runDirectory === void 0) {
4365
4303
  throw new Error(`${options.roleLabel} requires a run directory carrying the institutional resolution page`);
@@ -4404,12 +4342,10 @@ async function executeAuditorChild(options) {
4404
4342
  const parentHeader = parentSessionManager?.getHeader?.();
4405
4343
  const parentSessionFile = parentSessionManager?.getSessionFile?.();
4406
4344
  const parentAttemptEntryId = parentSessionManager?.getLeafId?.();
4407
- const ticketNumber = await readRunTicketNumber(runDirectory);
4408
- const memorySubject = ticketNumber !== void 0 && isTicketSeatMemorySeat(seat) ? ticketSeatMemorySubject(ticketNumber, seat) : void 0;
4345
+ const { createRecordSession: createRecordSession2 } = await Promise.resolve().then(() => (init_archivist_record_entry(), archivist_record_entry_exports));
4409
4346
  const auditorSessionManager = createRecordSession2({
4410
4347
  cwd,
4411
- kind: TICKET_SEAT_MEMORY_KIND,
4412
- ...memorySubject === void 0 ? {} : { subject: memorySubject },
4348
+ kind: "auditor-roles",
4413
4349
  ...parentSessionManager === void 0 ? {} : { parent: parentSessionManager }
4414
4350
  });
4415
4351
  const { openPiInstitutionalSession: openPiInstitutionalSession2 } = await Promise.resolve().then(() => (init_in_process_session(), in_process_session_exports));
@@ -5062,7 +4998,7 @@ function createPiDoctorAuditor() {
5062
4998
  }
5063
4999
 
5064
5000
  // src/doctor-evidence.ts
5065
- import { readdir, readFile as readFile8, realpath as realpath2, stat } from "node:fs/promises";
5001
+ import { readdir, readFile as readFile7, realpath as realpath2, stat } from "node:fs/promises";
5066
5002
  import { dirname as dirname9, relative as relative2, resolve as resolve8, sep as sep2 } from "node:path";
5067
5003
 
5068
5004
  // src/audit-escalation.ts
@@ -5464,7 +5400,7 @@ async function loadDoctorCase(runsPath) {
5464
5400
  const turns = { count: 0, sources: [] }, calls = { count: 0, sources: [] }, tokens = { count: 0, sources: [] };
5465
5401
  for (const path of await discoverCaseFiles(root)) {
5466
5402
  const id = relative2(root, path).split(sep2).join("/");
5467
- const bytes = await readFile8(path);
5403
+ const bytes = await readFile7(path);
5468
5404
  const content = bytes.toString("utf8");
5469
5405
  const kind = id.endsWith(".jsonl") ? "session" : "stderr";
5470
5406
  evidence.push({ id, kind, byteLength: bytes.byteLength, contentLength: content.length, sha256: sha256Hex(bytes), content });
@@ -6469,23 +6405,23 @@ ${helpContext}
6469
6405
  }
6470
6406
 
6471
6407
  // src/navigator-work-context.ts
6472
- import { readFile as readFile12 } from "node:fs/promises";
6408
+ import { readFile as readFile11 } from "node:fs/promises";
6473
6409
  import { resolve as resolve13 } from "node:path";
6474
6410
 
6475
6411
  // src/notary-source-run.ts
6476
6412
  init_activation_ledger_git();
6477
6413
  init_activation_ledger_topology();
6478
- import { dirname as dirname11, isAbsolute as isAbsolute4, join as join18, resolve as resolve12, basename as basename5 } from "node:path";
6414
+ import { dirname as dirname11, isAbsolute as isAbsolute4, join as join17, resolve as resolve12, basename as basename5 } from "node:path";
6479
6415
  import { lstat as lstat2, realpath as realpath4 } from "node:fs/promises";
6480
6416
 
6481
6417
  // src/public-cli/run-lifecycle.ts
6482
6418
  init_activation_ledger_topology();
6483
- import { chmod, open, readdir as readdir2, readFile as readFile11, unlink as unlink2, writeFile as writeFile7 } from "node:fs/promises";
6484
- import { join as join17 } from "node:path";
6419
+ import { chmod, open, readdir as readdir2, readFile as readFile10, unlink as unlink2, writeFile as writeFile6 } from "node:fs/promises";
6420
+ import { join as join16 } from "node:path";
6485
6421
 
6486
6422
  // src/collector-config.ts
6487
6423
  import { createHash as createHash6 } from "node:crypto";
6488
- import { readFile as readFile9 } from "node:fs/promises";
6424
+ import { readFile as readFile8 } from "node:fs/promises";
6489
6425
  var COLLECTOR_HOST = "github.com";
6490
6426
  var COLLECTOR_OWNER_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/;
6491
6427
  var COLLECTOR_REPO_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,98}[A-Za-z0-9])?$/;
@@ -6532,7 +6468,7 @@ function emptyCollectorManifest() {
6532
6468
  async function loadCollectorManifest(path) {
6533
6469
  let bytes;
6534
6470
  try {
6535
- bytes = await readFile9(path);
6471
+ bytes = await readFile8(path);
6536
6472
  } catch (error) {
6537
6473
  fail3(`Collector request manifest is unreadable at ${path}`, error);
6538
6474
  }
@@ -6563,11 +6499,11 @@ init_activation_ledger_git();
6563
6499
  import {
6564
6500
  lstat,
6565
6501
  mkdir as mkdir2,
6566
- readFile as readFile10,
6502
+ readFile as readFile9,
6567
6503
  realpath as realpath3,
6568
- writeFile as writeFile6
6504
+ writeFile as writeFile5
6569
6505
  } from "node:fs/promises";
6570
- import { basename as basename4, isAbsolute as isAbsolute3, join as join16, resolve as resolve11, sep as sep3 } from "node:path";
6506
+ import { basename as basename4, isAbsolute as isAbsolute3, join as join15, resolve as resolve11, sep as sep3 } from "node:path";
6571
6507
 
6572
6508
  // src/public-cli/option-definitions.ts
6573
6509
  var SHARED_PROJECT_SEMANTICS = {
@@ -7030,7 +6966,7 @@ var PUBLIC_COMMAND_HELP = {
7030
6966
  async function loadAdmittedJudgeRequest(runDirectory) {
7031
6967
  try {
7032
6968
  const raw = JSON.parse(
7033
- await readFile10(join16(runDirectory, "admitted-request.json"), "utf8")
6969
+ await readFile9(join15(runDirectory, "admitted-request.json"), "utf8")
7034
6970
  );
7035
6971
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return void 0;
7036
6972
  const record4 = raw;
@@ -7054,10 +6990,51 @@ var RUN_STATE_FILE = "run-state.json";
7054
6990
  function isV1ResumableProvider(provider) {
7055
6991
  return V1_RESUMABLE_PROVIDERS.includes(provider);
7056
6992
  }
6993
+ function parseSameTicketSummonsMaterials(raw) {
6994
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return void 0;
6995
+ const record4 = raw;
6996
+ const instruction = typeof record4.instruction === "string" ? record4.instruction : void 0;
6997
+ const instructionEmpty = typeof record4.instructionEmpty === "boolean" ? record4.instructionEmpty : void 0;
6998
+ const attachmentPaths = Array.isArray(record4.attachmentPaths) ? record4.attachmentPaths.filter((p) => typeof p === "string" && p.length > 0) : void 0;
6999
+ const sourceRunPath = typeof record4.sourceRunPath === "string" && record4.sourceRunPath.trim() !== "" ? record4.sourceRunPath : void 0;
7000
+ let sourceRun;
7001
+ if (record4.sourceRun !== null && typeof record4.sourceRun === "object" && !Array.isArray(record4.sourceRun)) {
7002
+ const sr = record4.sourceRun;
7003
+ if (typeof sr.runId === "string" && sr.runId.trim() !== "" && typeof sr.role === "string" && sr.role.trim() !== "" && typeof sr.runDirectory === "string" && sr.runDirectory.trim() !== "") {
7004
+ sourceRun = {
7005
+ runId: sr.runId,
7006
+ role: sr.role,
7007
+ runDirectory: sr.runDirectory
7008
+ };
7009
+ }
7010
+ }
7011
+ if (instruction === void 0 && instructionEmpty === void 0 && (attachmentPaths === void 0 || attachmentPaths.length === 0) && sourceRunPath === void 0 && sourceRun === void 0) {
7012
+ return void 0;
7013
+ }
7014
+ return {
7015
+ ...instruction === void 0 ? {} : { instruction },
7016
+ ...instructionEmpty === void 0 ? {} : { instructionEmpty },
7017
+ ...attachmentPaths === void 0 || attachmentPaths.length === 0 ? {} : { attachmentPaths },
7018
+ ...sourceRunPath === void 0 ? {} : { sourceRunPath },
7019
+ ...sourceRun === void 0 ? {} : { sourceRun }
7020
+ };
7021
+ }
7022
+ function parseCurrentCourtState(raw) {
7023
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return void 0;
7024
+ const record4 = raw;
7025
+ if (typeof record4.courtAttemptId !== "string" || record4.courtAttemptId.length === 0) {
7026
+ return void 0;
7027
+ }
7028
+ const summons = parseSameTicketSummonsMaterials(record4.summons);
7029
+ return {
7030
+ courtAttemptId: record4.courtAttemptId,
7031
+ ...summons === void 0 ? {} : { summons }
7032
+ };
7033
+ }
7057
7034
  async function readRoleRunStateDisk(runDirectory) {
7058
7035
  let raw;
7059
7036
  try {
7060
- raw = JSON.parse(await readFile11(join17(runDirectory, RUN_STATE_FILE), "utf8"));
7037
+ raw = JSON.parse(await readFile10(join16(runDirectory, RUN_STATE_FILE), "utf8"));
7061
7038
  } catch {
7062
7039
  return void 0;
7063
7040
  }
@@ -7093,6 +7070,7 @@ async function readRoleRunStateDisk(runDirectory) {
7093
7070
  }
7094
7071
  }
7095
7072
  const phase = record4.phase === "plan" || record4.phase === "apply" ? record4.phase : void 0;
7073
+ const currentCourt = parseCurrentCourtState(record4.currentCourt);
7096
7074
  return {
7097
7075
  runId: record4.runId,
7098
7076
  role: record4.role,
@@ -7103,7 +7081,8 @@ async function readRoleRunStateDisk(runDirectory) {
7103
7081
  admittedRequestPath: record4.admittedRequestPath,
7104
7082
  principalWire,
7105
7083
  ...phase === void 0 ? {} : { phase },
7106
- ...resumable === void 0 ? {} : { resumable }
7084
+ ...resumable === void 0 ? {} : { resumable },
7085
+ ...currentCourt === void 0 ? {} : { currentCourt }
7107
7086
  };
7108
7087
  }
7109
7088
  async function readRoleRunIdentity(runDirectory) {
@@ -7198,7 +7177,7 @@ function navigatorInputReference(getFlag, role) {
7198
7177
  }
7199
7178
  async function loadNavigatorWorkContext(options) {
7200
7179
  const reference = navigatorInputReference(options.getFlag, options.role);
7201
- const input = reference === void 0 || options.role === "doctor" || options.role === "notary" ? void 0 : await readFile12(reference, "utf8");
7180
+ const input = reference === void 0 || options.role === "doctor" || options.role === "notary" ? void 0 : await readFile11(reference, "utf8");
7202
7181
  const subjectRoot = subjectPath(reference ?? options.context.sessionManager.getSessionDir(), options.context.cwd);
7203
7182
  let subjectKey = reference === void 0 ? subjectRoot : navigatorSubjectKeyForInput(subjectRoot, reference, options.context.cwd);
7204
7183
  let subject = input ?? `work subject: ${subjectKey}`;
@@ -7255,7 +7234,7 @@ async function loadNavigatorWorkContext(options) {
7255
7234
  let authorityMaterial;
7256
7235
  for (const path of authorityFiles) {
7257
7236
  try {
7258
- const content = await readFile12(path, "utf8");
7237
+ const content = await readFile11(path, "utf8");
7259
7238
  if (content.trim() !== "") {
7260
7239
  authorityMaterial = content;
7261
7240
  break;
@@ -7281,8 +7260,8 @@ import { dirname as dirname12 } from "node:path";
7281
7260
 
7282
7261
  // src/package-resources/method-skill.ts
7283
7262
  import { createHash as createHash7 } from "node:crypto";
7284
- import { readFile as readFile13, realpath as realpath5 } from "node:fs/promises";
7285
- import { join as join19 } from "node:path";
7263
+ import { readFile as readFile12, realpath as realpath5 } from "node:fs/promises";
7264
+ import { join as join18 } from "node:path";
7286
7265
  var PackagedMethodSkillUnavailableError = class extends Error {
7287
7266
  constructor(skillName, path, cause) {
7288
7267
  super(`Canonical ${skillName} Skill is unavailable at ${path}`, { cause });
@@ -7318,10 +7297,10 @@ function packagedMethodSkillRelativeDirectory(name) {
7318
7297
  return `${METHOD_SKILL_RELATIVE_ROOT}/${name}`;
7319
7298
  }
7320
7299
  function resolvePackagedMethodSkillRoot(packageRoot, name) {
7321
- return join19(packageRoot, packagedMethodSkillRelativeDirectory(name));
7300
+ return join18(packageRoot, packagedMethodSkillRelativeDirectory(name));
7322
7301
  }
7323
7302
  function resolvePackagedMethodSkillPath(packageRoot, name) {
7324
- return join19(resolvePackagedMethodSkillRoot(packageRoot, name), "SKILL.md");
7303
+ return join18(resolvePackagedMethodSkillRoot(packageRoot, name), "SKILL.md");
7325
7304
  }
7326
7305
  function isRecord11(value) {
7327
7306
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -7415,11 +7394,11 @@ function parseProvenance(raw, expectedName) {
7415
7394
  }
7416
7395
  async function loadPackagedMethodSkillMaterial(packageRoot, name) {
7417
7396
  const rootDirectory = resolvePackagedMethodSkillRoot(packageRoot, name);
7418
- const skillPathConfigured = join19(rootDirectory, "SKILL.md");
7419
- const provenancePath = join19(rootDirectory, "provenance.json");
7397
+ const skillPathConfigured = join18(rootDirectory, "SKILL.md");
7398
+ const provenancePath = join18(rootDirectory, "provenance.json");
7420
7399
  let provenanceRaw;
7421
7400
  try {
7422
- provenanceRaw = await readFile13(provenancePath, "utf8");
7401
+ provenanceRaw = await readFile12(provenancePath, "utf8");
7423
7402
  } catch (error) {
7424
7403
  throw new PackagedMethodSkillUnavailableError(name, provenancePath, error);
7425
7404
  }
@@ -7433,10 +7412,10 @@ async function loadPackagedMethodSkillMaterial(packageRoot, name) {
7433
7412
  }
7434
7413
  const provenance = parseProvenance(provenanceJson, name);
7435
7414
  for (const [rel, expected] of Object.entries(provenance.files)) {
7436
- const absolute = join19(rootDirectory, rel);
7415
+ const absolute = join18(rootDirectory, rel);
7437
7416
  let bytes;
7438
7417
  try {
7439
- bytes = await readFile13(absolute);
7418
+ bytes = await readFile12(absolute);
7440
7419
  } catch (error) {
7441
7420
  throw new PackagedMethodSkillUnavailableError(name, absolute, error);
7442
7421
  }
@@ -7452,7 +7431,7 @@ async function loadPackagedMethodSkillMaterial(packageRoot, name) {
7452
7431
  let raw;
7453
7432
  try {
7454
7433
  skillPath = await realpath5(skillPathConfigured);
7455
- raw = await readFile13(skillPath, "utf8");
7434
+ raw = await readFile12(skillPath, "utf8");
7456
7435
  } catch (error) {
7457
7436
  throw new PackagedMethodSkillUnavailableError(name, skillPathConfigured, error);
7458
7437
  }
@@ -7546,7 +7525,7 @@ async function executeReviewerChild(workspace, leg, context, options = {}) {
7546
7525
  import { spawn as spawn3 } from "node:child_process";
7547
7526
  import { mkdtemp as mkdtemp4, rm as rm4 } from "node:fs/promises";
7548
7527
  import { tmpdir as tmpdir4 } from "node:os";
7549
- import { join as join20 } from "node:path";
7528
+ import { join as join19 } from "node:path";
7550
7529
 
7551
7530
  // src/reviewer-git-snapshot.ts
7552
7531
  var REVIEW_REF_PREFIXES = ["refs/heads", "refs/tags", "refs/remotes"];
@@ -7647,8 +7626,8 @@ async function prepareSnapshot(accepted, signal, dependencies) {
7647
7626
  if (!sameReviewerPinnedTarget({ repositoryRoot: accepted.repositoryRoot, objectFormat, targetHead }, accepted)) throw new Error("Accepted Reviewer target identity no longer matches the repository");
7648
7627
  await git2(accepted.repositoryRoot, ["cat-file", "-e", `${targetHead}^{commit}`], signal);
7649
7628
  dependencies.fault?.("mirror.before-create");
7650
- mirrorRoot = await mkdtemp4(join20(tmpdir4(), "ak-reviewer-snapshot-"));
7651
- const mirrorPath = join20(mirrorRoot, "repository.git");
7629
+ mirrorRoot = await mkdtemp4(join19(tmpdir4(), "ak-reviewer-snapshot-"));
7630
+ const mirrorPath = join19(mirrorRoot, "repository.git");
7652
7631
  dependencies.fault?.("mirror.create");
7653
7632
  await runCommand("git", ["init", "--bare", `--object-format=${accepted.objectFormat}`, mirrorPath], signal === void 0 ? {} : { signal });
7654
7633
  await git2(mirrorPath, ["fetch", "--no-tags", accepted.repositoryRoot, targetHead], signal);
@@ -7665,7 +7644,7 @@ async function prepareClone(snapshot, signal, dependencies) {
7665
7644
  const target = { repositoryRoot: snapshot.repositoryRoot, objectFormat: snapshot.objectFormat, targetHead: snapshot.targetHead, refs: { ...snapshot.refs } };
7666
7645
  try {
7667
7646
  dependencies.fault?.("workspace.before-create");
7668
- workspace = await mkdtemp4(join20(tmpdir4(), "ak-reviewer-leg-"));
7647
+ workspace = await mkdtemp4(join19(tmpdir4(), "ak-reviewer-leg-"));
7669
7648
  dependencies.fault?.("workspace.init");
7670
7649
  await git2(workspace, ["init", `--object-format=${snapshot.objectFormat}`, "--initial-branch=ak-reviewer-unborn"], signal);
7671
7650
  dependencies.fault?.("workspace.fetch");
@@ -7847,7 +7826,7 @@ function stringEnum(values, options = {}) {
7847
7826
 
7848
7827
  // src/public-cli/reviewer-dispatch-rejection.ts
7849
7828
  import { writeFileSync as writeFileSync4 } from "node:fs";
7850
- import { join as join21 } from "node:path";
7829
+ import { join as join20 } from "node:path";
7851
7830
 
7852
7831
  // src/adr-path-refs.ts
7853
7832
  var ADR_PATH_IN_BODY = /docs\/adr\/(?:[A-Za-z0-9][A-Za-z0-9._-]*\/)*[A-Za-z0-9][A-Za-z0-9._-]*\.md/g;
@@ -8446,7 +8425,7 @@ function createReviewerDispatcher(d) {
8446
8425
  // src/public-cli/reviewer-dispatch-rejection.ts
8447
8426
  var REVIEWER_DISPATCH_REJECTION_FILE = "typed-known-failure.json";
8448
8427
  function reviewerDispatchRejectionPath(runDirectory) {
8449
- return join21(runDirectory, REVIEWER_DISPATCH_REJECTION_FILE);
8428
+ return join20(runDirectory, REVIEWER_DISPATCH_REJECTION_FILE);
8450
8429
  }
8451
8430
  function recordReviewerDispatchRejectionSync(runDirectory, rejection) {
8452
8431
  writeFileSync4(
@@ -8614,7 +8593,7 @@ async function requireGatekeeperPass(options) {
8614
8593
  }
8615
8594
 
8616
8595
  // src/run-terminal-artifacts.ts
8617
- import { basename as basename6, dirname as dirname13, join as join22 } from "node:path";
8596
+ import { basename as basename6, dirname as dirname13, join as join21 } from "node:path";
8618
8597
  function runIdFromRunDirectory(runDirectory) {
8619
8598
  const name = basename6(runDirectory);
8620
8599
  const at = name.lastIndexOf("@");
@@ -8633,7 +8612,10 @@ function runIdentity(context) {
8633
8612
  if (typeof headerId === "string" && headerId.length > 0) return headerId;
8634
8613
  throw new Error("\u63D0\u4EA4\u8D26\u9700\u8981\u5DF2\u53D7\u7406\u7684 run \u8EAB\u4EFD");
8635
8614
  }
8615
+ var COURT_ATTEMPT_ENV = "AK_ROLE_COURT_ATTEMPT";
8636
8616
  function attemptIdentity(context, runId) {
8617
+ const courtAttempt = process.env[COURT_ATTEMPT_ENV];
8618
+ if (typeof courtAttempt === "string" && courtAttempt.length > 0) return courtAttempt;
8637
8619
  return context.sessionManager.getHeader?.()?.id ?? context.sessionManager.getLeafId?.() ?? `${runId}:initial`;
8638
8620
  }
8639
8621
  function submissionRecordFile(cwd, runId, home) {
@@ -8653,12 +8635,22 @@ async function readOwnedSubmissionRecords(cwd, runId, home) {
8653
8635
  owned: records2.filter((record4) => typeof record4.subject === "object" && record4.subject !== null && record4.subject.runId === runId)
8654
8636
  };
8655
8637
  }
8638
+ function sealedAttemptIdFromRecord(record4) {
8639
+ if (record4.kind !== "sealed") return void 0;
8640
+ const payload = record4.payload;
8641
+ return payload?.type === "sealed" && typeof payload.attemptId === "string" && payload.attemptId.length > 0 ? payload.attemptId : void 0;
8642
+ }
8656
8643
  async function restoreState(cwd, runId, home) {
8657
8644
  const { file, owned } = await readOwnedSubmissionRecords(cwd, runId, home);
8658
8645
  const last = owned.at(-1);
8646
+ const sealedAttemptIds = /* @__PURE__ */ new Set();
8647
+ for (const record4 of owned) {
8648
+ const attemptId = sealedAttemptIdFromRecord(record4);
8649
+ if (attemptId !== void 0) sealedAttemptIds.add(attemptId);
8650
+ }
8659
8651
  return {
8660
8652
  ...last === void 0 ? {} : { prior: { identity: last.identity, recordFile: file, kind: last.kind, level: last.level } },
8661
- sealed: owned.some((record4) => record4.kind === "sealed"),
8653
+ sealedAttemptIds,
8662
8654
  sequence: owned.reduce((maximum, record4) => {
8663
8655
  const payload = record4.payload;
8664
8656
  return payload?.type === "candidate" && typeof payload.sequence === "number" ? Math.max(maximum, payload.sequence) : maximum;
@@ -8701,7 +8693,9 @@ function createSubmissionLedgerHost(host, outputTools, failInfrastructure2 = (er
8701
8693
  const runId = runIdentity(context);
8702
8694
  const attemptId = attemptIdentity(context, runId);
8703
8695
  const state = await stateFor(context, runId);
8704
- if (state.sealed) appendFor(state, context, runId, attemptId, { type: "post-seal-anomaly", attemptId, toolCallId, toolName });
8696
+ if (state.sealedAttemptIds.has(attemptId)) {
8697
+ appendFor(state, context, runId, attemptId, { type: "post-seal-anomaly", attemptId, toolCallId, toolName });
8698
+ }
8705
8699
  } catch (error) {
8706
8700
  failInfrastructure2(error, context);
8707
8701
  }
@@ -8742,7 +8736,7 @@ function createSubmissionLedgerHost(host, outputTools, failInfrastructure2 = (er
8742
8736
  if (typeof status !== "string" || status.length === 0) throw new Error("\u63D0\u4EA4\u8D26\u5C01\u8D26\u7F3A\u5C11 acceptedFacts.status");
8743
8737
  const projection = { kind: "accepted", role: candidate.role, status, decisiveFacts: details };
8744
8738
  appendFor(state, candidate.context, runId, attemptId, { type: "sealed", attemptId, toolCallId: candidate.toolCallId, accepted: candidate.result.details, projection });
8745
- state.sealed = true;
8739
+ state.sealedAttemptIds.add(attemptId);
8746
8740
  await projectClosure(projection, context);
8747
8741
  context.abort();
8748
8742
  } catch (error) {
@@ -8761,7 +8755,7 @@ function createSubmissionLedgerHost(host, outputTools, failInfrastructure2 = (er
8761
8755
  const attemptId = attemptIdentity(context, runId);
8762
8756
  const state = await stateFor(context, runId);
8763
8757
  const append = (event) => appendFor(state, context, runId, attemptId, event);
8764
- if (state.sealed) throw new Error("\u63D0\u4EA4\u8D26\u5DF2\u5C01\u8D26");
8758
+ if (state.sealedAttemptIds.has(attemptId)) throw new Error("\u63D0\u4EA4\u8D26\u5DF2\u5C01\u8D26");
8765
8759
  append({ type: "candidate", attemptId, toolCallId, toolName: tool2.name, sequence: ++state.sequence });
8766
8760
  const projectOfficerEscalation = (officer, original, deliveredOutput = original) => projectAuditEscalation({
8767
8761
  ...original,
@@ -13564,15 +13558,15 @@ function createRoleRuntimeExtension(dependencies) {
13564
13558
 
13565
13559
  // src/grok/role-envelope.ts
13566
13560
  import { randomUUID as randomUUID2 } from "node:crypto";
13567
- import { mkdir as mkdir5, readFile as readFile14, writeFile as writeFile9 } from "node:fs/promises";
13561
+ import { mkdir as mkdir5, readFile as readFile13, writeFile as writeFile8 } from "node:fs/promises";
13568
13562
  import { createServer } from "node:net";
13569
- import { basename as basename8, dirname as dirname16, join as join25 } from "node:path";
13563
+ import { basename as basename8, dirname as dirname16, join as join24 } from "node:path";
13570
13564
  import { fileURLToPath as fileURLToPath2 } from "node:url";
13571
13565
 
13572
13566
  // src/grok/role-turn-host.ts
13573
13567
  import { execFile as execFile3, spawn as spawn4 } from "node:child_process";
13574
13568
  import { copyFile, lstat as lstat3, mkdir as mkdir4, open as open2, realpath as realpath7, rm as rm5 } from "node:fs/promises";
13575
- import { basename as basename7, dirname as dirname15, isAbsolute as isAbsolute7, join as join24, relative as pathRelative } from "node:path";
13569
+ import { basename as basename7, dirname as dirname15, isAbsolute as isAbsolute7, join as join23, relative as pathRelative } from "node:path";
13576
13570
  import { createInterface } from "node:readline";
13577
13571
  import { promisify as promisify3 } from "node:util";
13578
13572
 
@@ -13583,8 +13577,8 @@ function renderAgentStartMaterials(body, materials) {
13583
13577
  }
13584
13578
 
13585
13579
  // src/grok/bash-seatbelt.ts
13586
- import { mkdir as mkdir3, writeFile as writeFile8 } from "node:fs/promises";
13587
- import { join as join23 } from "node:path";
13580
+ import { mkdir as mkdir3, writeFile as writeFile7 } from "node:fs/promises";
13581
+ import { join as join22 } from "node:path";
13588
13582
  function renderGrokBashSeatbeltHookScript() {
13589
13583
  const reasons = Object.fromEntries(
13590
13584
  FIXER_BASH_FORBIDDEN_LITERALS.map((literal) => [literal, fixerBashSeatbeltDenyReason(literal)])
@@ -13612,12 +13606,12 @@ process.stdin.on("end", () => {
13612
13606
  `;
13613
13607
  }
13614
13608
  async function installGrokPreToolUseDeny(controlledHome) {
13615
- const hooksDir = join23(controlledHome, "hooks");
13609
+ const hooksDir = join22(controlledHome, "hooks");
13616
13610
  await mkdir3(hooksDir, { recursive: true });
13617
13611
  const scriptName = "ak-bash-seatbelt.mjs";
13618
- const scriptPath = join23(hooksDir, scriptName);
13619
- await writeFile8(scriptPath, renderGrokBashSeatbeltHookScript(), { mode: 493 });
13620
- await writeFile8(join23(hooksDir, "ak-bash-seatbelt.json"), `${JSON.stringify({
13612
+ const scriptPath = join22(hooksDir, scriptName);
13613
+ await writeFile7(scriptPath, renderGrokBashSeatbeltHookScript(), { mode: 493 });
13614
+ await writeFile7(join22(hooksDir, "ak-bash-seatbelt.json"), `${JSON.stringify({
13621
13615
  hooks: {
13622
13616
  PreToolUse: [
13623
13617
  {
@@ -13990,7 +13984,7 @@ async function resolveHeadTreePath(topLevel, relativePath) {
13990
13984
  encoding: "utf8"
13991
13985
  });
13992
13986
  const needle = leaf.toLowerCase();
13993
- const hits = listing.split("\n").map((name) => name.trim()).filter((name) => name !== "" && basename7(name).toLowerCase() === needle).map((name) => parent === "." ? basename7(name) : join24(parent, basename7(name)));
13987
+ const hits = listing.split("\n").map((name) => name.trim()).filter((name) => name !== "" && basename7(name).toLowerCase() === needle).map((name) => parent === "." ? basename7(name) : join23(parent, basename7(name)));
13994
13988
  return hits.length === 1 ? hits[0] : void 0;
13995
13989
  }
13996
13990
  async function isHeadMatchedProjectInstruction(repositoryCwd, absolutePath) {
@@ -14008,14 +14002,14 @@ async function isHeadMatchedProjectInstruction(repositoryCwd, absolutePath) {
14008
14002
  if (parent === void 0) return false;
14009
14003
  const leaf = basename7(absolutePath);
14010
14004
  if (leaf === "" || leaf === "." || leaf === "..") return false;
14011
- const candidate = join24(parent, leaf);
14005
+ const candidate = join23(parent, leaf);
14012
14006
  const relative3 = pathRelative(topLevel, candidate);
14013
14007
  if (relative3 === "" || relative3.startsWith("..") || isAbsolute7(relative3) || relative3.includes("\0")) {
14014
14008
  return false;
14015
14009
  }
14016
14010
  const headRel = await resolveHeadTreePath(topLevel, relative3);
14017
14011
  if (headRel === void 0) return false;
14018
- const headFile = join24(topLevel, headRel);
14012
+ const headFile = join23(topLevel, headRel);
14019
14013
  const { stdout: headBlobOut } = await execFileAsync3(
14020
14014
  "git",
14021
14015
  ["rev-parse", "--verify", `HEAD:${headRel}`],
@@ -14114,20 +14108,20 @@ async function assertControlledGrokAuthIsNotSymlink(authPath) {
14114
14108
  }
14115
14109
  }
14116
14110
  async function scrubAkBashSeatbeltHooks(controlledHome) {
14117
- const hooksDir = join24(controlledHome, "hooks");
14111
+ const hooksDir = join23(controlledHome, "hooks");
14118
14112
  for (const name of AK_BASH_SEATBELT_HOOK_FILES) {
14119
- await rm5(join24(hooksDir, name), { force: true });
14113
+ await rm5(join23(hooksDir, name), { force: true });
14120
14114
  }
14121
14115
  }
14122
14116
  async function prepareControlledGrokHome(sourceHome, controlledHome) {
14123
14117
  await assertControlledGrokHomeIsRealDirectory(controlledHome);
14124
14118
  await mkdir4(controlledHome, { recursive: true, mode: 448 });
14125
14119
  await assertControlledGrokHomeIsRealDirectory(controlledHome);
14126
- const authPath = join24(controlledHome, "auth.json");
14120
+ const authPath = join23(controlledHome, "auth.json");
14127
14121
  await assertControlledGrokAuthIsNotSymlink(authPath);
14128
14122
  await rm5(authPath, { force: true });
14129
14123
  await scrubAkBashSeatbeltHooks(controlledHome);
14130
- await copyFile(join24(sourceHome, ".grok", "auth.json"), authPath);
14124
+ await copyFile(join23(sourceHome, ".grok", "auth.json"), authPath);
14131
14125
  }
14132
14126
  async function inspectControlledGrok(options) {
14133
14127
  const { stdout } = await execFileAsync3(options.binary, ["inspect", "--json"], {
@@ -14248,14 +14242,14 @@ async function prepareGrokRoleEnvelope(options) {
14248
14242
  for (const method of request.methods) {
14249
14243
  if (method.kind !== "skill") continue;
14250
14244
  const name = basename8(dirname16(method.path));
14251
- const raw = await readFile14(method.path, "utf8");
14245
+ const raw = await readFile13(method.path, "utf8");
14252
14246
  methodSkills.set(name, { path: method.path, body: stripSkillFrontmatter(raw).trim() });
14253
14247
  }
14254
- let sessionFile = options.sessionFile ?? join25(request.runDirectory, "session", "session.jsonl");
14248
+ let sessionFile = options.sessionFile ?? join24(request.runDirectory, "session", "session.jsonl");
14255
14249
  await mkdir5(dirname16(sessionFile), { recursive: true });
14256
14250
  if (request.continuation.kind !== "resume") {
14257
14251
  try {
14258
- await writeFile9(
14252
+ await writeFile8(
14259
14253
  sessionFile,
14260
14254
  `${JSON.stringify({
14261
14255
  type: "session",
@@ -14580,12 +14574,15 @@ async function prepareGrokRoleEnvelope(options) {
14580
14574
  const relay = fileURLToPath2(new URL("./mcp-relay.mjs", import.meta.url));
14581
14575
  let disposed = false;
14582
14576
  let priorAkRoleRunDir;
14577
+ let priorAkRoleCourtAttempt;
14583
14578
  let runDirInjected = false;
14584
- const restoreAkRoleRunDir = () => {
14579
+ const restoreAkRoleRunEnv = () => {
14585
14580
  if (!runDirInjected) return;
14586
14581
  runDirInjected = false;
14587
14582
  if (priorAkRoleRunDir === void 0) delete process.env.AK_ROLE_RUN_DIR;
14588
14583
  else process.env.AK_ROLE_RUN_DIR = priorAkRoleRunDir;
14584
+ if (priorAkRoleCourtAttempt === void 0) delete process.env.AK_ROLE_COURT_ATTEMPT;
14585
+ else process.env.AK_ROLE_COURT_ATTEMPT = priorAkRoleCourtAttempt;
14589
14586
  };
14590
14587
  const dispose = async () => {
14591
14588
  if (disposed) return;
@@ -14597,7 +14594,7 @@ async function prepareGrokRoleEnvelope(options) {
14597
14594
  cleanupFailures.push(error);
14598
14595
  }
14599
14596
  try {
14600
- restoreAkRoleRunDir();
14597
+ restoreAkRoleRunEnv();
14601
14598
  } catch (error) {
14602
14599
  cleanupFailures.push(error);
14603
14600
  }
@@ -14663,7 +14660,7 @@ async function prepareGrokRoleEnvelope(options) {
14663
14660
  message: { role: "user", content: prompt }
14664
14661
  });
14665
14662
  }
14666
- const methodPrompt = (await Promise.all(request.methods.map(({ path }) => readFile14(path, "utf8")))).join("\n\n");
14663
+ const methodPrompt = (await Promise.all(request.methods.map(({ path }) => readFile13(path, "utf8")))).join("\n\n");
14667
14664
  const promptResults = await emit("before_agent_start", {
14668
14665
  prompt,
14669
14666
  systemPrompt: methodPrompt,
@@ -14678,7 +14675,10 @@ async function prepareGrokRoleEnvelope(options) {
14678
14675
  if (material !== void 0) readingMaterials.push(material);
14679
14676
  }
14680
14677
  priorAkRoleRunDir = process.env.AK_ROLE_RUN_DIR;
14678
+ priorAkRoleCourtAttempt = process.env.AK_ROLE_COURT_ATTEMPT;
14681
14679
  process.env.AK_ROLE_RUN_DIR = request.runDirectory;
14680
+ if (request.courtAttemptId === void 0) delete process.env.AK_ROLE_COURT_ATTEMPT;
14681
+ else process.env.AK_ROLE_COURT_ATTEMPT = request.courtAttemptId;
14682
14682
  runDirInjected = true;
14683
14683
  return {
14684
14684
  mcpServers: [{
@@ -14711,18 +14711,18 @@ async function prepareGrokRoleEnvelope(options) {
14711
14711
  }
14712
14712
 
14713
14713
  // src/grok/session-identity.ts
14714
- import { mkdir as mkdir6, readFile as readFile15, rename, writeFile as writeFile10 } from "node:fs/promises";
14715
- import { dirname as dirname17, join as join26 } from "node:path";
14714
+ import { mkdir as mkdir6, readFile as readFile14, rename, writeFile as writeFile9 } from "node:fs/promises";
14715
+ import { dirname as dirname17, join as join25 } from "node:path";
14716
14716
  var GROK_ACP_SESSION_BINDING = "grok-acp-session.json";
14717
14717
  function createGrokSessionIdentityAuthority(authority) {
14718
- const bindingPath = (principal) => join26(authority.decode(principal).sessionDirectory, GROK_ACP_SESSION_BINDING);
14718
+ const bindingPath = (principal) => join25(authority.decode(principal).sessionDirectory, GROK_ACP_SESSION_BINDING);
14719
14719
  return {
14720
14720
  resolveSessionFile(principal) {
14721
14721
  return authority.decode(principal).sessionFile;
14722
14722
  },
14723
14723
  async load(principal) {
14724
14724
  try {
14725
- const value = JSON.parse(await readFile15(bindingPath(principal), "utf8"));
14725
+ const value = JSON.parse(await readFile14(bindingPath(principal), "utf8"));
14726
14726
  if (typeof value !== "object" || value === null || typeof value.sessionId !== "string") {
14727
14727
  throw new Error("durable Grok ACP session binding is invalid");
14728
14728
  }
@@ -14736,7 +14736,7 @@ function createGrokSessionIdentityAuthority(authority) {
14736
14736
  const target = bindingPath(principal);
14737
14737
  await mkdir6(dirname17(target), { recursive: true });
14738
14738
  const temporary = `${target}.${process.pid}.tmp`;
14739
- await writeFile10(temporary, `${JSON.stringify({ sessionId })}
14739
+ await writeFile9(temporary, `${JSON.stringify({ sessionId })}
14740
14740
  `, { encoding: "utf8", mode: 384 });
14741
14741
  await rename(temporary, target);
14742
14742
  }
@@ -14745,7 +14745,7 @@ function createGrokSessionIdentityAuthority(authority) {
14745
14745
 
14746
14746
  // src/grok/production-host.ts
14747
14747
  function resolveGrokBinary(operatorHome) {
14748
- return join27(operatorHome, ".grok", "bin", "grok");
14748
+ return join26(operatorHome, ".grok", "bin", "grok");
14749
14749
  }
14750
14750
  var NO_PRODUCTION_GROK_PRIMARY_FAILURE = {
14751
14751
  present: false
@@ -14753,7 +14753,7 @@ var NO_PRODUCTION_GROK_PRIMARY_FAILURE = {
14753
14753
  async function settleProductionGrokHomeCleanup(controlledHome, primaryFailure, concurrentMessage) {
14754
14754
  try {
14755
14755
  await assertControlledGrokHomeIsRealDirectory(controlledHome);
14756
- const authPath = join27(controlledHome, "auth.json");
14756
+ const authPath = join26(controlledHome, "auth.json");
14757
14757
  await assertControlledGrokAuthIsNotSymlink(authPath);
14758
14758
  await rm6(authPath, { force: true });
14759
14759
  await scrubAkBashSeatbeltHooks(controlledHome);
@@ -14770,7 +14770,7 @@ async function settleProductionGrokHomeCleanup(controlledHome, primaryFailure, c
14770
14770
  }
14771
14771
  }
14772
14772
  async function openProductionGrokHome(runDirectory, operatorHome) {
14773
- const controlledHome = join27(runDirectory, "grok-home");
14773
+ const controlledHome = join26(runDirectory, "grok-home");
14774
14774
  try {
14775
14775
  await prepareControlledGrokHome(operatorHome, controlledHome);
14776
14776
  return controlledHome;
@@ -14798,13 +14798,12 @@ async function bindProductionGrokIsolation(runDirectory, operatorHome, packageRo
14798
14798
  env: childEnv(controlledHome, packageRoot)
14799
14799
  };
14800
14800
  }
14801
- async function withProductionGrokIsolation(runDirectory, operatorHome, packageRoot, run, noteOpened) {
14801
+ async function withProductionGrokIsolation(runDirectory, operatorHome, packageRoot, run) {
14802
14802
  let binding;
14803
14803
  let primaryFailure = NO_PRODUCTION_GROK_PRIMARY_FAILURE;
14804
14804
  let value;
14805
14805
  try {
14806
14806
  binding = await bindProductionGrokIsolation(runDirectory, operatorHome, packageRoot);
14807
- noteOpened?.(runDirectory);
14808
14807
  value = await run(binding);
14809
14808
  } catch (error) {
14810
14809
  primaryFailure = { present: true, value: error };
@@ -14830,9 +14829,9 @@ function createGrokRoleRuntimeDependencies(packageRoot) {
14830
14829
  return {
14831
14830
  loadJudgeSoul: () => loadMainRoleSessionMaterials("judge"),
14832
14831
  loadFixerSoul: () => loadMainRoleSessionMaterials("fixer"),
14833
- loadFixPacket: (path) => readFile16(path, "utf8"),
14832
+ loadFixPacket: (path) => readFile15(path, "utf8"),
14834
14833
  loadCoderSoul: () => loadMainRoleSessionMaterials("coder"),
14835
- loadCoderTask: (path) => readFile16(path, "utf8"),
14834
+ loadCoderTask: (path) => readFile15(path, "utf8"),
14836
14835
  loadReviewerSoul: () => loadMainRoleSessionMaterials("reviewer"),
14837
14836
  createReviewerPinnedGitReader: () => createReviewerPinnedGitReader(),
14838
14837
  createReviewerIssueFetcher: () => createGhIssueSoftFetcher(),
@@ -14848,7 +14847,7 @@ function createGrokRoleRuntimeDependencies(packageRoot) {
14848
14847
  loadGleanerLeftSoul: () => loadMainRoleSessionMaterials("gleaner-left"),
14849
14848
  loadNotarySourceRun: loadNotarySourceRunLocator,
14850
14849
  loadMergerSoul: () => loadMainRoleSessionMaterials("merger"),
14851
- loadMergerInput: async (path) => JSON.parse(await readFile16(path, "utf8")),
14850
+ loadMergerInput: async (path) => JSON.parse(await readFile15(path, "utf8")),
14852
14851
  createMergerGitState: (repositoryRoot) => createProductionMergerGitState(repositoryRoot),
14853
14852
  async loadCanonicalSkillBinding(name) {
14854
14853
  if (name === "tdd") {
@@ -14878,7 +14877,7 @@ function createGrokRoleRuntimeDependencies(packageRoot) {
14878
14877
  authority: options.authority,
14879
14878
  invocationId: options.invocationId,
14880
14879
  loadSoul: () => loadMainRoleSessionMaterials("navigator"),
14881
- loadRoutePlaybook: () => readFile16(navigatorRoutePlaybookPath, "utf8"),
14880
+ loadRoutePlaybook: () => readFile15(navigatorRoutePlaybookPath, "utf8"),
14882
14881
  loadRoleHelp: async (role) => formatNavigatorRoleHelp(role),
14883
14882
  createSession: navigatorSessionFactory,
14884
14883
  ...options.contextError === void 0 ? {} : { contextError: options.contextError },
@@ -14887,19 +14886,13 @@ function createGrokRoleRuntimeDependencies(packageRoot) {
14887
14886
  };
14888
14887
  }
14889
14888
  async function recordGrokCapabilities(request, declaration) {
14890
- await writeFile11(
14891
- join27(request.runDirectory, "grok-capabilities.json"),
14889
+ await writeFile10(
14890
+ join26(request.runDirectory, "grok-capabilities.json"),
14892
14891
  `${JSON.stringify(declaration)}
14893
14892
  `,
14894
14893
  "utf8"
14895
14894
  );
14896
14895
  }
14897
- function resolveProductionGrokIsolationRunDirectory(request) {
14898
- if (request.continuation.kind === "resume" && typeof request.nativeHomeRunDirectory === "string" && request.nativeHomeRunDirectory.length > 0) {
14899
- return request.nativeHomeRunDirectory;
14900
- }
14901
- return request.runDirectory;
14902
- }
14903
14896
  function createProductionGrokRoleTurnHost(options) {
14904
14897
  const { packageRoot, principalAuthority } = options;
14905
14898
  let turn;
@@ -14933,10 +14926,9 @@ function createProductionGrokRoleTurnHost(options) {
14933
14926
  });
14934
14927
  return {
14935
14928
  executeTurn(request) {
14936
- const isolationRunDirectory = resolveProductionGrokIsolationRunDirectory(request);
14937
14929
  const execution = serial.then(
14938
14930
  () => withProductionGrokIsolation(
14939
- isolationRunDirectory,
14931
+ request.runDirectory,
14940
14932
  request.home,
14941
14933
  packageRoot,
14942
14934
  async (binding) => {
@@ -14946,8 +14938,7 @@ function createProductionGrokRoleTurnHost(options) {
14946
14938
  } finally {
14947
14939
  turn = void 0;
14948
14940
  }
14949
- },
14950
- request.noteNativeHomeOpened
14941
+ }
14951
14942
  )
14952
14943
  );
14953
14944
  serial = execution.then(