@akagilnc/pi-workflow-roles 0.1.5216 → 0.1.5241

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";
@@ -4659,14 +4517,6 @@ function resolveSitianRecordPathInLedger(input, ledgerHome) {
4659
4517
  }
4660
4518
  return { sessionDir, recordFile, ledgerHome };
4661
4519
  }
4662
- function projectTicketRecordsPathShape() {
4663
- const { recordFile } = ticketProvenanceUnderBookPaths(
4664
- join3("~", ".ak-roles"),
4665
- "<\u7C3F>",
4666
- "<\u7968\u53F7>"
4667
- );
4668
- return recordFile.replace(/\\/g, "/");
4669
- }
4670
4520
  function resolveSitianRecordPath(input) {
4671
4521
  const ledgerHome = input.home !== void 0 && input.home.length > 0 ? resolveActivationLedgerHome(input.home) : resolveActivationLedgerHomeForPath(input.runDirectory ?? input.sessionParent);
4672
4522
  return resolveSitianRecordPathInLedger(input, ledgerHome);
@@ -4693,7 +4543,13 @@ function appendSitianRecord(input) {
4693
4543
  };
4694
4544
  const row = `${JSON.stringify(record4)}
4695
4545
  `;
4696
- return appendWithIdentityClaim(recordFile, record4, row);
4546
+ appendFileSync(recordFile, row, "utf8");
4547
+ return {
4548
+ identity: record4.identity,
4549
+ recordFile,
4550
+ kind: record4.kind,
4551
+ level: record4.level
4552
+ };
4697
4553
  } catch (error) {
4698
4554
  if (error instanceof SitianInfrastructureError) throw error;
4699
4555
  throw new SitianInfrastructureError(
@@ -4721,13 +4577,13 @@ var init_sitian_appender = __esm({
4721
4577
  });
4722
4578
 
4723
4579
  // src/sitian-reader.ts
4724
- import { existsSync as existsSync2 } from "node:fs";
4580
+ import { existsSync } from "node:fs";
4725
4581
  import { readFile as readFile4 } from "node:fs/promises";
4726
- function isRecord4(value) {
4582
+ function isRecord3(value) {
4727
4583
  return typeof value === "object" && value !== null && !Array.isArray(value);
4728
4584
  }
4729
4585
  async function readSitianRecords(recordFile) {
4730
- if (!existsSync2(recordFile)) {
4586
+ if (!existsSync(recordFile)) {
4731
4587
  return { records: [], diagnostics: [] };
4732
4588
  }
4733
4589
  const text = await readFile4(recordFile, "utf8");
@@ -4739,7 +4595,7 @@ async function readSitianRecords(recordFile) {
4739
4595
  if (!line2.trim()) continue;
4740
4596
  try {
4741
4597
  const parsed = JSON.parse(line2);
4742
- if (isRecord4(parsed)) {
4598
+ if (isRecord3(parsed)) {
4743
4599
  records.push(parsed);
4744
4600
  } else {
4745
4601
  const typeDesc = parsed === null ? "null" : Array.isArray(parsed) ? "array" : typeof parsed;
@@ -4883,7 +4739,7 @@ var init_host_descriptions = __esm({
4883
4739
  });
4884
4740
 
4885
4741
  // src/package-resources/engine-material.ts
4886
- import { existsSync as existsSync3, readdirSync } from "node:fs";
4742
+ import { existsSync as existsSync2, readdirSync } from "node:fs";
4887
4743
  import { join as join4 } from "node:path";
4888
4744
  function pickEngineAxis(source) {
4889
4745
  return {
@@ -4926,7 +4782,7 @@ function engineSessionMaterialFromOptions(options) {
4926
4782
  const model = options.engineModel === void 0 ? void 0 : assertLegalEngineModel(options.engineModel);
4927
4783
  const materialPath = resolveEngineMaterialPath(options.packageRoot, name);
4928
4784
  const modelField = model === void 0 ? {} : { model };
4929
- if (existsSync3(materialPath)) {
4785
+ if (existsSync2(materialPath)) {
4930
4786
  return Object.freeze({ name, materialPath, ...modelField });
4931
4787
  }
4932
4788
  return Object.freeze({ name, ...modelField });
@@ -5941,14 +5797,14 @@ function isMissingPathError3(error) {
5941
5797
  function errorText2(error) {
5942
5798
  return error instanceof Error ? error.message : String(error);
5943
5799
  }
5944
- function isRecord5(value) {
5800
+ function isRecord4(value) {
5945
5801
  return typeof value === "object" && value !== null && !Array.isArray(value);
5946
5802
  }
5947
5803
  function readUsableTerminalArtifactBody(body) {
5948
5804
  if (body === null) {
5949
5805
  return { ok: false, reason: "terminal artifact JSON value is null" };
5950
5806
  }
5951
- if (!isRecord5(body)) {
5807
+ if (!isRecord4(body)) {
5952
5808
  return {
5953
5809
  ok: false,
5954
5810
  reason: `terminal artifact JSON value is not a typed object (${Array.isArray(body) ? "array" : typeof body})`
@@ -6410,10 +6266,10 @@ __export(session_assistant_usage_exports, {
6410
6266
  });
6411
6267
  import { join as join13 } from "node:path";
6412
6268
  async function readAssistantUsageFromSessionFile(sessionFile) {
6413
- const { readFile: readFile27 } = await import("node:fs/promises");
6269
+ const { readFile: readFile26 } = await import("node:fs/promises");
6414
6270
  let text;
6415
6271
  try {
6416
- text = await readFile27(sessionFile, "utf8");
6272
+ text = await readFile26(sessionFile, "utf8");
6417
6273
  } catch (error) {
6418
6274
  if (error?.code === "ENOENT") return void 0;
6419
6275
  throw error;
@@ -6946,19 +6802,7 @@ function createPiRoleTurnHost(config) {
6946
6802
  });
6947
6803
  return {
6948
6804
  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
- }
6805
+ const turnRequest = request;
6962
6806
  const roleEntry = await realpath2(resolveInternalRoleEntrypoint(config.packageRoot));
6963
6807
  const extraArgs = buildPiTurnExtraArgs(
6964
6808
  turnRequest,
@@ -7038,7 +6882,6 @@ var init_role_turn_host = __esm({
7038
6882
  "src/pi/role-turn-host.ts"() {
7039
6883
  "use strict";
7040
6884
  init_host_contracts();
7041
- init_packaged_role_registry();
7042
6885
  init_engine_detour();
7043
6886
  init_role_activation_flags();
7044
6887
  init_user_dialogue_stdin();
@@ -7344,7 +7187,7 @@ var init_merger_git_state = __esm({
7344
7187
 
7345
7188
  // src/ledger-session-read.ts
7346
7189
  import { readFile as readFile11 } from "node:fs/promises";
7347
- function isRecord6(value) {
7190
+ function isRecord5(value) {
7348
7191
  return typeof value === "object" && value !== null && !Array.isArray(value);
7349
7192
  }
7350
7193
  async function readLedgerSessionJsonlLines(path) {
@@ -7369,7 +7212,7 @@ async function readLedgerSessionJsonlLines(path) {
7369
7212
  });
7370
7213
  continue;
7371
7214
  }
7372
- if (!isRecord6(row)) {
7215
+ if (!isRecord5(row)) {
7373
7216
  const kind = row === null ? "null" : Array.isArray(row) ? "array" : typeof row;
7374
7217
  out.push({
7375
7218
  line: lineNumber,
@@ -7422,7 +7265,7 @@ function extractSessionModelSequence(rows) {
7422
7265
  if (row.type === "model_change" && typeof row.modelId === "string") {
7423
7266
  push(row.modelId);
7424
7267
  }
7425
- const message = isRecord6(row.message) ? row.message : void 0;
7268
+ const message = isRecord5(row.message) ? row.message : void 0;
7426
7269
  if (message?.role === "assistant" && typeof message.model === "string") {
7427
7270
  push(message.model);
7428
7271
  }
@@ -7438,11 +7281,11 @@ function extractSessionToolIntervals(rows) {
7438
7281
  const openById = /* @__PURE__ */ new Map();
7439
7282
  for (const row of rows) {
7440
7283
  const rowTimestamp = typeof row.timestamp === "string" ? row.timestamp : void 0;
7441
- const message = isRecord6(row.message) ? row.message : void 0;
7284
+ const message = isRecord5(row.message) ? row.message : void 0;
7442
7285
  if (message?.role === "assistant" && Array.isArray(message.content)) {
7443
7286
  const callTimestamp = typeof message.timestamp === "string" && message.timestamp ? message.timestamp : rowTimestamp;
7444
7287
  for (const part of message.content) {
7445
- if (!isRecord6(part) || part.type !== "toolCall") continue;
7288
+ if (!isRecord5(part) || part.type !== "toolCall") continue;
7446
7289
  if (typeof part.id !== "string" || part.id.length === 0) {
7447
7290
  throw new Error("toolCall frame missing string id");
7448
7291
  }
@@ -7455,7 +7298,7 @@ function extractSessionToolIntervals(rows) {
7455
7298
  if (openById.has(part.id)) {
7456
7299
  throw new Error(`duplicate toolCall id ${part.id}`);
7457
7300
  }
7458
- const args = isRecord6(part.arguments) ? part.arguments : void 0;
7301
+ const args = isRecord5(part.arguments) ? part.arguments : void 0;
7459
7302
  const command = part.name === "bash" && args !== void 0 && typeof args.command === "string" ? bashCommandFirstLine(args.command) : void 0;
7460
7303
  const interval = {
7461
7304
  toolCallId: part.id,
@@ -7539,7 +7382,7 @@ var init_ledger_session_read = __esm({
7539
7382
  });
7540
7383
 
7541
7384
  // src/session-dialogue.ts
7542
- function isRecord7(value) {
7385
+ function isRecord6(value) {
7543
7386
  return typeof value === "object" && value !== null && !Array.isArray(value);
7544
7387
  }
7545
7388
  function nativeEventId(row) {
@@ -7549,7 +7392,7 @@ function nativeEventId(row) {
7549
7392
  }
7550
7393
  for (const nestKey of ["message", "payload"]) {
7551
7394
  const nested = row[nestKey];
7552
- if (!isRecord7(nested)) continue;
7395
+ if (!isRecord6(nested)) continue;
7553
7396
  for (const key of ["uuid", "id"]) {
7554
7397
  const value = nested[key];
7555
7398
  if (typeof value === "string" && value !== "") return value;
@@ -7562,19 +7405,19 @@ function textParts(content) {
7562
7405
  if (!Array.isArray(content)) return [];
7563
7406
  const out = [];
7564
7407
  for (const part of content) {
7565
- if (!isRecord7(part) || !SPEAKER_TEXT_PART_TYPES.has(String(part.type))) continue;
7408
+ if (!isRecord6(part) || !SPEAKER_TEXT_PART_TYPES.has(String(part.type))) continue;
7566
7409
  const text = part.text;
7567
7410
  if (typeof text === "string" && text !== "") out.push(text);
7568
7411
  }
7569
7412
  return out;
7570
7413
  }
7571
7414
  function responseItemMessage(row) {
7572
- if (row.type !== "response_item" || !isRecord7(row.payload)) return void 0;
7415
+ if (row.type !== "response_item" || !isRecord6(row.payload)) return void 0;
7573
7416
  if (row.payload.type !== "message") return void 0;
7574
7417
  return row.payload;
7575
7418
  }
7576
7419
  function messageBody(row) {
7577
- if (isRecord7(row.message)) return row.message;
7420
+ if (isRecord6(row.message)) return row.message;
7578
7421
  return responseItemMessage(row);
7579
7422
  }
7580
7423
  function speakerOf(message) {
@@ -7584,7 +7427,7 @@ function speakerOf(message) {
7584
7427
  }
7585
7428
  function codexContentItemKinds(message) {
7586
7429
  const pass = message.internal_chat_message_metadata_passthrough;
7587
- if (!isRecord7(pass) || !Array.isArray(pass.content_item_kinds)) return void 0;
7430
+ if (!isRecord6(pass) || !Array.isArray(pass.content_item_kinds)) return void 0;
7588
7431
  const kinds = [];
7589
7432
  for (const kind of pass.content_item_kinds) {
7590
7433
  if (typeof kind === "string" && kind !== "") kinds.push(kind);
@@ -7613,7 +7456,7 @@ function isFixedNonOwnerEnqueueShape(content) {
7613
7456
  return hasFixedOpenTagPrefix(content, TASK_NOTIFICATION_OPEN_TAG);
7614
7457
  }
7615
7458
  function materializationOriginKind(row) {
7616
- if (!isRecord7(row.origin)) return void 0;
7459
+ if (!isRecord6(row.origin)) return void 0;
7617
7460
  const kind = row.origin.kind;
7618
7461
  return typeof kind === "string" && kind !== "" ? kind : void 0;
7619
7462
  }
@@ -7704,12 +7547,6 @@ function ticketProvenanceRecordInput(ticketNumber, cwd, home, runDirectory) {
7704
7547
  ...home === void 0 ? {} : { home }
7705
7548
  };
7706
7549
  }
7707
- function resolveTicketProvenanceVolume(ticketNumber, cwd, home) {
7708
- const path = resolveSitianRecordPath(
7709
- ticketProvenanceRecordInput(ticketNumber, cwd, home)
7710
- );
7711
- return { recordFile: path.recordFile, volumeDir: path.sessionDir };
7712
- }
7713
7550
  async function rehomeUnboundTicketProvenance(runDirectory, ticketNumber, cwd, home) {
7714
7551
  const source = join16(runDirectory, "records.jsonl");
7715
7552
  let content;
@@ -9107,7 +8944,7 @@ var init_option_definitions = __esm({
9107
8944
 
9108
8945
  // src/public-cli/invocation.ts
9109
8946
  import { execFileSync as execFileSync3 } from "node:child_process";
9110
- import { existsSync as existsSync5 } from "node:fs";
8947
+ import { existsSync as existsSync4 } from "node:fs";
9111
8948
  import {
9112
8949
  lstat as lstat3,
9113
8950
  mkdtemp as mkdtemp2,
@@ -9333,7 +9170,7 @@ async function relocateAdmittedRunToTicket(admitted, authority, heldLease) {
9333
9170
  for (const childRunId of Array.isArray(childRunIds) ? childRunIds : []) {
9334
9171
  if (typeof childRunId !== "string") continue;
9335
9172
  const childDirectory = join18(dirname13(oldRunDirectory), `${childRunId}@diarist`);
9336
- if (!existsSync5(childDirectory)) continue;
9173
+ if (!existsSync4(childDirectory)) continue;
9337
9174
  const childTarget = roleRunPlacement(ledgerHome, {
9338
9175
  bookKey: admitted.bookKey,
9339
9176
  subject: { ticketNumber: admitted.ticketNumber },
@@ -10815,7 +10652,7 @@ var init_invocation = __esm({
10815
10652
  });
10816
10653
 
10817
10654
  // src/public-cli/load-production-acp-host.ts
10818
- import { existsSync as existsSync6 } from "node:fs";
10655
+ import { existsSync as existsSync5 } from "node:fs";
10819
10656
  import { join as join19 } from "node:path";
10820
10657
  import { pathToFileURL } from "node:url";
10821
10658
  async function loadProductionAcpHostFactory(packageRoot, host) {
@@ -10825,7 +10662,7 @@ async function loadProductionAcpHostFactory(packageRoot, host) {
10825
10662
  }
10826
10663
  const built = join19(packageRoot, "dist/acp-host/production-host.js");
10827
10664
  const source = join19(packageRoot, "src/acp-host/production-host.ts");
10828
- const target = existsSync6(built) ? built : source;
10665
+ const target = existsSync5(built) ? built : source;
10829
10666
  const href = pathToFileURL(target).href;
10830
10667
  const mod = await import(href);
10831
10668
  const create = mod.createProductionAcpRoleTurnHost;
@@ -10839,7 +10676,7 @@ var init_load_production_acp_host = __esm({
10839
10676
  });
10840
10677
 
10841
10678
  // src/public-cli/load-production-headless-host.ts
10842
- import { existsSync as existsSync7 } from "node:fs";
10679
+ import { existsSync as existsSync6 } from "node:fs";
10843
10680
  import { join as join20 } from "node:path";
10844
10681
  import { pathToFileURL as pathToFileURL2 } from "node:url";
10845
10682
  async function loadProductionHeadlessHostFactory(packageRoot, host) {
@@ -10849,7 +10686,7 @@ async function loadProductionHeadlessHostFactory(packageRoot, host) {
10849
10686
  }
10850
10687
  const built = join20(packageRoot, "dist/headless-host/production-host.js");
10851
10688
  const source = join20(packageRoot, "src/headless-host/production-host.ts");
10852
- const target = existsSync7(built) ? built : source;
10689
+ const target = existsSync6(built) ? built : source;
10853
10690
  const href = pathToFileURL2(target).href;
10854
10691
  const mod = await import(href);
10855
10692
  const create = mod.createProductionHeadlessRoleTurnHost;
@@ -10986,7 +10823,7 @@ __export(host_providers_exports, {
10986
10823
  projectHostFacingProvider: () => projectHostFacingProvider,
10987
10824
  renderHostProvidersTable: () => renderHostProvidersTable
10988
10825
  });
10989
- import { readFileSync as readFileSync2 } from "node:fs";
10826
+ import { readFileSync } from "node:fs";
10990
10827
  import { join as join21 } from "node:path";
10991
10828
  function hostProvidersPath(home) {
10992
10829
  if (typeof home !== "string" || home.trim() === "") {
@@ -11034,7 +10871,7 @@ function parseHostProvidersTable(value) {
11034
10871
  function loadHostProvidersTable(home) {
11035
10872
  const path = hostProvidersPath(home);
11036
10873
  try {
11037
- const raw = readFileSync2(path, "utf8");
10874
+ const raw = readFileSync(path, "utf8");
11038
10875
  return parseHostProvidersTable(JSON.parse(raw));
11039
10876
  } catch (error) {
11040
10877
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -11052,7 +10889,7 @@ function listHermesProvidersForModel(home, seatModel) {
11052
10889
  const path = hermesProviderModelsCachePath(home);
11053
10890
  let text;
11054
10891
  try {
11055
- text = readFileSync2(path, "utf8");
10892
+ text = readFileSync(path, "utf8");
11056
10893
  } catch (error) {
11057
10894
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
11058
10895
  return [];
@@ -11152,7 +10989,7 @@ var init_host_providers = __esm({
11152
10989
  // src/analyst-gate-cycles-read.ts
11153
10990
  import { readdir as readdir4 } from "node:fs/promises";
11154
10991
  import { join as join22 } from "node:path";
11155
- function isRecord8(value) {
10992
+ function isRecord7(value) {
11156
10993
  return typeof value === "object" && value !== null && !Array.isArray(value);
11157
10994
  }
11158
10995
  function isParentAttemptBindingRow(row) {
@@ -11182,7 +11019,7 @@ function isGateTerminatingToolName(toolName) {
11182
11019
  function acceptedGateReceiptIds(rows) {
11183
11020
  const accepted = /* @__PURE__ */ new Set();
11184
11021
  for (const row of rows) {
11185
- const message = isRecord8(row.message) ? row.message : void 0;
11022
+ const message = isRecord7(row.message) ? row.message : void 0;
11186
11023
  if (message?.role !== "toolResult") continue;
11187
11024
  if (typeof message.toolCallId !== "string" || message.toolCallId.length === 0) continue;
11188
11025
  if (message.isError === false) accepted.add(message.toolCallId);
@@ -11217,7 +11054,7 @@ function nearestAttemptBindingBefore(rows, beforeIndex) {
11217
11054
  for (let i = beforeIndex - 1; i >= 0; i -= 1) {
11218
11055
  const row = rows[i];
11219
11056
  if (!isParentAttemptBindingRow(row)) continue;
11220
- if (!isRecord8(row.data) || !isRecord8(row.data.parent)) continue;
11057
+ if (!isRecord7(row.data) || !isRecord7(row.data.parent)) continue;
11221
11058
  const id = row.data.parent.attemptEntryId;
11222
11059
  const sessionFile = row.data.parent.sessionFile;
11223
11060
  return {
@@ -11232,10 +11069,10 @@ function extractAllAcceptedGateToolCalls(rows) {
11232
11069
  const out = [];
11233
11070
  for (let rowIndex = 0; rowIndex < rows.length; rowIndex += 1) {
11234
11071
  const row = rows[rowIndex];
11235
- const message = isRecord8(row.message) ? row.message : void 0;
11072
+ const message = isRecord7(row.message) ? row.message : void 0;
11236
11073
  if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
11237
11074
  for (const part of message.content) {
11238
- if (!isRecord8(part) || part.type !== "toolCall") continue;
11075
+ if (!isRecord7(part) || part.type !== "toolCall") continue;
11239
11076
  if (typeof part.id !== "string" || part.id.length === 0) continue;
11240
11077
  if (typeof part.name !== "string" || part.name.length === 0) continue;
11241
11078
  if (!isGateTerminatingToolName(part.name)) continue;
@@ -11243,7 +11080,7 @@ function extractAllAcceptedGateToolCalls(rows) {
11243
11080
  const binding = nearestAttemptBindingBefore(rows, rowIndex);
11244
11081
  out.push({
11245
11082
  toolName: part.name,
11246
- args: isRecord8(part.arguments) ? part.arguments : void 0,
11083
+ args: isRecord7(part.arguments) ? part.arguments : void 0,
11247
11084
  accepted: true,
11248
11085
  rowIndex,
11249
11086
  ...binding
@@ -11366,17 +11203,17 @@ function pairGateRounds(volumes) {
11366
11203
  return rounds.sort((a, b) => a.officerStartedAt.localeCompare(b.officerStartedAt)).map((round, index) => ({ ...round, roundIndex: index + 1 }));
11367
11204
  }
11368
11205
  async function resolveOfficerSessionFromPointerFile(pointerPath) {
11369
- const { readFile: readFile27 } = await import("node:fs/promises");
11206
+ const { readFile: readFile26 } = await import("node:fs/promises");
11370
11207
  let raw;
11371
11208
  try {
11372
- raw = JSON.parse(await readFile27(pointerPath, "utf8"));
11209
+ raw = JSON.parse(await readFile26(pointerPath, "utf8"));
11373
11210
  } catch (error) {
11374
11211
  throw new Error(
11375
11212
  `direct officer run pointer unreadable in ${pointerPath}: ${error instanceof Error ? error.message : String(error)}`,
11376
11213
  { cause: error }
11377
11214
  );
11378
11215
  }
11379
- if (!isRecord8(raw) || raw.kind !== "direct-officer-run-pointer" || raw.version !== 1) {
11216
+ if (!isRecord7(raw) || raw.kind !== "direct-officer-run-pointer" || raw.version !== 1) {
11380
11217
  throw new Error(`direct officer run pointer has unknown shape in ${pointerPath}`);
11381
11218
  }
11382
11219
  const sessionFile = raw.sessionFile;
@@ -11850,14 +11687,14 @@ var init_audit_escalation = __esm({
11850
11687
  });
11851
11688
 
11852
11689
  // src/session-opening-materials.ts
11853
- import { existsSync as existsSync8 } from "node:fs";
11690
+ import { existsSync as existsSync7 } from "node:fs";
11854
11691
  import { readFile as readFile14 } from "node:fs/promises";
11855
11692
  import { dirname as dirname14, join as join24 } from "node:path";
11856
11693
  import { fileURLToPath, pathToFileURL as pathToFileURL3 } from "node:url";
11857
11694
  function resolvePackageRootDir(moduleUrl = import.meta.url) {
11858
11695
  let dir = dirname14(fileURLToPath(moduleUrl));
11859
11696
  for (let i = 0; i < 8; i += 1) {
11860
- if (existsSync8(join24(dir, "package.json")) && existsSync8(join24(dir, "souls"))) {
11697
+ if (existsSync7(join24(dir, "package.json")) && existsSync7(join24(dir, "souls"))) {
11861
11698
  return dir;
11862
11699
  }
11863
11700
  const parent = dirname14(dir);
@@ -12080,7 +11917,7 @@ var init_serialize_thrown_value = __esm({
12080
11917
 
12081
11918
  // src/engine-detour-usage.ts
12082
11919
  import { randomUUID as randomUUID4 } from "node:crypto";
12083
- import { readFileSync as readFileSync3 } from "node:fs";
11920
+ import { readFileSync as readFileSync2 } from "node:fs";
12084
11921
  import { dirname as dirname15, join as join26 } from "node:path";
12085
11922
  function engineDetourStdoutByteLength(stdout) {
12086
11923
  return Buffer.byteLength(stdout, "utf8");
@@ -12134,11 +11971,11 @@ function reportEngineDetourCall(input) {
12134
11971
  recordPointer: pointer
12135
11972
  };
12136
11973
  }
12137
- function isRecord9(value) {
11974
+ function isRecord8(value) {
12138
11975
  return typeof value === "object" && value !== null && !Array.isArray(value);
12139
11976
  }
12140
11977
  function callFactFromSitianPayload(payload, pointer) {
12141
- if (!isRecord9(payload)) return void 0;
11978
+ if (!isRecord8(payload)) return void 0;
12142
11979
  if (payload.tool !== ENGINE_DETOUR_TOOL_NAME) return void 0;
12143
11980
  if (typeof payload.toolCallId !== "string" || payload.toolCallId.length === 0) {
12144
11981
  return void 0;
@@ -12155,11 +11992,11 @@ function callFactFromSitianPayload(payload, pointer) {
12155
11992
  };
12156
11993
  }
12157
11994
  function invocationScopeIdOfRecord(record4) {
12158
- if (isRecord9(record4.subject)) {
11995
+ if (isRecord8(record4.subject)) {
12159
11996
  const fromSubject = record4.subject.invocationScopeId;
12160
11997
  if (typeof fromSubject === "string" && fromSubject.length > 0) return fromSubject;
12161
11998
  }
12162
- if (isRecord9(record4.payload)) {
11999
+ if (isRecord8(record4.payload)) {
12163
12000
  const fromPayload = record4.payload.invocationScopeId;
12164
12001
  if (typeof fromPayload === "string" && fromPayload.length > 0) return fromPayload;
12165
12002
  }
@@ -12175,7 +12012,7 @@ async function readEngineDetourToolUsage(input) {
12175
12012
  ...input.cwd === void 0 ? {} : { cwd: input.cwd }
12176
12013
  });
12177
12014
  const { records } = await readSitianRecords(recordFile);
12178
- const calls = [];
12015
+ const callsByToolCallId = /* @__PURE__ */ new Map();
12179
12016
  for (const record4 of records) {
12180
12017
  if (record4.kind !== ENGINE_DETOUR_CALL_KIND) continue;
12181
12018
  const boundScope = invocationScopeIdOfRecord(record4);
@@ -12192,8 +12029,9 @@ async function readEngineDetourToolUsage(input) {
12192
12029
  };
12193
12030
  const fact = callFactFromSitianPayload(record4.payload, pointer);
12194
12031
  if (fact === void 0) continue;
12195
- calls.push(fact);
12032
+ callsByToolCallId.set(fact.toolCallId, fact);
12196
12033
  }
12034
+ const calls = Array.from(callsByToolCallId.values());
12197
12035
  return { callCount: calls.length, calls };
12198
12036
  }
12199
12037
  function projectEngineDetourToolUsageForPublicTerminal(usage, options) {
@@ -12217,9 +12055,9 @@ function projectEngineDetourToolUsageForPublicTerminal(usage, options) {
12217
12055
  function readInvocationRecord(runDirectory) {
12218
12056
  try {
12219
12057
  const raw = JSON.parse(
12220
- readFileSync3(join26(runDirectory, "invocation.json"), "utf8")
12058
+ readFileSync2(join26(runDirectory, "invocation.json"), "utf8")
12221
12059
  );
12222
- return isRecord9(raw) ? raw : void 0;
12060
+ return isRecord8(raw) ? raw : void 0;
12223
12061
  } catch (error) {
12224
12062
  if (error?.code === "ENOENT") return void 0;
12225
12063
  throw error;
@@ -12230,14 +12068,9 @@ async function readInvocationEngineMounted(runDirectory) {
12230
12068
  if (raw === void 0) return false;
12231
12069
  return typeof raw.engine === "string" && raw.engine.trim() !== "";
12232
12070
  }
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
12071
  function withEngineDetourToolUsageFact(outcome, usage) {
12239
12072
  if (usage === void 0) return outcome;
12240
- const prior = isRecord9(outcome.decisiveFacts) ? outcome.decisiveFacts : {};
12073
+ const prior = isRecord8(outcome.decisiveFacts) ? outcome.decisiveFacts : {};
12241
12074
  return {
12242
12075
  ...outcome,
12243
12076
  decisiveFacts: {
@@ -12279,7 +12112,7 @@ var init_engine_detour_usage = __esm({
12279
12112
  });
12280
12113
 
12281
12114
  // src/dossier-resolution.ts
12282
- import { existsSync as existsSync9, statSync as statSync2 } from "node:fs";
12115
+ import { existsSync as existsSync8, statSync as statSync2 } from "node:fs";
12283
12116
  import { resolve as resolve12 } from "node:path";
12284
12117
  function isHostContext(value) {
12285
12118
  return "sessionManager" in value;
@@ -12299,7 +12132,7 @@ function resolveAuditDossier(source) {
12299
12132
  }
12300
12133
  const runDirectory = resolve12(raw);
12301
12134
  try {
12302
- if (!existsSync9(runDirectory) || !statSync2(runDirectory).isDirectory()) {
12135
+ if (!existsSync8(runDirectory) || !statSync2(runDirectory).isDirectory()) {
12303
12136
  return { status: "incomplete", observation: { kind: "missing-dossier" } };
12304
12137
  }
12305
12138
  } catch {
@@ -12307,13 +12140,13 @@ function resolveAuditDossier(source) {
12307
12140
  }
12308
12141
  return { status: "ok", runDirectory };
12309
12142
  }
12310
- function isRecord10(value) {
12143
+ function isRecord9(value) {
12311
12144
  return typeof value === "object" && value !== null && !Array.isArray(value);
12312
12145
  }
12313
12146
  function readDoctorAuditSubjects(context) {
12314
12147
  const entries = context.sessionManager.getEntries?.() ?? [];
12315
12148
  for (const entry of entries) {
12316
- if (isRecord10(entry) && entry.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
12149
+ if (isRecord9(entry) && entry.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
12317
12150
  return { status: "ok" };
12318
12151
  }
12319
12152
  }
@@ -12346,11 +12179,11 @@ var init_dossier_resolution = __esm({
12346
12179
  });
12347
12180
 
12348
12181
  // src/receipt-delivery-policy.ts
12349
- function isRecord11(value) {
12182
+ function isRecord10(value) {
12350
12183
  return typeof value === "object" && value !== null && !Array.isArray(value);
12351
12184
  }
12352
12185
  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")) {
12186
+ 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
12187
  throw new TypeError("malformed no-receipt lifecycle facts");
12355
12188
  }
12356
12189
  return {
@@ -12975,7 +12808,7 @@ async function readSitianRetainedAuditorProviderStop(sessionFile) {
12975
12808
  const { records } = await readSitianRecords(recordFile);
12976
12809
  for (let i = records.length - 1; i >= 0; i -= 1) {
12977
12810
  const payload = records[i]?.payload;
12978
- if (!isRecord12(payload) || !isRecord12(payload.response)) continue;
12811
+ if (!isRecord11(payload) || !isRecord11(payload.response)) continue;
12979
12812
  if (typeof payload.type === "string") continue;
12980
12813
  const stop = sessionProviderStopFromAssistant(payload.response);
12981
12814
  if (stop !== void 0) return stop;
@@ -13025,7 +12858,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
13025
12858
  throw sessionReadFailure(error, "failed to read discovered auditor session");
13026
12859
  }
13027
12860
  const header = entries.find((entry) => entry.type === "session");
13028
- if (!isRecord12(header)) continue;
12861
+ if (!isRecord11(header)) continue;
13029
12862
  const bindingIndexes = [];
13030
12863
  for (let i = 0; i < entries.length; i += 1) {
13031
12864
  const entry = entries[i];
@@ -13039,7 +12872,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
13039
12872
  end: idx + 1 < bindingIndexes.length ? bindingIndexes[idx + 1] : entries.length
13040
12873
  })) : [{ entry: void 0, start: 0, end: entries.length }];
13041
12874
  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;
12875
+ const bindingParent = bindingEntry !== void 0 && isRecord11(bindingEntry.data) && isRecord11(bindingEntry.data.parent) ? bindingEntry.data.parent : void 0;
13043
12876
  const attemptEntryId = typeof bindingParent?.attemptEntryId === "string" ? bindingParent.attemptEntryId : void 0;
13044
12877
  const boundSessionFile = typeof bindingParent?.sessionFile === "string" ? bindingParent.sessionFile : typeof header.parentSession === "string" ? header.parentSession : void 0;
13045
12878
  if (boundSessionFile !== sessionFile) continue;
@@ -13063,12 +12896,12 @@ function complianceFailureFromAuditorVolumes(volumes) {
13063
12896
  if (stop === void 0) continue;
13064
12897
  for (let i = entries.length - 1; i >= 0; i -= 1) {
13065
12898
  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;
12899
+ if (entry?.type !== "custom" || entry.customType !== AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE || !isRecord11(entry.data)) continue;
12900
+ const parent = isRecord11(entry.data.parent) ? entry.data.parent : void 0;
12901
+ const failure2 = isRecord11(entry.data.failure) ? entry.data.failure : void 0;
13069
12902
  if (parent?.sessionId !== parentId || parent.sessionFile !== sessionFile || parent.attemptEntryId !== attemptEntryId) continue;
13070
12903
  if (failure2 === void 0) continue;
13071
- const identity = isRecord12(failure2.identity) ? failure2.identity : void 0;
12904
+ const identity = isRecord11(failure2.identity) ? failure2.identity : void 0;
13072
12905
  const typedCause = failure2.cause === "provider" || failure2.cause === "activation" || failure2.cause === "session" || failure2.cause === "output" || failure2.cause === "timeout" ? failure2.cause : void 0;
13073
12906
  return {
13074
12907
  ...typedCause === void 0 ? {} : { cause: typedCause },
@@ -13077,7 +12910,7 @@ function complianceFailureFromAuditorVolumes(volumes) {
13077
12910
  ...typeof identity.code === "string" || typeof identity.code === "number" ? { code: identity.code } : {}
13078
12911
  } },
13079
12912
  ...typeof failure2.diagnostic === "string" ? { diagnostic: failure2.diagnostic } : {},
13080
- ...isRecord12(failure2.details) ? { details: failure2.details } : {}
12913
+ ...isRecord11(failure2.details) ? { details: failure2.details } : {}
13081
12914
  };
13082
12915
  }
13083
12916
  }
@@ -13124,9 +12957,9 @@ function typedFailedTerminatingToolKnownFailure(entries) {
13124
12957
  if (classification.kind !== "infrastructure") continue;
13125
12958
  if (typeof message.toolCallId !== "string" || typeof message.toolName !== "string") continue;
13126
12959
  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;
12960
+ const textPart = Array.isArray(message.content) ? message.content.find((part) => isRecord11(part) && part.type === "text" && typeof part.text === "string") : void 0;
12961
+ const diagnostic = isRecord11(textPart) ? textPart.text : void 0;
12962
+ const details = isRecord11(message.details) ? message.details : classification.fact;
13130
12963
  return {
13131
12964
  cause: "activation",
13132
12965
  identity: { name: message.toolName, code: message.toolCallId },
@@ -13263,7 +13096,7 @@ function controlledFailureInputFromResolution(resolution) {
13263
13096
  } : {}
13264
13097
  };
13265
13098
  }
13266
- function isRecord12(value) {
13099
+ function isRecord11(value) {
13267
13100
  return typeof value === "object" && value !== null && !Array.isArray(value);
13268
13101
  }
13269
13102
  function toolResultText(message) {
@@ -13288,7 +13121,7 @@ function extractCollectorTargetBindRejection(entries) {
13288
13121
  const diagnostic = toolResultText(message);
13289
13122
  if (diagnostic.length === 0) return void 0;
13290
13123
  const details = message.details;
13291
- const code = isRecord12(details) && typeof details.code === "string" && details.code.trim() !== "" ? details.code : void 0;
13124
+ const code = isRecord11(details) && typeof details.code === "string" && details.code.trim() !== "" ? details.code : void 0;
13292
13125
  return code === void 0 ? { diagnostic } : { diagnostic, code };
13293
13126
  }
13294
13127
  return void 0;
@@ -13389,7 +13222,7 @@ function boundRoleToolCallForResult(entries, resultIndex, message, outputToolNam
13389
13222
  const candidateMessage = entries[index]?.message;
13390
13223
  if (candidateMessage?.role === "assistant" && Array.isArray(candidateMessage.content)) {
13391
13224
  for (const part of candidateMessage.content) {
13392
- if (!isRecord12(part) || part.type !== "toolCall" || part.id !== callId) {
13225
+ if (!isRecord11(part) || part.type !== "toolCall" || part.id !== callId) {
13393
13226
  continue;
13394
13227
  }
13395
13228
  if (part.name !== outputToolName) return void 0;
@@ -13460,7 +13293,7 @@ function parseNavigatorAttendanceDetails(details) {
13460
13293
  if (typeof details.prose === "string" && details.prose.trim() !== "") {
13461
13294
  prose = details.prose;
13462
13295
  } else {
13463
- const next = isRecord12(details.next) && typeof details.next.role === "string" ? details.next.role : void 0;
13296
+ const next = isRecord11(details.next) && typeof details.next.role === "string" ? details.next.role : void 0;
13464
13297
  const reason = typeof details.reason === "string" && details.reason.trim() !== "" ? details.reason : void 0;
13465
13298
  const command = typeof details.command === "string" && details.command.trim() !== "" ? details.command : void 0;
13466
13299
  if (reason !== void 0 && next !== void 0) {
@@ -13569,7 +13402,7 @@ function detourGateContext(admitted, scope) {
13569
13402
  }
13570
13403
  async function withOptionalGateProjection(base, sessionDirectory, gateContext = {}) {
13571
13404
  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);
13405
+ const skipGate = isRecord11(secondaryEvidence) && secondaryEvidence.kind === "role_infrastructure_failure" && packagedSkipsGateOnInfrastructureStage(secondaryEvidence.stage);
13573
13406
  let next = base;
13574
13407
  if (!skipGate) {
13575
13408
  const gate = await extractGateFactFromSessionDirectory(sessionDirectory, gateContext);
@@ -13582,7 +13415,7 @@ function routePlaybookFailureMessage(entries) {
13582
13415
  const entry = entries[i];
13583
13416
  if (entry?.type !== "custom" || entry.customType !== NAVIGATOR_ROUTE_PLAYBOOK_FAILURE_ENTRY) continue;
13584
13417
  const data = entry.data;
13585
- if (!isRecord12(data) || typeof data.message !== "string" || data.message.trim() === "") return void 0;
13418
+ if (!isRecord11(data) || typeof data.message !== "string" || data.message.trim() === "") return void 0;
13586
13419
  return data.message;
13587
13420
  }
13588
13421
  return void 0;
@@ -13629,7 +13462,7 @@ function extractNavigatorAttendanceFact(entries) {
13629
13462
  const entry = entries[i];
13630
13463
  if (entry?.type === "custom_message" && entry.customType === "ak-navigator-attendance") {
13631
13464
  const details = entry.message?.details ?? entry.details;
13632
- if (!isRecord12(details)) {
13465
+ if (!isRecord11(details)) {
13633
13466
  return {
13634
13467
  disposition: "unavailable",
13635
13468
  source: "unknown",
@@ -13780,7 +13613,7 @@ async function settleSealedAcceptedOrToolResidual(admitted, authority, scope, ro
13780
13613
  const residual = boundErroredToolCandidate(entries, index, message, residualToolName);
13781
13614
  if (residual === void 0) continue;
13782
13615
  const candidate = residual.candidate;
13783
- const details = isRecord12(candidate) ? candidate : { candidate };
13616
+ const details = isRecord11(candidate) ? candidate : { candidate };
13784
13617
  const failed = await settleFailureTerminalResult(
13785
13618
  admitted,
13786
13619
  {
@@ -13855,7 +13688,7 @@ function extractDoctorCandidateFacts(entries) {
13855
13688
  continue;
13856
13689
  }
13857
13690
  const data = entry.data;
13858
- if (!isRecord12(data)) return {};
13691
+ if (!isRecord11(data)) return {};
13859
13692
  return {
13860
13693
  ...data.cost === void 0 ? {} : { cost: data.cost },
13861
13694
  ...data.auditNoReceipt === void 0 ? {} : { auditNoReceipt: data.auditNoReceipt }
@@ -13940,7 +13773,7 @@ async function settleLawfulSeatAcceptedTerminalResult(admitted, authority, spec,
13940
13773
  let residual;
13941
13774
  for (let index = entries.length - 1; index >= scanStart; index -= 1) {
13942
13775
  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") {
13776
+ if (entry?.type === "custom" && entry.customType === "ak-role-submission-closure" && isRecord11(entry.data) && entry.data.toolName === spec.toolName && classifyPackagedRoleTerminalResult(entry.data).kind === "accepted") {
13944
13777
  thisAttemptHasSeatSuccess = true;
13945
13778
  }
13946
13779
  const message = entries[index]?.message;
@@ -13980,7 +13813,7 @@ async function settleLawfulSeatAcceptedTerminalResult(admitted, authority, spec,
13980
13813
  );
13981
13814
  }
13982
13815
  if (residual !== void 0) {
13983
- const details = isRecord12(residual.candidate) ? residual.candidate : { candidate: residual.candidate };
13816
+ const details = isRecord11(residual.candidate) ? residual.candidate : { candidate: residual.candidate };
13984
13817
  const failed = await settleFailureTerminalResult(
13985
13818
  admitted,
13986
13819
  {
@@ -14030,7 +13863,7 @@ function countersignTerminalFromEntries(entries) {
14030
13863
  return void 0;
14031
13864
  }
14032
13865
  function withCountersignTerminalFact(roleOutcome, officer) {
14033
- const prior = roleOutcome.decisiveFacts !== void 0 && isRecord12(roleOutcome.decisiveFacts) ? roleOutcome.decisiveFacts : {};
13866
+ const prior = roleOutcome.decisiveFacts !== void 0 && isRecord11(roleOutcome.decisiveFacts) ? roleOutcome.decisiveFacts : {};
14034
13867
  return {
14035
13868
  ...roleOutcome,
14036
13869
  decisiveFacts: {
@@ -14043,7 +13876,7 @@ function acceptedSecretariatDefinesOfficerProjection(roleOutcome) {
14043
13876
  const payloads = roleOutcome.payloads ?? [];
14044
13877
  for (let index = payloads.length - 1; index >= 0; index -= 1) {
14045
13878
  const payload = payloads[index];
14046
- if (!isRecord12(payload)) continue;
13879
+ if (!isRecord11(payload)) continue;
14047
13880
  const status = payload.secretariatStatus;
14048
13881
  if (typeof status !== "string") continue;
14049
13882
  return status === "converged";
@@ -14488,7 +14321,7 @@ var init_settlement = __esm({
14488
14321
  });
14489
14322
 
14490
14323
  // src/archivist-record-pointer.ts
14491
- import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
14324
+ import { mkdirSync as mkdirSync2, writeFileSync } from "node:fs";
14492
14325
  import { dirname as dirname17, join as join28 } from "node:path";
14493
14326
  function bookDirectOfficerRunPointer(options) {
14494
14327
  const nest = join28(dirname17(options.parentSessionFile), "auditor-roles");
@@ -14500,7 +14333,7 @@ function bookDirectOfficerRunPointer(options) {
14500
14333
  sessionFile: options.sessionFile,
14501
14334
  ...options.runDirectory !== void 0 && options.runDirectory.trim() !== "" ? { runDirectory: options.runDirectory } : {}
14502
14335
  };
14503
- writeFileSync2(
14336
+ writeFileSync(
14504
14337
  join28(nest, `${options.officer}.pointer.json`),
14505
14338
  `${JSON.stringify(pointer)}
14506
14339
  `,
@@ -14813,159 +14646,281 @@ var init_session_identity = __esm({
14813
14646
  }
14814
14647
  });
14815
14648
 
14816
- // src/public-cli/case-dossier-delivery.ts
14817
- var case_dossier_delivery_exports = {};
14818
- __export(case_dossier_delivery_exports, {
14819
- deliverCaseDossierAsAttachment: () => deliverCaseDossierAsAttachment,
14820
- loadCaseDossierReadingMaterial: () => loadCaseDossierReadingMaterial,
14821
- projectCaseDossierPointerSection: () => projectCaseDossierPointerSection
14822
- });
14823
- import { mkdtemp as mkdtemp3, readFile as readFile18, rm as rm5, writeFile as writeFile8 } from "node:fs/promises";
14824
- import { tmpdir as tmpdir3 } from "node:os";
14825
- import { join as join30 } from "node:path";
14826
- async function projectCaseDossierPointerSection(input) {
14827
- if (input.ticketNumber === void 0) {
14828
- return [
14829
- UNBOUND_DOSSIER_PATH_HEADING,
14830
- "",
14831
- `\u8BB0\u5F55\u5377\u5B97\uFF1A${projectTicketRecordsPathShape()}`
14832
- ].join("\n");
14833
- }
14834
- const volume = resolveTicketProvenanceVolume(
14835
- input.ticketNumber,
14836
- input.projectRoot,
14837
- input.home
14838
- );
14839
- return [
14840
- CASE_DOSSIER_SECTION_HEADING,
14841
- "",
14842
- `\u7968\u53F7\uFF1A#${input.ticketNumber}`,
14843
- `\u8BB0\u5F55\u5377\u5B97\uFF1A${volume.recordFile}`
14844
- ].join("\n");
14845
- }
14846
- async function deliverCaseDossierAsAttachment(input) {
14847
- const section = await projectCaseDossierPointerSection({
14848
- ticketNumber: input.ticketNumber,
14849
- projectRoot: input.projectRoot,
14850
- home: input.home
14851
- });
14852
- const stagingDir = await mkdtemp3(join30(tmpdir3(), "ak-case-dossier-"));
14853
- try {
14854
- const stagingPath = join30(stagingDir, CASE_DOSSIER_ATTACH_FILE);
14855
- await writeFile8(stagingPath, `${section}
14856
- `, "utf8");
14857
- return await freezeAttachmentsIntoRun(
14858
- [stagingPath],
14859
- input.runDirectory,
14860
- CASE_DOSSIER_ATTACH_KEY
14861
- );
14862
- } finally {
14863
- await rm5(stagingDir, { recursive: true, force: true });
14649
+ // src/public-cli/process-cancel.ts
14650
+ function processCancelSignalName(signal) {
14651
+ if (signal === void 0 || signal.aborted !== true) return void 0;
14652
+ const reason = signal.reason;
14653
+ if (reason === "SIGTERM" || reason === "SIGINT" || reason === "SIGHUP") {
14654
+ return reason;
14864
14655
  }
14656
+ return void 0;
14865
14657
  }
14866
- async function loadCaseDossierReadingMaterial(runDirectory) {
14867
- const frozenPath = join30(
14868
- runDirectory,
14869
- "attachments",
14870
- CASE_DOSSIER_ATTACH_KEY,
14871
- `00-${CASE_DOSSIER_ATTACH_FILE}`
14872
- );
14873
- let section;
14874
- try {
14875
- section = await readFile18(frozenPath, "utf8");
14876
- } catch (error) {
14877
- if (error.code === "ENOENT") return void 0;
14878
- throw error;
14879
- }
14880
- if (section.trim() === "") return void 0;
14881
- return { kind: "case-dossier-pointer", frozenPath, section };
14658
+ function processCancelDiagnostic(signalName) {
14659
+ return `ak-role terminated by ${signalName}`;
14882
14660
  }
14883
- var CASE_DOSSIER_SECTION_HEADING, UNBOUND_DOSSIER_PATH_HEADING, CASE_DOSSIER_ATTACH_KEY, CASE_DOSSIER_ATTACH_FILE;
14884
- var init_case_dossier_delivery = __esm({
14885
- "src/public-cli/case-dossier-delivery.ts"() {
14661
+ var init_process_cancel = __esm({
14662
+ "src/public-cli/process-cancel.ts"() {
14886
14663
  "use strict";
14887
- init_sitian_facade();
14888
- init_ticket_provenance();
14889
- init_invocation();
14890
- CASE_DOSSIER_SECTION_HEADING = "## \u672C\u7968\u8D77\u5C45\u5F55\uFF08\u7CFB\u7EDF\u968F\u6848\u63D0\u4F9B\uFF09";
14891
- UNBOUND_DOSSIER_PATH_HEADING = "## \u8D77\u5C45\u5F55\u8DEF\u5F84\uFF08\u7CFB\u7EDF\u968F\u6848\u63D0\u4F9B\uFF09";
14892
- CASE_DOSSIER_ATTACH_KEY = "case-dossier";
14893
- CASE_DOSSIER_ATTACH_FILE = "case-dossier-pointer.md";
14894
14664
  }
14895
14665
  });
14896
14666
 
14897
- // src/host-transition-prior-native.ts
14898
- import { access as access3, readdir as readdir6 } from "node:fs/promises";
14899
- import { dirname as dirname19, join as join31 } from "node:path";
14900
- function isEnoent2(error) {
14901
- return typeof error === "object" && error !== null && error.code === "ENOENT";
14667
+ // src/host-session-record.ts
14668
+ import { spawnSync } from "node:child_process";
14669
+ import {
14670
+ appendFileSync as appendFileSync2,
14671
+ copyFileSync,
14672
+ closeSync,
14673
+ existsSync as existsSync9,
14674
+ openSync,
14675
+ readFileSync as readFileSync3,
14676
+ mkdirSync as mkdirSync3,
14677
+ readdirSync as readdirSync2,
14678
+ rmSync,
14679
+ statSync as statSync3
14680
+ } from "node:fs";
14681
+ import { homedir } from "node:os";
14682
+ import { dirname as dirname19, join as join30 } from "node:path";
14683
+ function declareHostSessionFailure(error) {
14684
+ const message = error instanceof Error ? error.stack || error.message : String(error);
14685
+ process.stderr.write(`[host-session] Dossier record failure: ${message}
14686
+ `);
14902
14687
  }
14903
- async function listPiNativeRecordPaths(sessionFile) {
14688
+ function sitianReportSafe(input) {
14904
14689
  try {
14905
- await access3(sessionFile);
14906
- return [sessionFile];
14690
+ sitianReport(input);
14907
14691
  } catch (error) {
14908
- if (isEnoent2(error)) return [];
14909
- throw error;
14692
+ declareHostSessionFailure(error);
14910
14693
  }
14911
14694
  }
14912
- async function listSitianRecordPaths(sessionParent) {
14913
- const sessionRoot = dirname19(sessionParent);
14914
- let entries;
14695
+ function findCodexRollout(sessionsDir, sessionId) {
14696
+ if (!existsSync9(sessionsDir)) return void 0;
14697
+ const matches = [];
14698
+ function scan(dir, depth = 0) {
14699
+ if (depth > 6) return;
14700
+ let entries;
14701
+ try {
14702
+ entries = readdirSync2(dir, { withFileTypes: true });
14703
+ } catch {
14704
+ return;
14705
+ }
14706
+ for (const entry of entries) {
14707
+ const fullPath = join30(dir, entry.name);
14708
+ if (entry.isDirectory()) {
14709
+ scan(fullPath, depth + 1);
14710
+ } else if (entry.isFile() && entry.name.endsWith(".jsonl") && entry.name.includes(sessionId)) {
14711
+ try {
14712
+ const stat2 = statSync3(fullPath);
14713
+ matches.push({ path: fullPath, mtime: stat2.mtimeMs });
14714
+ } catch {
14715
+ matches.push({ path: fullPath, mtime: 0 });
14716
+ }
14717
+ }
14718
+ }
14719
+ }
14720
+ scan(sessionsDir);
14721
+ if (matches.length === 0 || matches[0] === void 0) return void 0;
14722
+ matches.sort((a, b) => b.mtime - a.mtime);
14723
+ return matches[0]?.path;
14724
+ }
14725
+ function sanitizeClaudeCwd(cwd) {
14726
+ return cwd.replace(/[^a-zA-Z0-9]/g, "-");
14727
+ }
14728
+ function resolveNativeSessionPath(options) {
14729
+ const home = options.home || homedir();
14730
+ if (options.host === "claude") {
14731
+ const configDir = process.env.CLAUDE_CONFIG_DIR || join30(home, ".claude");
14732
+ const sanitizedCwd = sanitizeClaudeCwd(options.cwd);
14733
+ return join30(configDir, "projects", sanitizedCwd, `${options.sessionId}.jsonl`);
14734
+ }
14735
+ if (options.host === "codex") {
14736
+ return findCodexRollout(codexSessionsDirectory(home), options.sessionId);
14737
+ }
14738
+ if (options.host === "grok-build") {
14739
+ const grokHome = process.env.GROK_HOME || join30(home, ".grok");
14740
+ return join30(grokHome, "sessions", encodeURIComponent(options.cwd), options.sessionId);
14741
+ }
14742
+ return void 0;
14743
+ }
14744
+ function codexSessionsDirectory(home) {
14745
+ return join30(process.env.CODEX_HOME || join30(home || homedir(), ".codex"), "sessions");
14746
+ }
14747
+ function recordRunStart(runDirectory) {
14915
14748
  try {
14916
- entries = await readdir6(sessionRoot, { withFileTypes: true });
14749
+ appendFileSync2(join30(runDirectory, ".run-starts"), "\n");
14917
14750
  } catch (error) {
14918
- if (isEnoent2(error)) return [];
14919
- throw error;
14751
+ declareHostSessionFailure(error);
14920
14752
  }
14921
- const recordPaths = [];
14922
- for (const entry of entries) {
14923
- if (!entry.isDirectory()) continue;
14924
- const recordFile = join31(sessionRoot, entry.name, "records.jsonl");
14753
+ }
14754
+ function resolveHostDossierLandingPath(options) {
14755
+ const sanitizedModel = (options.model?.model ?? "default").replace(/[\/\\]+/g, "-");
14756
+ let maxOrdinal = 0;
14757
+ if (existsSync9(options.sessionDirectory)) {
14925
14758
  try {
14926
- await access3(recordFile);
14927
- recordPaths.push(recordFile);
14928
- } catch (error) {
14929
- if (!isEnoent2(error)) throw error;
14759
+ const entries = readdirSync2(options.sessionDirectory);
14760
+ for (const entry of entries) {
14761
+ const match = entry.match(/-(\d+)(?:\.jsonl|\.failed)?$/);
14762
+ const first = match?.[1];
14763
+ if (first !== void 0) {
14764
+ const val = parseInt(first, 10);
14765
+ if (!isNaN(val) && val > maxOrdinal) {
14766
+ maxOrdinal = val;
14767
+ }
14768
+ }
14769
+ }
14770
+ } catch {
14930
14771
  }
14931
14772
  }
14932
- recordPaths.sort();
14933
- return recordPaths;
14773
+ const startsPath = join30(dirname19(options.sessionDirectory), ".run-starts");
14774
+ let starts = 0;
14775
+ if (existsSync9(startsPath)) starts = readFileSync3(startsPath, "utf8").length;
14776
+ const ordinal = Math.max(maxOrdinal + 1, starts, options.continuation.kind === "resume" ? 2 : 1);
14777
+ const baseName = `${options.host}-${sanitizedModel}-${ordinal}`;
14778
+ const landingPath = options.host === "grok-build" ? join30(options.sessionDirectory, baseName) : join30(options.sessionDirectory, `${baseName}.jsonl`);
14779
+ return { landingPath, ordinal, sanitizedModel };
14934
14780
  }
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
- };
14781
+ function recordNativeSessionPointer(options) {
14782
+ if (options.host === "pi" || options.host === "hermes") {
14783
+ return void 0;
14942
14784
  }
14943
- return {
14944
- priorNativeKind: "sitian",
14945
- priorNativePaths: await listSitianRecordPaths(input.piSessionFile)
14946
- };
14785
+ const nativePath = options.host === "codex" ? codexSessionsDirectory(options.home) : resolveNativeSessionPath(options);
14786
+ if (nativePath === void 0) return void 0;
14787
+ sitianReportSafe({
14788
+ level: "event",
14789
+ kind: HOST_SESSION_RECORD_KIND,
14790
+ host: options.host,
14791
+ cwd: options.cwd,
14792
+ sessionParent: options.sessionParent,
14793
+ source: `${options.host}-dossier`,
14794
+ payload: {
14795
+ type: "native-session-pointer",
14796
+ nativePath,
14797
+ sessionId: options.sessionId
14798
+ }
14799
+ });
14800
+ return nativePath;
14947
14801
  }
14948
- var init_host_transition_prior_native = __esm({
14949
- "src/host-transition-prior-native.ts"() {
14950
- "use strict";
14802
+ function copyFileCloneOrFallback(src, dest) {
14803
+ try {
14804
+ const res = spawnSync("cp", ["-c", src, dest]);
14805
+ if (res.status === 0) return;
14806
+ } catch {
14951
14807
  }
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;
14808
+ copyFileSync(src, dest);
14809
+ }
14810
+ function copyGrokDossier(srcDir, destDir) {
14811
+ const chatHistorySrc = join30(srcDir, "chat_history.jsonl");
14812
+ if (!existsSync9(chatHistorySrc)) {
14813
+ throw new Error(`Grok native chat_history.jsonl missing at ${chatHistorySrc}`);
14960
14814
  }
14961
- return void 0;
14815
+ mkdirSync3(destDir, { recursive: true });
14816
+ const chatHistoryDest = join30(destDir, "chat_history.jsonl");
14817
+ copyFileCloneOrFallback(chatHistorySrc, chatHistoryDest);
14818
+ const usageSrc = join30(srcDir, "usage.json");
14819
+ if (!existsSync9(usageSrc)) {
14820
+ throw new Error(`Grok native usage.json missing at ${usageSrc}`);
14821
+ }
14822
+ copyFileCloneOrFallback(usageSrc, join30(destDir, "usage.json"));
14962
14823
  }
14963
- function processCancelDiagnostic(signalName) {
14964
- return `ak-role terminated by ${signalName}`;
14824
+ function copyAndRecordHostDossier(options) {
14825
+ if (options.host === "pi" || options.host === "hermes") {
14826
+ return;
14827
+ }
14828
+ const nativePath = resolveNativeSessionPath({
14829
+ host: options.host,
14830
+ sessionId: options.sessionId,
14831
+ cwd: options.cwd,
14832
+ ...options.home !== void 0 ? { home: options.home } : {}
14833
+ });
14834
+ if (nativePath === void 0 && options.host !== "codex") return;
14835
+ let destination;
14836
+ try {
14837
+ destination = resolveHostDossierLandingPath(options);
14838
+ } catch (error) {
14839
+ sitianReportSafe({
14840
+ level: "event",
14841
+ kind: HOST_SESSION_RECORD_KIND,
14842
+ host: options.host,
14843
+ cwd: options.cwd,
14844
+ sessionParent: options.sessionParent,
14845
+ source: `${options.host}-dossier`,
14846
+ payload: {
14847
+ type: "native-session-warning",
14848
+ sessionId: options.sessionId,
14849
+ error: error instanceof Error ? error.message : String(error)
14850
+ }
14851
+ });
14852
+ return;
14853
+ }
14854
+ const { landingPath, ordinal, sanitizedModel } = destination;
14855
+ let lastError;
14856
+ let copySuccess = false;
14857
+ for (let attempt = 1; attempt <= 2; attempt++) {
14858
+ try {
14859
+ if (options.host === "grok-build") {
14860
+ copyGrokDossier(nativePath, landingPath);
14861
+ } else {
14862
+ if (nativePath === void 0 || !existsSync9(nativePath)) {
14863
+ throw new Error(`Native session file missing for ${options.host} session ${options.sessionId}`);
14864
+ }
14865
+ mkdirSync3(dirname19(landingPath), { recursive: true });
14866
+ copyFileCloneOrFallback(nativePath, landingPath);
14867
+ }
14868
+ copySuccess = true;
14869
+ break;
14870
+ } catch (error) {
14871
+ lastError = error;
14872
+ }
14873
+ }
14874
+ if (copySuccess) {
14875
+ sitianReportSafe({
14876
+ level: "event",
14877
+ kind: HOST_SESSION_RECORD_KIND,
14878
+ host: options.host,
14879
+ cwd: options.cwd,
14880
+ sessionParent: options.sessionParent,
14881
+ source: `${options.host}-dossier`,
14882
+ payload: {
14883
+ type: "native-session-copy",
14884
+ nativePath,
14885
+ landingPath,
14886
+ ordinal,
14887
+ sessionId: options.sessionId
14888
+ }
14889
+ });
14890
+ } else {
14891
+ try {
14892
+ rmSync(landingPath, { recursive: options.host === "grok-build", force: true });
14893
+ } catch {
14894
+ }
14895
+ try {
14896
+ mkdirSync3(options.sessionDirectory, { recursive: true });
14897
+ closeSync(openSync(join30(options.sessionDirectory, `${options.host}-${sanitizedModel}-${ordinal}.failed`), "a"));
14898
+ } catch {
14899
+ }
14900
+ sitianReportSafe({
14901
+ level: "event",
14902
+ kind: HOST_SESSION_RECORD_KIND,
14903
+ host: options.host,
14904
+ cwd: options.cwd,
14905
+ sessionParent: options.sessionParent,
14906
+ source: `${options.host}-dossier`,
14907
+ payload: {
14908
+ type: "native-session-warning",
14909
+ nativePath,
14910
+ landingPath,
14911
+ ordinal,
14912
+ sessionId: options.sessionId,
14913
+ error: lastError instanceof Error ? lastError.message : String(lastError)
14914
+ }
14915
+ });
14916
+ }
14965
14917
  }
14966
- var init_process_cancel = __esm({
14967
- "src/public-cli/process-cancel.ts"() {
14918
+ var HOST_SESSION_RECORD_KIND;
14919
+ var init_host_session_record = __esm({
14920
+ "src/host-session-record.ts"() {
14968
14921
  "use strict";
14922
+ init_sitian_facade();
14923
+ HOST_SESSION_RECORD_KIND = "host-session";
14969
14924
  }
14970
14925
  });
14971
14926
 
@@ -14973,7 +14928,7 @@ var init_process_cancel = __esm({
14973
14928
  import { constants as fsConstants2 } from "node:fs";
14974
14929
  import { randomUUID as randomUUID6 } from "node:crypto";
14975
14930
  import { lstat as lstat5, mkdir as mkdir3, open } from "node:fs/promises";
14976
- import { join as join32 } from "node:path";
14931
+ import { join as join31 } from "node:path";
14977
14932
  async function persistReturnedRunState(admitted, authority, options) {
14978
14933
  if (options?.lawful === true) {
14979
14934
  await markRunTerminal(admitted.runDirectory);
@@ -15044,7 +14999,7 @@ function jsonSafeReplacer() {
15044
14999
  };
15045
15000
  }
15046
15001
  async function writeHardenedArtifactFile(artifactsDir, namePrefix, payload) {
15047
- const filePath = join32(artifactsDir, `${namePrefix}-${randomUUID6()}.json`);
15002
+ const filePath = join31(artifactsDir, `${namePrefix}-${randomUUID6()}.json`);
15048
15003
  const body = `${JSON.stringify(payload, jsonSafeReplacer(), 2)}
15049
15004
  `;
15050
15005
  const noFollowFlag = typeof fsConstants2.O_NOFOLLOW === "number" ? fsConstants2.O_NOFOLLOW : 0;
@@ -15332,8 +15287,8 @@ var init_auto_resume = __esm({
15332
15287
 
15333
15288
  // src/public-cli/post-admission.ts
15334
15289
  import { randomUUID as randomUUID7 } from "node:crypto";
15335
- import { writeFile as writeFile9 } from "node:fs/promises";
15336
- import { isAbsolute as isAbsolute7, join as join33, resolve as resolve13 } from "node:path";
15290
+ import { writeFile as writeFile8 } from "node:fs/promises";
15291
+ import { isAbsolute as isAbsolute7, join as join32, resolve as resolve13 } from "node:path";
15337
15292
  function describeCaughtError(error) {
15338
15293
  if (error instanceof Error) {
15339
15294
  const code = error.code;
@@ -15428,8 +15383,8 @@ async function recordBestEffortPostDispatchDiagnostic(admitted, env, diagnostic,
15428
15383
  } catch (appendError) {
15429
15384
  try {
15430
15385
  const artifactsDir = await ensureRealArtifactsDirectory(admitted.runDirectory);
15431
- await writeFile9(
15432
- join33(artifactsDir, `post-admission-diagnostic-${randomUUID7()}.json`),
15386
+ await writeFile8(
15387
+ join32(artifactsDir, `post-admission-diagnostic-${randomUUID7()}.json`),
15433
15388
  `${JSON.stringify({ version: 1, ...payload }, null, 2)}
15434
15389
  `,
15435
15390
  { encoding: "utf8", flag: "wx" }
@@ -15575,7 +15530,7 @@ async function dispatchPostAdmissionTurn(input) {
15575
15530
  const rows = await readRecordedSubmissionRows(
15576
15531
  admitted.projectRoot,
15577
15532
  admitted.runId,
15578
- { home: homeFromRunDirectory(admitted.runDirectory), sessionParent: join33(admitted.runDirectory, "session", "session.jsonl") }
15533
+ { home: homeFromRunDirectory(admitted.runDirectory), sessionParent: join32(admitted.runDirectory, "session", "session.jsonl") }
15579
15534
  );
15580
15535
  let ticketNumber;
15581
15536
  for (const row of rows) {
@@ -15631,35 +15586,6 @@ async function dispatchPostAdmissionTurn(input) {
15631
15586
  }
15632
15587
  };
15633
15588
  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
15589
  await clearTypedProviderHttpObservation(admitted.runDirectory);
15664
15590
  if (adapters.beforeDispatch !== void 0) {
15665
15591
  try {
@@ -15695,18 +15621,9 @@ async function dispatchPostAdmissionTurn(input) {
15695
15621
  if (env.stationChild !== void 0) {
15696
15622
  turnRequest = { ...turnRequest, stationChild: env.stationChild };
15697
15623
  }
15698
- if (hostTransition !== void 0) {
15699
- turnRequest = { ...turnRequest, hostTransition };
15700
- }
15701
- if (typeof liveHost === "string" && liveHost.trim() !== "") {
15702
- turnRequest = { ...turnRequest, host: liveHost.trim() };
15624
+ if (typeof env.host === "string" && env.host.trim() !== "") {
15625
+ turnRequest = { ...turnRequest, host: env.host.trim() };
15703
15626
  }
15704
- await deliverCaseDossierAsAttachment({
15705
- ticketNumber: admitted.ticketNumber,
15706
- projectRoot: admitted.projectRoot,
15707
- home: env.home,
15708
- runDirectory: admitted.runDirectory
15709
- });
15710
15627
  await markRunRunning(
15711
15628
  admitted.runDirectory,
15712
15629
  env.model,
@@ -15716,6 +15633,7 @@ async function dispatchPostAdmissionTurn(input) {
15716
15633
  );
15717
15634
  let result;
15718
15635
  try {
15636
+ recordRunStart(admitted.runDirectory);
15719
15637
  result = await env.roleTurnHost.executeTurn(turnRequest);
15720
15638
  } catch (error) {
15721
15639
  const processCancelName = processCancelSignalName(env.signal);
@@ -15741,8 +15659,8 @@ async function dispatchPostAdmissionTurn(input) {
15741
15659
  }
15742
15660
  let stderrLogWriteFailure;
15743
15661
  try {
15744
- await writeFile9(
15745
- join33(admitted.runDirectory, "stderr.log"),
15662
+ await writeFile8(
15663
+ join32(admitted.runDirectory, "stderr.log"),
15746
15664
  result.stderr,
15747
15665
  "utf8"
15748
15666
  );
@@ -16021,7 +15939,7 @@ async function dispatchAfterWriterLease(input) {
16021
15939
  }
16022
15940
  function isAlreadyFrozenSummonsAttachment(runDirectory, attachmentPath) {
16023
15941
  const absolute = isAbsolute7(attachmentPath) ? attachmentPath : resolve13(attachmentPath);
16024
- return pathContainedIn(join33(runDirectory, "attachments"), absolute);
15942
+ return pathContainedIn(join32(runDirectory, "attachments"), absolute);
16025
15943
  }
16026
15944
  async function prepareSummonsResumeMaterials(runDirectory, summons) {
16027
15945
  if (summons === void 0) return void 0;
@@ -16280,8 +16198,8 @@ async function presentResumeFailurePointer(io, thrown, publish) {
16280
16198
  }
16281
16199
  async function writeResumeDiagnosticFile(runDirectory, runId, failure2, role) {
16282
16200
  const dir = await ensureRealArtifactsDirectory(runDirectory);
16283
- const path = join33(dir, `resume-diagnostic-${randomUUID7()}.json`);
16284
- await writeFile9(
16201
+ const path = join32(dir, `resume-diagnostic-${randomUUID7()}.json`);
16202
+ await writeFile8(
16285
16203
  path,
16286
16204
  `${JSON.stringify({
16287
16205
  runId,
@@ -16413,12 +16331,11 @@ var init_post_admission = __esm({
16413
16331
  init_session_identity();
16414
16332
  init_role_run_relocation();
16415
16333
  init_packaged_role_registry();
16416
- init_case_dossier_delivery();
16417
16334
  init_engine_detour_usage();
16418
- init_host_transition_prior_native();
16419
16335
  init_run_lifecycle();
16420
16336
  init_process_cancel();
16421
16337
  init_activation_ledger_topology();
16338
+ init_host_session_record();
16422
16339
  init_settlement();
16423
16340
  init_terminal();
16424
16341
  init_auto_resume();
@@ -16452,20 +16369,20 @@ var init_seat_ticket_binding = __esm({
16452
16369
  });
16453
16370
 
16454
16371
  // src/public-cli/machine-method-skills.ts
16455
- import { accessSync, constants as constants2, statSync as statSync3 } from "node:fs";
16372
+ import { accessSync, constants as constants2, statSync as statSync4 } from "node:fs";
16456
16373
  import { lstat as lstat6, mkdir as mkdir4, symlink } from "node:fs/promises";
16457
- import { join as join34 } from "node:path";
16458
- import { spawnSync } from "node:child_process";
16374
+ import { join as join33 } from "node:path";
16375
+ import { spawnSync as spawnSync2 } from "node:child_process";
16459
16376
  function skillRoot(home) {
16460
- return join34(home, ".agents/skills");
16377
+ return join33(home, ".agents/skills");
16461
16378
  }
16462
16379
  function installedMethodSkillPath(home, name) {
16463
16380
  return installedSkillPath(skillRoot(home), name);
16464
16381
  }
16465
16382
  function installedSkillPath(root, name) {
16466
- const path = join34(root, name, "SKILL.md");
16383
+ const path = join33(root, name, "SKILL.md");
16467
16384
  try {
16468
- if (!statSync3(path).isFile()) return void 0;
16385
+ if (!statSync4(path).isFile()) return void 0;
16469
16386
  accessSync(path, constants2.R_OK);
16470
16387
  return path;
16471
16388
  } catch (error) {
@@ -16476,9 +16393,9 @@ function installedSkillPath(root, name) {
16476
16393
  }
16477
16394
  function linkedSkillRoot(home, host) {
16478
16395
  if (host === "claude" || host === "claude-code") {
16479
- return join34(process.env.CLAUDE_CONFIG_DIR?.trim() || join34(home, ".claude"), "skills");
16396
+ return join33(process.env.CLAUDE_CONFIG_DIR?.trim() || join33(home, ".claude"), "skills");
16480
16397
  }
16481
- if (host === "hermes") return join34(home, ".hermes/skills");
16398
+ if (host === "hermes") return join33(home, ".hermes/skills");
16482
16399
  return void 0;
16483
16400
  }
16484
16401
  async function occupied(path) {
@@ -16506,7 +16423,7 @@ async function warnMissingMethodSkills(home, host, role, skills, stdout) {
16506
16423
  }
16507
16424
  }
16508
16425
  function runSkillsCli(args, home) {
16509
- const result = spawnSync("npx", ["--yes", "skills", ...args], {
16426
+ const result = spawnSync2("npx", ["--yes", "skills", ...args], {
16510
16427
  stdio: "inherit",
16511
16428
  env: { ...process.env, HOME: home }
16512
16429
  });
@@ -16535,7 +16452,7 @@ async function runMachineSkillSetup(home, stdout) {
16535
16452
  const missingBySource = /* @__PURE__ */ new Map();
16536
16453
  let unsourced = false;
16537
16454
  for (const name of packagedMethodSkillNames()) {
16538
- const path = join34(canonical, name);
16455
+ const path = join33(canonical, name);
16539
16456
  if (await occupied(path)) {
16540
16457
  warnOccupied(path, stdout);
16541
16458
  continue;
@@ -16559,15 +16476,15 @@ async function runMachineSkillSetup(home, stdout) {
16559
16476
  const root = linkedSkillRoot(home, host);
16560
16477
  const binaryFromHome = host === "claude-code" ? HEADLESS_HOST_DESCRIPTIONS.claude.binaryFromHome : HOST_DESCRIPTIONS.hermes.binaryFromHome;
16561
16478
  try {
16562
- accessSync(join34(home, ...binaryFromHome), constants2.X_OK);
16479
+ accessSync(join33(home, ...binaryFromHome), constants2.X_OK);
16563
16480
  } catch (error) {
16564
16481
  if (["ENOENT", "ENOTDIR", "EACCES"].includes(error.code ?? "")) continue;
16565
16482
  throw error;
16566
16483
  }
16567
16484
  for (const name of packagedMethodSkillNames()) {
16568
- const target = join34(canonical, name);
16485
+ const target = join33(canonical, name);
16569
16486
  if (installedMethodSkillPath(home, name) === void 0) continue;
16570
- const link = join34(root, name);
16487
+ const link = join33(root, name);
16571
16488
  if (await occupied(link)) {
16572
16489
  warnOccupied(link, stdout);
16573
16490
  continue;
@@ -16693,11 +16610,11 @@ var init_turn_request = __esm({
16693
16610
  });
16694
16611
 
16695
16612
  // src/public-cli/countersign-run.ts
16696
- function isRecord13(value) {
16613
+ function isRecord12(value) {
16697
16614
  return typeof value === "object" && value !== null && !Array.isArray(value);
16698
16615
  }
16699
16616
  function isEscalatePayload(payload) {
16700
- if (!isRecord13(payload)) return false;
16617
+ if (!isRecord12(payload)) return false;
16701
16618
  return payload.status === "escalate";
16702
16619
  }
16703
16620
  function courtDiaristPayloadRows(roleOutcome, submissions) {
@@ -17912,13 +17829,13 @@ var init_instruction_seat_run = __esm({
17912
17829
  });
17913
17830
 
17914
17831
  // src/analyst-book-key.ts
17915
- import { statSync as statSync4 } from "node:fs";
17832
+ import { statSync as statSync5 } from "node:fs";
17916
17833
  import { isAbsolute as isAbsolute8 } from "node:path";
17917
17834
  function resolveAnalystBookKey(projectRoot) {
17918
17835
  const identity = physicalPathIdentity(projectRoot);
17919
17836
  let stats;
17920
17837
  try {
17921
- stats = statSync4(identity);
17838
+ stats = statSync5(identity);
17922
17839
  } catch (error) {
17923
17840
  const code = errnoCode(error);
17924
17841
  if (code === "ENOENT" || code === "ENOTDIR") return `root:${identity}`;
@@ -17946,8 +17863,8 @@ var init_analyst_book_key = __esm({
17946
17863
  });
17947
17864
 
17948
17865
  // src/analyst-index.ts
17949
- import { open as open2, readFile as readFile19, unlink as unlink4 } from "node:fs/promises";
17950
- import { dirname as dirname21, join as join35 } from "node:path";
17866
+ import { open as open2, readFile as readFile18, unlink as unlink4 } from "node:fs/promises";
17867
+ import { dirname as dirname21, join as join34 } from "node:path";
17951
17868
  function sleep(ms) {
17952
17869
  return new Promise((resolve22) => {
17953
17870
  setTimeout(resolve22, ms);
@@ -17956,7 +17873,7 @@ function sleep(ms) {
17956
17873
  async function withAnalystLibraryIndexLock(ledgerHome, fn) {
17957
17874
  const indexPath = analystLibraryIndexPath(ledgerHome);
17958
17875
  ensureRealDirectoryTree(ledgerHome, dirname21(indexPath));
17959
- const lockPath = join35(dirname21(indexPath), LIBRARY_INDEX_LOCK_NAME);
17876
+ const lockPath = join34(dirname21(indexPath), LIBRARY_INDEX_LOCK_NAME);
17960
17877
  assertLedgerFileInsideHome(lockPath, ledgerHome);
17961
17878
  const startedAt = Date.now();
17962
17879
  while (true) {
@@ -17983,7 +17900,7 @@ async function withAnalystLibraryIndexLock(ledgerHome, fn) {
17983
17900
  }
17984
17901
  }
17985
17902
  function analystLibraryIndexPath(ledgerHome) {
17986
- return join35(ledgerHome, "analyst", "library-index.json");
17903
+ return join34(ledgerHome, "analyst", "library-index.json");
17987
17904
  }
17988
17905
  function rowFromIssueMetricsPage(page) {
17989
17906
  return {
@@ -18074,7 +17991,7 @@ async function readAnalystLibraryIndexPage(ledgerHome) {
18074
17991
  const path = analystLibraryIndexPath(ledgerHome);
18075
17992
  let raw;
18076
17993
  try {
18077
- raw = await readFile19(path, "utf8");
17994
+ raw = await readFile18(path, "utf8");
18078
17995
  } catch (error) {
18079
17996
  if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
18080
17997
  return void 0;
@@ -18278,15 +18195,15 @@ var init_analyst_cohort = __esm({
18278
18195
  });
18279
18196
 
18280
18197
  // src/analyst-ledger.ts
18281
- import { readdir as readdir7, readFile as readFile20 } from "node:fs/promises";
18282
- import { basename as basename9, join as join36 } from "node:path";
18198
+ import { readdir as readdir6, readFile as readFile19 } from "node:fs/promises";
18199
+ import { basename as basename9, join as join35 } from "node:path";
18283
18200
  function isMissingPathError6(error) {
18284
18201
  return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
18285
18202
  }
18286
18203
  function errorText3(error) {
18287
18204
  return error instanceof Error ? error.message : String(error);
18288
18205
  }
18289
- function isRecord14(value) {
18206
+ function isRecord13(value) {
18290
18207
  return typeof value === "object" && value !== null && !Array.isArray(value);
18291
18208
  }
18292
18209
  async function readExistingRunLifecycleState(runDirectory) {
@@ -18308,7 +18225,7 @@ function ghostLeaseCheckFromAutopsy(autopsy) {
18308
18225
  }
18309
18226
  }
18310
18227
  async function classifyGhostCandidate(input) {
18311
- const autopsy = await autopsyWriterLock(join36(input.runDirectory, "writer.lock"));
18228
+ const autopsy = await autopsyWriterLock(join35(input.runDirectory, "writer.lock"));
18312
18229
  const leaseCheck = ghostLeaseCheckFromAutopsy(autopsy);
18313
18230
  if (leaseCheck === void 0) return { kind: "live" };
18314
18231
  return {
@@ -18327,7 +18244,7 @@ function parseRunDirectoryName2(name) {
18327
18244
  }
18328
18245
  async function listLedgerBookNames(booksRoot) {
18329
18246
  try {
18330
- const entries = await readdir7(booksRoot, { withFileTypes: true });
18247
+ const entries = await readdir6(booksRoot, { withFileTypes: true });
18331
18248
  return entries.filter((e) => e.isDirectory()).map((e) => e.name).sort();
18332
18249
  } catch (error) {
18333
18250
  if (isMissingPathError6(error)) return [];
@@ -18337,13 +18254,13 @@ async function listLedgerBookNames(booksRoot) {
18337
18254
  async function readInvocationScopeFields(runDirectory) {
18338
18255
  let raw;
18339
18256
  try {
18340
- raw = await readFile20(join36(runDirectory, "invocation.json"), "utf8");
18257
+ raw = await readFile19(join35(runDirectory, "invocation.json"), "utf8");
18341
18258
  } catch (error) {
18342
18259
  if (isMissingPathError6(error)) return void 0;
18343
18260
  throw error;
18344
18261
  }
18345
18262
  const parsed = JSON.parse(raw);
18346
- if (!isRecord14(parsed)) return void 0;
18263
+ if (!isRecord13(parsed)) return void 0;
18347
18264
  if (typeof parsed.projectRoot !== "string" || parsed.projectRoot.trim() === "") {
18348
18265
  return void 0;
18349
18266
  }
@@ -18370,15 +18287,15 @@ function decideIssueScope(input) {
18370
18287
  }
18371
18288
  async function resolveSessionFile(runDirectory) {
18372
18289
  try {
18373
- const raw = await readFile20(join36(runDirectory, "invocation.json"), "utf8");
18290
+ const raw = await readFile19(join35(runDirectory, "invocation.json"), "utf8");
18374
18291
  const parsed = JSON.parse(raw);
18375
- if (isRecord14(parsed) && typeof parsed.sessionFile === "string" && parsed.sessionFile.trim() !== "") {
18292
+ if (isRecord13(parsed) && typeof parsed.sessionFile === "string" && parsed.sessionFile.trim() !== "") {
18376
18293
  return parsed.sessionFile;
18377
18294
  }
18378
18295
  } catch (error) {
18379
18296
  if (!isMissingPathError6(error)) throw error;
18380
18297
  }
18381
- return join36(runDirectory, "session", "session.jsonl");
18298
+ return join35(runDirectory, "session", "session.jsonl");
18382
18299
  }
18383
18300
  function attributeSessionRowsForRun(input) {
18384
18301
  if (pathContainedIn(input.runDirectory, input.sessionFile)) {
@@ -18570,9 +18487,9 @@ async function classifyScopedRun(input) {
18570
18487
  }
18571
18488
  let gateCycles;
18572
18489
  try {
18573
- const parentSessionFile = join36(input.runDirectory, "session", "session.jsonl");
18490
+ const parentSessionFile = join35(input.runDirectory, "session", "session.jsonl");
18574
18491
  gateCycles = await readAnalystGateCyclesFromAuditorRoles(
18575
- join36(input.runDirectory, "session", "auditor-roles"),
18492
+ join35(input.runDirectory, "session", "auditor-roles"),
18576
18493
  { parentSessionFile }
18577
18494
  );
18578
18495
  } catch (error) {
@@ -18607,7 +18524,7 @@ async function classifyScopedRun(input) {
18607
18524
  async function scanAnalystIssueRuns(input) {
18608
18525
  const ledgerHome = resolveActivationLedgerHome(input.home);
18609
18526
  const scopeTicketNumber = input.ticketNumber;
18610
- const booksRoot = join36(ledgerHome, "books");
18527
+ const booksRoot = join35(ledgerHome, "books");
18611
18528
  let wholeBook = false;
18612
18529
  let scopeRootIdentity;
18613
18530
  let bookNames;
@@ -18640,7 +18557,7 @@ async function scanAnalystIssueRuns(input) {
18640
18557
  const ghostLegs = [];
18641
18558
  const scopeConflicts = [];
18642
18559
  for (const book of bookNames) {
18643
- const bookDir = join36(booksRoot, book);
18560
+ const bookDir = join35(booksRoot, book);
18644
18561
  let runDirectories;
18645
18562
  try {
18646
18563
  runDirectories = await listBookRunDirectories(bookDir);
@@ -18710,7 +18627,7 @@ var init_analyst_ledger = __esm({
18710
18627
  });
18711
18628
 
18712
18629
  // src/analyst-metric-families/acceptance-success-rework.ts
18713
- function isRecord15(value) {
18630
+ function isRecord14(value) {
18714
18631
  return typeof value === "object" && value !== null && !Array.isArray(value);
18715
18632
  }
18716
18633
  function wallMsFromSpan(span) {
@@ -18719,21 +18636,21 @@ function wallMsFromSpan(span) {
18719
18636
  function findCollectorGroups(body) {
18720
18637
  if (Array.isArray(body.groups)) return body.groups;
18721
18638
  const receipt = body.receipt;
18722
- if (isRecord15(receipt) && Array.isArray(receipt.groups)) return receipt.groups;
18639
+ if (isRecord14(receipt) && Array.isArray(receipt.groups)) return receipt.groups;
18723
18640
  const outcome = body.outcome;
18724
- if (isRecord15(outcome)) {
18641
+ if (isRecord14(outcome)) {
18725
18642
  const facts = outcome.decisiveFacts;
18726
- if (isRecord15(facts) && Array.isArray(facts.groups)) return facts.groups;
18643
+ if (isRecord14(facts) && Array.isArray(facts.groups)) return facts.groups;
18727
18644
  }
18728
18645
  return void 0;
18729
18646
  }
18730
18647
  function extractStatus(body) {
18731
18648
  const outcome = body.outcome;
18732
- if (isRecord15(outcome) && typeof outcome.status === "string" && outcome.status.trim() !== "") {
18649
+ if (isRecord14(outcome) && typeof outcome.status === "string" && outcome.status.trim() !== "") {
18733
18650
  return outcome.status;
18734
18651
  }
18735
18652
  const receipt = body.receipt;
18736
- if (isRecord15(receipt) && typeof receipt.status === "string" && receipt.status.trim() !== "") {
18653
+ if (isRecord14(receipt) && typeof receipt.status === "string" && receipt.status.trim() !== "") {
18737
18654
  return receipt.status;
18738
18655
  }
18739
18656
  if (typeof body.status === "string" && body.status.trim() !== "") {
@@ -19359,15 +19276,15 @@ var init_leg_wall_clock = __esm({
19359
19276
  });
19360
19277
 
19361
19278
  // src/analyst-metric-families/round-timeline.ts
19362
- function isRecord16(value) {
19279
+ function isRecord15(value) {
19363
19280
  return typeof value === "object" && value !== null && !Array.isArray(value);
19364
19281
  }
19365
19282
  function wallMsFromSpan2(startedAt, endedAt) {
19366
19283
  return Date.parse(endedAt) - Date.parse(startedAt);
19367
19284
  }
19368
19285
  function readClassCount(body) {
19369
- if (!isRecord16(body.outcome)) return void 0;
19370
- if (!isRecord16(body.outcome.decisiveFacts)) return void 0;
19286
+ if (!isRecord15(body.outcome)) return void 0;
19287
+ if (!isRecord15(body.outcome.decisiveFacts)) return void 0;
19371
19288
  const classCount = body.outcome.decisiveFacts.classCount;
19372
19289
  if (typeof classCount !== "number" || !Number.isFinite(classCount)) {
19373
19290
  return void 0;
@@ -19511,8 +19428,8 @@ var init_analyst_metric_family = __esm({
19511
19428
  });
19512
19429
 
19513
19430
  // src/analyst-page.ts
19514
- import { createHash as createHash6 } from "node:crypto";
19515
- import { dirname as dirname22, join as join37 } from "node:path";
19431
+ import { createHash as createHash5 } from "node:crypto";
19432
+ import { dirname as dirname22, join as join36 } from "node:path";
19516
19433
  function analystIssuePageKey(address) {
19517
19434
  const parts = ["book", address.bookKey];
19518
19435
  if (address.issueNumber !== void 0) {
@@ -19520,10 +19437,10 @@ function analystIssuePageKey(address) {
19520
19437
  } else if (address.scopeRootIdentity !== void 0) {
19521
19438
  parts.push("root", physicalPathIdentity(address.scopeRootIdentity));
19522
19439
  }
19523
- return createHash6("sha256").update(parts.join("\0")).digest("hex").slice(0, 32);
19440
+ return createHash5("sha256").update(parts.join("\0")).digest("hex").slice(0, 32);
19524
19441
  }
19525
19442
  function analystIssuePagePath(ledgerHome, address) {
19526
- return join37(ledgerHome, "analyst", "issues", `${analystIssuePageKey(address)}.json`);
19443
+ return join36(ledgerHome, "analyst", "issues", `${analystIssuePageKey(address)}.json`);
19527
19444
  }
19528
19445
  function analystIssuePageAddressFromPage(page) {
19529
19446
  return {
@@ -19659,7 +19576,7 @@ var init_analyst_page = __esm({
19659
19576
  });
19660
19577
 
19661
19578
  // src/analyst-entry.ts
19662
- import { readFile as readFile21 } from "node:fs/promises";
19579
+ import { readFile as readFile20 } from "node:fs/promises";
19663
19580
  import { Type as Type12 } from "typebox";
19664
19581
  function isMissingPathError7(error) {
19665
19582
  return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
@@ -19690,7 +19607,7 @@ async function readOrComputeAnalystIssuePage(input, options) {
19690
19607
  ...issueNumber === void 0 && input.bookKey === void 0 ? { scopeRootIdentity: projectRoot } : {}
19691
19608
  });
19692
19609
  try {
19693
- const raw = await readFile21(pagePath, "utf8");
19610
+ const raw = await readFile20(pagePath, "utf8");
19694
19611
  const page = JSON.parse(raw);
19695
19612
  if (cachedPageMatchesRequestedScope(page, { bookKey, ...input })) {
19696
19613
  const ghostScan = await scanAnalystIssueRuns({
@@ -19791,7 +19708,7 @@ async function runAnalystModelGroupsMode(input, home) {
19791
19708
  scopeRootIdentity: projectRoot
19792
19709
  });
19793
19710
  try {
19794
- const raw = await readFile21(pagePath, "utf8");
19711
+ const raw = await readFile20(pagePath, "utf8");
19795
19712
  JSON.parse(raw);
19796
19713
  } catch (error) {
19797
19714
  if (!isMissingPathError7(error)) {
@@ -19889,7 +19806,7 @@ var init_analyst_entry = __esm({
19889
19806
  });
19890
19807
 
19891
19808
  // src/public-cli/analyst-run.ts
19892
- import { readFile as readFile22 } from "node:fs/promises";
19809
+ import { readFile as readFile21 } from "node:fs/promises";
19893
19810
  import { isAbsolute as isAbsolute9, resolve as resolve15 } from "node:path";
19894
19811
  import { Value as Value3 } from "typebox/value";
19895
19812
  function resolveAnalystIssueBookKeyFromCwd(cwd = process.cwd()) {
@@ -19943,7 +19860,7 @@ async function buildAnalystSweepModeInputFromAttachmentPaths(attachmentPaths) {
19943
19860
  const absolute = isAbsolute9(sourcePath) ? sourcePath : resolve15(sourcePath);
19944
19861
  let bytes;
19945
19862
  try {
19946
- bytes = await readFile22(absolute);
19863
+ bytes = await readFile21(absolute);
19947
19864
  } catch (error) {
19948
19865
  throw new CliUsageError(
19949
19866
  `analyst sweep attachment is not a readable regular file: ${sourcePath}`,
@@ -20063,7 +19980,7 @@ __export(cli_exports, {
20063
19980
  runAkRole: () => runAkRole
20064
19981
  });
20065
19982
  import { realpath as realpath5 } from "node:fs/promises";
20066
- import { join as join38 } from "node:path";
19983
+ import { join as join37 } from "node:path";
20067
19984
  function publicSeatArgv(owner) {
20068
19985
  return {
20069
19986
  parse: (args) => parsePublicSeatArgv(owner, args),
@@ -20202,7 +20119,7 @@ function resolveHome(env) {
20202
20119
  return env.home ?? packageMachineHome();
20203
20120
  }
20204
20121
  function resolveAgentDir(env, home) {
20205
- return env.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? join38(home, ".pi", "agent");
20122
+ return env.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? join37(home, ".pi", "agent");
20206
20123
  }
20207
20124
  function parseThinking(value) {
20208
20125
  return value;
@@ -20974,7 +20891,7 @@ __export(public_role_summons_exports, {
20974
20891
  import { execFile as execFile3 } from "node:child_process";
20975
20892
  import { existsSync as existsSync10 } from "node:fs";
20976
20893
  import { realpath as realpath6 } from "node:fs/promises";
20977
- import { join as join39 } from "node:path";
20894
+ import { join as join38 } from "node:path";
20978
20895
  import { promisify as promisify3 } from "node:util";
20979
20896
  function createCapturingIo() {
20980
20897
  const chunks = [];
@@ -20998,7 +20915,7 @@ function parentDir(path) {
20998
20915
  function walkPackageRoot(start) {
20999
20916
  let dir = start;
21000
20917
  for (let i = 0; i < 12; i += 1) {
21001
- if (existsSync10(join39(dir, "package.json")) && existsSync10(join39(dir, "souls"))) {
20918
+ if (existsSync10(join38(dir, "package.json")) && existsSync10(join38(dir, "souls"))) {
21002
20919
  return dir;
21003
20920
  }
21004
20921
  const parent = parentDir(dir);
@@ -21114,7 +21031,7 @@ async function createSummonEnv(options, afterHost) {
21114
21031
  async function summonPublicRole(options) {
21115
21032
  const packageRoot = resolveSummonsPackageRoot(options.packageRoot);
21116
21033
  const home = await resolveSummonHome(options);
21117
- const agentDir = options.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? join39(home, ".pi", "agent");
21034
+ const agentDir = options.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? join38(home, ".pi", "agent");
21118
21035
  const {
21119
21036
  loadCredentialProviders: loadCredentialProviders2,
21120
21037
  loadPublicCliConfig: loadPublicCliConfig2,
@@ -21622,7 +21539,7 @@ var init_compliance_transport = __esm({
21622
21539
  });
21623
21540
 
21624
21541
  // src/role-run-relocation.ts
21625
- import { join as join40, sep as sep5 } from "node:path";
21542
+ import { join as join39, sep as sep5 } from "node:path";
21626
21543
  function rewriteRunDirectoryPathValue(value, oldRunDirectory, newRunDirectory) {
21627
21544
  if (typeof value !== "string") return value;
21628
21545
  if (value === oldRunDirectory) return newRunDirectory;
@@ -21750,8 +21667,8 @@ __export(run_lifecycle_exports, {
21750
21667
  renderResumeCommand: () => renderResumeCommand,
21751
21668
  writeRoleRunState: () => writeRoleRunState
21752
21669
  });
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";
21754
- import { basename as basename10, join as join41 } from "node:path";
21670
+ import { chmod, lstat as lstat7, open as open3, readdir as readdir7, readFile as readFile22, unlink as unlink5, writeFile as writeFile9 } from "node:fs/promises";
21671
+ import { basename as basename10, join as join40 } from "node:path";
21755
21672
  function buildAutoResumeContinuationPrompt(options) {
21756
21673
  return appendEngineSessionMaterial(
21757
21674
  [RESUME_TRANSPORT_ENVELOPE],
@@ -21776,8 +21693,8 @@ function renderResumeCommand(runId) {
21776
21693
  }
21777
21694
  async function writeRoleRunState(runDirectory, record4) {
21778
21695
  const payload = { ...record4, runDirectory };
21779
- await writeFile10(
21780
- join41(runDirectory, RUN_STATE_FILE),
21696
+ await writeFile9(
21697
+ join40(runDirectory, RUN_STATE_FILE),
21781
21698
  `${JSON.stringify(payload, null, 2)}
21782
21699
  `,
21783
21700
  "utf8"
@@ -21827,9 +21744,9 @@ function parseCurrentCourtState(raw) {
21827
21744
  async function readRoleRunStateRaw(runDirectory) {
21828
21745
  let raw;
21829
21746
  try {
21830
- raw = JSON.parse(await readFile23(join41(runDirectory, RUN_STATE_FILE), "utf8"));
21747
+ raw = JSON.parse(await readFile22(join40(runDirectory, RUN_STATE_FILE), "utf8"));
21831
21748
  } catch (error) {
21832
- if (errorCodeOf2(error) === "ENOENT") return void 0;
21749
+ if (errorCodeOf(error) === "ENOENT") return void 0;
21833
21750
  throw error;
21834
21751
  }
21835
21752
  return raw;
@@ -21920,8 +21837,8 @@ async function writeRoleRunStateDisk(runDirectory, disk) {
21920
21837
  ...disk.resumable === void 0 ? {} : { resumable: disk.resumable },
21921
21838
  ...disk.currentCourt === void 0 ? {} : { currentCourt: disk.currentCourt }
21922
21839
  };
21923
- await writeFile10(
21924
- join41(runDirectory, RUN_STATE_FILE),
21840
+ await writeFile9(
21841
+ join40(runDirectory, RUN_STATE_FILE),
21925
21842
  `${JSON.stringify(payload, null, 2)}
21926
21843
  `,
21927
21844
  "utf8"
@@ -22074,7 +21991,7 @@ function describeErrorIdentity(error) {
22074
21991
  const message = typeof candidate?.message === "string" && candidate.message !== "" ? `: ${candidate.message}` : "";
22075
21992
  return `${name}${code}${message}`;
22076
21993
  }
22077
- function errorCodeOf2(error) {
21994
+ function errorCodeOf(error) {
22078
21995
  return error.code;
22079
21996
  }
22080
21997
  function isProcessAlive(pid) {
@@ -22082,15 +21999,15 @@ function isProcessAlive(pid) {
22082
21999
  process.kill(pid, 0);
22083
22000
  return true;
22084
22001
  } catch (error) {
22085
- return errorCodeOf2(error) !== "ESRCH";
22002
+ return errorCodeOf(error) !== "ESRCH";
22086
22003
  }
22087
22004
  }
22088
22005
  async function autopsyWriterLock(lockPath) {
22089
22006
  let content;
22090
22007
  try {
22091
- content = await readFile23(lockPath, "utf8");
22008
+ content = await readFile22(lockPath, "utf8");
22092
22009
  } catch (error) {
22093
- if (errorCodeOf2(error) === "ENOENT") return { verdict: "absent" };
22010
+ if (errorCodeOf(error) === "ENOENT") return { verdict: "absent" };
22094
22011
  return { verdict: "unknown", reason: "unreadable", readFailure: error };
22095
22012
  }
22096
22013
  const normalized = content.trim();
@@ -22122,8 +22039,8 @@ async function reclaimStaleWriterLock(lockPath, runDirectory) {
22122
22039
  await unlink5(lockPath);
22123
22040
  return { reclaimed: true };
22124
22041
  } catch (error) {
22125
- if (errorCodeOf2(error) === "ENOENT") return { reclaimed: false };
22126
- if (errorCodeOf2(error) !== "EACCES") throw error;
22042
+ if (errorCodeOf(error) === "ENOENT") return { reclaimed: false };
22043
+ if (errorCodeOf(error) !== "EACCES") throw error;
22127
22044
  await chmod(runDirectory, 493);
22128
22045
  return { reclaimed: false, eaccesFailure: error };
22129
22046
  }
@@ -22147,7 +22064,7 @@ async function createWriterLease(lockPath, runDirectory, reportCleanupFailure) {
22147
22064
  },
22148
22065
  relocate(nextRunDirectory) {
22149
22066
  currentRunDirectory = nextRunDirectory;
22150
- currentLockPath = join41(nextRunDirectory, WRITER_LOCK_FILE);
22067
+ currentLockPath = join40(nextRunDirectory, WRITER_LOCK_FILE);
22151
22068
  },
22152
22069
  async release() {
22153
22070
  if (released) return;
@@ -22156,7 +22073,7 @@ async function createWriterLease(lockPath, runDirectory, reportCleanupFailure) {
22156
22073
  try {
22157
22074
  await unlink5(currentLockPath);
22158
22075
  } catch (error) {
22159
- if (errorCodeOf2(error) === "EACCES") {
22076
+ if (errorCodeOf(error) === "EACCES") {
22160
22077
  try {
22161
22078
  await chmod(currentRunDirectory, 493);
22162
22079
  await unlink5(currentLockPath);
@@ -22186,17 +22103,17 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
22186
22103
  };
22187
22104
  const reportReadFailure = (error) => {
22188
22105
  reportDiagnostic(
22189
- `writer lease lock read failed (holder liveness unverifiable; lock left in place) at ${join41(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
22106
+ `writer lease lock read failed (holder liveness unverifiable; lock left in place) at ${join40(runDirectory, WRITER_LOCK_FILE)}: ${describeErrorIdentity(error)}`
22190
22107
  );
22191
22108
  };
22192
- const lockPath = join41(runDirectory, WRITER_LOCK_FILE);
22109
+ const lockPath = join40(runDirectory, WRITER_LOCK_FILE);
22193
22110
  let lastAutopsy = { verdict: "absent" };
22194
22111
  let lastReclaimFailure;
22195
22112
  for (let reclaimsLeft = WRITER_LEASE_RECLAIM_ROUNDS; ; reclaimsLeft -= 1) {
22196
22113
  try {
22197
22114
  return await createWriterLease(lockPath, runDirectory, reportCleanupFailure);
22198
22115
  } catch (error) {
22199
- if (errorCodeOf2(error) !== "EEXIST") throw error;
22116
+ if (errorCodeOf(error) !== "EEXIST") throw error;
22200
22117
  }
22201
22118
  lastAutopsy = await autopsyWriterLock(lockPath);
22202
22119
  if (lastAutopsy.verdict === "unknown" && lastAutopsy.reason === "unreadable") {
@@ -22244,12 +22161,12 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
22244
22161
  async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole) {
22245
22162
  if (runId.trim() === "") return void 0;
22246
22163
  const ledgerHome = resolveActivationLedgerHome(home);
22247
- const booksRoot = join41(ledgerHome, "books");
22164
+ const booksRoot = join40(ledgerHome, "books");
22248
22165
  let bookKeys;
22249
22166
  try {
22250
- bookKeys = await readdir8(booksRoot);
22167
+ bookKeys = await readdir7(booksRoot);
22251
22168
  } catch (error) {
22252
- if (errorCodeOf2(error) === "ENOENT") return void 0;
22169
+ if (errorCodeOf(error) === "ENOENT") return void 0;
22253
22170
  throw error;
22254
22171
  }
22255
22172
  const matches = [];
@@ -22260,7 +22177,7 @@ async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole) {
22260
22177
  try {
22261
22178
  runDirectories = await listBookRunDirectories(bookDir);
22262
22179
  } catch (error) {
22263
- if (errorCodeOf2(error) === "ENOENT") continue;
22180
+ if (errorCodeOf(error) === "ENOENT") continue;
22264
22181
  throw error;
22265
22182
  }
22266
22183
  for (const runDirectory of runDirectories) {
@@ -22285,10 +22202,10 @@ async function readRunParentPath(runDirectory) {
22285
22202
  let raw;
22286
22203
  try {
22287
22204
  raw = JSON.parse(
22288
- await readFile23(join41(runDirectory, "admitted-request.json"), "utf8")
22205
+ await readFile22(join40(runDirectory, "admitted-request.json"), "utf8")
22289
22206
  );
22290
22207
  } catch (error) {
22291
- if (errorCodeOf2(error) === "ENOENT") return void 0;
22208
+ if (errorCodeOf(error) === "ENOENT") return void 0;
22292
22209
  throw error;
22293
22210
  }
22294
22211
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
@@ -22306,12 +22223,12 @@ async function readRunParentPath(runDirectory) {
22306
22223
  async function runHasFormedSessionPrincipal(runDirectory) {
22307
22224
  const disk = await readRoleRunStateDisk(runDirectory);
22308
22225
  if (disk === void 0) return false;
22309
- const sessionFile = typeof disk.principalWire.sessionFile === "string" && disk.principalWire.sessionFile.trim() !== "" ? disk.principalWire.sessionFile : join41(disk.principalWire.sessionDirectory, "session.jsonl");
22226
+ const sessionFile = typeof disk.principalWire.sessionFile === "string" && disk.principalWire.sessionFile.trim() !== "" ? disk.principalWire.sessionFile : join40(disk.principalWire.sessionDirectory, "session.jsonl");
22310
22227
  try {
22311
22228
  const stat2 = await lstat7(sessionFile);
22312
22229
  return stat2.isFile() && !stat2.isSymbolicLink();
22313
22230
  } catch (error) {
22314
- if (errorCodeOf2(error) === "ENOENT") return false;
22231
+ if (errorCodeOf(error) === "ENOENT") return false;
22315
22232
  throw error;
22316
22233
  }
22317
22234
  }
@@ -22324,10 +22241,10 @@ async function findLatestRunIdForSeatTicket(input) {
22324
22241
  let runDirectories;
22325
22242
  try {
22326
22243
  runDirectories = await listBookRunDirectories(
22327
- input.ticketNumber === void 0 ? bookDir : join41(bookDir, String(input.ticketNumber))
22244
+ input.ticketNumber === void 0 ? bookDir : join40(bookDir, String(input.ticketNumber))
22328
22245
  );
22329
22246
  } catch (error) {
22330
- if (errorCodeOf2(error) === "ENOENT") return void 0;
22247
+ if (errorCodeOf(error) === "ENOENT") return void 0;
22331
22248
  throw error;
22332
22249
  }
22333
22250
  const suffix = `@${input.role}`;
@@ -22451,7 +22368,7 @@ async function loadResumableRunRecord(home, runId, authority, allowUnformedAdmit
22451
22368
  let sourceRun;
22452
22369
  try {
22453
22370
  const raw = JSON.parse(
22454
- await readFile23(run.admittedRequestPath, "utf8")
22371
+ await readFile22(run.admittedRequestPath, "utf8")
22455
22372
  );
22456
22373
  if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) {
22457
22374
  const record4 = raw;
@@ -22574,7 +22491,7 @@ async function loadResumableRunRecord(home, runId, authority, allowUnformedAdmit
22574
22491
  let model;
22575
22492
  try {
22576
22493
  const invocationRaw = JSON.parse(
22577
- await readFile23(join41(run.runDirectory, "invocation.json"), "utf8")
22494
+ await readFile22(join40(run.runDirectory, "invocation.json"), "utf8")
22578
22495
  );
22579
22496
  if (invocationRaw !== null && typeof invocationRaw === "object" && !Array.isArray(invocationRaw)) {
22580
22497
  const rec = invocationRaw;
@@ -22958,8 +22875,8 @@ var init_run_lifecycle = __esm({
22958
22875
  });
22959
22876
 
22960
22877
  // src/archivist-record-topology.ts
22961
- import { createHash as createHash7 } from "node:crypto";
22962
- import { join as join42 } from "node:path";
22878
+ import { createHash as createHash6 } from "node:crypto";
22879
+ import { join as join41 } from "node:path";
22963
22880
  function resolveNavigatorWorkSubjectPlacement(input) {
22964
22881
  let ledgerHome;
22965
22882
  if (input.parentSessionFile !== void 0 && input.parentSessionFile.length > 0) {
@@ -22969,10 +22886,10 @@ function resolveNavigatorWorkSubjectPlacement(input) {
22969
22886
  }
22970
22887
  }
22971
22888
  ledgerHome ??= resolveActivationLedgerHome(input.home);
22972
- const digest = createHash7("sha256").update(input.subject).digest("hex").slice(0, 32);
22889
+ const digest = createHash6("sha256").update(input.subject).digest("hex").slice(0, 32);
22973
22890
  return {
22974
22891
  ledgerHome,
22975
- sessionDir: join42(
22892
+ sessionDir: join41(
22976
22893
  activationBookDirectory(ledgerHome, resolveBookKeyFromGit(input.cwd)),
22977
22894
  NAVIGATOR_RECORD_KIND,
22978
22895
  digest
@@ -23034,20 +22951,20 @@ __export(archivist_record_entry_exports, {
23034
22951
  resolveNavigatorWorkSubjectPlacement: () => resolveNavigatorWorkSubjectPlacement
23035
22952
  });
23036
22953
  import {
23037
- closeSync,
22954
+ closeSync as closeSync2,
23038
22955
  existsSync as existsSync12,
23039
- openSync,
23040
- readdirSync as readdirSync2,
22956
+ openSync as openSync2,
22957
+ readdirSync as readdirSync3,
23041
22958
  readFileSync as readFileSync4,
23042
22959
  readSync,
23043
22960
  realpathSync as realpathSync3,
23044
- statSync as statSync5,
23045
- writeFileSync as writeFileSync3
22961
+ statSync as statSync6,
22962
+ writeFileSync as writeFileSync2
23046
22963
  } from "node:fs";
23047
- import { dirname as dirname23, resolve as resolve16, join as join43 } from "node:path";
22964
+ import { dirname as dirname23, resolve as resolve16, join as join42 } from "node:path";
23048
22965
  import { StringDecoder } from "node:string_decoder";
23049
22966
  function readCurrentSession(sessionDir) {
23050
- const ledger = join43(sessionDir, CURRENT_SESSION_LEDGER);
22967
+ const ledger = join42(sessionDir, CURRENT_SESSION_LEDGER);
23051
22968
  try {
23052
22969
  const value = JSON.parse(readFileSync4(ledger, "utf8"));
23053
22970
  if (typeof value !== "object" || value === null || typeof value.sessionFile !== "string" || value.sessionFile.length === 0) {
@@ -23062,9 +22979,9 @@ function readCurrentSession(sessionDir) {
23062
22979
  }
23063
22980
  }
23064
22981
  function writeCurrentSession(sessionDir, sessionFile) {
23065
- const ledger = join43(sessionDir, CURRENT_SESSION_LEDGER);
22982
+ const ledger = join42(sessionDir, CURRENT_SESSION_LEDGER);
23066
22983
  try {
23067
- writeFileSync3(ledger, `${JSON.stringify({ sessionFile })}
22984
+ writeFileSync2(ledger, `${JSON.stringify({ sessionFile })}
23068
22985
  `, { flag: "wx" });
23069
22986
  } catch (error) {
23070
22987
  throw new ActivationLedgerError(
@@ -23078,10 +22995,10 @@ function isCurrentSessionClaimRace(error) {
23078
22995
  return errnoCode(error.cause) === "EEXIST";
23079
22996
  }
23080
22997
  function currentSessionLedgerPath(sessionDir) {
23081
- return join43(sessionDir, CURRENT_SESSION_LEDGER);
22998
+ return join42(sessionDir, CURRENT_SESSION_LEDGER);
23082
22999
  }
23083
23000
  function readBoundedSessionHeader(filePath) {
23084
- const fd = openSync(filePath, "r");
23001
+ const fd = openSync2(filePath, "r");
23085
23002
  try {
23086
23003
  const buffer = Buffer.allocUnsafe(SESSION_HEADER_CHUNK_BYTES);
23087
23004
  const decoder2 = new StringDecoder("utf8");
@@ -23129,7 +23046,7 @@ function readBoundedSessionHeader(filePath) {
23129
23046
  }
23130
23047
  return void 0;
23131
23048
  } finally {
23132
- closeSync(fd);
23049
+ closeSync2(fd);
23133
23050
  }
23134
23051
  }
23135
23052
  function parseSessionHeaderLine(line2) {
@@ -23155,7 +23072,7 @@ function mostRecentNavigatorSessionFile(sessionDir, cwd) {
23155
23072
  const absoluteCwd = resolve16(cwd);
23156
23073
  let names;
23157
23074
  try {
23158
- names = readdirSync2(absoluteSessionDir);
23075
+ names = readdirSync3(absoluteSessionDir);
23159
23076
  } catch (error) {
23160
23077
  throw new ActivationLedgerError(
23161
23078
  `archivist navigator nest is not readable (${sessionDir}): ${errorText(error)}`,
@@ -23165,10 +23082,10 @@ function mostRecentNavigatorSessionFile(sessionDir, cwd) {
23165
23082
  const matched = [];
23166
23083
  for (const name of names) {
23167
23084
  if (!name.endsWith(".jsonl")) continue;
23168
- const filePath = join43(absoluteSessionDir, name);
23085
+ const filePath = join42(absoluteSessionDir, name);
23169
23086
  let st;
23170
23087
  try {
23171
- st = statSync5(filePath);
23088
+ st = statSync6(filePath);
23172
23089
  } catch (error) {
23173
23090
  throw new ActivationLedgerError(
23174
23091
  `archivist navigator session file is not stat-able (${filePath}): ${errorText(error)}`,
@@ -23277,7 +23194,7 @@ function createRecordSessionOpen(options, host = piRecordSessionHost) {
23277
23194
  if (!physicallyContainedIn(ledgerHome, parentResolved)) {
23278
23195
  throw new Error("Durable record ownership requires a parent session inside the ledger home");
23279
23196
  }
23280
- sessionDir = join43(dirname23(parentResolved), options.kind);
23197
+ sessionDir = join42(dirname23(parentResolved), options.kind);
23281
23198
  parentSession = parentFile;
23282
23199
  mayResumeSameNest = options.kind === WORKER_SUBMISSION_GATE_KIND;
23283
23200
  }
@@ -23309,7 +23226,7 @@ function createRecordSessionOpen(options, host = piRecordSessionHost) {
23309
23226
  if (file !== void 0 && !existsSync12(file)) {
23310
23227
  const header = session.getHeader();
23311
23228
  if (header !== null && header.type === "session") {
23312
- writeFileSync3(file, `${JSON.stringify(header)}
23229
+ writeFileSync2(file, `${JSON.stringify(header)}
23313
23230
  `, { flag: "wx" });
23314
23231
  session.setSessionFile(file);
23315
23232
  }
@@ -23345,11 +23262,11 @@ import { randomUUID as randomUUID11 } from "node:crypto";
23345
23262
  // src/role-runtime-dependencies.ts
23346
23263
  init_collector_github();
23347
23264
  init_doctor_evidence();
23348
- import { readFile as readFile26 } from "node:fs/promises";
23349
- import { join as join47 } from "node:path";
23265
+ import { readFile as readFile25 } from "node:fs/promises";
23266
+ import { join as join46 } from "node:path";
23350
23267
 
23351
23268
  // src/navigator-attendance.ts
23352
- import { createHash as createHash8 } from "node:crypto";
23269
+ import { createHash as createHash7 } from "node:crypto";
23353
23270
  init_navigator_invocation_identity();
23354
23271
  init_packaged_role_registry();
23355
23272
  init_activation_ledger_topology();
@@ -23553,7 +23470,7 @@ init_packaged_role_registry();
23553
23470
 
23554
23471
  // src/navigator-work-base.ts
23555
23472
  init_atomic_write();
23556
- import { existsSync as existsSync4, realpathSync as realpathSync2 } from "node:fs";
23473
+ import { existsSync as existsSync3, realpathSync as realpathSync2 } from "node:fs";
23557
23474
  import { readFile as readFile6 } from "node:fs/promises";
23558
23475
  import { basename as basename3, dirname as dirname7, join as join7, resolve as resolve5 } from "node:path";
23559
23476
  var NAVIGATOR_WORK_CONTEXT_BASENAME = "work-context.json";
@@ -23577,7 +23494,7 @@ function canonicalNavigatorWorkContextFile(path) {
23577
23494
  }
23578
23495
  }
23579
23496
  async function persistNavigatorWorkBase(sessionDir, body) {
23580
- if (sessionDir.trim() === "" || !existsSync4(sessionDir)) return void 0;
23497
+ if (sessionDir.trim() === "" || !existsSync3(sessionDir)) return void 0;
23581
23498
  if (body.authority.trim() === "") return void 0;
23582
23499
  const path = navigatorWorkContextFile(sessionDir);
23583
23500
  const next = `${JSON.stringify({ subject: body.subject, authority: body.authority })}
@@ -23910,7 +23827,7 @@ function navigatorSubjectKey(subjectRoot, subject, provenance = "role_input") {
23910
23827
  if (provenance === "placeholder") return subjectRoot;
23911
23828
  const normalized = subject.trim().replace(/\s+/g, " ");
23912
23829
  if (normalized === "") return subjectRoot;
23913
- return `${subjectRoot}#${createHash8("sha256").update(normalized).digest("hex").slice(0, 32)}`;
23830
+ return `${subjectRoot}#${createHash7("sha256").update(normalized).digest("hex").slice(0, 32)}`;
23914
23831
  }
23915
23832
  function navigatorSubjectKeyForInput(subjectRoot, reference, cwd = process.cwd()) {
23916
23833
  if (issueRoot(subjectRoot) !== void 0 || !subjectRoot.includes("/.ak/work/")) return subjectRoot;
@@ -24311,7 +24228,7 @@ function createNavigatorAttendance(options) {
24311
24228
  // src/navigator-work-context.ts
24312
24229
  init_doctor_evidence();
24313
24230
  init_host_contracts();
24314
- import { readFile as readFile24 } from "node:fs/promises";
24231
+ import { readFile as readFile23 } from "node:fs/promises";
24315
24232
  import { resolve as resolve18 } from "node:path";
24316
24233
  init_notary_source_run();
24317
24234
  init_packaged_role_registry();
@@ -24325,7 +24242,7 @@ function navigatorInputReference(getFlag, role) {
24325
24242
  async function loadNavigatorWorkContext(options) {
24326
24243
  const reference = navigatorInputReference(options.getFlag, options.role);
24327
24244
  const subjectMode = packagedNavigatorSubject(options.role);
24328
- const input = reference === void 0 || subjectMode === "case" || subjectMode === "source-run" ? void 0 : await readFile24(reference, "utf8");
24245
+ const input = reference === void 0 || subjectMode === "case" || subjectMode === "source-run" ? void 0 : await readFile23(reference, "utf8");
24329
24246
  const subjectRoot = subjectPath(reference ?? options.context.sessionManager.getSessionDir(), options.context.cwd);
24330
24247
  let subjectKey = reference === void 0 ? subjectRoot : navigatorSubjectKeyForInput(subjectRoot, reference, options.context.cwd);
24331
24248
  let subject = input ?? `work subject: ${subjectKey}`;
@@ -24382,7 +24299,7 @@ async function loadNavigatorWorkContext(options) {
24382
24299
  let authorityMaterial;
24383
24300
  for (const path of authorityFiles) {
24384
24301
  try {
24385
- const content = await readFile24(path, "utf8");
24302
+ const content = await readFile23(path, "utf8");
24386
24303
  if (content.trim() !== "") {
24387
24304
  authorityMaterial = content;
24388
24305
  break;
@@ -24413,7 +24330,7 @@ init_submission_ledger();
24413
24330
  init_collector_ledger();
24414
24331
  import { randomUUID as randomUUID8 } from "node:crypto";
24415
24332
  import { readFileSync as readFileSync6, writeSync as writeSync2 } from "node:fs";
24416
- import { join as join46 } from "node:path";
24333
+ import { join as join45 } from "node:path";
24417
24334
  import { Value as Value4 } from "typebox/value";
24418
24335
 
24419
24336
  // src/activation-trace.ts
@@ -24461,8 +24378,8 @@ init_activation_ledger_topology();
24461
24378
  import {
24462
24379
  lstatSync as lstatSync2,
24463
24380
  realpathSync as realpathSync4,
24464
- statSync as statSync6,
24465
- writeFileSync as writeFileSync4
24381
+ statSync as statSync7,
24382
+ writeFileSync as writeFileSync3
24466
24383
  } from "node:fs";
24467
24384
  import { isAbsolute as isAbsolute11, resolve as resolve19 } from "node:path";
24468
24385
  var ActivationSessionFileMissingError = class extends Error {
@@ -24483,7 +24400,7 @@ function materializeDeferredSessionFile(sessionManager, resolvedFile) {
24483
24400
  throw new ActivationSessionFileMissingError(resolvedFile);
24484
24401
  }
24485
24402
  try {
24486
- writeFileSync4(resolvedFile, `${JSON.stringify(header)}
24403
+ writeFileSync3(resolvedFile, `${JSON.stringify(header)}
24487
24404
  `, { flag: "wx" });
24488
24405
  } catch (error) {
24489
24406
  if (errnoCode(error) !== "EEXIST") {
@@ -24536,7 +24453,7 @@ function durableSessionPointer(sessionManager) {
24536
24453
  }
24537
24454
  let info;
24538
24455
  try {
24539
- info = statSync6(realFile);
24456
+ info = statSync7(realFile);
24540
24457
  } catch (error) {
24541
24458
  throw new Error(
24542
24459
  `Workflow role activation failed to stat durable session file (${realFile}): ${errorText(error)}`,
@@ -24736,8 +24653,8 @@ init_collector_github();
24736
24653
  // src/collector-handbook.ts
24737
24654
  init_atomic_write();
24738
24655
  init_activation_ledger_topology();
24739
- import { readFile as readFile25 } from "node:fs/promises";
24740
- import { join as join45, sep as sep6 } from "node:path";
24656
+ import { readFile as readFile24 } from "node:fs/promises";
24657
+ import { join as join44, sep as sep6 } from "node:path";
24741
24658
 
24742
24659
  // src/collector-tool-schemas.ts
24743
24660
  init_open_tool_schema();
@@ -24852,7 +24769,7 @@ function resolveCollectorHandbookRoot(sessionPath) {
24852
24769
  throw new Error(`\u901A\u8FDB\u53F8\u624B\u518C\u62D2\u7EDD\u4E0D\u5B89\u5168 bookKey ${JSON.stringify(bookKey)}`);
24853
24770
  }
24854
24771
  const ledgerHome = resolveActivationLedgerHomeForPath(sessionPath);
24855
- const root = join45(activationBookDirectory(ledgerHome, bookKey), "collector-handbook");
24772
+ const root = join44(activationBookDirectory(ledgerHome, bookKey), "collector-handbook");
24856
24773
  return { ledgerHome, bookKey, root };
24857
24774
  }
24858
24775
  function collectorHandbookRepoFileName(repositoryCanonical) {
@@ -24864,9 +24781,9 @@ function collectorHandbookRepoFileName(repositoryCanonical) {
24864
24781
  return `${repositoryCanonical.replaceAll("/", "__")}.md`;
24865
24782
  }
24866
24783
  function createCollectorHandbookStore(input) {
24867
- const generalPath = join45(input.handbookRoot, "general.md");
24868
- const repoDir = join45(input.handbookRoot, "repos");
24869
- const repoPath = join45(repoDir, collectorHandbookRepoFileName(input.repositoryCanonical));
24784
+ const generalPath = join44(input.handbookRoot, "general.md");
24785
+ const repoDir = join44(input.handbookRoot, "repos");
24786
+ const repoPath = join44(repoDir, collectorHandbookRepoFileName(input.repositoryCanonical));
24870
24787
  const assertHandbookBudget = (body, label) => {
24871
24788
  const byteLength = Buffer.byteLength(body, "utf8");
24872
24789
  if (byteLength > COLLECTOR_HANDBOOK_MAX_BYTES) {
@@ -24880,7 +24797,7 @@ function createCollectorHandbookStore(input) {
24880
24797
  ensureRealDirectoryTree(input.ledgerHome, parentDir2);
24881
24798
  assertLedgerFileInsideHome(path, input.ledgerHome);
24882
24799
  try {
24883
- const body = await readFile25(path, "utf8");
24800
+ const body = await readFile24(path, "utf8");
24884
24801
  assertHandbookBudget(body, "\u6B63\u6587");
24885
24802
  return body;
24886
24803
  } catch (error) {
@@ -25968,7 +25885,7 @@ init_worker_submission_contracts();
25968
25885
  init_submission_errors();
25969
25886
  init_worker_submission_contracts();
25970
25887
  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";
25888
+ import { existsSync as existsSync14, lstatSync as lstatSync3, readdirSync as readdirSync4, readFileSync as readFileSync5, rmdirSync, rmSync as rmSync2 } from "node:fs";
25972
25889
  import { resolve as resolve20 } from "node:path";
25973
25890
  var WORKER_SUBMISSION_GATE_RECORD_KIND = WORKER_SUBMISSION_GATE_KIND;
25974
25891
  var WORKER_COMMIT_BASELINE_ENTRY_TYPE = "commit-baseline";
@@ -26034,13 +25951,13 @@ function unsetOwnedHooksPath(file) {
26034
25951
  function rmOwnedDir(dir) {
26035
25952
  const hookPath = resolve20(dir, HOOK_FILE);
26036
25953
  if (!ownedHook(hookPath)) return;
26037
- rmSync(hookPath, { force: true });
26038
- if (existsSync14(dir) && readdirSync3(dir).length === 0) rmdirSync(dir);
25954
+ rmSync2(hookPath, { force: true });
25955
+ if (existsSync14(dir) && readdirSync4(dir).length === 0) rmdirSync(dir);
26039
25956
  }
26040
25957
  function linkedGitDirs(commonDir) {
26041
25958
  const root = resolve20(commonDir, "worktrees");
26042
25959
  if (!existsSync14(root)) return [];
26043
- return readdirSync3(root).map((name) => resolve20(root, name)).filter((dir) => lstatSync3(dir).isDirectory());
25960
+ return readdirSync4(root).map((name) => resolve20(root, name)).filter((dir) => lstatSync3(dir).isDirectory());
26044
25961
  }
26045
25962
  function uninstallPackageWorkerHooks(cwd) {
26046
25963
  let inside;
@@ -26058,13 +25975,13 @@ function uninstallPackageWorkerHooks(cwd) {
26058
25975
  clear(resolve20(commonDir, "config.worktree"));
26059
25976
  rmOwnedDir(resolve20(commonDir, HOOKS_DIR));
26060
25977
  const legacy = resolve20(commonDir, "hooks", HOOK_FILE);
26061
- if (ownedHook(legacy)) rmSync(legacy, { force: true });
25978
+ if (ownedHook(legacy)) rmSync2(legacy, { force: true });
26062
25979
  for (const gitDir of linkedGitDirs(commonDir)) {
26063
25980
  clear(resolve20(gitDir, "config.worktree"));
26064
25981
  rmOwnedDir(resolve20(gitDir, HOOKS_DIR));
26065
25982
  }
26066
25983
  }
26067
- function isRecord17(value) {
25984
+ function isRecord16(value) {
26068
25985
  return typeof value === "object" && value !== null && !Array.isArray(value);
26069
25986
  }
26070
25987
  function unfinishedReasonPresent(details) {
@@ -26080,7 +25997,7 @@ function readGateState(session) {
26080
25997
  if (entry.type !== "custom") continue;
26081
25998
  if (entry.customType === WORKER_COMMIT_BASELINE_ENTRY_TYPE) {
26082
25999
  const data = entry.data;
26083
- if (isRecord17(data) && (data.head === null || typeof data.head === "string")) {
26000
+ if (isRecord16(data) && (data.head === null || typeof data.head === "string")) {
26084
26001
  baseline = data.head;
26085
26002
  }
26086
26003
  } else if (entry.customType === WORKER_COMMIT_REMINDER_BOUNCE_ENTRY_TYPE) {
@@ -26273,11 +26190,11 @@ var FIXER_PHASES = ["plan", "apply"];
26273
26190
  function isWorkerPhase(value) {
26274
26191
  return typeof value === "string" && FIXER_PHASES.includes(value);
26275
26192
  }
26276
- function isRecord18(value) {
26193
+ function isRecord17(value) {
26277
26194
  return typeof value === "object" && value !== null && !Array.isArray(value);
26278
26195
  }
26279
26196
  function workerStatusOf(output) {
26280
- return isRecord18(output) && typeof output.status === "string" ? output.status : void 0;
26197
+ return isRecord17(output) && typeof output.status === "string" ? output.status : void 0;
26281
26198
  }
26282
26199
  function deepFreeze2(value) {
26283
26200
  if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
@@ -26963,7 +26880,7 @@ function readDiaristTicketAssertion(submitted) {
26963
26880
  function readRoleRunCoordinates(ctx, label) {
26964
26881
  const runDirectory = runDirectoryFromHostContext(ctx);
26965
26882
  if (runDirectory === void 0) throw new Error(`${label} requires AK_ROLE_RUN_DIR`);
26966
- const admittedPath = join46(runDirectory, "admitted-request.json");
26883
+ const admittedPath = join45(runDirectory, "admitted-request.json");
26967
26884
  const admitted = JSON.parse(readFileSync6(admittedPath, "utf8"));
26968
26885
  if (typeof admitted.projectRoot !== "string" || admitted.projectRoot.trim() === "") {
26969
26886
  throw new Error(`${label} admitted-request missing projectRoot (${admittedPath})`);
@@ -27316,14 +27233,6 @@ function createRoleRuntimeExtension(dependencies) {
27316
27233
  }
27317
27234
  };
27318
27235
  });
27319
- roleHost.on("before_agent_start", async (_event, ctx) => {
27320
- const runDir = runDirectoryFromHostContext(ctx);
27321
- if (runDir === void 0) return;
27322
- const { loadCaseDossierReadingMaterial: loadCaseDossierReadingMaterial2 } = await Promise.resolve().then(() => (init_case_dossier_delivery(), case_dossier_delivery_exports));
27323
- const caseDossier = await loadCaseDossierReadingMaterial2(runDir);
27324
- if (caseDossier === void 0) return;
27325
- return { readingMaterial: caseDossier };
27326
- });
27327
27236
  roleHost.on("tool_result", async (event) => {
27328
27237
  const role = selectedRole;
27329
27238
  if (role === void 0) return;
@@ -27901,19 +27810,19 @@ function loadRegisteredRoleSoul(role) {
27901
27810
  return usesSubjectSoul(role) ? loadAuditorSoulFromSubjectInput() : loadMainRoleSessionMaterials(role);
27902
27811
  }
27903
27812
  function createRoleRuntimeDependencies(packageRoot) {
27904
- const collectorHandbookSeedPath = join47(packageRoot, "resources/collector-bot-handbook.md");
27813
+ const collectorHandbookSeedPath = join46(packageRoot, "resources/collector-bot-handbook.md");
27905
27814
  const navigatorSessionFactory = createNativeNavigatorSessionFactory();
27906
27815
  return {
27907
27816
  packageRoot,
27908
27817
  loadRoleReferenceMaterials: loadPackagedRoleReferenceMaterials,
27909
27818
  loadRoleSoul: loadRegisteredRoleSoul,
27910
- loadFixPacket: (path) => readFile26(path, "utf8"),
27911
- loadCoderTask: (path) => readFile26(path, "utf8"),
27912
- loadCollectorHandbookSeed: () => readFile26(collectorHandbookSeedPath, "utf8"),
27819
+ loadFixPacket: (path) => readFile25(path, "utf8"),
27820
+ loadCoderTask: (path) => readFile25(path, "utf8"),
27821
+ loadCollectorHandbookSeed: () => readFile25(collectorHandbookSeedPath, "utf8"),
27913
27822
  createCollectorTransport: () => createGhCollectorGitHubTransport(),
27914
27823
  loadDoctorCase,
27915
27824
  loadNotarySourceRun: loadNotarySourceRunLocator,
27916
- loadMergerInput: async (path) => JSON.parse(await readFile26(path, "utf8")),
27825
+ loadMergerInput: async (path) => JSON.parse(await readFile25(path, "utf8")),
27917
27826
  loadNavigatorWorkContext: (options) => loadNavigatorWorkContext({
27918
27827
  context: options.context,
27919
27828
  role: options.role,
@@ -27938,9 +27847,9 @@ function createRoleRuntimeDependencies(packageRoot) {
27938
27847
  init_engine_detour();
27939
27848
  init_packaged_role_registry();
27940
27849
  import { randomUUID as randomUUID9 } from "node:crypto";
27941
- import { appendFile as appendFile3, mkdir as mkdir5, writeFile as writeFile11 } from "node:fs/promises";
27850
+ import { appendFile as appendFile3, mkdir as mkdir5, writeFile as writeFile10 } from "node:fs/promises";
27942
27851
  import { createServer } from "node:net";
27943
- import { dirname as dirname25, join as join48 } from "node:path";
27852
+ import { dirname as dirname25, join as join47 } from "node:path";
27944
27853
  import { fileURLToPath as fileURLToPath2 } from "node:url";
27945
27854
  init_role_activation_flags();
27946
27855
  init_submission_correctable_error();
@@ -27986,11 +27895,11 @@ async function prepareRoleEnvelope(options) {
27986
27895
  const hostAbort = new AbortController();
27987
27896
  const runId = request.runDirectory.split("/").filter(Boolean).at(-1) ?? randomUUID9();
27988
27897
  await mkdir5(request.runDirectory, { recursive: true });
27989
- let sessionFile = options.sessionFile ?? join48(request.runDirectory, "session", "session.jsonl");
27898
+ let sessionFile = options.sessionFile ?? join47(request.runDirectory, "session", "session.jsonl");
27990
27899
  await mkdir5(dirname25(sessionFile), { recursive: true });
27991
27900
  if (request.continuation.kind !== "resume") {
27992
27901
  try {
27993
- await writeFile11(
27902
+ await writeFile10(
27994
27903
  sessionFile,
27995
27904
  `${JSON.stringify({
27996
27905
  type: "session",
@@ -28506,7 +28415,7 @@ async function prepareRoleEnvelope(options) {
28506
28415
  init_session_identity();
28507
28416
 
28508
28417
  // src/headless-host/description.ts
28509
- import { join as join49 } from "node:path";
28418
+ import { join as join48 } from "node:path";
28510
28419
  function isClaudePrintDescription(description) {
28511
28420
  return description.protocol === "claude-print";
28512
28421
  }
@@ -28514,7 +28423,7 @@ function isCodexExecDescription(description) {
28514
28423
  return description.protocol === "codex-exec";
28515
28424
  }
28516
28425
  function resolveHeadlessBinary(description, operatorHome) {
28517
- return join49(operatorHome, ...description.binaryFromHome);
28426
+ return join48(operatorHome, ...description.binaryFromHome);
28518
28427
  }
28519
28428
  function headlessTurnArgs(options) {
28520
28429
  const { description } = options;
@@ -28774,30 +28683,19 @@ function headlessMcpConfigDocument(mcpServers) {
28774
28683
  }
28775
28684
 
28776
28685
  // src/headless-host/role-turn-host.ts
28777
- import { spawn as spawn4, spawnSync as spawnSync2 } from "node:child_process";
28686
+ import { spawn as spawn4, spawnSync as spawnSync3 } from "node:child_process";
28778
28687
  import { randomUUID as randomUUID10 } from "node:crypto";
28779
28688
  import { existsSync as existsSync15 } from "node:fs";
28780
- import { writeFile as writeFile12 } from "node:fs/promises";
28781
- import { dirname as dirname26, isAbsolute as isAbsolute12, join as join50, resolve as resolve21 } from "node:path";
28689
+ import { writeFile as writeFile11 } from "node:fs/promises";
28690
+ import { dirname as dirname26, isAbsolute as isAbsolute12, join as join49, resolve as resolve21 } from "node:path";
28782
28691
 
28783
28692
  // src/external-host-turn-loop.ts
28784
- init_packaged_role_registry();
28785
28693
  var EXTERNAL_ROLE_TURN_ROUND_LIMIT = 8;
28786
28694
  function mergeRoleTurnAbortSignals(prepared, request) {
28787
28695
  if (request === void 0) return prepared;
28788
28696
  if (prepared === void 0) return request;
28789
28697
  return AbortSignal.any([prepared, request]);
28790
28698
  }
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
28699
  function isHostAbortedError(error) {
28802
28700
  return typeof error === "object" && error !== null && error.code === "host-aborted";
28803
28701
  }
@@ -28817,7 +28715,7 @@ async function settleHostAborted(prepared, sessionId) {
28817
28715
  });
28818
28716
  }
28819
28717
  async function driveExternalRoleTurnRounds(prepared, request, driver) {
28820
- let prompt = promptWithPriorNativePaths(prepared.prompt, request);
28718
+ let prompt = prepared.prompt;
28821
28719
  const abortSignal = mergeRoleTurnAbortSignals(prepared.abortSignal, request.signal);
28822
28720
  let stderr = "";
28823
28721
  for (let attempt = 0; attempt < EXTERNAL_ROLE_TURN_ROUND_LIMIT; attempt += 1) {
@@ -28872,31 +28770,8 @@ function renderSystemPromptOverride(authority) {
28872
28770
  return renderAgentStartMaterials(authority.body, authority.materials);
28873
28771
  }
28874
28772
 
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
28773
  // src/headless-host/role-turn-host.ts
28774
+ init_host_session_record();
28900
28775
  init_navigator_output();
28901
28776
  function failure(cause, name, code, details, diagnostic) {
28902
28777
  return {
@@ -28998,7 +28873,7 @@ function formatCodexFailurePayload(payload) {
28998
28873
  function cwdIsGitWorkTree(cwd) {
28999
28874
  let dir = cwd;
29000
28875
  for (; ; ) {
29001
- if (existsSync15(join50(dir, ".git"))) return true;
28876
+ if (existsSync15(join49(dir, ".git"))) return true;
29002
28877
  const parent = dirname26(dir);
29003
28878
  if (parent === dir) return false;
29004
28879
  dir = parent;
@@ -29008,7 +28883,7 @@ function resolveGitCommonDir(cwd) {
29008
28883
  if (!cwdIsGitWorkTree(cwd)) return void 0;
29009
28884
  let result;
29010
28885
  try {
29011
- result = spawnSync2("git", ["rev-parse", "--git-common-dir"], {
28886
+ result = spawnSync3("git", ["rev-parse", "--git-common-dir"], {
29012
28887
  cwd,
29013
28888
  encoding: "utf8"
29014
28889
  });
@@ -29094,8 +28969,15 @@ function spawnHeadlessTurn(options) {
29094
28969
  lineBuffer = "";
29095
28970
  }
29096
28971
  };
28972
+ let aborted = false;
29097
28973
  const settle = (code) => {
29098
28974
  if (settled) return;
28975
+ if (aborted) {
28976
+ settled = true;
28977
+ if (timer !== void 0) clearTimeout(timer);
28978
+ reject(hostAbortedError("headless host aborted"));
28979
+ return;
28980
+ }
29099
28981
  flushStdoutLines("", true);
29100
28982
  if (settled) return;
29101
28983
  settled = true;
@@ -29108,11 +28990,9 @@ function spawnHeadlessTurn(options) {
29108
28990
  resolve22({ code, stdout: resultStdout, stderr, timedOut });
29109
28991
  };
29110
28992
  const onAbort = () => {
29111
- child.kill("SIGTERM");
29112
28993
  if (settled) return;
29113
- settled = true;
29114
- if (timer !== void 0) clearTimeout(timer);
29115
- reject(hostAbortedError("headless host aborted"));
28994
+ aborted = true;
28995
+ child.kill("SIGTERM");
29116
28996
  };
29117
28997
  child.stdout.setEncoding("utf8").on("data", (chunk) => {
29118
28998
  flushStdoutLines(chunk, false);
@@ -29127,7 +29007,10 @@ function spawnHeadlessTurn(options) {
29127
29007
  options.signal?.removeEventListener("abort", onAbort);
29128
29008
  reject(error);
29129
29009
  });
29130
- child.on("close", (code) => settle(code));
29010
+ child.on("close", (code) => {
29011
+ options.onClose?.();
29012
+ settle(code);
29013
+ });
29131
29014
  options.signal?.addEventListener("abort", onAbort, { once: true });
29132
29015
  if (options.timeoutMs !== void 0 && options.timeoutMs > 0) {
29133
29016
  timer = setTimeout(() => {
@@ -29206,14 +29089,14 @@ function createHeadlessRoleTurnHost(config) {
29206
29089
  await config.sessionIdentity.bind(request.principal, sessionId);
29207
29090
  }
29208
29091
  const env = { ...process.env, ...config.env ?? {} };
29209
- const systemPromptPath = join50(request.runDirectory, "headless-system-prompt.txt");
29210
- await writeFile12(systemPromptPath, systemPrompt, "utf8");
29092
+ const systemPromptPath = join49(request.runDirectory, "headless-system-prompt.txt");
29093
+ await writeFile11(systemPromptPath, systemPrompt, "utf8");
29211
29094
  let mcpConfigPath;
29212
29095
  let outputSchemaPath;
29213
29096
  if (codex) {
29214
29097
  if (prepared.terminatingToolName !== NAVIGATOR_OUTPUT_TOOL_NAME) {
29215
- outputSchemaPath = join50(request.runDirectory, "headless-output-schema.json");
29216
- await writeFile12(
29098
+ outputSchemaPath = join49(request.runDirectory, "headless-output-schema.json");
29099
+ await writeFile11(
29217
29100
  outputSchemaPath,
29218
29101
  `${JSON.stringify(closeJsonSchemaForCodex(prepared.jsonSchema), null, 2)}
29219
29102
  `,
@@ -29221,8 +29104,8 @@ function createHeadlessRoleTurnHost(config) {
29221
29104
  );
29222
29105
  }
29223
29106
  } else {
29224
- mcpConfigPath = join50(request.runDirectory, "headless-mcp-config.json");
29225
- await writeFile12(
29107
+ mcpConfigPath = join49(request.runDirectory, "headless-mcp-config.json");
29108
+ await writeFile11(
29226
29109
  mcpConfigPath,
29227
29110
  `${JSON.stringify(headlessMcpConfigDocument(prepared.mcpServers), null, 2)}
29228
29111
  `,
@@ -29230,236 +29113,268 @@ function createHeadlessRoleTurnHost(config) {
29230
29113
  );
29231
29114
  }
29232
29115
  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) {
29116
+ let exitedSessionId;
29117
+ try {
29118
+ outcome = await driveExternalRoleTurnRounds(prepared, request, {
29119
+ roundLimitName: "HeadlessRoundLimit",
29120
+ currentSessionId: () => sessionId,
29121
+ afterRetry() {
29122
+ sessionKind = "resume";
29123
+ },
29124
+ async runRound({ prompt, abortSignal }) {
29125
+ let args;
29126
+ try {
29127
+ const gitCommonDir = codex ? resolveGitCommonDir(request.cwd) : void 0;
29128
+ args = buildTurnArgs({
29129
+ description: config.description,
29130
+ systemPromptPath,
29131
+ // #959: navigator prose exit — no closed JSON schema on claude either.
29132
+ ...prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME ? {} : { jsonSchema: prepared.jsonSchema },
29133
+ mcpServers: prepared.mcpServers,
29134
+ ...mcpConfigPath === void 0 ? {} : { mcpConfigPath },
29135
+ ...outputSchemaPath === void 0 ? {} : { outputSchemaPath },
29136
+ ...request.model?.model !== void 0 ? { model: request.model.model } : {},
29137
+ ...request.model?.thinking !== void 0 ? { effort: request.model.thinking } : {},
29138
+ sessionId,
29139
+ sessionKind,
29140
+ cwd: request.cwd,
29141
+ ...gitCommonDir === void 0 ? {} : { writableRoots: [gitCommonDir] }
29142
+ });
29143
+ } catch (error) {
29144
+ const message = error instanceof Error ? error.message : String(error);
29300
29145
  return {
29301
29146
  status: "terminal",
29302
- result: failure("output", "HeadlessCliError", "codex-turn-failed", {
29303
- diagnostic: observedHostFailure,
29304
- sessionRecordDiagnostic: message,
29305
- sessionId
29306
- }, observedHostFailure)
29147
+ result: failure("session", "HeadlessArgvFailure", "argv-failed", { diagnostic: message }, message)
29307
29148
  };
29308
29149
  }
29309
- const isRecordFailure = typeof error === "object" && error !== null && (error.knownCause === "session" || error.name === "SitianInfrastructureError");
29310
- if (isRecordFailure) {
29150
+ const codexObserver = codex ? createCodexExecTurnObserver() : void 0;
29151
+ let pointerRecorded = false;
29152
+ let codexIdObserved = false;
29153
+ if (sessionId !== void 0 && sessionId !== "") {
29154
+ pointerRecorded = recordNativeSessionPointer({
29155
+ host: config.hostName,
29156
+ sessionId,
29157
+ cwd: request.cwd,
29158
+ sessionParent,
29159
+ home: request.home
29160
+ }) !== void 0;
29161
+ }
29162
+ let spawned;
29163
+ let childExited = false;
29164
+ try {
29165
+ spawned = await spawnHeadlessTurn({
29166
+ onClose() {
29167
+ childExited = true;
29168
+ },
29169
+ binary: config.binary,
29170
+ args,
29171
+ cwd: request.cwd,
29172
+ env,
29173
+ stdin: prompt,
29174
+ ...abortSignal === void 0 ? {} : { signal: abortSignal },
29175
+ ...request.timeoutMs === void 0 ? {} : { timeoutMs: request.timeoutMs },
29176
+ onStdoutLine(line2) {
29177
+ const trimmed = line2.trim();
29178
+ if (trimmed === "") return;
29179
+ let event;
29180
+ try {
29181
+ event = JSON.parse(trimmed);
29182
+ } catch {
29183
+ return;
29184
+ }
29185
+ codexObserver?.observe(event);
29186
+ if (!codex && typeof event === "object" && event !== null && "session_id" in event && typeof event.session_id === "string" && event.session_id !== "" && event.session_id !== sessionId) {
29187
+ sessionId = event.session_id;
29188
+ recordNativeSessionPointer({ host: config.hostName, sessionId, cwd: request.cwd, sessionParent, home: request.home });
29189
+ }
29190
+ if (codex && !codexIdObserved) {
29191
+ const tid = codexObserver?.result().threadId;
29192
+ if (tid !== void 0 && tid !== "") {
29193
+ codexIdObserved = true;
29194
+ pointerRecorded = recordNativeSessionPointer({
29195
+ host: config.hostName,
29196
+ sessionId: tid,
29197
+ cwd: request.cwd,
29198
+ sessionParent,
29199
+ home: request.home
29200
+ }) !== void 0;
29201
+ }
29202
+ }
29203
+ }
29204
+ });
29205
+ const roundSessionId = (codex ? codexObserver?.result().threadId : void 0) ?? sessionId;
29206
+ exitedSessionId = roundSessionId;
29207
+ if (codex && roundSessionId !== void 0 && roundSessionId !== "" && !pointerRecorded) {
29208
+ recordNativeSessionPointer({ host: config.hostName, sessionId: roundSessionId, cwd: request.cwd, sessionParent, home: request.home });
29209
+ }
29210
+ } catch (error) {
29211
+ if (childExited) exitedSessionId = (codex ? codexObserver?.result().threadId : void 0) ?? sessionId;
29212
+ if (isHostAbortedError(error)) throw error;
29213
+ const message = error instanceof Error ? error.message : String(error);
29214
+ const observedHostFailure = codexObserver?.result().failureDiagnostic;
29215
+ if (observedHostFailure !== void 0) {
29216
+ return {
29217
+ status: "terminal",
29218
+ result: failure("output", "HeadlessCliError", "codex-turn-failed", {
29219
+ diagnostic: observedHostFailure,
29220
+ sessionRecordDiagnostic: message,
29221
+ sessionId
29222
+ }, observedHostFailure)
29223
+ };
29224
+ }
29311
29225
  return {
29312
29226
  status: "terminal",
29313
- result: failure(
29314
- "session",
29315
- "HostSessionRecordFailure",
29316
- "host-session-record-failed",
29317
- { diagnostic: message, sessionId },
29318
- message
29319
- )
29227
+ result: failure("activation", "HeadlessSpawnFailure", "spawn-failed", {
29228
+ diagnostic: message,
29229
+ binary: config.binary
29230
+ }, message)
29320
29231
  };
29321
29232
  }
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) {
29233
+ if (spawned.timedOut) {
29352
29234
  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
- }
29235
+ cause: "timeout",
29236
+ identity: { name: "HeadlessTimeout", code: "timeout" },
29237
+ details: { sessionId }
29361
29238
  });
29362
29239
  }
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 }
29240
+ if (codex) {
29241
+ const observation = codexObserver.result();
29242
+ if (observation.threadId !== void 0 && observation.threadId !== "") {
29243
+ sessionId = observation.threadId;
29244
+ }
29245
+ let sessionBindingDiagnostic;
29246
+ const hostFailed = observation.failureDiagnostic !== void 0 || spawned.code !== 0 && spawned.code !== null;
29247
+ if (hostFailed && observation.threadId !== void 0 && observation.threadId !== "") {
29248
+ try {
29249
+ await config.sessionIdentity.bind(request.principal, observation.threadId);
29250
+ } catch (error) {
29251
+ sessionBindingDiagnostic = error instanceof Error ? error.message : String(error);
29372
29252
  }
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() === "") {
29253
+ }
29254
+ if (observation.failureDiagnostic !== void 0) {
29255
+ return terminalFromSpawned(spawned, {
29256
+ cause: "output",
29257
+ identity: { name: "HeadlessCliError", code: "codex-turn-failed" },
29258
+ diagnostic: observation.failureDiagnostic,
29259
+ details: {
29260
+ sessionId,
29261
+ exitCode: spawned.code,
29262
+ ...sessionBindingDiagnostic === void 0 ? {} : { sessionBindingDiagnostic }
29263
+ }
29264
+ });
29265
+ }
29266
+ if (spawned.code !== 0 && spawned.code !== null) {
29267
+ return terminalFromSpawned(spawned, {
29268
+ cause: "output",
29269
+ identity: { name: "HeadlessCliError", code: "codex-nonzero-exit" },
29270
+ diagnostic: spawned.stderr.trim() || `codex exec exited ${String(spawned.code)}`,
29271
+ details: {
29272
+ sessionId,
29273
+ exitCode: spawned.code,
29274
+ ...sessionBindingDiagnostic === void 0 ? {} : { sessionBindingDiagnostic }
29275
+ }
29276
+ });
29277
+ }
29278
+ if (observation.threadId === void 0 || observation.threadId === "") {
29279
+ return terminalFromSpawned(spawned, {
29280
+ cause: "session",
29281
+ identity: { name: "HeadlessMissingThreadId", code: "missing-thread-id" },
29282
+ diagnostic: "codex exec emitted no thread.started thread_id",
29283
+ details: { sessionId, exitCode: spawned.code }
29284
+ });
29285
+ }
29286
+ sessionId = observation.threadId;
29287
+ await config.sessionIdentity.bind(request.principal, sessionId);
29288
+ if (!observation.turnCompleted) {
29289
+ return terminalFromSpawned(spawned, {
29290
+ cause: "output",
29291
+ identity: { name: "HeadlessCliError", code: "codex-missing-terminal-event" },
29292
+ diagnostic: "codex exec exited without turn.completed",
29293
+ details: { sessionId, exitCode: spawned.code }
29294
+ });
29295
+ }
29296
+ if (observation.finalMessage === void 0) {
29403
29297
  return terminalFromSpawned(spawned, {
29404
29298
  cause: "output",
29405
29299
  identity: { name: "HeadlessEmptyOutput", code: "empty-stdout" },
29406
- diagnostic: spawned.stderr.trim() || "codex exec produced empty agent_message",
29300
+ diagnostic: spawned.stderr.trim() || "codex exec produced no agent_message",
29301
+ details: { sessionId, exitCode: spawned.code }
29302
+ });
29303
+ }
29304
+ if (prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME) {
29305
+ if (observation.finalMessage.trim() === "") {
29306
+ return terminalFromSpawned(spawned, {
29307
+ cause: "output",
29308
+ identity: { name: "HeadlessEmptyOutput", code: "empty-stdout" },
29309
+ diagnostic: spawned.stderr.trim() || "codex exec produced empty agent_message",
29310
+ details: { sessionId, exitCode: spawned.code }
29311
+ });
29312
+ }
29313
+ await prepared.ingestStructuredOutput({ prose: observation.finalMessage });
29314
+ return { status: "delivered", stderr: spawned.stderr };
29315
+ }
29316
+ let receipt;
29317
+ try {
29318
+ receipt = JSON.parse(observation.finalMessage);
29319
+ } catch {
29320
+ return terminalFromSpawned(spawned, {
29321
+ cause: "output",
29322
+ identity: { name: "HeadlessEmptyOutput", code: "unparseable-final-message" },
29323
+ diagnostic: "codex final agent_message was not JSON",
29407
29324
  details: { sessionId, exitCode: spawned.code }
29408
29325
  });
29409
29326
  }
29410
- await prepared.ingestStructuredOutput({ prose: observation.finalMessage });
29327
+ await prepared.ingestStructuredOutput(receipt);
29411
29328
  return { status: "delivered", stderr: spawned.stderr };
29412
29329
  }
29413
- let receipt;
29414
- try {
29415
- receipt = JSON.parse(observation.finalMessage);
29416
- } catch {
29330
+ const envelope = parseHeadlessCliStdout(spawned.stdout);
29331
+ if (envelope === void 0) {
29417
29332
  return terminalFromSpawned(spawned, {
29418
29333
  cause: "output",
29419
- identity: { name: "HeadlessEmptyOutput", code: "unparseable-final-message" },
29420
- diagnostic: "codex final agent_message was not JSON",
29334
+ identity: { name: "HeadlessEmptyOutput", code: "empty-stdout" },
29335
+ diagnostic: spawned.stderr.length > 0 ? spawned.stderr : "headless CLI produced no parseable result",
29421
29336
  details: { sessionId, exitCode: spawned.code }
29422
29337
  });
29423
29338
  }
29424
- await prepared.ingestStructuredOutput(receipt);
29339
+ if (typeof envelope.session_id === "string" && envelope.session_id !== "") {
29340
+ sessionId = envelope.session_id;
29341
+ await config.sessionIdentity.bind(request.principal, sessionId);
29342
+ }
29343
+ if (envelope.is_error === true || typeof envelope.subtype === "string" && envelope.subtype.startsWith("error_")) {
29344
+ const errorCode = typeof envelope.subtype === "string" && envelope.subtype.startsWith("error_") ? envelope.subtype : envelope.is_error === true ? "is_error" : "cli-error";
29345
+ 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";
29346
+ return terminalFromSpawned(spawned, {
29347
+ cause: "output",
29348
+ identity: { name: "HeadlessCliError", code: errorCode },
29349
+ diagnostic,
29350
+ details: {
29351
+ sessionId,
29352
+ subtype: envelope.subtype,
29353
+ errors: envelope.errors,
29354
+ exitCode: spawned.code
29355
+ }
29356
+ });
29357
+ }
29358
+ if (envelope.structured_output !== void 0) {
29359
+ await prepared.ingestStructuredOutput(envelope.structured_output);
29360
+ } else if (prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME && typeof envelope.result === "string" && envelope.result.trim() !== "") {
29361
+ await prepared.ingestStructuredOutput({ prose: envelope.result });
29362
+ }
29425
29363
  return { status: "delivered", stderr: spawned.stderr };
29426
29364
  }
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
- });
29365
+ });
29366
+ } finally {
29367
+ if (exitedSessionId !== void 0 && exitedSessionId !== "") copyAndRecordHostDossier({
29368
+ host: config.hostName,
29369
+ sessionId: exitedSessionId,
29370
+ cwd: request.cwd,
29371
+ sessionDirectory: join49(request.runDirectory, "session"),
29372
+ sessionParent,
29373
+ continuation: request.continuation,
29374
+ ...request.model !== void 0 ? { model: request.model } : {},
29375
+ ...request.home !== void 0 ? { home: request.home } : {}
29376
+ });
29377
+ }
29463
29378
  } finally {
29464
29379
  try {
29465
29380
  await prepared.dispose?.();