@akagilnc/pi-workflow-roles 0.1.5216 → 0.1.5235

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.
@@ -4462,57 +4462,15 @@ var init_sitian_contracts = __esm({
4462
4462
  });
4463
4463
 
4464
4464
  // src/sitian-appender.ts
4465
- import { createHash as createHash5, randomUUID } from "node:crypto";
4466
- import {
4467
- appendFileSync,
4468
- existsSync,
4469
- readFileSync,
4470
- unlinkSync,
4471
- writeFileSync
4472
- } from "node:fs";
4465
+ import { randomUUID } from "node:crypto";
4466
+ import { appendFileSync } from "node:fs";
4473
4467
  import { dirname as dirname4, join as join3 } from "node:path";
4474
- function isRecord3(value) {
4475
- return typeof value === "object" && value !== null && !Array.isArray(value);
4476
- }
4477
- function errorCodeOf(error) {
4478
- return error.code;
4479
- }
4480
- function identityClaimPath(recordFile, identity) {
4481
- const digest = createHash5("sha256").update(identity, "utf8").digest("hex");
4482
- return `${recordFile}.id-${digest}`;
4483
- }
4484
- function createExclusiveFile(path, contents) {
4485
- writeFileSync(path, contents, { encoding: "utf8", flag: "wx" });
4486
- }
4487
- function sealTornTail(recordFile) {
4488
- if (!existsSync(recordFile)) return;
4489
- const buffer = readFileSync(recordFile);
4490
- if (buffer.length > 0 && buffer[buffer.length - 1] !== 10) {
4491
- appendFileSync(recordFile, "\n", "utf8");
4492
- }
4493
- }
4494
4468
  function appendSitianRecordBlock(input, block) {
4495
4469
  if (block === "") return;
4496
4470
  try {
4497
4471
  const { sessionDir, recordFile, ledgerHome } = resolveSitianRecordPath(input);
4498
4472
  ensureRealDirectoryTree(ledgerHome, sessionDir);
4499
- appendFileSync(recordFile, "", "utf8");
4500
- sealTornTail(recordFile);
4501
- const identityOf = (line2) => {
4502
- try {
4503
- const row = JSON.parse(line2);
4504
- return isRecord3(row) && typeof row.identity === "string" ? row.identity : void 0;
4505
- } catch {
4506
- return void 0;
4507
- }
4508
- };
4509
- const identities = new Set(readFileSync(recordFile, "utf8").split("\n").map(identityOf).filter((id) => id !== void 0));
4510
- for (const line2 of block.match(/[^\n]*\n|[^\n]+$/g) ?? []) {
4511
- const identity = identityOf(line2);
4512
- if (identity !== void 0 && identities.has(identity)) continue;
4513
- appendFileSync(recordFile, line2, "utf8");
4514
- if (identity !== void 0) identities.add(identity);
4515
- }
4473
+ appendFileSync(recordFile, block, "utf8");
4516
4474
  } catch (error) {
4517
4475
  if (error instanceof SitianInfrastructureError) throw error;
4518
4476
  throw new SitianInfrastructureError(
@@ -4521,106 +4479,6 @@ function appendSitianRecordBlock(input, block) {
4521
4479
  );
4522
4480
  }
4523
4481
  }
4524
- function findIdentityPointer(recordFile, identity, kind, level) {
4525
- if (!existsSync(recordFile)) return void 0;
4526
- const text = readFileSync(recordFile, "utf8");
4527
- for (const line2 of text.split("\n")) {
4528
- const trimmed = line2.trim();
4529
- if (!trimmed) continue;
4530
- try {
4531
- const parsed = JSON.parse(trimmed);
4532
- if (isRecord3(parsed) && parsed.identity === identity) {
4533
- return { identity, recordFile, kind, level };
4534
- }
4535
- } catch {
4536
- }
4537
- }
4538
- return void 0;
4539
- }
4540
- function unlinkAbsentOk(path) {
4541
- try {
4542
- unlinkSync(path);
4543
- return void 0;
4544
- } catch (error) {
4545
- if (errorCodeOf(error) === "ENOENT") return void 0;
4546
- return error instanceof Error ? error : new Error(errorText(error));
4547
- }
4548
- }
4549
- function appendWithIdentityClaim(recordFile, record4, row) {
4550
- sealTornTail(recordFile);
4551
- const claimPath = identityClaimPath(recordFile, record4.identity);
4552
- const existing = findIdentityPointer(
4553
- recordFile,
4554
- record4.identity,
4555
- record4.kind,
4556
- record4.level
4557
- );
4558
- if (existing !== void 0) {
4559
- unlinkAbsentOk(claimPath);
4560
- return existing;
4561
- }
4562
- try {
4563
- createExclusiveFile(claimPath, "");
4564
- } catch (error) {
4565
- if (errorCodeOf(error) !== "EEXIST") throw error;
4566
- sealTornTail(recordFile);
4567
- const published = findIdentityPointer(
4568
- recordFile,
4569
- record4.identity,
4570
- record4.kind,
4571
- record4.level
4572
- );
4573
- if (published !== void 0) {
4574
- unlinkAbsentOk(claimPath);
4575
- return published;
4576
- }
4577
- throw new SitianInfrastructureError(
4578
- `Sitian identity claim at ${claimPath} already exists for identity ${record4.identity}`,
4579
- { cause: error }
4580
- );
4581
- }
4582
- let primaryFailure;
4583
- let result;
4584
- let cleanupFailure;
4585
- try {
4586
- sealTornTail(recordFile);
4587
- const raced = findIdentityPointer(
4588
- recordFile,
4589
- record4.identity,
4590
- record4.kind,
4591
- record4.level
4592
- );
4593
- if (raced !== void 0) {
4594
- result = raced;
4595
- } else {
4596
- appendFileSync(recordFile, row, "utf8");
4597
- result = {
4598
- identity: record4.identity,
4599
- recordFile,
4600
- kind: record4.kind,
4601
- level: record4.level
4602
- };
4603
- }
4604
- } catch (error) {
4605
- primaryFailure = error;
4606
- } finally {
4607
- cleanupFailure = unlinkAbsentOk(claimPath);
4608
- }
4609
- if (primaryFailure !== void 0) {
4610
- if (primaryFailure instanceof SitianInfrastructureError) throw primaryFailure;
4611
- throw new SitianInfrastructureError(
4612
- `Sitian appender persistence failure: ${errorText(primaryFailure)}`,
4613
- { cause: primaryFailure }
4614
- );
4615
- }
4616
- if (cleanupFailure !== void 0) {
4617
- throw new SitianInfrastructureError(
4618
- `Sitian identity claim at ${claimPath} could not be released after append for identity ${record4.identity}: ${errorText(cleanupFailure)}`,
4619
- { cause: cleanupFailure }
4620
- );
4621
- }
4622
- return result;
4623
- }
4624
4482
  function resolveSitianVolumeCategory(kind) {
4625
4483
  if (S4_SUBMISSION_LEDGER_KINDS.has(kind)) {
4626
4484
  return "submission-ledger";
@@ -4693,7 +4551,13 @@ function appendSitianRecord(input) {
4693
4551
  };
4694
4552
  const row = `${JSON.stringify(record4)}
4695
4553
  `;
4696
- return appendWithIdentityClaim(recordFile, record4, row);
4554
+ appendFileSync(recordFile, row, "utf8");
4555
+ return {
4556
+ identity: record4.identity,
4557
+ recordFile,
4558
+ kind: record4.kind,
4559
+ level: record4.level
4560
+ };
4697
4561
  } catch (error) {
4698
4562
  if (error instanceof SitianInfrastructureError) throw error;
4699
4563
  throw new SitianInfrastructureError(
@@ -4721,13 +4585,13 @@ var init_sitian_appender = __esm({
4721
4585
  });
4722
4586
 
4723
4587
  // src/sitian-reader.ts
4724
- import { existsSync as existsSync2 } from "node:fs";
4588
+ import { existsSync } from "node:fs";
4725
4589
  import { readFile as readFile4 } from "node:fs/promises";
4726
- function isRecord4(value) {
4590
+ function isRecord3(value) {
4727
4591
  return typeof value === "object" && value !== null && !Array.isArray(value);
4728
4592
  }
4729
4593
  async function readSitianRecords(recordFile) {
4730
- if (!existsSync2(recordFile)) {
4594
+ if (!existsSync(recordFile)) {
4731
4595
  return { records: [], diagnostics: [] };
4732
4596
  }
4733
4597
  const text = await readFile4(recordFile, "utf8");
@@ -4739,7 +4603,7 @@ async function readSitianRecords(recordFile) {
4739
4603
  if (!line2.trim()) continue;
4740
4604
  try {
4741
4605
  const parsed = JSON.parse(line2);
4742
- if (isRecord4(parsed)) {
4606
+ if (isRecord3(parsed)) {
4743
4607
  records.push(parsed);
4744
4608
  } else {
4745
4609
  const typeDesc = parsed === null ? "null" : Array.isArray(parsed) ? "array" : typeof parsed;
@@ -4883,7 +4747,7 @@ var init_host_descriptions = __esm({
4883
4747
  });
4884
4748
 
4885
4749
  // src/package-resources/engine-material.ts
4886
- import { existsSync as existsSync3, readdirSync } from "node:fs";
4750
+ import { existsSync as existsSync2, readdirSync } from "node:fs";
4887
4751
  import { join as join4 } from "node:path";
4888
4752
  function pickEngineAxis(source) {
4889
4753
  return {
@@ -4926,7 +4790,7 @@ function engineSessionMaterialFromOptions(options) {
4926
4790
  const model = options.engineModel === void 0 ? void 0 : assertLegalEngineModel(options.engineModel);
4927
4791
  const materialPath = resolveEngineMaterialPath(options.packageRoot, name);
4928
4792
  const modelField = model === void 0 ? {} : { model };
4929
- if (existsSync3(materialPath)) {
4793
+ if (existsSync2(materialPath)) {
4930
4794
  return Object.freeze({ name, materialPath, ...modelField });
4931
4795
  }
4932
4796
  return Object.freeze({ name, ...modelField });
@@ -5941,14 +5805,14 @@ function isMissingPathError3(error) {
5941
5805
  function errorText2(error) {
5942
5806
  return error instanceof Error ? error.message : String(error);
5943
5807
  }
5944
- function isRecord5(value) {
5808
+ function isRecord4(value) {
5945
5809
  return typeof value === "object" && value !== null && !Array.isArray(value);
5946
5810
  }
5947
5811
  function readUsableTerminalArtifactBody(body) {
5948
5812
  if (body === null) {
5949
5813
  return { ok: false, reason: "terminal artifact JSON value is null" };
5950
5814
  }
5951
- if (!isRecord5(body)) {
5815
+ if (!isRecord4(body)) {
5952
5816
  return {
5953
5817
  ok: false,
5954
5818
  reason: `terminal artifact JSON value is not a typed object (${Array.isArray(body) ? "array" : typeof body})`
@@ -6946,19 +6810,7 @@ function createPiRoleTurnHost(config) {
6946
6810
  });
6947
6811
  return {
6948
6812
  async executeTurn(request) {
6949
- let turnRequest = request;
6950
- const officerStationChild = request.stationChild === true && isOfficerReviewSeat(request.activation.role);
6951
- const paths = !officerStationChild && request.hostTransition?.priorNativeKind === "sitian" ? request.hostTransition.priorNativePaths : void 0;
6952
- if (request.continuation.kind === "resume" && paths !== void 0 && paths.length > 0) {
6953
- turnRequest = {
6954
- ...request,
6955
- continuation: {
6956
- ...request.continuation,
6957
- prompt: `${request.continuation.prompt}
6958
- ${paths.join("\n")}`
6959
- }
6960
- };
6961
- }
6813
+ const turnRequest = request;
6962
6814
  const roleEntry = await realpath2(resolveInternalRoleEntrypoint(config.packageRoot));
6963
6815
  const extraArgs = buildPiTurnExtraArgs(
6964
6816
  turnRequest,
@@ -7038,7 +6890,6 @@ var init_role_turn_host = __esm({
7038
6890
  "src/pi/role-turn-host.ts"() {
7039
6891
  "use strict";
7040
6892
  init_host_contracts();
7041
- init_packaged_role_registry();
7042
6893
  init_engine_detour();
7043
6894
  init_role_activation_flags();
7044
6895
  init_user_dialogue_stdin();
@@ -7344,7 +7195,7 @@ var init_merger_git_state = __esm({
7344
7195
 
7345
7196
  // src/ledger-session-read.ts
7346
7197
  import { readFile as readFile11 } from "node:fs/promises";
7347
- function isRecord6(value) {
7198
+ function isRecord5(value) {
7348
7199
  return typeof value === "object" && value !== null && !Array.isArray(value);
7349
7200
  }
7350
7201
  async function readLedgerSessionJsonlLines(path) {
@@ -7369,7 +7220,7 @@ async function readLedgerSessionJsonlLines(path) {
7369
7220
  });
7370
7221
  continue;
7371
7222
  }
7372
- if (!isRecord6(row)) {
7223
+ if (!isRecord5(row)) {
7373
7224
  const kind = row === null ? "null" : Array.isArray(row) ? "array" : typeof row;
7374
7225
  out.push({
7375
7226
  line: lineNumber,
@@ -7422,7 +7273,7 @@ function extractSessionModelSequence(rows) {
7422
7273
  if (row.type === "model_change" && typeof row.modelId === "string") {
7423
7274
  push(row.modelId);
7424
7275
  }
7425
- const message = isRecord6(row.message) ? row.message : void 0;
7276
+ const message = isRecord5(row.message) ? row.message : void 0;
7426
7277
  if (message?.role === "assistant" && typeof message.model === "string") {
7427
7278
  push(message.model);
7428
7279
  }
@@ -7438,11 +7289,11 @@ function extractSessionToolIntervals(rows) {
7438
7289
  const openById = /* @__PURE__ */ new Map();
7439
7290
  for (const row of rows) {
7440
7291
  const rowTimestamp = typeof row.timestamp === "string" ? row.timestamp : void 0;
7441
- const message = isRecord6(row.message) ? row.message : void 0;
7292
+ const message = isRecord5(row.message) ? row.message : void 0;
7442
7293
  if (message?.role === "assistant" && Array.isArray(message.content)) {
7443
7294
  const callTimestamp = typeof message.timestamp === "string" && message.timestamp ? message.timestamp : rowTimestamp;
7444
7295
  for (const part of message.content) {
7445
- if (!isRecord6(part) || part.type !== "toolCall") continue;
7296
+ if (!isRecord5(part) || part.type !== "toolCall") continue;
7446
7297
  if (typeof part.id !== "string" || part.id.length === 0) {
7447
7298
  throw new Error("toolCall frame missing string id");
7448
7299
  }
@@ -7455,7 +7306,7 @@ function extractSessionToolIntervals(rows) {
7455
7306
  if (openById.has(part.id)) {
7456
7307
  throw new Error(`duplicate toolCall id ${part.id}`);
7457
7308
  }
7458
- const args = isRecord6(part.arguments) ? part.arguments : void 0;
7309
+ const args = isRecord5(part.arguments) ? part.arguments : void 0;
7459
7310
  const command = part.name === "bash" && args !== void 0 && typeof args.command === "string" ? bashCommandFirstLine(args.command) : void 0;
7460
7311
  const interval = {
7461
7312
  toolCallId: part.id,
@@ -7539,7 +7390,7 @@ var init_ledger_session_read = __esm({
7539
7390
  });
7540
7391
 
7541
7392
  // src/session-dialogue.ts
7542
- function isRecord7(value) {
7393
+ function isRecord6(value) {
7543
7394
  return typeof value === "object" && value !== null && !Array.isArray(value);
7544
7395
  }
7545
7396
  function nativeEventId(row) {
@@ -7549,7 +7400,7 @@ function nativeEventId(row) {
7549
7400
  }
7550
7401
  for (const nestKey of ["message", "payload"]) {
7551
7402
  const nested = row[nestKey];
7552
- if (!isRecord7(nested)) continue;
7403
+ if (!isRecord6(nested)) continue;
7553
7404
  for (const key of ["uuid", "id"]) {
7554
7405
  const value = nested[key];
7555
7406
  if (typeof value === "string" && value !== "") return value;
@@ -7562,19 +7413,19 @@ function textParts(content) {
7562
7413
  if (!Array.isArray(content)) return [];
7563
7414
  const out = [];
7564
7415
  for (const part of content) {
7565
- if (!isRecord7(part) || !SPEAKER_TEXT_PART_TYPES.has(String(part.type))) continue;
7416
+ if (!isRecord6(part) || !SPEAKER_TEXT_PART_TYPES.has(String(part.type))) continue;
7566
7417
  const text = part.text;
7567
7418
  if (typeof text === "string" && text !== "") out.push(text);
7568
7419
  }
7569
7420
  return out;
7570
7421
  }
7571
7422
  function responseItemMessage(row) {
7572
- if (row.type !== "response_item" || !isRecord7(row.payload)) return void 0;
7423
+ if (row.type !== "response_item" || !isRecord6(row.payload)) return void 0;
7573
7424
  if (row.payload.type !== "message") return void 0;
7574
7425
  return row.payload;
7575
7426
  }
7576
7427
  function messageBody(row) {
7577
- if (isRecord7(row.message)) return row.message;
7428
+ if (isRecord6(row.message)) return row.message;
7578
7429
  return responseItemMessage(row);
7579
7430
  }
7580
7431
  function speakerOf(message) {
@@ -7584,7 +7435,7 @@ function speakerOf(message) {
7584
7435
  }
7585
7436
  function codexContentItemKinds(message) {
7586
7437
  const pass = message.internal_chat_message_metadata_passthrough;
7587
- if (!isRecord7(pass) || !Array.isArray(pass.content_item_kinds)) return void 0;
7438
+ if (!isRecord6(pass) || !Array.isArray(pass.content_item_kinds)) return void 0;
7588
7439
  const kinds = [];
7589
7440
  for (const kind of pass.content_item_kinds) {
7590
7441
  if (typeof kind === "string" && kind !== "") kinds.push(kind);
@@ -7613,7 +7464,7 @@ function isFixedNonOwnerEnqueueShape(content) {
7613
7464
  return hasFixedOpenTagPrefix(content, TASK_NOTIFICATION_OPEN_TAG);
7614
7465
  }
7615
7466
  function materializationOriginKind(row) {
7616
- if (!isRecord7(row.origin)) return void 0;
7467
+ if (!isRecord6(row.origin)) return void 0;
7617
7468
  const kind = row.origin.kind;
7618
7469
  return typeof kind === "string" && kind !== "" ? kind : void 0;
7619
7470
  }
@@ -9107,7 +8958,7 @@ var init_option_definitions = __esm({
9107
8958
 
9108
8959
  // src/public-cli/invocation.ts
9109
8960
  import { execFileSync as execFileSync3 } from "node:child_process";
9110
- import { existsSync as existsSync5 } from "node:fs";
8961
+ import { existsSync as existsSync4 } from "node:fs";
9111
8962
  import {
9112
8963
  lstat as lstat3,
9113
8964
  mkdtemp as mkdtemp2,
@@ -9333,7 +9184,7 @@ async function relocateAdmittedRunToTicket(admitted, authority, heldLease) {
9333
9184
  for (const childRunId of Array.isArray(childRunIds) ? childRunIds : []) {
9334
9185
  if (typeof childRunId !== "string") continue;
9335
9186
  const childDirectory = join18(dirname13(oldRunDirectory), `${childRunId}@diarist`);
9336
- if (!existsSync5(childDirectory)) continue;
9187
+ if (!existsSync4(childDirectory)) continue;
9337
9188
  const childTarget = roleRunPlacement(ledgerHome, {
9338
9189
  bookKey: admitted.bookKey,
9339
9190
  subject: { ticketNumber: admitted.ticketNumber },
@@ -10815,7 +10666,7 @@ var init_invocation = __esm({
10815
10666
  });
10816
10667
 
10817
10668
  // src/public-cli/load-production-acp-host.ts
10818
- import { existsSync as existsSync6 } from "node:fs";
10669
+ import { existsSync as existsSync5 } from "node:fs";
10819
10670
  import { join as join19 } from "node:path";
10820
10671
  import { pathToFileURL } from "node:url";
10821
10672
  async function loadProductionAcpHostFactory(packageRoot, host) {
@@ -10825,7 +10676,7 @@ async function loadProductionAcpHostFactory(packageRoot, host) {
10825
10676
  }
10826
10677
  const built = join19(packageRoot, "dist/acp-host/production-host.js");
10827
10678
  const source = join19(packageRoot, "src/acp-host/production-host.ts");
10828
- const target = existsSync6(built) ? built : source;
10679
+ const target = existsSync5(built) ? built : source;
10829
10680
  const href = pathToFileURL(target).href;
10830
10681
  const mod = await import(href);
10831
10682
  const create = mod.createProductionAcpRoleTurnHost;
@@ -10839,7 +10690,7 @@ var init_load_production_acp_host = __esm({
10839
10690
  });
10840
10691
 
10841
10692
  // src/public-cli/load-production-headless-host.ts
10842
- import { existsSync as existsSync7 } from "node:fs";
10693
+ import { existsSync as existsSync6 } from "node:fs";
10843
10694
  import { join as join20 } from "node:path";
10844
10695
  import { pathToFileURL as pathToFileURL2 } from "node:url";
10845
10696
  async function loadProductionHeadlessHostFactory(packageRoot, host) {
@@ -10849,7 +10700,7 @@ async function loadProductionHeadlessHostFactory(packageRoot, host) {
10849
10700
  }
10850
10701
  const built = join20(packageRoot, "dist/headless-host/production-host.js");
10851
10702
  const source = join20(packageRoot, "src/headless-host/production-host.ts");
10852
- const target = existsSync7(built) ? built : source;
10703
+ const target = existsSync6(built) ? built : source;
10853
10704
  const href = pathToFileURL2(target).href;
10854
10705
  const mod = await import(href);
10855
10706
  const create = mod.createProductionHeadlessRoleTurnHost;
@@ -10986,7 +10837,7 @@ __export(host_providers_exports, {
10986
10837
  projectHostFacingProvider: () => projectHostFacingProvider,
10987
10838
  renderHostProvidersTable: () => renderHostProvidersTable
10988
10839
  });
10989
- import { readFileSync as readFileSync2 } from "node:fs";
10840
+ import { readFileSync } from "node:fs";
10990
10841
  import { join as join21 } from "node:path";
10991
10842
  function hostProvidersPath(home) {
10992
10843
  if (typeof home !== "string" || home.trim() === "") {
@@ -11034,7 +10885,7 @@ function parseHostProvidersTable(value) {
11034
10885
  function loadHostProvidersTable(home) {
11035
10886
  const path = hostProvidersPath(home);
11036
10887
  try {
11037
- const raw = readFileSync2(path, "utf8");
10888
+ const raw = readFileSync(path, "utf8");
11038
10889
  return parseHostProvidersTable(JSON.parse(raw));
11039
10890
  } catch (error) {
11040
10891
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -11052,7 +10903,7 @@ function listHermesProvidersForModel(home, seatModel) {
11052
10903
  const path = hermesProviderModelsCachePath(home);
11053
10904
  let text;
11054
10905
  try {
11055
- text = readFileSync2(path, "utf8");
10906
+ text = readFileSync(path, "utf8");
11056
10907
  } catch (error) {
11057
10908
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
11058
10909
  return [];
@@ -11152,7 +11003,7 @@ var init_host_providers = __esm({
11152
11003
  // src/analyst-gate-cycles-read.ts
11153
11004
  import { readdir as readdir4 } from "node:fs/promises";
11154
11005
  import { join as join22 } from "node:path";
11155
- function isRecord8(value) {
11006
+ function isRecord7(value) {
11156
11007
  return typeof value === "object" && value !== null && !Array.isArray(value);
11157
11008
  }
11158
11009
  function isParentAttemptBindingRow(row) {
@@ -11182,7 +11033,7 @@ function isGateTerminatingToolName(toolName) {
11182
11033
  function acceptedGateReceiptIds(rows) {
11183
11034
  const accepted = /* @__PURE__ */ new Set();
11184
11035
  for (const row of rows) {
11185
- const message = isRecord8(row.message) ? row.message : void 0;
11036
+ const message = isRecord7(row.message) ? row.message : void 0;
11186
11037
  if (message?.role !== "toolResult") continue;
11187
11038
  if (typeof message.toolCallId !== "string" || message.toolCallId.length === 0) continue;
11188
11039
  if (message.isError === false) accepted.add(message.toolCallId);
@@ -11217,7 +11068,7 @@ function nearestAttemptBindingBefore(rows, beforeIndex) {
11217
11068
  for (let i = beforeIndex - 1; i >= 0; i -= 1) {
11218
11069
  const row = rows[i];
11219
11070
  if (!isParentAttemptBindingRow(row)) continue;
11220
- if (!isRecord8(row.data) || !isRecord8(row.data.parent)) continue;
11071
+ if (!isRecord7(row.data) || !isRecord7(row.data.parent)) continue;
11221
11072
  const id = row.data.parent.attemptEntryId;
11222
11073
  const sessionFile = row.data.parent.sessionFile;
11223
11074
  return {
@@ -11232,10 +11083,10 @@ function extractAllAcceptedGateToolCalls(rows) {
11232
11083
  const out = [];
11233
11084
  for (let rowIndex = 0; rowIndex < rows.length; rowIndex += 1) {
11234
11085
  const row = rows[rowIndex];
11235
- const message = isRecord8(row.message) ? row.message : void 0;
11086
+ const message = isRecord7(row.message) ? row.message : void 0;
11236
11087
  if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
11237
11088
  for (const part of message.content) {
11238
- if (!isRecord8(part) || part.type !== "toolCall") continue;
11089
+ if (!isRecord7(part) || part.type !== "toolCall") continue;
11239
11090
  if (typeof part.id !== "string" || part.id.length === 0) continue;
11240
11091
  if (typeof part.name !== "string" || part.name.length === 0) continue;
11241
11092
  if (!isGateTerminatingToolName(part.name)) continue;
@@ -11243,7 +11094,7 @@ function extractAllAcceptedGateToolCalls(rows) {
11243
11094
  const binding = nearestAttemptBindingBefore(rows, rowIndex);
11244
11095
  out.push({
11245
11096
  toolName: part.name,
11246
- args: isRecord8(part.arguments) ? part.arguments : void 0,
11097
+ args: isRecord7(part.arguments) ? part.arguments : void 0,
11247
11098
  accepted: true,
11248
11099
  rowIndex,
11249
11100
  ...binding
@@ -11376,7 +11227,7 @@ async function resolveOfficerSessionFromPointerFile(pointerPath) {
11376
11227
  { cause: error }
11377
11228
  );
11378
11229
  }
11379
- if (!isRecord8(raw) || raw.kind !== "direct-officer-run-pointer" || raw.version !== 1) {
11230
+ if (!isRecord7(raw) || raw.kind !== "direct-officer-run-pointer" || raw.version !== 1) {
11380
11231
  throw new Error(`direct officer run pointer has unknown shape in ${pointerPath}`);
11381
11232
  }
11382
11233
  const sessionFile = raw.sessionFile;
@@ -11850,14 +11701,14 @@ var init_audit_escalation = __esm({
11850
11701
  });
11851
11702
 
11852
11703
  // src/session-opening-materials.ts
11853
- import { existsSync as existsSync8 } from "node:fs";
11704
+ import { existsSync as existsSync7 } from "node:fs";
11854
11705
  import { readFile as readFile14 } from "node:fs/promises";
11855
11706
  import { dirname as dirname14, join as join24 } from "node:path";
11856
11707
  import { fileURLToPath, pathToFileURL as pathToFileURL3 } from "node:url";
11857
11708
  function resolvePackageRootDir(moduleUrl = import.meta.url) {
11858
11709
  let dir = dirname14(fileURLToPath(moduleUrl));
11859
11710
  for (let i = 0; i < 8; i += 1) {
11860
- if (existsSync8(join24(dir, "package.json")) && existsSync8(join24(dir, "souls"))) {
11711
+ if (existsSync7(join24(dir, "package.json")) && existsSync7(join24(dir, "souls"))) {
11861
11712
  return dir;
11862
11713
  }
11863
11714
  const parent = dirname14(dir);
@@ -12080,7 +11931,7 @@ var init_serialize_thrown_value = __esm({
12080
11931
 
12081
11932
  // src/engine-detour-usage.ts
12082
11933
  import { randomUUID as randomUUID4 } from "node:crypto";
12083
- import { readFileSync as readFileSync3 } from "node:fs";
11934
+ import { readFileSync as readFileSync2 } from "node:fs";
12084
11935
  import { dirname as dirname15, join as join26 } from "node:path";
12085
11936
  function engineDetourStdoutByteLength(stdout) {
12086
11937
  return Buffer.byteLength(stdout, "utf8");
@@ -12134,11 +11985,11 @@ function reportEngineDetourCall(input) {
12134
11985
  recordPointer: pointer
12135
11986
  };
12136
11987
  }
12137
- function isRecord9(value) {
11988
+ function isRecord8(value) {
12138
11989
  return typeof value === "object" && value !== null && !Array.isArray(value);
12139
11990
  }
12140
11991
  function callFactFromSitianPayload(payload, pointer) {
12141
- if (!isRecord9(payload)) return void 0;
11992
+ if (!isRecord8(payload)) return void 0;
12142
11993
  if (payload.tool !== ENGINE_DETOUR_TOOL_NAME) return void 0;
12143
11994
  if (typeof payload.toolCallId !== "string" || payload.toolCallId.length === 0) {
12144
11995
  return void 0;
@@ -12155,11 +12006,11 @@ function callFactFromSitianPayload(payload, pointer) {
12155
12006
  };
12156
12007
  }
12157
12008
  function invocationScopeIdOfRecord(record4) {
12158
- if (isRecord9(record4.subject)) {
12009
+ if (isRecord8(record4.subject)) {
12159
12010
  const fromSubject = record4.subject.invocationScopeId;
12160
12011
  if (typeof fromSubject === "string" && fromSubject.length > 0) return fromSubject;
12161
12012
  }
12162
- if (isRecord9(record4.payload)) {
12013
+ if (isRecord8(record4.payload)) {
12163
12014
  const fromPayload = record4.payload.invocationScopeId;
12164
12015
  if (typeof fromPayload === "string" && fromPayload.length > 0) return fromPayload;
12165
12016
  }
@@ -12175,7 +12026,7 @@ async function readEngineDetourToolUsage(input) {
12175
12026
  ...input.cwd === void 0 ? {} : { cwd: input.cwd }
12176
12027
  });
12177
12028
  const { records } = await readSitianRecords(recordFile);
12178
- const calls = [];
12029
+ const callsByToolCallId = /* @__PURE__ */ new Map();
12179
12030
  for (const record4 of records) {
12180
12031
  if (record4.kind !== ENGINE_DETOUR_CALL_KIND) continue;
12181
12032
  const boundScope = invocationScopeIdOfRecord(record4);
@@ -12192,8 +12043,9 @@ async function readEngineDetourToolUsage(input) {
12192
12043
  };
12193
12044
  const fact = callFactFromSitianPayload(record4.payload, pointer);
12194
12045
  if (fact === void 0) continue;
12195
- calls.push(fact);
12046
+ callsByToolCallId.set(fact.toolCallId, fact);
12196
12047
  }
12048
+ const calls = Array.from(callsByToolCallId.values());
12197
12049
  return { callCount: calls.length, calls };
12198
12050
  }
12199
12051
  function projectEngineDetourToolUsageForPublicTerminal(usage, options) {
@@ -12217,9 +12069,9 @@ function projectEngineDetourToolUsageForPublicTerminal(usage, options) {
12217
12069
  function readInvocationRecord(runDirectory) {
12218
12070
  try {
12219
12071
  const raw = JSON.parse(
12220
- readFileSync3(join26(runDirectory, "invocation.json"), "utf8")
12072
+ readFileSync2(join26(runDirectory, "invocation.json"), "utf8")
12221
12073
  );
12222
- return isRecord9(raw) ? raw : void 0;
12074
+ return isRecord8(raw) ? raw : void 0;
12223
12075
  } catch (error) {
12224
12076
  if (error?.code === "ENOENT") return void 0;
12225
12077
  throw error;
@@ -12230,14 +12082,9 @@ async function readInvocationEngineMounted(runDirectory) {
12230
12082
  if (raw === void 0) return false;
12231
12083
  return typeof raw.engine === "string" && raw.engine.trim() !== "";
12232
12084
  }
12233
- function readInvocationSelectedHost(runDirectory) {
12234
- const raw = readInvocationRecord(runDirectory);
12235
- if (raw === void 0) return void 0;
12236
- return typeof raw.host === "string" && raw.host.trim() !== "" ? raw.host.trim() : void 0;
12237
- }
12238
12085
  function withEngineDetourToolUsageFact(outcome, usage) {
12239
12086
  if (usage === void 0) return outcome;
12240
- const prior = isRecord9(outcome.decisiveFacts) ? outcome.decisiveFacts : {};
12087
+ const prior = isRecord8(outcome.decisiveFacts) ? outcome.decisiveFacts : {};
12241
12088
  return {
12242
12089
  ...outcome,
12243
12090
  decisiveFacts: {
@@ -12279,7 +12126,7 @@ var init_engine_detour_usage = __esm({
12279
12126
  });
12280
12127
 
12281
12128
  // src/dossier-resolution.ts
12282
- import { existsSync as existsSync9, statSync as statSync2 } from "node:fs";
12129
+ import { existsSync as existsSync8, statSync as statSync2 } from "node:fs";
12283
12130
  import { resolve as resolve12 } from "node:path";
12284
12131
  function isHostContext(value) {
12285
12132
  return "sessionManager" in value;
@@ -12299,7 +12146,7 @@ function resolveAuditDossier(source) {
12299
12146
  }
12300
12147
  const runDirectory = resolve12(raw);
12301
12148
  try {
12302
- if (!existsSync9(runDirectory) || !statSync2(runDirectory).isDirectory()) {
12149
+ if (!existsSync8(runDirectory) || !statSync2(runDirectory).isDirectory()) {
12303
12150
  return { status: "incomplete", observation: { kind: "missing-dossier" } };
12304
12151
  }
12305
12152
  } catch {
@@ -12307,13 +12154,13 @@ function resolveAuditDossier(source) {
12307
12154
  }
12308
12155
  return { status: "ok", runDirectory };
12309
12156
  }
12310
- function isRecord10(value) {
12157
+ function isRecord9(value) {
12311
12158
  return typeof value === "object" && value !== null && !Array.isArray(value);
12312
12159
  }
12313
12160
  function readDoctorAuditSubjects(context) {
12314
12161
  const entries = context.sessionManager.getEntries?.() ?? [];
12315
12162
  for (const entry of entries) {
12316
- if (isRecord10(entry) && entry.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
12163
+ if (isRecord9(entry) && entry.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
12317
12164
  return { status: "ok" };
12318
12165
  }
12319
12166
  }
@@ -12346,11 +12193,11 @@ var init_dossier_resolution = __esm({
12346
12193
  });
12347
12194
 
12348
12195
  // src/receipt-delivery-policy.ts
12349
- function isRecord11(value) {
12196
+ function isRecord10(value) {
12350
12197
  return typeof value === "object" && value !== null && !Array.isArray(value);
12351
12198
  }
12352
12199
  function parseNoReceiptLifecycleFacts(input) {
12353
- if (!isRecord11(input) || typeof input.terminalToolCalled !== "boolean" || input.deliveryTurns !== RECEIPT_DELIVERY_TURN_LIMIT || input.sessionCompletion !== "settled-without-accepted-receipt" || input.acceptedReceipt !== false || typeof input.runPointer !== "string" || input.runPointer.trim() === "" || typeof input.attemptPointer !== "string" || input.attemptPointer.trim() === "" || !Array.isArray(input.rejectedReceipts) || !input.rejectedReceipts.every((item) => isRecord11(item) && typeof item.reason === "string")) {
12200
+ if (!isRecord10(input) || typeof input.terminalToolCalled !== "boolean" || input.deliveryTurns !== RECEIPT_DELIVERY_TURN_LIMIT || input.sessionCompletion !== "settled-without-accepted-receipt" || input.acceptedReceipt !== false || typeof input.runPointer !== "string" || input.runPointer.trim() === "" || typeof input.attemptPointer !== "string" || input.attemptPointer.trim() === "" || !Array.isArray(input.rejectedReceipts) || !input.rejectedReceipts.every((item) => isRecord10(item) && typeof item.reason === "string")) {
12354
12201
  throw new TypeError("malformed no-receipt lifecycle facts");
12355
12202
  }
12356
12203
  return {
@@ -12975,7 +12822,7 @@ async function readSitianRetainedAuditorProviderStop(sessionFile) {
12975
12822
  const { records } = await readSitianRecords(recordFile);
12976
12823
  for (let i = records.length - 1; i >= 0; i -= 1) {
12977
12824
  const payload = records[i]?.payload;
12978
- if (!isRecord12(payload) || !isRecord12(payload.response)) continue;
12825
+ if (!isRecord11(payload) || !isRecord11(payload.response)) continue;
12979
12826
  if (typeof payload.type === "string") continue;
12980
12827
  const stop = sessionProviderStopFromAssistant(payload.response);
12981
12828
  if (stop !== void 0) return stop;
@@ -13025,7 +12872,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
13025
12872
  throw sessionReadFailure(error, "failed to read discovered auditor session");
13026
12873
  }
13027
12874
  const header = entries.find((entry) => entry.type === "session");
13028
- if (!isRecord12(header)) continue;
12875
+ if (!isRecord11(header)) continue;
13029
12876
  const bindingIndexes = [];
13030
12877
  for (let i = 0; i < entries.length; i += 1) {
13031
12878
  const entry = entries[i];
@@ -13039,7 +12886,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
13039
12886
  end: idx + 1 < bindingIndexes.length ? bindingIndexes[idx + 1] : entries.length
13040
12887
  })) : [{ entry: void 0, start: 0, end: entries.length }];
13041
12888
  for (const { entry: bindingEntry, start, end } of bindingPasses) {
13042
- const bindingParent = bindingEntry !== void 0 && isRecord12(bindingEntry.data) && isRecord12(bindingEntry.data.parent) ? bindingEntry.data.parent : void 0;
12889
+ const bindingParent = bindingEntry !== void 0 && isRecord11(bindingEntry.data) && isRecord11(bindingEntry.data.parent) ? bindingEntry.data.parent : void 0;
13043
12890
  const attemptEntryId = typeof bindingParent?.attemptEntryId === "string" ? bindingParent.attemptEntryId : void 0;
13044
12891
  const boundSessionFile = typeof bindingParent?.sessionFile === "string" ? bindingParent.sessionFile : typeof header.parentSession === "string" ? header.parentSession : void 0;
13045
12892
  if (boundSessionFile !== sessionFile) continue;
@@ -13063,12 +12910,12 @@ function complianceFailureFromAuditorVolumes(volumes) {
13063
12910
  if (stop === void 0) continue;
13064
12911
  for (let i = entries.length - 1; i >= 0; i -= 1) {
13065
12912
  const entry = entries[i];
13066
- if (entry?.type !== "custom" || entry.customType !== AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE || !isRecord12(entry.data)) continue;
13067
- const parent = isRecord12(entry.data.parent) ? entry.data.parent : void 0;
13068
- const failure2 = isRecord12(entry.data.failure) ? entry.data.failure : void 0;
12913
+ if (entry?.type !== "custom" || entry.customType !== AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE || !isRecord11(entry.data)) continue;
12914
+ const parent = isRecord11(entry.data.parent) ? entry.data.parent : void 0;
12915
+ const failure2 = isRecord11(entry.data.failure) ? entry.data.failure : void 0;
13069
12916
  if (parent?.sessionId !== parentId || parent.sessionFile !== sessionFile || parent.attemptEntryId !== attemptEntryId) continue;
13070
12917
  if (failure2 === void 0) continue;
13071
- const identity = isRecord12(failure2.identity) ? failure2.identity : void 0;
12918
+ const identity = isRecord11(failure2.identity) ? failure2.identity : void 0;
13072
12919
  const typedCause = failure2.cause === "provider" || failure2.cause === "activation" || failure2.cause === "session" || failure2.cause === "output" || failure2.cause === "timeout" ? failure2.cause : void 0;
13073
12920
  return {
13074
12921
  ...typedCause === void 0 ? {} : { cause: typedCause },
@@ -13077,7 +12924,7 @@ function complianceFailureFromAuditorVolumes(volumes) {
13077
12924
  ...typeof identity.code === "string" || typeof identity.code === "number" ? { code: identity.code } : {}
13078
12925
  } },
13079
12926
  ...typeof failure2.diagnostic === "string" ? { diagnostic: failure2.diagnostic } : {},
13080
- ...isRecord12(failure2.details) ? { details: failure2.details } : {}
12927
+ ...isRecord11(failure2.details) ? { details: failure2.details } : {}
13081
12928
  };
13082
12929
  }
13083
12930
  }
@@ -13124,9 +12971,9 @@ function typedFailedTerminatingToolKnownFailure(entries) {
13124
12971
  if (classification.kind !== "infrastructure") continue;
13125
12972
  if (typeof message.toolCallId !== "string" || typeof message.toolName !== "string") continue;
13126
12973
  if (boundRoleToolCallForResult(attemptEntries, i, message, message.toolName) === void 0) continue;
13127
- const textPart = Array.isArray(message.content) ? message.content.find((part) => isRecord12(part) && part.type === "text" && typeof part.text === "string") : void 0;
13128
- const diagnostic = isRecord12(textPart) ? textPart.text : void 0;
13129
- const details = isRecord12(message.details) ? message.details : classification.fact;
12974
+ const textPart = Array.isArray(message.content) ? message.content.find((part) => isRecord11(part) && part.type === "text" && typeof part.text === "string") : void 0;
12975
+ const diagnostic = isRecord11(textPart) ? textPart.text : void 0;
12976
+ const details = isRecord11(message.details) ? message.details : classification.fact;
13130
12977
  return {
13131
12978
  cause: "activation",
13132
12979
  identity: { name: message.toolName, code: message.toolCallId },
@@ -13263,7 +13110,7 @@ function controlledFailureInputFromResolution(resolution) {
13263
13110
  } : {}
13264
13111
  };
13265
13112
  }
13266
- function isRecord12(value) {
13113
+ function isRecord11(value) {
13267
13114
  return typeof value === "object" && value !== null && !Array.isArray(value);
13268
13115
  }
13269
13116
  function toolResultText(message) {
@@ -13288,7 +13135,7 @@ function extractCollectorTargetBindRejection(entries) {
13288
13135
  const diagnostic = toolResultText(message);
13289
13136
  if (diagnostic.length === 0) return void 0;
13290
13137
  const details = message.details;
13291
- const code = isRecord12(details) && typeof details.code === "string" && details.code.trim() !== "" ? details.code : void 0;
13138
+ const code = isRecord11(details) && typeof details.code === "string" && details.code.trim() !== "" ? details.code : void 0;
13292
13139
  return code === void 0 ? { diagnostic } : { diagnostic, code };
13293
13140
  }
13294
13141
  return void 0;
@@ -13389,7 +13236,7 @@ function boundRoleToolCallForResult(entries, resultIndex, message, outputToolNam
13389
13236
  const candidateMessage = entries[index]?.message;
13390
13237
  if (candidateMessage?.role === "assistant" && Array.isArray(candidateMessage.content)) {
13391
13238
  for (const part of candidateMessage.content) {
13392
- if (!isRecord12(part) || part.type !== "toolCall" || part.id !== callId) {
13239
+ if (!isRecord11(part) || part.type !== "toolCall" || part.id !== callId) {
13393
13240
  continue;
13394
13241
  }
13395
13242
  if (part.name !== outputToolName) return void 0;
@@ -13460,7 +13307,7 @@ function parseNavigatorAttendanceDetails(details) {
13460
13307
  if (typeof details.prose === "string" && details.prose.trim() !== "") {
13461
13308
  prose = details.prose;
13462
13309
  } else {
13463
- const next = isRecord12(details.next) && typeof details.next.role === "string" ? details.next.role : void 0;
13310
+ const next = isRecord11(details.next) && typeof details.next.role === "string" ? details.next.role : void 0;
13464
13311
  const reason = typeof details.reason === "string" && details.reason.trim() !== "" ? details.reason : void 0;
13465
13312
  const command = typeof details.command === "string" && details.command.trim() !== "" ? details.command : void 0;
13466
13313
  if (reason !== void 0 && next !== void 0) {
@@ -13569,7 +13416,7 @@ function detourGateContext(admitted, scope) {
13569
13416
  }
13570
13417
  async function withOptionalGateProjection(base, sessionDirectory, gateContext = {}) {
13571
13418
  const secondaryEvidence = base.roleOutcome.kind === "failure" ? base.roleOutcome.decisiveFacts.secondaryEvidence : void 0;
13572
- const skipGate = isRecord12(secondaryEvidence) && secondaryEvidence.kind === "role_infrastructure_failure" && packagedSkipsGateOnInfrastructureStage(secondaryEvidence.stage);
13419
+ const skipGate = isRecord11(secondaryEvidence) && secondaryEvidence.kind === "role_infrastructure_failure" && packagedSkipsGateOnInfrastructureStage(secondaryEvidence.stage);
13573
13420
  let next = base;
13574
13421
  if (!skipGate) {
13575
13422
  const gate = await extractGateFactFromSessionDirectory(sessionDirectory, gateContext);
@@ -13582,7 +13429,7 @@ function routePlaybookFailureMessage(entries) {
13582
13429
  const entry = entries[i];
13583
13430
  if (entry?.type !== "custom" || entry.customType !== NAVIGATOR_ROUTE_PLAYBOOK_FAILURE_ENTRY) continue;
13584
13431
  const data = entry.data;
13585
- if (!isRecord12(data) || typeof data.message !== "string" || data.message.trim() === "") return void 0;
13432
+ if (!isRecord11(data) || typeof data.message !== "string" || data.message.trim() === "") return void 0;
13586
13433
  return data.message;
13587
13434
  }
13588
13435
  return void 0;
@@ -13629,7 +13476,7 @@ function extractNavigatorAttendanceFact(entries) {
13629
13476
  const entry = entries[i];
13630
13477
  if (entry?.type === "custom_message" && entry.customType === "ak-navigator-attendance") {
13631
13478
  const details = entry.message?.details ?? entry.details;
13632
- if (!isRecord12(details)) {
13479
+ if (!isRecord11(details)) {
13633
13480
  return {
13634
13481
  disposition: "unavailable",
13635
13482
  source: "unknown",
@@ -13780,7 +13627,7 @@ async function settleSealedAcceptedOrToolResidual(admitted, authority, scope, ro
13780
13627
  const residual = boundErroredToolCandidate(entries, index, message, residualToolName);
13781
13628
  if (residual === void 0) continue;
13782
13629
  const candidate = residual.candidate;
13783
- const details = isRecord12(candidate) ? candidate : { candidate };
13630
+ const details = isRecord11(candidate) ? candidate : { candidate };
13784
13631
  const failed = await settleFailureTerminalResult(
13785
13632
  admitted,
13786
13633
  {
@@ -13855,7 +13702,7 @@ function extractDoctorCandidateFacts(entries) {
13855
13702
  continue;
13856
13703
  }
13857
13704
  const data = entry.data;
13858
- if (!isRecord12(data)) return {};
13705
+ if (!isRecord11(data)) return {};
13859
13706
  return {
13860
13707
  ...data.cost === void 0 ? {} : { cost: data.cost },
13861
13708
  ...data.auditNoReceipt === void 0 ? {} : { auditNoReceipt: data.auditNoReceipt }
@@ -13940,7 +13787,7 @@ async function settleLawfulSeatAcceptedTerminalResult(admitted, authority, spec,
13940
13787
  let residual;
13941
13788
  for (let index = entries.length - 1; index >= scanStart; index -= 1) {
13942
13789
  const entry = entries[index];
13943
- if (entry?.type === "custom" && entry.customType === "ak-role-submission-closure" && isRecord12(entry.data) && entry.data.toolName === spec.toolName && classifyPackagedRoleTerminalResult(entry.data).kind === "accepted") {
13790
+ if (entry?.type === "custom" && entry.customType === "ak-role-submission-closure" && isRecord11(entry.data) && entry.data.toolName === spec.toolName && classifyPackagedRoleTerminalResult(entry.data).kind === "accepted") {
13944
13791
  thisAttemptHasSeatSuccess = true;
13945
13792
  }
13946
13793
  const message = entries[index]?.message;
@@ -13980,7 +13827,7 @@ async function settleLawfulSeatAcceptedTerminalResult(admitted, authority, spec,
13980
13827
  );
13981
13828
  }
13982
13829
  if (residual !== void 0) {
13983
- const details = isRecord12(residual.candidate) ? residual.candidate : { candidate: residual.candidate };
13830
+ const details = isRecord11(residual.candidate) ? residual.candidate : { candidate: residual.candidate };
13984
13831
  const failed = await settleFailureTerminalResult(
13985
13832
  admitted,
13986
13833
  {
@@ -14030,7 +13877,7 @@ function countersignTerminalFromEntries(entries) {
14030
13877
  return void 0;
14031
13878
  }
14032
13879
  function withCountersignTerminalFact(roleOutcome, officer) {
14033
- const prior = roleOutcome.decisiveFacts !== void 0 && isRecord12(roleOutcome.decisiveFacts) ? roleOutcome.decisiveFacts : {};
13880
+ const prior = roleOutcome.decisiveFacts !== void 0 && isRecord11(roleOutcome.decisiveFacts) ? roleOutcome.decisiveFacts : {};
14034
13881
  return {
14035
13882
  ...roleOutcome,
14036
13883
  decisiveFacts: {
@@ -14043,7 +13890,7 @@ function acceptedSecretariatDefinesOfficerProjection(roleOutcome) {
14043
13890
  const payloads = roleOutcome.payloads ?? [];
14044
13891
  for (let index = payloads.length - 1; index >= 0; index -= 1) {
14045
13892
  const payload = payloads[index];
14046
- if (!isRecord12(payload)) continue;
13893
+ if (!isRecord11(payload)) continue;
14047
13894
  const status = payload.secretariatStatus;
14048
13895
  if (typeof status !== "string") continue;
14049
13896
  return status === "converged";
@@ -14488,7 +14335,7 @@ var init_settlement = __esm({
14488
14335
  });
14489
14336
 
14490
14337
  // src/archivist-record-pointer.ts
14491
- import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
14338
+ import { mkdirSync as mkdirSync2, writeFileSync } from "node:fs";
14492
14339
  import { dirname as dirname17, join as join28 } from "node:path";
14493
14340
  function bookDirectOfficerRunPointer(options) {
14494
14341
  const nest = join28(dirname17(options.parentSessionFile), "auditor-roles");
@@ -14500,7 +14347,7 @@ function bookDirectOfficerRunPointer(options) {
14500
14347
  sessionFile: options.sessionFile,
14501
14348
  ...options.runDirectory !== void 0 && options.runDirectory.trim() !== "" ? { runDirectory: options.runDirectory } : {}
14502
14349
  };
14503
- writeFileSync2(
14350
+ writeFileSync(
14504
14351
  join28(nest, `${options.officer}.pointer.json`),
14505
14352
  `${JSON.stringify(pointer)}
14506
14353
  `,
@@ -14894,78 +14741,281 @@ var init_case_dossier_delivery = __esm({
14894
14741
  }
14895
14742
  });
14896
14743
 
14897
- // src/host-transition-prior-native.ts
14898
- import { access as access3, readdir as readdir6 } from "node:fs/promises";
14744
+ // src/public-cli/process-cancel.ts
14745
+ function processCancelSignalName(signal) {
14746
+ if (signal === void 0 || signal.aborted !== true) return void 0;
14747
+ const reason = signal.reason;
14748
+ if (reason === "SIGTERM" || reason === "SIGINT" || reason === "SIGHUP") {
14749
+ return reason;
14750
+ }
14751
+ return void 0;
14752
+ }
14753
+ function processCancelDiagnostic(signalName) {
14754
+ return `ak-role terminated by ${signalName}`;
14755
+ }
14756
+ var init_process_cancel = __esm({
14757
+ "src/public-cli/process-cancel.ts"() {
14758
+ "use strict";
14759
+ }
14760
+ });
14761
+
14762
+ // src/host-session-record.ts
14763
+ import { spawnSync } from "node:child_process";
14764
+ import {
14765
+ appendFileSync as appendFileSync2,
14766
+ copyFileSync,
14767
+ closeSync,
14768
+ existsSync as existsSync9,
14769
+ openSync,
14770
+ readFileSync as readFileSync3,
14771
+ mkdirSync as mkdirSync3,
14772
+ readdirSync as readdirSync2,
14773
+ rmSync,
14774
+ statSync as statSync3
14775
+ } from "node:fs";
14776
+ import { homedir } from "node:os";
14899
14777
  import { dirname as dirname19, join as join31 } from "node:path";
14900
- function isEnoent2(error) {
14901
- return typeof error === "object" && error !== null && error.code === "ENOENT";
14778
+ function declareHostSessionFailure(error) {
14779
+ const message = error instanceof Error ? error.stack || error.message : String(error);
14780
+ process.stderr.write(`[host-session] Dossier record failure: ${message}
14781
+ `);
14902
14782
  }
14903
- async function listPiNativeRecordPaths(sessionFile) {
14783
+ function sitianReportSafe(input) {
14904
14784
  try {
14905
- await access3(sessionFile);
14906
- return [sessionFile];
14785
+ sitianReport(input);
14907
14786
  } catch (error) {
14908
- if (isEnoent2(error)) return [];
14909
- throw error;
14787
+ declareHostSessionFailure(error);
14788
+ }
14789
+ }
14790
+ function findCodexRollout(sessionsDir, sessionId) {
14791
+ if (!existsSync9(sessionsDir)) return void 0;
14792
+ const matches = [];
14793
+ function scan(dir, depth = 0) {
14794
+ if (depth > 6) return;
14795
+ let entries;
14796
+ try {
14797
+ entries = readdirSync2(dir, { withFileTypes: true });
14798
+ } catch {
14799
+ return;
14800
+ }
14801
+ for (const entry of entries) {
14802
+ const fullPath = join31(dir, entry.name);
14803
+ if (entry.isDirectory()) {
14804
+ scan(fullPath, depth + 1);
14805
+ } else if (entry.isFile() && entry.name.endsWith(".jsonl") && entry.name.includes(sessionId)) {
14806
+ try {
14807
+ const stat2 = statSync3(fullPath);
14808
+ matches.push({ path: fullPath, mtime: stat2.mtimeMs });
14809
+ } catch {
14810
+ matches.push({ path: fullPath, mtime: 0 });
14811
+ }
14812
+ }
14813
+ }
14910
14814
  }
14815
+ scan(sessionsDir);
14816
+ if (matches.length === 0 || matches[0] === void 0) return void 0;
14817
+ matches.sort((a, b) => b.mtime - a.mtime);
14818
+ return matches[0]?.path;
14911
14819
  }
14912
- async function listSitianRecordPaths(sessionParent) {
14913
- const sessionRoot = dirname19(sessionParent);
14914
- let entries;
14820
+ function sanitizeClaudeCwd(cwd) {
14821
+ return cwd.replace(/[^a-zA-Z0-9]/g, "-");
14822
+ }
14823
+ function resolveNativeSessionPath(options) {
14824
+ const home = options.home || homedir();
14825
+ if (options.host === "claude") {
14826
+ const configDir = process.env.CLAUDE_CONFIG_DIR || join31(home, ".claude");
14827
+ const sanitizedCwd = sanitizeClaudeCwd(options.cwd);
14828
+ return join31(configDir, "projects", sanitizedCwd, `${options.sessionId}.jsonl`);
14829
+ }
14830
+ if (options.host === "codex") {
14831
+ return findCodexRollout(codexSessionsDirectory(home), options.sessionId);
14832
+ }
14833
+ if (options.host === "grok-build") {
14834
+ const grokHome = process.env.GROK_HOME || join31(home, ".grok");
14835
+ return join31(grokHome, "sessions", encodeURIComponent(options.cwd), options.sessionId);
14836
+ }
14837
+ return void 0;
14838
+ }
14839
+ function codexSessionsDirectory(home) {
14840
+ return join31(process.env.CODEX_HOME || join31(home || homedir(), ".codex"), "sessions");
14841
+ }
14842
+ function recordRunStart(runDirectory) {
14915
14843
  try {
14916
- entries = await readdir6(sessionRoot, { withFileTypes: true });
14844
+ appendFileSync2(join31(runDirectory, ".run-starts"), "\n");
14917
14845
  } catch (error) {
14918
- if (isEnoent2(error)) return [];
14919
- throw error;
14846
+ declareHostSessionFailure(error);
14920
14847
  }
14921
- const recordPaths = [];
14922
- for (const entry of entries) {
14923
- if (!entry.isDirectory()) continue;
14924
- const recordFile = join31(sessionRoot, entry.name, "records.jsonl");
14848
+ }
14849
+ function resolveHostDossierLandingPath(options) {
14850
+ const sanitizedModel = (options.model?.model ?? "default").replace(/[\/\\]+/g, "-");
14851
+ let maxOrdinal = 0;
14852
+ if (existsSync9(options.sessionDirectory)) {
14925
14853
  try {
14926
- await access3(recordFile);
14927
- recordPaths.push(recordFile);
14928
- } catch (error) {
14929
- if (!isEnoent2(error)) throw error;
14854
+ const entries = readdirSync2(options.sessionDirectory);
14855
+ for (const entry of entries) {
14856
+ const match = entry.match(/-(\d+)(?:\.jsonl|\.failed)?$/);
14857
+ const first = match?.[1];
14858
+ if (first !== void 0) {
14859
+ const val = parseInt(first, 10);
14860
+ if (!isNaN(val) && val > maxOrdinal) {
14861
+ maxOrdinal = val;
14862
+ }
14863
+ }
14864
+ }
14865
+ } catch {
14930
14866
  }
14931
14867
  }
14932
- recordPaths.sort();
14933
- return recordPaths;
14868
+ const startsPath = join31(dirname19(options.sessionDirectory), ".run-starts");
14869
+ let starts = 0;
14870
+ if (existsSync9(startsPath)) starts = readFileSync3(startsPath, "utf8").length;
14871
+ const ordinal = Math.max(maxOrdinal + 1, starts, options.continuation.kind === "resume" ? 2 : 1);
14872
+ const baseName = `${options.host}-${sanitizedModel}-${ordinal}`;
14873
+ const landingPath = options.host === "grok-build" ? join31(options.sessionDirectory, baseName) : join31(options.sessionDirectory, `${baseName}.jsonl`);
14874
+ return { landingPath, ordinal, sanitizedModel };
14934
14875
  }
14935
- async function projectHostTransitionPriorNative(input) {
14936
- if (input.previousHost === input.liveHost) return void 0;
14937
- if (input.previousHost === "pi") {
14938
- return {
14939
- priorNativeKind: "pi-native",
14940
- priorNativePaths: await listPiNativeRecordPaths(input.piSessionFile)
14941
- };
14876
+ function recordNativeSessionPointer(options) {
14877
+ if (options.host === "pi" || options.host === "hermes") {
14878
+ return void 0;
14942
14879
  }
14943
- return {
14944
- priorNativeKind: "sitian",
14945
- priorNativePaths: await listSitianRecordPaths(input.piSessionFile)
14946
- };
14880
+ const nativePath = options.host === "codex" ? codexSessionsDirectory(options.home) : resolveNativeSessionPath(options);
14881
+ if (nativePath === void 0) return void 0;
14882
+ sitianReportSafe({
14883
+ level: "event",
14884
+ kind: HOST_SESSION_RECORD_KIND,
14885
+ host: options.host,
14886
+ cwd: options.cwd,
14887
+ sessionParent: options.sessionParent,
14888
+ source: `${options.host}-dossier`,
14889
+ payload: {
14890
+ type: "native-session-pointer",
14891
+ nativePath,
14892
+ sessionId: options.sessionId
14893
+ }
14894
+ });
14895
+ return nativePath;
14947
14896
  }
14948
- var init_host_transition_prior_native = __esm({
14949
- "src/host-transition-prior-native.ts"() {
14950
- "use strict";
14897
+ function copyFileCloneOrFallback(src, dest) {
14898
+ try {
14899
+ const res = spawnSync("cp", ["-c", src, dest]);
14900
+ if (res.status === 0) return;
14901
+ } catch {
14951
14902
  }
14952
- });
14953
-
14954
- // src/public-cli/process-cancel.ts
14955
- function processCancelSignalName(signal) {
14956
- if (signal === void 0 || signal.aborted !== true) return void 0;
14957
- const reason = signal.reason;
14958
- if (reason === "SIGTERM" || reason === "SIGINT" || reason === "SIGHUP") {
14959
- return reason;
14903
+ copyFileSync(src, dest);
14904
+ }
14905
+ function copyGrokDossier(srcDir, destDir) {
14906
+ const chatHistorySrc = join31(srcDir, "chat_history.jsonl");
14907
+ if (!existsSync9(chatHistorySrc)) {
14908
+ throw new Error(`Grok native chat_history.jsonl missing at ${chatHistorySrc}`);
14960
14909
  }
14961
- return void 0;
14910
+ mkdirSync3(destDir, { recursive: true });
14911
+ const chatHistoryDest = join31(destDir, "chat_history.jsonl");
14912
+ copyFileCloneOrFallback(chatHistorySrc, chatHistoryDest);
14913
+ const usageSrc = join31(srcDir, "usage.json");
14914
+ if (!existsSync9(usageSrc)) {
14915
+ throw new Error(`Grok native usage.json missing at ${usageSrc}`);
14916
+ }
14917
+ copyFileCloneOrFallback(usageSrc, join31(destDir, "usage.json"));
14962
14918
  }
14963
- function processCancelDiagnostic(signalName) {
14964
- return `ak-role terminated by ${signalName}`;
14919
+ function copyAndRecordHostDossier(options) {
14920
+ if (options.host === "pi" || options.host === "hermes") {
14921
+ return;
14922
+ }
14923
+ const nativePath = resolveNativeSessionPath({
14924
+ host: options.host,
14925
+ sessionId: options.sessionId,
14926
+ cwd: options.cwd,
14927
+ ...options.home !== void 0 ? { home: options.home } : {}
14928
+ });
14929
+ if (nativePath === void 0 && options.host !== "codex") return;
14930
+ let destination;
14931
+ try {
14932
+ destination = resolveHostDossierLandingPath(options);
14933
+ } catch (error) {
14934
+ sitianReportSafe({
14935
+ level: "event",
14936
+ kind: HOST_SESSION_RECORD_KIND,
14937
+ host: options.host,
14938
+ cwd: options.cwd,
14939
+ sessionParent: options.sessionParent,
14940
+ source: `${options.host}-dossier`,
14941
+ payload: {
14942
+ type: "native-session-warning",
14943
+ sessionId: options.sessionId,
14944
+ error: error instanceof Error ? error.message : String(error)
14945
+ }
14946
+ });
14947
+ return;
14948
+ }
14949
+ const { landingPath, ordinal, sanitizedModel } = destination;
14950
+ let lastError;
14951
+ let copySuccess = false;
14952
+ for (let attempt = 1; attempt <= 2; attempt++) {
14953
+ try {
14954
+ if (options.host === "grok-build") {
14955
+ copyGrokDossier(nativePath, landingPath);
14956
+ } else {
14957
+ if (nativePath === void 0 || !existsSync9(nativePath)) {
14958
+ throw new Error(`Native session file missing for ${options.host} session ${options.sessionId}`);
14959
+ }
14960
+ mkdirSync3(dirname19(landingPath), { recursive: true });
14961
+ copyFileCloneOrFallback(nativePath, landingPath);
14962
+ }
14963
+ copySuccess = true;
14964
+ break;
14965
+ } catch (error) {
14966
+ lastError = error;
14967
+ }
14968
+ }
14969
+ if (copySuccess) {
14970
+ sitianReportSafe({
14971
+ level: "event",
14972
+ kind: HOST_SESSION_RECORD_KIND,
14973
+ host: options.host,
14974
+ cwd: options.cwd,
14975
+ sessionParent: options.sessionParent,
14976
+ source: `${options.host}-dossier`,
14977
+ payload: {
14978
+ type: "native-session-copy",
14979
+ nativePath,
14980
+ landingPath,
14981
+ ordinal,
14982
+ sessionId: options.sessionId
14983
+ }
14984
+ });
14985
+ } else {
14986
+ try {
14987
+ rmSync(landingPath, { recursive: options.host === "grok-build", force: true });
14988
+ } catch {
14989
+ }
14990
+ try {
14991
+ mkdirSync3(options.sessionDirectory, { recursive: true });
14992
+ closeSync(openSync(join31(options.sessionDirectory, `${options.host}-${sanitizedModel}-${ordinal}.failed`), "a"));
14993
+ } catch {
14994
+ }
14995
+ sitianReportSafe({
14996
+ level: "event",
14997
+ kind: HOST_SESSION_RECORD_KIND,
14998
+ host: options.host,
14999
+ cwd: options.cwd,
15000
+ sessionParent: options.sessionParent,
15001
+ source: `${options.host}-dossier`,
15002
+ payload: {
15003
+ type: "native-session-warning",
15004
+ nativePath,
15005
+ landingPath,
15006
+ ordinal,
15007
+ sessionId: options.sessionId,
15008
+ error: lastError instanceof Error ? lastError.message : String(lastError)
15009
+ }
15010
+ });
15011
+ }
14965
15012
  }
14966
- var init_process_cancel = __esm({
14967
- "src/public-cli/process-cancel.ts"() {
15013
+ var HOST_SESSION_RECORD_KIND;
15014
+ var init_host_session_record = __esm({
15015
+ "src/host-session-record.ts"() {
14968
15016
  "use strict";
15017
+ init_sitian_facade();
15018
+ HOST_SESSION_RECORD_KIND = "host-session";
14969
15019
  }
14970
15020
  });
14971
15021
 
@@ -15631,35 +15681,6 @@ async function dispatchPostAdmissionTurn(input) {
15631
15681
  }
15632
15682
  };
15633
15683
  try {
15634
- let previousHost;
15635
- const liveHost = env.host;
15636
- const principalCoordinates = admitted.principal === void 0 ? void 0 : env.principalAuthority.decode(admitted.principal);
15637
- let hostTransition;
15638
- try {
15639
- previousHost = readInvocationSelectedHost(admitted.runDirectory);
15640
- hostTransition = previousHost !== void 0 && liveHost !== void 0 && principalCoordinates !== void 0 ? await projectHostTransitionPriorNative({
15641
- previousHost,
15642
- liveHost,
15643
- piSessionFile: principalCoordinates.sessionFile
15644
- }) : void 0;
15645
- } catch (error) {
15646
- return {
15647
- ...await presentControlledFailure2(
15648
- admitted,
15649
- withEngineDetourInvocationScope({
15650
- timedOut: false,
15651
- code: null,
15652
- stderr: "",
15653
- thrown: error
15654
- }, request.invocationScopeId),
15655
- adapters,
15656
- env.principalAuthority,
15657
- io,
15658
- persistRunState
15659
- ),
15660
- ...deferredPersist
15661
- };
15662
- }
15663
15684
  await clearTypedProviderHttpObservation(admitted.runDirectory);
15664
15685
  if (adapters.beforeDispatch !== void 0) {
15665
15686
  try {
@@ -15695,11 +15716,8 @@ async function dispatchPostAdmissionTurn(input) {
15695
15716
  if (env.stationChild !== void 0) {
15696
15717
  turnRequest = { ...turnRequest, stationChild: env.stationChild };
15697
15718
  }
15698
- if (hostTransition !== void 0) {
15699
- turnRequest = { ...turnRequest, hostTransition };
15700
- }
15701
- if (typeof liveHost === "string" && liveHost.trim() !== "") {
15702
- turnRequest = { ...turnRequest, host: liveHost.trim() };
15719
+ if (typeof env.host === "string" && env.host.trim() !== "") {
15720
+ turnRequest = { ...turnRequest, host: env.host.trim() };
15703
15721
  }
15704
15722
  await deliverCaseDossierAsAttachment({
15705
15723
  ticketNumber: admitted.ticketNumber,
@@ -15716,6 +15734,7 @@ async function dispatchPostAdmissionTurn(input) {
15716
15734
  );
15717
15735
  let result;
15718
15736
  try {
15737
+ recordRunStart(admitted.runDirectory);
15719
15738
  result = await env.roleTurnHost.executeTurn(turnRequest);
15720
15739
  } catch (error) {
15721
15740
  const processCancelName = processCancelSignalName(env.signal);
@@ -16415,10 +16434,10 @@ var init_post_admission = __esm({
16415
16434
  init_packaged_role_registry();
16416
16435
  init_case_dossier_delivery();
16417
16436
  init_engine_detour_usage();
16418
- init_host_transition_prior_native();
16419
16437
  init_run_lifecycle();
16420
16438
  init_process_cancel();
16421
16439
  init_activation_ledger_topology();
16440
+ init_host_session_record();
16422
16441
  init_settlement();
16423
16442
  init_terminal();
16424
16443
  init_auto_resume();
@@ -16452,10 +16471,10 @@ var init_seat_ticket_binding = __esm({
16452
16471
  });
16453
16472
 
16454
16473
  // src/public-cli/machine-method-skills.ts
16455
- import { accessSync, constants as constants2, statSync as statSync3 } from "node:fs";
16474
+ import { accessSync, constants as constants2, statSync as statSync4 } from "node:fs";
16456
16475
  import { lstat as lstat6, mkdir as mkdir4, symlink } from "node:fs/promises";
16457
16476
  import { join as join34 } from "node:path";
16458
- import { spawnSync } from "node:child_process";
16477
+ import { spawnSync as spawnSync2 } from "node:child_process";
16459
16478
  function skillRoot(home) {
16460
16479
  return join34(home, ".agents/skills");
16461
16480
  }
@@ -16465,7 +16484,7 @@ function installedMethodSkillPath(home, name) {
16465
16484
  function installedSkillPath(root, name) {
16466
16485
  const path = join34(root, name, "SKILL.md");
16467
16486
  try {
16468
- if (!statSync3(path).isFile()) return void 0;
16487
+ if (!statSync4(path).isFile()) return void 0;
16469
16488
  accessSync(path, constants2.R_OK);
16470
16489
  return path;
16471
16490
  } catch (error) {
@@ -16506,7 +16525,7 @@ async function warnMissingMethodSkills(home, host, role, skills, stdout) {
16506
16525
  }
16507
16526
  }
16508
16527
  function runSkillsCli(args, home) {
16509
- const result = spawnSync("npx", ["--yes", "skills", ...args], {
16528
+ const result = spawnSync2("npx", ["--yes", "skills", ...args], {
16510
16529
  stdio: "inherit",
16511
16530
  env: { ...process.env, HOME: home }
16512
16531
  });
@@ -16693,11 +16712,11 @@ var init_turn_request = __esm({
16693
16712
  });
16694
16713
 
16695
16714
  // src/public-cli/countersign-run.ts
16696
- function isRecord13(value) {
16715
+ function isRecord12(value) {
16697
16716
  return typeof value === "object" && value !== null && !Array.isArray(value);
16698
16717
  }
16699
16718
  function isEscalatePayload(payload) {
16700
- if (!isRecord13(payload)) return false;
16719
+ if (!isRecord12(payload)) return false;
16701
16720
  return payload.status === "escalate";
16702
16721
  }
16703
16722
  function courtDiaristPayloadRows(roleOutcome, submissions) {
@@ -17912,13 +17931,13 @@ var init_instruction_seat_run = __esm({
17912
17931
  });
17913
17932
 
17914
17933
  // src/analyst-book-key.ts
17915
- import { statSync as statSync4 } from "node:fs";
17934
+ import { statSync as statSync5 } from "node:fs";
17916
17935
  import { isAbsolute as isAbsolute8 } from "node:path";
17917
17936
  function resolveAnalystBookKey(projectRoot) {
17918
17937
  const identity = physicalPathIdentity(projectRoot);
17919
17938
  let stats;
17920
17939
  try {
17921
- stats = statSync4(identity);
17940
+ stats = statSync5(identity);
17922
17941
  } catch (error) {
17923
17942
  const code = errnoCode(error);
17924
17943
  if (code === "ENOENT" || code === "ENOTDIR") return `root:${identity}`;
@@ -18278,7 +18297,7 @@ var init_analyst_cohort = __esm({
18278
18297
  });
18279
18298
 
18280
18299
  // src/analyst-ledger.ts
18281
- import { readdir as readdir7, readFile as readFile20 } from "node:fs/promises";
18300
+ import { readdir as readdir6, readFile as readFile20 } from "node:fs/promises";
18282
18301
  import { basename as basename9, join as join36 } from "node:path";
18283
18302
  function isMissingPathError6(error) {
18284
18303
  return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
@@ -18286,7 +18305,7 @@ function isMissingPathError6(error) {
18286
18305
  function errorText3(error) {
18287
18306
  return error instanceof Error ? error.message : String(error);
18288
18307
  }
18289
- function isRecord14(value) {
18308
+ function isRecord13(value) {
18290
18309
  return typeof value === "object" && value !== null && !Array.isArray(value);
18291
18310
  }
18292
18311
  async function readExistingRunLifecycleState(runDirectory) {
@@ -18327,7 +18346,7 @@ function parseRunDirectoryName2(name) {
18327
18346
  }
18328
18347
  async function listLedgerBookNames(booksRoot) {
18329
18348
  try {
18330
- const entries = await readdir7(booksRoot, { withFileTypes: true });
18349
+ const entries = await readdir6(booksRoot, { withFileTypes: true });
18331
18350
  return entries.filter((e) => e.isDirectory()).map((e) => e.name).sort();
18332
18351
  } catch (error) {
18333
18352
  if (isMissingPathError6(error)) return [];
@@ -18343,7 +18362,7 @@ async function readInvocationScopeFields(runDirectory) {
18343
18362
  throw error;
18344
18363
  }
18345
18364
  const parsed = JSON.parse(raw);
18346
- if (!isRecord14(parsed)) return void 0;
18365
+ if (!isRecord13(parsed)) return void 0;
18347
18366
  if (typeof parsed.projectRoot !== "string" || parsed.projectRoot.trim() === "") {
18348
18367
  return void 0;
18349
18368
  }
@@ -18372,7 +18391,7 @@ async function resolveSessionFile(runDirectory) {
18372
18391
  try {
18373
18392
  const raw = await readFile20(join36(runDirectory, "invocation.json"), "utf8");
18374
18393
  const parsed = JSON.parse(raw);
18375
- if (isRecord14(parsed) && typeof parsed.sessionFile === "string" && parsed.sessionFile.trim() !== "") {
18394
+ if (isRecord13(parsed) && typeof parsed.sessionFile === "string" && parsed.sessionFile.trim() !== "") {
18376
18395
  return parsed.sessionFile;
18377
18396
  }
18378
18397
  } catch (error) {
@@ -18710,7 +18729,7 @@ var init_analyst_ledger = __esm({
18710
18729
  });
18711
18730
 
18712
18731
  // src/analyst-metric-families/acceptance-success-rework.ts
18713
- function isRecord15(value) {
18732
+ function isRecord14(value) {
18714
18733
  return typeof value === "object" && value !== null && !Array.isArray(value);
18715
18734
  }
18716
18735
  function wallMsFromSpan(span) {
@@ -18719,21 +18738,21 @@ function wallMsFromSpan(span) {
18719
18738
  function findCollectorGroups(body) {
18720
18739
  if (Array.isArray(body.groups)) return body.groups;
18721
18740
  const receipt = body.receipt;
18722
- if (isRecord15(receipt) && Array.isArray(receipt.groups)) return receipt.groups;
18741
+ if (isRecord14(receipt) && Array.isArray(receipt.groups)) return receipt.groups;
18723
18742
  const outcome = body.outcome;
18724
- if (isRecord15(outcome)) {
18743
+ if (isRecord14(outcome)) {
18725
18744
  const facts = outcome.decisiveFacts;
18726
- if (isRecord15(facts) && Array.isArray(facts.groups)) return facts.groups;
18745
+ if (isRecord14(facts) && Array.isArray(facts.groups)) return facts.groups;
18727
18746
  }
18728
18747
  return void 0;
18729
18748
  }
18730
18749
  function extractStatus(body) {
18731
18750
  const outcome = body.outcome;
18732
- if (isRecord15(outcome) && typeof outcome.status === "string" && outcome.status.trim() !== "") {
18751
+ if (isRecord14(outcome) && typeof outcome.status === "string" && outcome.status.trim() !== "") {
18733
18752
  return outcome.status;
18734
18753
  }
18735
18754
  const receipt = body.receipt;
18736
- if (isRecord15(receipt) && typeof receipt.status === "string" && receipt.status.trim() !== "") {
18755
+ if (isRecord14(receipt) && typeof receipt.status === "string" && receipt.status.trim() !== "") {
18737
18756
  return receipt.status;
18738
18757
  }
18739
18758
  if (typeof body.status === "string" && body.status.trim() !== "") {
@@ -19359,15 +19378,15 @@ var init_leg_wall_clock = __esm({
19359
19378
  });
19360
19379
 
19361
19380
  // src/analyst-metric-families/round-timeline.ts
19362
- function isRecord16(value) {
19381
+ function isRecord15(value) {
19363
19382
  return typeof value === "object" && value !== null && !Array.isArray(value);
19364
19383
  }
19365
19384
  function wallMsFromSpan2(startedAt, endedAt) {
19366
19385
  return Date.parse(endedAt) - Date.parse(startedAt);
19367
19386
  }
19368
19387
  function readClassCount(body) {
19369
- if (!isRecord16(body.outcome)) return void 0;
19370
- if (!isRecord16(body.outcome.decisiveFacts)) return void 0;
19388
+ if (!isRecord15(body.outcome)) return void 0;
19389
+ if (!isRecord15(body.outcome.decisiveFacts)) return void 0;
19371
19390
  const classCount = body.outcome.decisiveFacts.classCount;
19372
19391
  if (typeof classCount !== "number" || !Number.isFinite(classCount)) {
19373
19392
  return void 0;
@@ -19511,7 +19530,7 @@ var init_analyst_metric_family = __esm({
19511
19530
  });
19512
19531
 
19513
19532
  // src/analyst-page.ts
19514
- import { createHash as createHash6 } from "node:crypto";
19533
+ import { createHash as createHash5 } from "node:crypto";
19515
19534
  import { dirname as dirname22, join as join37 } from "node:path";
19516
19535
  function analystIssuePageKey(address) {
19517
19536
  const parts = ["book", address.bookKey];
@@ -19520,7 +19539,7 @@ function analystIssuePageKey(address) {
19520
19539
  } else if (address.scopeRootIdentity !== void 0) {
19521
19540
  parts.push("root", physicalPathIdentity(address.scopeRootIdentity));
19522
19541
  }
19523
- return createHash6("sha256").update(parts.join("\0")).digest("hex").slice(0, 32);
19542
+ return createHash5("sha256").update(parts.join("\0")).digest("hex").slice(0, 32);
19524
19543
  }
19525
19544
  function analystIssuePagePath(ledgerHome, address) {
19526
19545
  return join37(ledgerHome, "analyst", "issues", `${analystIssuePageKey(address)}.json`);
@@ -21750,7 +21769,7 @@ __export(run_lifecycle_exports, {
21750
21769
  renderResumeCommand: () => renderResumeCommand,
21751
21770
  writeRoleRunState: () => writeRoleRunState
21752
21771
  });
21753
- import { chmod, lstat as lstat7, open as open3, readdir as readdir8, readFile as readFile23, unlink as unlink5, writeFile as writeFile10 } from "node:fs/promises";
21772
+ import { chmod, lstat as lstat7, open as open3, readdir as readdir7, readFile as readFile23, unlink as unlink5, writeFile as writeFile10 } from "node:fs/promises";
21754
21773
  import { basename as basename10, join as join41 } from "node:path";
21755
21774
  function buildAutoResumeContinuationPrompt(options) {
21756
21775
  return appendEngineSessionMaterial(
@@ -21829,7 +21848,7 @@ async function readRoleRunStateRaw(runDirectory) {
21829
21848
  try {
21830
21849
  raw = JSON.parse(await readFile23(join41(runDirectory, RUN_STATE_FILE), "utf8"));
21831
21850
  } catch (error) {
21832
- if (errorCodeOf2(error) === "ENOENT") return void 0;
21851
+ if (errorCodeOf(error) === "ENOENT") return void 0;
21833
21852
  throw error;
21834
21853
  }
21835
21854
  return raw;
@@ -22074,7 +22093,7 @@ function describeErrorIdentity(error) {
22074
22093
  const message = typeof candidate?.message === "string" && candidate.message !== "" ? `: ${candidate.message}` : "";
22075
22094
  return `${name}${code}${message}`;
22076
22095
  }
22077
- function errorCodeOf2(error) {
22096
+ function errorCodeOf(error) {
22078
22097
  return error.code;
22079
22098
  }
22080
22099
  function isProcessAlive(pid) {
@@ -22082,7 +22101,7 @@ function isProcessAlive(pid) {
22082
22101
  process.kill(pid, 0);
22083
22102
  return true;
22084
22103
  } catch (error) {
22085
- return errorCodeOf2(error) !== "ESRCH";
22104
+ return errorCodeOf(error) !== "ESRCH";
22086
22105
  }
22087
22106
  }
22088
22107
  async function autopsyWriterLock(lockPath) {
@@ -22090,7 +22109,7 @@ async function autopsyWriterLock(lockPath) {
22090
22109
  try {
22091
22110
  content = await readFile23(lockPath, "utf8");
22092
22111
  } catch (error) {
22093
- if (errorCodeOf2(error) === "ENOENT") return { verdict: "absent" };
22112
+ if (errorCodeOf(error) === "ENOENT") return { verdict: "absent" };
22094
22113
  return { verdict: "unknown", reason: "unreadable", readFailure: error };
22095
22114
  }
22096
22115
  const normalized = content.trim();
@@ -22122,8 +22141,8 @@ async function reclaimStaleWriterLock(lockPath, runDirectory) {
22122
22141
  await unlink5(lockPath);
22123
22142
  return { reclaimed: true };
22124
22143
  } catch (error) {
22125
- if (errorCodeOf2(error) === "ENOENT") return { reclaimed: false };
22126
- if (errorCodeOf2(error) !== "EACCES") throw error;
22144
+ if (errorCodeOf(error) === "ENOENT") return { reclaimed: false };
22145
+ if (errorCodeOf(error) !== "EACCES") throw error;
22127
22146
  await chmod(runDirectory, 493);
22128
22147
  return { reclaimed: false, eaccesFailure: error };
22129
22148
  }
@@ -22156,7 +22175,7 @@ async function createWriterLease(lockPath, runDirectory, reportCleanupFailure) {
22156
22175
  try {
22157
22176
  await unlink5(currentLockPath);
22158
22177
  } catch (error) {
22159
- if (errorCodeOf2(error) === "EACCES") {
22178
+ if (errorCodeOf(error) === "EACCES") {
22160
22179
  try {
22161
22180
  await chmod(currentRunDirectory, 493);
22162
22181
  await unlink5(currentLockPath);
@@ -22196,7 +22215,7 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
22196
22215
  try {
22197
22216
  return await createWriterLease(lockPath, runDirectory, reportCleanupFailure);
22198
22217
  } catch (error) {
22199
- if (errorCodeOf2(error) !== "EEXIST") throw error;
22218
+ if (errorCodeOf(error) !== "EEXIST") throw error;
22200
22219
  }
22201
22220
  lastAutopsy = await autopsyWriterLock(lockPath);
22202
22221
  if (lastAutopsy.verdict === "unknown" && lastAutopsy.reason === "unreadable") {
@@ -22247,9 +22266,9 @@ async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole) {
22247
22266
  const booksRoot = join41(ledgerHome, "books");
22248
22267
  let bookKeys;
22249
22268
  try {
22250
- bookKeys = await readdir8(booksRoot);
22269
+ bookKeys = await readdir7(booksRoot);
22251
22270
  } catch (error) {
22252
- if (errorCodeOf2(error) === "ENOENT") return void 0;
22271
+ if (errorCodeOf(error) === "ENOENT") return void 0;
22253
22272
  throw error;
22254
22273
  }
22255
22274
  const matches = [];
@@ -22260,7 +22279,7 @@ async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole) {
22260
22279
  try {
22261
22280
  runDirectories = await listBookRunDirectories(bookDir);
22262
22281
  } catch (error) {
22263
- if (errorCodeOf2(error) === "ENOENT") continue;
22282
+ if (errorCodeOf(error) === "ENOENT") continue;
22264
22283
  throw error;
22265
22284
  }
22266
22285
  for (const runDirectory of runDirectories) {
@@ -22288,7 +22307,7 @@ async function readRunParentPath(runDirectory) {
22288
22307
  await readFile23(join41(runDirectory, "admitted-request.json"), "utf8")
22289
22308
  );
22290
22309
  } catch (error) {
22291
- if (errorCodeOf2(error) === "ENOENT") return void 0;
22310
+ if (errorCodeOf(error) === "ENOENT") return void 0;
22292
22311
  throw error;
22293
22312
  }
22294
22313
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
@@ -22311,7 +22330,7 @@ async function runHasFormedSessionPrincipal(runDirectory) {
22311
22330
  const stat2 = await lstat7(sessionFile);
22312
22331
  return stat2.isFile() && !stat2.isSymbolicLink();
22313
22332
  } catch (error) {
22314
- if (errorCodeOf2(error) === "ENOENT") return false;
22333
+ if (errorCodeOf(error) === "ENOENT") return false;
22315
22334
  throw error;
22316
22335
  }
22317
22336
  }
@@ -22327,7 +22346,7 @@ async function findLatestRunIdForSeatTicket(input) {
22327
22346
  input.ticketNumber === void 0 ? bookDir : join41(bookDir, String(input.ticketNumber))
22328
22347
  );
22329
22348
  } catch (error) {
22330
- if (errorCodeOf2(error) === "ENOENT") return void 0;
22349
+ if (errorCodeOf(error) === "ENOENT") return void 0;
22331
22350
  throw error;
22332
22351
  }
22333
22352
  const suffix = `@${input.role}`;
@@ -22958,7 +22977,7 @@ var init_run_lifecycle = __esm({
22958
22977
  });
22959
22978
 
22960
22979
  // src/archivist-record-topology.ts
22961
- import { createHash as createHash7 } from "node:crypto";
22980
+ import { createHash as createHash6 } from "node:crypto";
22962
22981
  import { join as join42 } from "node:path";
22963
22982
  function resolveNavigatorWorkSubjectPlacement(input) {
22964
22983
  let ledgerHome;
@@ -22969,7 +22988,7 @@ function resolveNavigatorWorkSubjectPlacement(input) {
22969
22988
  }
22970
22989
  }
22971
22990
  ledgerHome ??= resolveActivationLedgerHome(input.home);
22972
- const digest = createHash7("sha256").update(input.subject).digest("hex").slice(0, 32);
22991
+ const digest = createHash6("sha256").update(input.subject).digest("hex").slice(0, 32);
22973
22992
  return {
22974
22993
  ledgerHome,
22975
22994
  sessionDir: join42(
@@ -23034,15 +23053,15 @@ __export(archivist_record_entry_exports, {
23034
23053
  resolveNavigatorWorkSubjectPlacement: () => resolveNavigatorWorkSubjectPlacement
23035
23054
  });
23036
23055
  import {
23037
- closeSync,
23056
+ closeSync as closeSync2,
23038
23057
  existsSync as existsSync12,
23039
- openSync,
23040
- readdirSync as readdirSync2,
23058
+ openSync as openSync2,
23059
+ readdirSync as readdirSync3,
23041
23060
  readFileSync as readFileSync4,
23042
23061
  readSync,
23043
23062
  realpathSync as realpathSync3,
23044
- statSync as statSync5,
23045
- writeFileSync as writeFileSync3
23063
+ statSync as statSync6,
23064
+ writeFileSync as writeFileSync2
23046
23065
  } from "node:fs";
23047
23066
  import { dirname as dirname23, resolve as resolve16, join as join43 } from "node:path";
23048
23067
  import { StringDecoder } from "node:string_decoder";
@@ -23064,7 +23083,7 @@ function readCurrentSession(sessionDir) {
23064
23083
  function writeCurrentSession(sessionDir, sessionFile) {
23065
23084
  const ledger = join43(sessionDir, CURRENT_SESSION_LEDGER);
23066
23085
  try {
23067
- writeFileSync3(ledger, `${JSON.stringify({ sessionFile })}
23086
+ writeFileSync2(ledger, `${JSON.stringify({ sessionFile })}
23068
23087
  `, { flag: "wx" });
23069
23088
  } catch (error) {
23070
23089
  throw new ActivationLedgerError(
@@ -23081,7 +23100,7 @@ function currentSessionLedgerPath(sessionDir) {
23081
23100
  return join43(sessionDir, CURRENT_SESSION_LEDGER);
23082
23101
  }
23083
23102
  function readBoundedSessionHeader(filePath) {
23084
- const fd = openSync(filePath, "r");
23103
+ const fd = openSync2(filePath, "r");
23085
23104
  try {
23086
23105
  const buffer = Buffer.allocUnsafe(SESSION_HEADER_CHUNK_BYTES);
23087
23106
  const decoder2 = new StringDecoder("utf8");
@@ -23129,7 +23148,7 @@ function readBoundedSessionHeader(filePath) {
23129
23148
  }
23130
23149
  return void 0;
23131
23150
  } finally {
23132
- closeSync(fd);
23151
+ closeSync2(fd);
23133
23152
  }
23134
23153
  }
23135
23154
  function parseSessionHeaderLine(line2) {
@@ -23155,7 +23174,7 @@ function mostRecentNavigatorSessionFile(sessionDir, cwd) {
23155
23174
  const absoluteCwd = resolve16(cwd);
23156
23175
  let names;
23157
23176
  try {
23158
- names = readdirSync2(absoluteSessionDir);
23177
+ names = readdirSync3(absoluteSessionDir);
23159
23178
  } catch (error) {
23160
23179
  throw new ActivationLedgerError(
23161
23180
  `archivist navigator nest is not readable (${sessionDir}): ${errorText(error)}`,
@@ -23168,7 +23187,7 @@ function mostRecentNavigatorSessionFile(sessionDir, cwd) {
23168
23187
  const filePath = join43(absoluteSessionDir, name);
23169
23188
  let st;
23170
23189
  try {
23171
- st = statSync5(filePath);
23190
+ st = statSync6(filePath);
23172
23191
  } catch (error) {
23173
23192
  throw new ActivationLedgerError(
23174
23193
  `archivist navigator session file is not stat-able (${filePath}): ${errorText(error)}`,
@@ -23309,7 +23328,7 @@ function createRecordSessionOpen(options, host = piRecordSessionHost) {
23309
23328
  if (file !== void 0 && !existsSync12(file)) {
23310
23329
  const header = session.getHeader();
23311
23330
  if (header !== null && header.type === "session") {
23312
- writeFileSync3(file, `${JSON.stringify(header)}
23331
+ writeFileSync2(file, `${JSON.stringify(header)}
23313
23332
  `, { flag: "wx" });
23314
23333
  session.setSessionFile(file);
23315
23334
  }
@@ -23349,7 +23368,7 @@ import { readFile as readFile26 } from "node:fs/promises";
23349
23368
  import { join as join47 } from "node:path";
23350
23369
 
23351
23370
  // src/navigator-attendance.ts
23352
- import { createHash as createHash8 } from "node:crypto";
23371
+ import { createHash as createHash7 } from "node:crypto";
23353
23372
  init_navigator_invocation_identity();
23354
23373
  init_packaged_role_registry();
23355
23374
  init_activation_ledger_topology();
@@ -23553,7 +23572,7 @@ init_packaged_role_registry();
23553
23572
 
23554
23573
  // src/navigator-work-base.ts
23555
23574
  init_atomic_write();
23556
- import { existsSync as existsSync4, realpathSync as realpathSync2 } from "node:fs";
23575
+ import { existsSync as existsSync3, realpathSync as realpathSync2 } from "node:fs";
23557
23576
  import { readFile as readFile6 } from "node:fs/promises";
23558
23577
  import { basename as basename3, dirname as dirname7, join as join7, resolve as resolve5 } from "node:path";
23559
23578
  var NAVIGATOR_WORK_CONTEXT_BASENAME = "work-context.json";
@@ -23577,7 +23596,7 @@ function canonicalNavigatorWorkContextFile(path) {
23577
23596
  }
23578
23597
  }
23579
23598
  async function persistNavigatorWorkBase(sessionDir, body) {
23580
- if (sessionDir.trim() === "" || !existsSync4(sessionDir)) return void 0;
23599
+ if (sessionDir.trim() === "" || !existsSync3(sessionDir)) return void 0;
23581
23600
  if (body.authority.trim() === "") return void 0;
23582
23601
  const path = navigatorWorkContextFile(sessionDir);
23583
23602
  const next = `${JSON.stringify({ subject: body.subject, authority: body.authority })}
@@ -23910,7 +23929,7 @@ function navigatorSubjectKey(subjectRoot, subject, provenance = "role_input") {
23910
23929
  if (provenance === "placeholder") return subjectRoot;
23911
23930
  const normalized = subject.trim().replace(/\s+/g, " ");
23912
23931
  if (normalized === "") return subjectRoot;
23913
- return `${subjectRoot}#${createHash8("sha256").update(normalized).digest("hex").slice(0, 32)}`;
23932
+ return `${subjectRoot}#${createHash7("sha256").update(normalized).digest("hex").slice(0, 32)}`;
23914
23933
  }
23915
23934
  function navigatorSubjectKeyForInput(subjectRoot, reference, cwd = process.cwd()) {
23916
23935
  if (issueRoot(subjectRoot) !== void 0 || !subjectRoot.includes("/.ak/work/")) return subjectRoot;
@@ -24461,8 +24480,8 @@ init_activation_ledger_topology();
24461
24480
  import {
24462
24481
  lstatSync as lstatSync2,
24463
24482
  realpathSync as realpathSync4,
24464
- statSync as statSync6,
24465
- writeFileSync as writeFileSync4
24483
+ statSync as statSync7,
24484
+ writeFileSync as writeFileSync3
24466
24485
  } from "node:fs";
24467
24486
  import { isAbsolute as isAbsolute11, resolve as resolve19 } from "node:path";
24468
24487
  var ActivationSessionFileMissingError = class extends Error {
@@ -24483,7 +24502,7 @@ function materializeDeferredSessionFile(sessionManager, resolvedFile) {
24483
24502
  throw new ActivationSessionFileMissingError(resolvedFile);
24484
24503
  }
24485
24504
  try {
24486
- writeFileSync4(resolvedFile, `${JSON.stringify(header)}
24505
+ writeFileSync3(resolvedFile, `${JSON.stringify(header)}
24487
24506
  `, { flag: "wx" });
24488
24507
  } catch (error) {
24489
24508
  if (errnoCode(error) !== "EEXIST") {
@@ -24536,7 +24555,7 @@ function durableSessionPointer(sessionManager) {
24536
24555
  }
24537
24556
  let info;
24538
24557
  try {
24539
- info = statSync6(realFile);
24558
+ info = statSync7(realFile);
24540
24559
  } catch (error) {
24541
24560
  throw new Error(
24542
24561
  `Workflow role activation failed to stat durable session file (${realFile}): ${errorText(error)}`,
@@ -25968,7 +25987,7 @@ init_worker_submission_contracts();
25968
25987
  init_submission_errors();
25969
25988
  init_worker_submission_contracts();
25970
25989
  import { execFileSync as execFileSync4 } from "node:child_process";
25971
- import { existsSync as existsSync14, lstatSync as lstatSync3, readdirSync as readdirSync3, readFileSync as readFileSync5, rmdirSync, rmSync } from "node:fs";
25990
+ import { existsSync as existsSync14, lstatSync as lstatSync3, readdirSync as readdirSync4, readFileSync as readFileSync5, rmdirSync, rmSync as rmSync2 } from "node:fs";
25972
25991
  import { resolve as resolve20 } from "node:path";
25973
25992
  var WORKER_SUBMISSION_GATE_RECORD_KIND = WORKER_SUBMISSION_GATE_KIND;
25974
25993
  var WORKER_COMMIT_BASELINE_ENTRY_TYPE = "commit-baseline";
@@ -26034,13 +26053,13 @@ function unsetOwnedHooksPath(file) {
26034
26053
  function rmOwnedDir(dir) {
26035
26054
  const hookPath = resolve20(dir, HOOK_FILE);
26036
26055
  if (!ownedHook(hookPath)) return;
26037
- rmSync(hookPath, { force: true });
26038
- if (existsSync14(dir) && readdirSync3(dir).length === 0) rmdirSync(dir);
26056
+ rmSync2(hookPath, { force: true });
26057
+ if (existsSync14(dir) && readdirSync4(dir).length === 0) rmdirSync(dir);
26039
26058
  }
26040
26059
  function linkedGitDirs(commonDir) {
26041
26060
  const root = resolve20(commonDir, "worktrees");
26042
26061
  if (!existsSync14(root)) return [];
26043
- return readdirSync3(root).map((name) => resolve20(root, name)).filter((dir) => lstatSync3(dir).isDirectory());
26062
+ return readdirSync4(root).map((name) => resolve20(root, name)).filter((dir) => lstatSync3(dir).isDirectory());
26044
26063
  }
26045
26064
  function uninstallPackageWorkerHooks(cwd) {
26046
26065
  let inside;
@@ -26058,13 +26077,13 @@ function uninstallPackageWorkerHooks(cwd) {
26058
26077
  clear(resolve20(commonDir, "config.worktree"));
26059
26078
  rmOwnedDir(resolve20(commonDir, HOOKS_DIR));
26060
26079
  const legacy = resolve20(commonDir, "hooks", HOOK_FILE);
26061
- if (ownedHook(legacy)) rmSync(legacy, { force: true });
26080
+ if (ownedHook(legacy)) rmSync2(legacy, { force: true });
26062
26081
  for (const gitDir of linkedGitDirs(commonDir)) {
26063
26082
  clear(resolve20(gitDir, "config.worktree"));
26064
26083
  rmOwnedDir(resolve20(gitDir, HOOKS_DIR));
26065
26084
  }
26066
26085
  }
26067
- function isRecord17(value) {
26086
+ function isRecord16(value) {
26068
26087
  return typeof value === "object" && value !== null && !Array.isArray(value);
26069
26088
  }
26070
26089
  function unfinishedReasonPresent(details) {
@@ -26080,7 +26099,7 @@ function readGateState(session) {
26080
26099
  if (entry.type !== "custom") continue;
26081
26100
  if (entry.customType === WORKER_COMMIT_BASELINE_ENTRY_TYPE) {
26082
26101
  const data = entry.data;
26083
- if (isRecord17(data) && (data.head === null || typeof data.head === "string")) {
26102
+ if (isRecord16(data) && (data.head === null || typeof data.head === "string")) {
26084
26103
  baseline = data.head;
26085
26104
  }
26086
26105
  } else if (entry.customType === WORKER_COMMIT_REMINDER_BOUNCE_ENTRY_TYPE) {
@@ -26273,11 +26292,11 @@ var FIXER_PHASES = ["plan", "apply"];
26273
26292
  function isWorkerPhase(value) {
26274
26293
  return typeof value === "string" && FIXER_PHASES.includes(value);
26275
26294
  }
26276
- function isRecord18(value) {
26295
+ function isRecord17(value) {
26277
26296
  return typeof value === "object" && value !== null && !Array.isArray(value);
26278
26297
  }
26279
26298
  function workerStatusOf(output) {
26280
- return isRecord18(output) && typeof output.status === "string" ? output.status : void 0;
26299
+ return isRecord17(output) && typeof output.status === "string" ? output.status : void 0;
26281
26300
  }
26282
26301
  function deepFreeze2(value) {
26283
26302
  if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
@@ -28774,30 +28793,19 @@ function headlessMcpConfigDocument(mcpServers) {
28774
28793
  }
28775
28794
 
28776
28795
  // src/headless-host/role-turn-host.ts
28777
- import { spawn as spawn4, spawnSync as spawnSync2 } from "node:child_process";
28796
+ import { spawn as spawn4, spawnSync as spawnSync3 } from "node:child_process";
28778
28797
  import { randomUUID as randomUUID10 } from "node:crypto";
28779
28798
  import { existsSync as existsSync15 } from "node:fs";
28780
28799
  import { writeFile as writeFile12 } from "node:fs/promises";
28781
28800
  import { dirname as dirname26, isAbsolute as isAbsolute12, join as join50, resolve as resolve21 } from "node:path";
28782
28801
 
28783
28802
  // src/external-host-turn-loop.ts
28784
- init_packaged_role_registry();
28785
28803
  var EXTERNAL_ROLE_TURN_ROUND_LIMIT = 8;
28786
28804
  function mergeRoleTurnAbortSignals(prepared, request) {
28787
28805
  if (request === void 0) return prepared;
28788
28806
  if (prepared === void 0) return request;
28789
28807
  return AbortSignal.any([prepared, request]);
28790
28808
  }
28791
- function promptWithPriorNativePaths(basePrompt, request) {
28792
- if (request.continuation.kind !== "resume") return basePrompt;
28793
- if (request.stationChild === true && isOfficerReviewSeat(request.activation.role)) {
28794
- return basePrompt;
28795
- }
28796
- const paths = request.hostTransition?.priorNativePaths;
28797
- if (paths === void 0 || paths.length === 0) return basePrompt;
28798
- return `${basePrompt}
28799
- ${paths.join("\n")}`;
28800
- }
28801
28809
  function isHostAbortedError(error) {
28802
28810
  return typeof error === "object" && error !== null && error.code === "host-aborted";
28803
28811
  }
@@ -28817,7 +28825,7 @@ async function settleHostAborted(prepared, sessionId) {
28817
28825
  });
28818
28826
  }
28819
28827
  async function driveExternalRoleTurnRounds(prepared, request, driver) {
28820
- let prompt = promptWithPriorNativePaths(prepared.prompt, request);
28828
+ let prompt = prepared.prompt;
28821
28829
  const abortSignal = mergeRoleTurnAbortSignals(prepared.abortSignal, request.signal);
28822
28830
  let stderr = "";
28823
28831
  for (let attempt = 0; attempt < EXTERNAL_ROLE_TURN_ROUND_LIMIT; attempt += 1) {
@@ -28872,31 +28880,8 @@ function renderSystemPromptOverride(authority) {
28872
28880
  return renderAgentStartMaterials(authority.body, authority.materials);
28873
28881
  }
28874
28882
 
28875
- // src/host-session-record.ts
28876
- init_sitian_facade();
28877
- var HOST_SESSION_RECORD_KIND = "host-session";
28878
- function eventField(event, key) {
28879
- if (typeof event !== "object" || event === null || Array.isArray(event)) return void 0;
28880
- const value = event[key];
28881
- return typeof value === "string" && value.length > 0 ? value : void 0;
28882
- }
28883
- function reportHostSessionEvent(input) {
28884
- const identity = input.identity ?? eventField(input.event, "uuid");
28885
- const timestamp2 = input.timestamp ?? eventField(input.event, "timestamp");
28886
- sitianReport({
28887
- level: "event",
28888
- kind: HOST_SESSION_RECORD_KIND,
28889
- host: input.host,
28890
- cwd: input.cwd,
28891
- sessionParent: input.sessionParent,
28892
- source: input.source,
28893
- payload: input.event,
28894
- ...identity === void 0 ? {} : { identity },
28895
- ...timestamp2 === void 0 ? {} : { timestamp: timestamp2 }
28896
- });
28897
- }
28898
-
28899
28883
  // src/headless-host/role-turn-host.ts
28884
+ init_host_session_record();
28900
28885
  init_navigator_output();
28901
28886
  function failure(cause, name, code, details, diagnostic) {
28902
28887
  return {
@@ -29008,7 +28993,7 @@ function resolveGitCommonDir(cwd) {
29008
28993
  if (!cwdIsGitWorkTree(cwd)) return void 0;
29009
28994
  let result;
29010
28995
  try {
29011
- result = spawnSync2("git", ["rev-parse", "--git-common-dir"], {
28996
+ result = spawnSync3("git", ["rev-parse", "--git-common-dir"], {
29012
28997
  cwd,
29013
28998
  encoding: "utf8"
29014
28999
  });
@@ -29094,8 +29079,15 @@ function spawnHeadlessTurn(options) {
29094
29079
  lineBuffer = "";
29095
29080
  }
29096
29081
  };
29082
+ let aborted = false;
29097
29083
  const settle = (code) => {
29098
29084
  if (settled) return;
29085
+ if (aborted) {
29086
+ settled = true;
29087
+ if (timer !== void 0) clearTimeout(timer);
29088
+ reject(hostAbortedError("headless host aborted"));
29089
+ return;
29090
+ }
29099
29091
  flushStdoutLines("", true);
29100
29092
  if (settled) return;
29101
29093
  settled = true;
@@ -29108,11 +29100,9 @@ function spawnHeadlessTurn(options) {
29108
29100
  resolve22({ code, stdout: resultStdout, stderr, timedOut });
29109
29101
  };
29110
29102
  const onAbort = () => {
29111
- child.kill("SIGTERM");
29112
29103
  if (settled) return;
29113
- settled = true;
29114
- if (timer !== void 0) clearTimeout(timer);
29115
- reject(hostAbortedError("headless host aborted"));
29104
+ aborted = true;
29105
+ child.kill("SIGTERM");
29116
29106
  };
29117
29107
  child.stdout.setEncoding("utf8").on("data", (chunk) => {
29118
29108
  flushStdoutLines(chunk, false);
@@ -29127,7 +29117,10 @@ function spawnHeadlessTurn(options) {
29127
29117
  options.signal?.removeEventListener("abort", onAbort);
29128
29118
  reject(error);
29129
29119
  });
29130
- child.on("close", (code) => settle(code));
29120
+ child.on("close", (code) => {
29121
+ options.onClose?.();
29122
+ settle(code);
29123
+ });
29131
29124
  options.signal?.addEventListener("abort", onAbort, { once: true });
29132
29125
  if (options.timeoutMs !== void 0 && options.timeoutMs > 0) {
29133
29126
  timer = setTimeout(() => {
@@ -29230,236 +29223,268 @@ function createHeadlessRoleTurnHost(config) {
29230
29223
  );
29231
29224
  }
29232
29225
  const sessionParent = config.sessionIdentity.resolveSessionFile(request.principal);
29233
- outcome = await driveExternalRoleTurnRounds(prepared, request, {
29234
- roundLimitName: "HeadlessRoundLimit",
29235
- currentSessionId: () => sessionId,
29236
- afterRetry() {
29237
- sessionKind = "resume";
29238
- },
29239
- async runRound({ prompt, abortSignal }) {
29240
- let args;
29241
- try {
29242
- const gitCommonDir = codex ? resolveGitCommonDir(request.cwd) : void 0;
29243
- args = buildTurnArgs({
29244
- description: config.description,
29245
- systemPromptPath,
29246
- // #959: navigator prose exit — no closed JSON schema on claude either.
29247
- ...prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME ? {} : { jsonSchema: prepared.jsonSchema },
29248
- mcpServers: prepared.mcpServers,
29249
- ...mcpConfigPath === void 0 ? {} : { mcpConfigPath },
29250
- ...outputSchemaPath === void 0 ? {} : { outputSchemaPath },
29251
- ...request.model?.model !== void 0 ? { model: request.model.model } : {},
29252
- ...request.model?.thinking !== void 0 ? { effort: request.model.thinking } : {},
29253
- sessionId,
29254
- sessionKind,
29255
- cwd: request.cwd,
29256
- ...gitCommonDir === void 0 ? {} : { writableRoots: [gitCommonDir] }
29257
- });
29258
- } catch (error) {
29259
- const message = error instanceof Error ? error.message : String(error);
29260
- return {
29261
- status: "terminal",
29262
- result: failure("session", "HeadlessArgvFailure", "argv-failed", { diagnostic: message }, message)
29263
- };
29264
- }
29265
- const codexObserver = codex ? createCodexExecTurnObserver() : void 0;
29266
- let spawned;
29267
- try {
29268
- spawned = await spawnHeadlessTurn({
29269
- binary: config.binary,
29270
- args,
29271
- cwd: request.cwd,
29272
- env,
29273
- stdin: prompt,
29274
- ...abortSignal === void 0 ? {} : { signal: abortSignal },
29275
- ...request.timeoutMs === void 0 ? {} : { timeoutMs: request.timeoutMs },
29276
- onStdoutLine(line2) {
29277
- const trimmed = line2.trim();
29278
- if (trimmed === "") return;
29279
- let event;
29280
- try {
29281
- event = JSON.parse(trimmed);
29282
- } catch {
29283
- return;
29284
- }
29285
- codexObserver?.observe(event);
29286
- reportHostSessionEvent({
29287
- host: config.hostName,
29288
- cwd: request.cwd,
29289
- sessionParent,
29290
- source: "headless-host",
29291
- event
29292
- });
29293
- }
29294
- });
29295
- } catch (error) {
29296
- if (isHostAbortedError(error)) throw error;
29297
- const message = error instanceof Error ? error.message : String(error);
29298
- const observedHostFailure = codexObserver?.result().failureDiagnostic;
29299
- if (observedHostFailure !== void 0) {
29226
+ let exitedSessionId;
29227
+ try {
29228
+ outcome = await driveExternalRoleTurnRounds(prepared, request, {
29229
+ roundLimitName: "HeadlessRoundLimit",
29230
+ currentSessionId: () => sessionId,
29231
+ afterRetry() {
29232
+ sessionKind = "resume";
29233
+ },
29234
+ async runRound({ prompt, abortSignal }) {
29235
+ let args;
29236
+ try {
29237
+ const gitCommonDir = codex ? resolveGitCommonDir(request.cwd) : void 0;
29238
+ args = buildTurnArgs({
29239
+ description: config.description,
29240
+ systemPromptPath,
29241
+ // #959: navigator prose exit — no closed JSON schema on claude either.
29242
+ ...prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME ? {} : { jsonSchema: prepared.jsonSchema },
29243
+ mcpServers: prepared.mcpServers,
29244
+ ...mcpConfigPath === void 0 ? {} : { mcpConfigPath },
29245
+ ...outputSchemaPath === void 0 ? {} : { outputSchemaPath },
29246
+ ...request.model?.model !== void 0 ? { model: request.model.model } : {},
29247
+ ...request.model?.thinking !== void 0 ? { effort: request.model.thinking } : {},
29248
+ sessionId,
29249
+ sessionKind,
29250
+ cwd: request.cwd,
29251
+ ...gitCommonDir === void 0 ? {} : { writableRoots: [gitCommonDir] }
29252
+ });
29253
+ } catch (error) {
29254
+ const message = error instanceof Error ? error.message : String(error);
29300
29255
  return {
29301
29256
  status: "terminal",
29302
- result: failure("output", "HeadlessCliError", "codex-turn-failed", {
29303
- diagnostic: observedHostFailure,
29304
- sessionRecordDiagnostic: message,
29305
- sessionId
29306
- }, observedHostFailure)
29257
+ result: failure("session", "HeadlessArgvFailure", "argv-failed", { diagnostic: message }, message)
29307
29258
  };
29308
29259
  }
29309
- const isRecordFailure = typeof error === "object" && error !== null && (error.knownCause === "session" || error.name === "SitianInfrastructureError");
29310
- if (isRecordFailure) {
29260
+ const codexObserver = codex ? createCodexExecTurnObserver() : void 0;
29261
+ let pointerRecorded = false;
29262
+ let codexIdObserved = false;
29263
+ if (sessionId !== void 0 && sessionId !== "") {
29264
+ pointerRecorded = recordNativeSessionPointer({
29265
+ host: config.hostName,
29266
+ sessionId,
29267
+ cwd: request.cwd,
29268
+ sessionParent,
29269
+ home: request.home
29270
+ }) !== void 0;
29271
+ }
29272
+ let spawned;
29273
+ let childExited = false;
29274
+ try {
29275
+ spawned = await spawnHeadlessTurn({
29276
+ onClose() {
29277
+ childExited = true;
29278
+ },
29279
+ binary: config.binary,
29280
+ args,
29281
+ cwd: request.cwd,
29282
+ env,
29283
+ stdin: prompt,
29284
+ ...abortSignal === void 0 ? {} : { signal: abortSignal },
29285
+ ...request.timeoutMs === void 0 ? {} : { timeoutMs: request.timeoutMs },
29286
+ onStdoutLine(line2) {
29287
+ const trimmed = line2.trim();
29288
+ if (trimmed === "") return;
29289
+ let event;
29290
+ try {
29291
+ event = JSON.parse(trimmed);
29292
+ } catch {
29293
+ return;
29294
+ }
29295
+ codexObserver?.observe(event);
29296
+ if (!codex && typeof event === "object" && event !== null && "session_id" in event && typeof event.session_id === "string" && event.session_id !== "" && event.session_id !== sessionId) {
29297
+ sessionId = event.session_id;
29298
+ recordNativeSessionPointer({ host: config.hostName, sessionId, cwd: request.cwd, sessionParent, home: request.home });
29299
+ }
29300
+ if (codex && !codexIdObserved) {
29301
+ const tid = codexObserver?.result().threadId;
29302
+ if (tid !== void 0 && tid !== "") {
29303
+ codexIdObserved = true;
29304
+ pointerRecorded = recordNativeSessionPointer({
29305
+ host: config.hostName,
29306
+ sessionId: tid,
29307
+ cwd: request.cwd,
29308
+ sessionParent,
29309
+ home: request.home
29310
+ }) !== void 0;
29311
+ }
29312
+ }
29313
+ }
29314
+ });
29315
+ const roundSessionId = (codex ? codexObserver?.result().threadId : void 0) ?? sessionId;
29316
+ exitedSessionId = roundSessionId;
29317
+ if (codex && roundSessionId !== void 0 && roundSessionId !== "" && !pointerRecorded) {
29318
+ recordNativeSessionPointer({ host: config.hostName, sessionId: roundSessionId, cwd: request.cwd, sessionParent, home: request.home });
29319
+ }
29320
+ } catch (error) {
29321
+ if (childExited) exitedSessionId = (codex ? codexObserver?.result().threadId : void 0) ?? sessionId;
29322
+ if (isHostAbortedError(error)) throw error;
29323
+ const message = error instanceof Error ? error.message : String(error);
29324
+ const observedHostFailure = codexObserver?.result().failureDiagnostic;
29325
+ if (observedHostFailure !== void 0) {
29326
+ return {
29327
+ status: "terminal",
29328
+ result: failure("output", "HeadlessCliError", "codex-turn-failed", {
29329
+ diagnostic: observedHostFailure,
29330
+ sessionRecordDiagnostic: message,
29331
+ sessionId
29332
+ }, observedHostFailure)
29333
+ };
29334
+ }
29311
29335
  return {
29312
29336
  status: "terminal",
29313
- result: failure(
29314
- "session",
29315
- "HostSessionRecordFailure",
29316
- "host-session-record-failed",
29317
- { diagnostic: message, sessionId },
29318
- message
29319
- )
29337
+ result: failure("activation", "HeadlessSpawnFailure", "spawn-failed", {
29338
+ diagnostic: message,
29339
+ binary: config.binary
29340
+ }, message)
29320
29341
  };
29321
29342
  }
29322
- return {
29323
- status: "terminal",
29324
- result: failure("activation", "HeadlessSpawnFailure", "spawn-failed", {
29325
- diagnostic: message,
29326
- binary: config.binary
29327
- }, message)
29328
- };
29329
- }
29330
- if (spawned.timedOut) {
29331
- return terminalFromSpawned(spawned, {
29332
- cause: "timeout",
29333
- identity: { name: "HeadlessTimeout", code: "timeout" },
29334
- details: { sessionId }
29335
- });
29336
- }
29337
- if (codex) {
29338
- const observation = codexObserver.result();
29339
- if (observation.threadId !== void 0 && observation.threadId !== "") {
29340
- sessionId = observation.threadId;
29341
- }
29342
- let sessionBindingDiagnostic;
29343
- const hostFailed = observation.failureDiagnostic !== void 0 || spawned.code !== 0 && spawned.code !== null;
29344
- if (hostFailed && observation.threadId !== void 0 && observation.threadId !== "") {
29345
- try {
29346
- await config.sessionIdentity.bind(request.principal, observation.threadId);
29347
- } catch (error) {
29348
- sessionBindingDiagnostic = error instanceof Error ? error.message : String(error);
29349
- }
29350
- }
29351
- if (observation.failureDiagnostic !== void 0) {
29343
+ if (spawned.timedOut) {
29352
29344
  return terminalFromSpawned(spawned, {
29353
- cause: "output",
29354
- identity: { name: "HeadlessCliError", code: "codex-turn-failed" },
29355
- diagnostic: observation.failureDiagnostic,
29356
- details: {
29357
- sessionId,
29358
- exitCode: spawned.code,
29359
- ...sessionBindingDiagnostic === void 0 ? {} : { sessionBindingDiagnostic }
29360
- }
29345
+ cause: "timeout",
29346
+ identity: { name: "HeadlessTimeout", code: "timeout" },
29347
+ details: { sessionId }
29361
29348
  });
29362
29349
  }
29363
- if (spawned.code !== 0 && spawned.code !== null) {
29364
- return terminalFromSpawned(spawned, {
29365
- cause: "output",
29366
- identity: { name: "HeadlessCliError", code: "codex-nonzero-exit" },
29367
- diagnostic: spawned.stderr.trim() || `codex exec exited ${String(spawned.code)}`,
29368
- details: {
29369
- sessionId,
29370
- exitCode: spawned.code,
29371
- ...sessionBindingDiagnostic === void 0 ? {} : { sessionBindingDiagnostic }
29350
+ if (codex) {
29351
+ const observation = codexObserver.result();
29352
+ if (observation.threadId !== void 0 && observation.threadId !== "") {
29353
+ sessionId = observation.threadId;
29354
+ }
29355
+ let sessionBindingDiagnostic;
29356
+ const hostFailed = observation.failureDiagnostic !== void 0 || spawned.code !== 0 && spawned.code !== null;
29357
+ if (hostFailed && observation.threadId !== void 0 && observation.threadId !== "") {
29358
+ try {
29359
+ await config.sessionIdentity.bind(request.principal, observation.threadId);
29360
+ } catch (error) {
29361
+ sessionBindingDiagnostic = error instanceof Error ? error.message : String(error);
29372
29362
  }
29373
- });
29374
- }
29375
- if (observation.threadId === void 0 || observation.threadId === "") {
29376
- return terminalFromSpawned(spawned, {
29377
- cause: "session",
29378
- identity: { name: "HeadlessMissingThreadId", code: "missing-thread-id" },
29379
- diagnostic: "codex exec emitted no thread.started thread_id",
29380
- details: { sessionId, exitCode: spawned.code }
29381
- });
29382
- }
29383
- sessionId = observation.threadId;
29384
- await config.sessionIdentity.bind(request.principal, sessionId);
29385
- if (!observation.turnCompleted) {
29386
- return terminalFromSpawned(spawned, {
29387
- cause: "output",
29388
- identity: { name: "HeadlessCliError", code: "codex-missing-terminal-event" },
29389
- diagnostic: "codex exec exited without turn.completed",
29390
- details: { sessionId, exitCode: spawned.code }
29391
- });
29392
- }
29393
- if (observation.finalMessage === void 0) {
29394
- return terminalFromSpawned(spawned, {
29395
- cause: "output",
29396
- identity: { name: "HeadlessEmptyOutput", code: "empty-stdout" },
29397
- diagnostic: spawned.stderr.trim() || "codex exec produced no agent_message",
29398
- details: { sessionId, exitCode: spawned.code }
29399
- });
29400
- }
29401
- if (prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME) {
29402
- if (observation.finalMessage.trim() === "") {
29363
+ }
29364
+ if (observation.failureDiagnostic !== void 0) {
29365
+ return terminalFromSpawned(spawned, {
29366
+ cause: "output",
29367
+ identity: { name: "HeadlessCliError", code: "codex-turn-failed" },
29368
+ diagnostic: observation.failureDiagnostic,
29369
+ details: {
29370
+ sessionId,
29371
+ exitCode: spawned.code,
29372
+ ...sessionBindingDiagnostic === void 0 ? {} : { sessionBindingDiagnostic }
29373
+ }
29374
+ });
29375
+ }
29376
+ if (spawned.code !== 0 && spawned.code !== null) {
29377
+ return terminalFromSpawned(spawned, {
29378
+ cause: "output",
29379
+ identity: { name: "HeadlessCliError", code: "codex-nonzero-exit" },
29380
+ diagnostic: spawned.stderr.trim() || `codex exec exited ${String(spawned.code)}`,
29381
+ details: {
29382
+ sessionId,
29383
+ exitCode: spawned.code,
29384
+ ...sessionBindingDiagnostic === void 0 ? {} : { sessionBindingDiagnostic }
29385
+ }
29386
+ });
29387
+ }
29388
+ if (observation.threadId === void 0 || observation.threadId === "") {
29389
+ return terminalFromSpawned(spawned, {
29390
+ cause: "session",
29391
+ identity: { name: "HeadlessMissingThreadId", code: "missing-thread-id" },
29392
+ diagnostic: "codex exec emitted no thread.started thread_id",
29393
+ details: { sessionId, exitCode: spawned.code }
29394
+ });
29395
+ }
29396
+ sessionId = observation.threadId;
29397
+ await config.sessionIdentity.bind(request.principal, sessionId);
29398
+ if (!observation.turnCompleted) {
29399
+ return terminalFromSpawned(spawned, {
29400
+ cause: "output",
29401
+ identity: { name: "HeadlessCliError", code: "codex-missing-terminal-event" },
29402
+ diagnostic: "codex exec exited without turn.completed",
29403
+ details: { sessionId, exitCode: spawned.code }
29404
+ });
29405
+ }
29406
+ if (observation.finalMessage === void 0) {
29403
29407
  return terminalFromSpawned(spawned, {
29404
29408
  cause: "output",
29405
29409
  identity: { name: "HeadlessEmptyOutput", code: "empty-stdout" },
29406
- diagnostic: spawned.stderr.trim() || "codex exec produced empty agent_message",
29410
+ diagnostic: spawned.stderr.trim() || "codex exec produced no agent_message",
29407
29411
  details: { sessionId, exitCode: spawned.code }
29408
29412
  });
29409
29413
  }
29410
- await prepared.ingestStructuredOutput({ prose: observation.finalMessage });
29414
+ if (prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME) {
29415
+ if (observation.finalMessage.trim() === "") {
29416
+ return terminalFromSpawned(spawned, {
29417
+ cause: "output",
29418
+ identity: { name: "HeadlessEmptyOutput", code: "empty-stdout" },
29419
+ diagnostic: spawned.stderr.trim() || "codex exec produced empty agent_message",
29420
+ details: { sessionId, exitCode: spawned.code }
29421
+ });
29422
+ }
29423
+ await prepared.ingestStructuredOutput({ prose: observation.finalMessage });
29424
+ return { status: "delivered", stderr: spawned.stderr };
29425
+ }
29426
+ let receipt;
29427
+ try {
29428
+ receipt = JSON.parse(observation.finalMessage);
29429
+ } catch {
29430
+ return terminalFromSpawned(spawned, {
29431
+ cause: "output",
29432
+ identity: { name: "HeadlessEmptyOutput", code: "unparseable-final-message" },
29433
+ diagnostic: "codex final agent_message was not JSON",
29434
+ details: { sessionId, exitCode: spawned.code }
29435
+ });
29436
+ }
29437
+ await prepared.ingestStructuredOutput(receipt);
29411
29438
  return { status: "delivered", stderr: spawned.stderr };
29412
29439
  }
29413
- let receipt;
29414
- try {
29415
- receipt = JSON.parse(observation.finalMessage);
29416
- } catch {
29440
+ const envelope = parseHeadlessCliStdout(spawned.stdout);
29441
+ if (envelope === void 0) {
29417
29442
  return terminalFromSpawned(spawned, {
29418
29443
  cause: "output",
29419
- identity: { name: "HeadlessEmptyOutput", code: "unparseable-final-message" },
29420
- diagnostic: "codex final agent_message was not JSON",
29444
+ identity: { name: "HeadlessEmptyOutput", code: "empty-stdout" },
29445
+ diagnostic: spawned.stderr.length > 0 ? spawned.stderr : "headless CLI produced no parseable result",
29421
29446
  details: { sessionId, exitCode: spawned.code }
29422
29447
  });
29423
29448
  }
29424
- await prepared.ingestStructuredOutput(receipt);
29449
+ if (typeof envelope.session_id === "string" && envelope.session_id !== "") {
29450
+ sessionId = envelope.session_id;
29451
+ await config.sessionIdentity.bind(request.principal, sessionId);
29452
+ }
29453
+ if (envelope.is_error === true || typeof envelope.subtype === "string" && envelope.subtype.startsWith("error_")) {
29454
+ const errorCode = typeof envelope.subtype === "string" && envelope.subtype.startsWith("error_") ? envelope.subtype : envelope.is_error === true ? "is_error" : "cli-error";
29455
+ const diagnostic = typeof envelope.result === "string" ? envelope.result : Array.isArray(envelope.errors) ? envelope.errors.map(String).join("\n") : spawned.stderr.length > 0 ? spawned.stderr : "headless CLI reported is_error";
29456
+ return terminalFromSpawned(spawned, {
29457
+ cause: "output",
29458
+ identity: { name: "HeadlessCliError", code: errorCode },
29459
+ diagnostic,
29460
+ details: {
29461
+ sessionId,
29462
+ subtype: envelope.subtype,
29463
+ errors: envelope.errors,
29464
+ exitCode: spawned.code
29465
+ }
29466
+ });
29467
+ }
29468
+ if (envelope.structured_output !== void 0) {
29469
+ await prepared.ingestStructuredOutput(envelope.structured_output);
29470
+ } else if (prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME && typeof envelope.result === "string" && envelope.result.trim() !== "") {
29471
+ await prepared.ingestStructuredOutput({ prose: envelope.result });
29472
+ }
29425
29473
  return { status: "delivered", stderr: spawned.stderr };
29426
29474
  }
29427
- const envelope = parseHeadlessCliStdout(spawned.stdout);
29428
- if (envelope === void 0) {
29429
- return terminalFromSpawned(spawned, {
29430
- cause: "output",
29431
- identity: { name: "HeadlessEmptyOutput", code: "empty-stdout" },
29432
- diagnostic: spawned.stderr.length > 0 ? spawned.stderr : "headless CLI produced no parseable result",
29433
- details: { sessionId, exitCode: spawned.code }
29434
- });
29435
- }
29436
- if (typeof envelope.session_id === "string" && envelope.session_id !== "") {
29437
- sessionId = envelope.session_id;
29438
- await config.sessionIdentity.bind(request.principal, sessionId);
29439
- }
29440
- if (envelope.is_error === true || typeof envelope.subtype === "string" && envelope.subtype.startsWith("error_")) {
29441
- const errorCode = typeof envelope.subtype === "string" && envelope.subtype.startsWith("error_") ? envelope.subtype : envelope.is_error === true ? "is_error" : "cli-error";
29442
- const diagnostic = typeof envelope.result === "string" ? envelope.result : Array.isArray(envelope.errors) ? envelope.errors.map(String).join("\n") : spawned.stderr.length > 0 ? spawned.stderr : "headless CLI reported is_error";
29443
- return terminalFromSpawned(spawned, {
29444
- cause: "output",
29445
- identity: { name: "HeadlessCliError", code: errorCode },
29446
- diagnostic,
29447
- details: {
29448
- sessionId,
29449
- subtype: envelope.subtype,
29450
- errors: envelope.errors,
29451
- exitCode: spawned.code
29452
- }
29453
- });
29454
- }
29455
- if (envelope.structured_output !== void 0) {
29456
- await prepared.ingestStructuredOutput(envelope.structured_output);
29457
- } else if (prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME && typeof envelope.result === "string" && envelope.result.trim() !== "") {
29458
- await prepared.ingestStructuredOutput({ prose: envelope.result });
29459
- }
29460
- return { status: "delivered", stderr: spawned.stderr };
29461
- }
29462
- });
29475
+ });
29476
+ } finally {
29477
+ if (exitedSessionId !== void 0 && exitedSessionId !== "") copyAndRecordHostDossier({
29478
+ host: config.hostName,
29479
+ sessionId: exitedSessionId,
29480
+ cwd: request.cwd,
29481
+ sessionDirectory: join50(request.runDirectory, "session"),
29482
+ sessionParent,
29483
+ continuation: request.continuation,
29484
+ ...request.model !== void 0 ? { model: request.model } : {},
29485
+ ...request.home !== void 0 ? { home: request.home } : {}
29486
+ });
29487
+ }
29463
29488
  } finally {
29464
29489
  try {
29465
29490
  await prepared.dispose?.();