@akagilnc/pi-workflow-roles 0.1.5212 → 0.1.5235

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2694,17 +2694,6 @@ function positiveInteger(value) {
2694
2694
  }
2695
2695
  return void 0;
2696
2696
  }
2697
- function nonNegativeInteger(value) {
2698
- if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) return value;
2699
- if (typeof value === "string" && /^(0|[1-9][0-9]*)$/.test(value)) {
2700
- const parsed = Number(value);
2701
- if (Number.isSafeInteger(parsed)) return parsed;
2702
- }
2703
- return void 0;
2704
- }
2705
- function projectSpeaker(value) {
2706
- return value === "owner" || value === "runner" ? value : void 0;
2707
- }
2708
2697
  function projectBound(value) {
2709
2698
  if (!isRecord2(value)) return void 0;
2710
2699
  const id = typeof value.id === "string" && value.id !== "" ? value.id : void 0;
@@ -2733,42 +2722,6 @@ function projectTicketProvenanceSessions(value) {
2733
2722
  }
2734
2723
  return sessions;
2735
2724
  }
2736
- function projectTicketProvenanceHeader(value) {
2737
- if (!isRecord2(value)) return void 0;
2738
- const ticket = value.ticket === null ? null : positiveInteger(value.ticket);
2739
- if (ticket === void 0) return void 0;
2740
- if (typeof value.repo !== "string") return void 0;
2741
- if (typeof value.createdAt !== "string" || typeof value.updatedAt !== "string") {
2742
- return void 0;
2743
- }
2744
- const sessions = projectTicketProvenanceSessions(value.sessions);
2745
- if (sessions === void 0) return void 0;
2746
- return {
2747
- repo: value.repo,
2748
- ticket,
2749
- createdAt: value.createdAt,
2750
- updatedAt: value.updatedAt,
2751
- sessions
2752
- };
2753
- }
2754
- function projectTicketProvenanceLine(value) {
2755
- if (!isRecord2(value)) return void 0;
2756
- const speaker = projectSpeaker(value.speaker);
2757
- const s = nonNegativeInteger(value.s);
2758
- if (speaker === void 0 || s === void 0) return void 0;
2759
- if (typeof value.text !== "string") return void 0;
2760
- const sourcePosition = nonNegativeInteger(value.sourcePosition);
2761
- const sourceIdentity = typeof value.sourceIdentity === "string" && value.sourceIdentity !== "" ? value.sourceIdentity : void 0;
2762
- const id = typeof value.id === "string" && value.id !== "" ? value.id : void 0;
2763
- return {
2764
- speaker,
2765
- s,
2766
- ...sourcePosition === void 0 ? {} : { sourcePosition },
2767
- ...sourceIdentity === void 0 ? {} : { sourceIdentity },
2768
- ...id === void 0 ? {} : { id },
2769
- text: value.text
2770
- };
2771
- }
2772
2725
  var TICKET_PROVENANCE_KIND;
2773
2726
  var init_ticket_provenance_contracts = __esm({
2774
2727
  "src/ticket-provenance-contracts.ts"() {
@@ -4509,57 +4462,15 @@ var init_sitian_contracts = __esm({
4509
4462
  });
4510
4463
 
4511
4464
  // src/sitian-appender.ts
4512
- import { createHash as createHash5, randomUUID } from "node:crypto";
4513
- import {
4514
- appendFileSync,
4515
- existsSync,
4516
- readFileSync,
4517
- unlinkSync,
4518
- writeFileSync
4519
- } from "node:fs";
4465
+ import { randomUUID } from "node:crypto";
4466
+ import { appendFileSync } from "node:fs";
4520
4467
  import { dirname as dirname4, join as join3 } from "node:path";
4521
- function isRecord3(value) {
4522
- return typeof value === "object" && value !== null && !Array.isArray(value);
4523
- }
4524
- function errorCodeOf(error) {
4525
- return error.code;
4526
- }
4527
- function identityClaimPath(recordFile, identity) {
4528
- const digest = createHash5("sha256").update(identity, "utf8").digest("hex");
4529
- return `${recordFile}.id-${digest}`;
4530
- }
4531
- function createExclusiveFile(path, contents) {
4532
- writeFileSync(path, contents, { encoding: "utf8", flag: "wx" });
4533
- }
4534
- function sealTornTail(recordFile) {
4535
- if (!existsSync(recordFile)) return;
4536
- const buffer = readFileSync(recordFile);
4537
- if (buffer.length > 0 && buffer[buffer.length - 1] !== 10) {
4538
- appendFileSync(recordFile, "\n", "utf8");
4539
- }
4540
- }
4541
4468
  function appendSitianRecordBlock(input, block) {
4542
4469
  if (block === "") return;
4543
4470
  try {
4544
4471
  const { sessionDir, recordFile, ledgerHome } = resolveSitianRecordPath(input);
4545
4472
  ensureRealDirectoryTree(ledgerHome, sessionDir);
4546
- appendFileSync(recordFile, "", "utf8");
4547
- sealTornTail(recordFile);
4548
- const identityOf = (line2) => {
4549
- try {
4550
- const row = JSON.parse(line2);
4551
- return isRecord3(row) && typeof row.identity === "string" ? row.identity : void 0;
4552
- } catch {
4553
- return void 0;
4554
- }
4555
- };
4556
- const identities = new Set(readFileSync(recordFile, "utf8").split("\n").map(identityOf).filter((id) => id !== void 0));
4557
- for (const line2 of block.match(/[^\n]*\n|[^\n]+$/g) ?? []) {
4558
- const identity = identityOf(line2);
4559
- if (identity !== void 0 && identities.has(identity)) continue;
4560
- appendFileSync(recordFile, line2, "utf8");
4561
- if (identity !== void 0) identities.add(identity);
4562
- }
4473
+ appendFileSync(recordFile, block, "utf8");
4563
4474
  } catch (error) {
4564
4475
  if (error instanceof SitianInfrastructureError) throw error;
4565
4476
  throw new SitianInfrastructureError(
@@ -4568,106 +4479,6 @@ function appendSitianRecordBlock(input, block) {
4568
4479
  );
4569
4480
  }
4570
4481
  }
4571
- function findIdentityPointer(recordFile, identity, kind, level) {
4572
- if (!existsSync(recordFile)) return void 0;
4573
- const text = readFileSync(recordFile, "utf8");
4574
- for (const line2 of text.split("\n")) {
4575
- const trimmed = line2.trim();
4576
- if (!trimmed) continue;
4577
- try {
4578
- const parsed = JSON.parse(trimmed);
4579
- if (isRecord3(parsed) && parsed.identity === identity) {
4580
- return { identity, recordFile, kind, level };
4581
- }
4582
- } catch {
4583
- }
4584
- }
4585
- return void 0;
4586
- }
4587
- function unlinkAbsentOk(path) {
4588
- try {
4589
- unlinkSync(path);
4590
- return void 0;
4591
- } catch (error) {
4592
- if (errorCodeOf(error) === "ENOENT") return void 0;
4593
- return error instanceof Error ? error : new Error(errorText(error));
4594
- }
4595
- }
4596
- function appendWithIdentityClaim(recordFile, record4, row) {
4597
- sealTornTail(recordFile);
4598
- const claimPath = identityClaimPath(recordFile, record4.identity);
4599
- const existing = findIdentityPointer(
4600
- recordFile,
4601
- record4.identity,
4602
- record4.kind,
4603
- record4.level
4604
- );
4605
- if (existing !== void 0) {
4606
- unlinkAbsentOk(claimPath);
4607
- return existing;
4608
- }
4609
- try {
4610
- createExclusiveFile(claimPath, "");
4611
- } catch (error) {
4612
- if (errorCodeOf(error) !== "EEXIST") throw error;
4613
- sealTornTail(recordFile);
4614
- const published = findIdentityPointer(
4615
- recordFile,
4616
- record4.identity,
4617
- record4.kind,
4618
- record4.level
4619
- );
4620
- if (published !== void 0) {
4621
- unlinkAbsentOk(claimPath);
4622
- return published;
4623
- }
4624
- throw new SitianInfrastructureError(
4625
- `Sitian identity claim at ${claimPath} already exists for identity ${record4.identity}`,
4626
- { cause: error }
4627
- );
4628
- }
4629
- let primaryFailure;
4630
- let result;
4631
- let cleanupFailure;
4632
- try {
4633
- sealTornTail(recordFile);
4634
- const raced = findIdentityPointer(
4635
- recordFile,
4636
- record4.identity,
4637
- record4.kind,
4638
- record4.level
4639
- );
4640
- if (raced !== void 0) {
4641
- result = raced;
4642
- } else {
4643
- appendFileSync(recordFile, row, "utf8");
4644
- result = {
4645
- identity: record4.identity,
4646
- recordFile,
4647
- kind: record4.kind,
4648
- level: record4.level
4649
- };
4650
- }
4651
- } catch (error) {
4652
- primaryFailure = error;
4653
- } finally {
4654
- cleanupFailure = unlinkAbsentOk(claimPath);
4655
- }
4656
- if (primaryFailure !== void 0) {
4657
- if (primaryFailure instanceof SitianInfrastructureError) throw primaryFailure;
4658
- throw new SitianInfrastructureError(
4659
- `Sitian appender persistence failure: ${errorText(primaryFailure)}`,
4660
- { cause: primaryFailure }
4661
- );
4662
- }
4663
- if (cleanupFailure !== void 0) {
4664
- throw new SitianInfrastructureError(
4665
- `Sitian identity claim at ${claimPath} could not be released after append for identity ${record4.identity}: ${errorText(cleanupFailure)}`,
4666
- { cause: cleanupFailure }
4667
- );
4668
- }
4669
- return result;
4670
- }
4671
4482
  function resolveSitianVolumeCategory(kind) {
4672
4483
  if (S4_SUBMISSION_LEDGER_KINDS.has(kind)) {
4673
4484
  return "submission-ledger";
@@ -4740,7 +4551,13 @@ function appendSitianRecord(input) {
4740
4551
  };
4741
4552
  const row = `${JSON.stringify(record4)}
4742
4553
  `;
4743
- return appendWithIdentityClaim(recordFile, record4, row);
4554
+ appendFileSync(recordFile, row, "utf8");
4555
+ return {
4556
+ identity: record4.identity,
4557
+ recordFile,
4558
+ kind: record4.kind,
4559
+ level: record4.level
4560
+ };
4744
4561
  } catch (error) {
4745
4562
  if (error instanceof SitianInfrastructureError) throw error;
4746
4563
  throw new SitianInfrastructureError(
@@ -4768,13 +4585,13 @@ var init_sitian_appender = __esm({
4768
4585
  });
4769
4586
 
4770
4587
  // src/sitian-reader.ts
4771
- import { existsSync as existsSync2 } from "node:fs";
4588
+ import { existsSync } from "node:fs";
4772
4589
  import { readFile as readFile4 } from "node:fs/promises";
4773
- function isRecord4(value) {
4590
+ function isRecord3(value) {
4774
4591
  return typeof value === "object" && value !== null && !Array.isArray(value);
4775
4592
  }
4776
4593
  async function readSitianRecords(recordFile) {
4777
- if (!existsSync2(recordFile)) {
4594
+ if (!existsSync(recordFile)) {
4778
4595
  return { records: [], diagnostics: [] };
4779
4596
  }
4780
4597
  const text = await readFile4(recordFile, "utf8");
@@ -4786,7 +4603,7 @@ async function readSitianRecords(recordFile) {
4786
4603
  if (!line2.trim()) continue;
4787
4604
  try {
4788
4605
  const parsed = JSON.parse(line2);
4789
- if (isRecord4(parsed)) {
4606
+ if (isRecord3(parsed)) {
4790
4607
  records.push(parsed);
4791
4608
  } else {
4792
4609
  const typeDesc = parsed === null ? "null" : Array.isArray(parsed) ? "array" : typeof parsed;
@@ -4930,7 +4747,7 @@ var init_host_descriptions = __esm({
4930
4747
  });
4931
4748
 
4932
4749
  // src/package-resources/engine-material.ts
4933
- import { existsSync as existsSync3, readdirSync } from "node:fs";
4750
+ import { existsSync as existsSync2, readdirSync } from "node:fs";
4934
4751
  import { join as join4 } from "node:path";
4935
4752
  function pickEngineAxis(source) {
4936
4753
  return {
@@ -4973,7 +4790,7 @@ function engineSessionMaterialFromOptions(options) {
4973
4790
  const model = options.engineModel === void 0 ? void 0 : assertLegalEngineModel(options.engineModel);
4974
4791
  const materialPath = resolveEngineMaterialPath(options.packageRoot, name);
4975
4792
  const modelField = model === void 0 ? {} : { model };
4976
- if (existsSync3(materialPath)) {
4793
+ if (existsSync2(materialPath)) {
4977
4794
  return Object.freeze({ name, materialPath, ...modelField });
4978
4795
  }
4979
4796
  return Object.freeze({ name, ...modelField });
@@ -5988,14 +5805,14 @@ function isMissingPathError3(error) {
5988
5805
  function errorText2(error) {
5989
5806
  return error instanceof Error ? error.message : String(error);
5990
5807
  }
5991
- function isRecord5(value) {
5808
+ function isRecord4(value) {
5992
5809
  return typeof value === "object" && value !== null && !Array.isArray(value);
5993
5810
  }
5994
5811
  function readUsableTerminalArtifactBody(body) {
5995
5812
  if (body === null) {
5996
5813
  return { ok: false, reason: "terminal artifact JSON value is null" };
5997
5814
  }
5998
- if (!isRecord5(body)) {
5815
+ if (!isRecord4(body)) {
5999
5816
  return {
6000
5817
  ok: false,
6001
5818
  reason: `terminal artifact JSON value is not a typed object (${Array.isArray(body) ? "array" : typeof body})`
@@ -6993,19 +6810,7 @@ function createPiRoleTurnHost(config) {
6993
6810
  });
6994
6811
  return {
6995
6812
  async executeTurn(request) {
6996
- let turnRequest = request;
6997
- const officerStationChild = request.stationChild === true && isOfficerReviewSeat(request.activation.role);
6998
- const paths = !officerStationChild && request.hostTransition?.priorNativeKind === "sitian" ? request.hostTransition.priorNativePaths : void 0;
6999
- if (request.continuation.kind === "resume" && paths !== void 0 && paths.length > 0) {
7000
- turnRequest = {
7001
- ...request,
7002
- continuation: {
7003
- ...request.continuation,
7004
- prompt: `${request.continuation.prompt}
7005
- ${paths.join("\n")}`
7006
- }
7007
- };
7008
- }
6813
+ const turnRequest = request;
7009
6814
  const roleEntry = await realpath2(resolveInternalRoleEntrypoint(config.packageRoot));
7010
6815
  const extraArgs = buildPiTurnExtraArgs(
7011
6816
  turnRequest,
@@ -7085,7 +6890,6 @@ var init_role_turn_host = __esm({
7085
6890
  "src/pi/role-turn-host.ts"() {
7086
6891
  "use strict";
7087
6892
  init_host_contracts();
7088
- init_packaged_role_registry();
7089
6893
  init_engine_detour();
7090
6894
  init_role_activation_flags();
7091
6895
  init_user_dialogue_stdin();
@@ -7391,7 +7195,7 @@ var init_merger_git_state = __esm({
7391
7195
 
7392
7196
  // src/ledger-session-read.ts
7393
7197
  import { readFile as readFile11 } from "node:fs/promises";
7394
- function isRecord6(value) {
7198
+ function isRecord5(value) {
7395
7199
  return typeof value === "object" && value !== null && !Array.isArray(value);
7396
7200
  }
7397
7201
  async function readLedgerSessionJsonlLines(path) {
@@ -7416,7 +7220,7 @@ async function readLedgerSessionJsonlLines(path) {
7416
7220
  });
7417
7221
  continue;
7418
7222
  }
7419
- if (!isRecord6(row)) {
7223
+ if (!isRecord5(row)) {
7420
7224
  const kind = row === null ? "null" : Array.isArray(row) ? "array" : typeof row;
7421
7225
  out.push({
7422
7226
  line: lineNumber,
@@ -7469,7 +7273,7 @@ function extractSessionModelSequence(rows) {
7469
7273
  if (row.type === "model_change" && typeof row.modelId === "string") {
7470
7274
  push(row.modelId);
7471
7275
  }
7472
- const message = isRecord6(row.message) ? row.message : void 0;
7276
+ const message = isRecord5(row.message) ? row.message : void 0;
7473
7277
  if (message?.role === "assistant" && typeof message.model === "string") {
7474
7278
  push(message.model);
7475
7279
  }
@@ -7485,11 +7289,11 @@ function extractSessionToolIntervals(rows) {
7485
7289
  const openById = /* @__PURE__ */ new Map();
7486
7290
  for (const row of rows) {
7487
7291
  const rowTimestamp = typeof row.timestamp === "string" ? row.timestamp : void 0;
7488
- const message = isRecord6(row.message) ? row.message : void 0;
7292
+ const message = isRecord5(row.message) ? row.message : void 0;
7489
7293
  if (message?.role === "assistant" && Array.isArray(message.content)) {
7490
7294
  const callTimestamp = typeof message.timestamp === "string" && message.timestamp ? message.timestamp : rowTimestamp;
7491
7295
  for (const part of message.content) {
7492
- if (!isRecord6(part) || part.type !== "toolCall") continue;
7296
+ if (!isRecord5(part) || part.type !== "toolCall") continue;
7493
7297
  if (typeof part.id !== "string" || part.id.length === 0) {
7494
7298
  throw new Error("toolCall frame missing string id");
7495
7299
  }
@@ -7502,7 +7306,7 @@ function extractSessionToolIntervals(rows) {
7502
7306
  if (openById.has(part.id)) {
7503
7307
  throw new Error(`duplicate toolCall id ${part.id}`);
7504
7308
  }
7505
- const args = isRecord6(part.arguments) ? part.arguments : void 0;
7309
+ const args = isRecord5(part.arguments) ? part.arguments : void 0;
7506
7310
  const command = part.name === "bash" && args !== void 0 && typeof args.command === "string" ? bashCommandFirstLine(args.command) : void 0;
7507
7311
  const interval = {
7508
7312
  toolCallId: part.id,
@@ -7586,7 +7390,7 @@ var init_ledger_session_read = __esm({
7586
7390
  });
7587
7391
 
7588
7392
  // src/session-dialogue.ts
7589
- function isRecord7(value) {
7393
+ function isRecord6(value) {
7590
7394
  return typeof value === "object" && value !== null && !Array.isArray(value);
7591
7395
  }
7592
7396
  function nativeEventId(row) {
@@ -7596,7 +7400,7 @@ function nativeEventId(row) {
7596
7400
  }
7597
7401
  for (const nestKey of ["message", "payload"]) {
7598
7402
  const nested = row[nestKey];
7599
- if (!isRecord7(nested)) continue;
7403
+ if (!isRecord6(nested)) continue;
7600
7404
  for (const key of ["uuid", "id"]) {
7601
7405
  const value = nested[key];
7602
7406
  if (typeof value === "string" && value !== "") return value;
@@ -7609,19 +7413,19 @@ function textParts(content) {
7609
7413
  if (!Array.isArray(content)) return [];
7610
7414
  const out = [];
7611
7415
  for (const part of content) {
7612
- if (!isRecord7(part) || !SPEAKER_TEXT_PART_TYPES.has(String(part.type))) continue;
7416
+ if (!isRecord6(part) || !SPEAKER_TEXT_PART_TYPES.has(String(part.type))) continue;
7613
7417
  const text = part.text;
7614
7418
  if (typeof text === "string" && text !== "") out.push(text);
7615
7419
  }
7616
7420
  return out;
7617
7421
  }
7618
7422
  function responseItemMessage(row) {
7619
- if (row.type !== "response_item" || !isRecord7(row.payload)) return void 0;
7423
+ if (row.type !== "response_item" || !isRecord6(row.payload)) return void 0;
7620
7424
  if (row.payload.type !== "message") return void 0;
7621
7425
  return row.payload;
7622
7426
  }
7623
7427
  function messageBody(row) {
7624
- if (isRecord7(row.message)) return row.message;
7428
+ if (isRecord6(row.message)) return row.message;
7625
7429
  return responseItemMessage(row);
7626
7430
  }
7627
7431
  function speakerOf(message) {
@@ -7631,7 +7435,7 @@ function speakerOf(message) {
7631
7435
  }
7632
7436
  function codexContentItemKinds(message) {
7633
7437
  const pass = message.internal_chat_message_metadata_passthrough;
7634
- if (!isRecord7(pass) || !Array.isArray(pass.content_item_kinds)) return void 0;
7438
+ if (!isRecord6(pass) || !Array.isArray(pass.content_item_kinds)) return void 0;
7635
7439
  const kinds = [];
7636
7440
  for (const kind of pass.content_item_kinds) {
7637
7441
  if (typeof kind === "string" && kind !== "") kinds.push(kind);
@@ -7660,7 +7464,7 @@ function isFixedNonOwnerEnqueueShape(content) {
7660
7464
  return hasFixedOpenTagPrefix(content, TASK_NOTIFICATION_OPEN_TAG);
7661
7465
  }
7662
7466
  function materializationOriginKind(row) {
7663
- if (!isRecord7(row.origin)) return void 0;
7467
+ if (!isRecord6(row.origin)) return void 0;
7664
7468
  const kind = row.origin.kind;
7665
7469
  return typeof kind === "string" && kind !== "" ? kind : void 0;
7666
7470
  }
@@ -7707,7 +7511,6 @@ var init_session_dialogue = __esm({
7707
7511
  });
7708
7512
 
7709
7513
  // src/ticket-provenance.ts
7710
- import { createHash as createHash6 } from "node:crypto";
7711
7514
  import { readFile as readFile12, unlink as unlink2 } from "node:fs/promises";
7712
7515
  import { basename as basename5, dirname as dirname11, join as join16, resolve as resolve9 } from "node:path";
7713
7516
  function dialogueSessionSourceRoots(home) {
@@ -7758,175 +7561,6 @@ function resolveTicketProvenanceVolume(ticketNumber, cwd, home) {
7758
7561
  );
7759
7562
  return { recordFile: path.recordFile, volumeDir: path.sessionDir };
7760
7563
  }
7761
- function projectTicketProvenanceRaw(value) {
7762
- if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
7763
- const raw = value;
7764
- if (typeof raw.raw !== "string" || !Number.isInteger(raw.s) || raw.s < 0 || !Number.isInteger(raw.sourcePosition) || raw.sourcePosition < 0) {
7765
- return void 0;
7766
- }
7767
- const sourceIdentity = typeof raw.sourceIdentity === "string" && raw.sourceIdentity !== "" ? raw.sourceIdentity : void 0;
7768
- return {
7769
- raw: raw.raw,
7770
- s: raw.s,
7771
- sourcePosition: raw.sourcePosition,
7772
- ...sourceIdentity === void 0 ? {} : { sourceIdentity }
7773
- };
7774
- }
7775
- function projectTicketProvenanceCommit(value) {
7776
- if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
7777
- const record4 = value;
7778
- if (record4.kind !== TICKET_PROVENANCE_KIND || typeof record4.timestamp !== "string") {
7779
- return void 0;
7780
- }
7781
- const payload = record4.payload;
7782
- if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return void 0;
7783
- const body = payload;
7784
- if (body.type !== "ticket-provenance-append") return void 0;
7785
- const sessions = projectTicketProvenanceSessions(body.sessions);
7786
- if (sessions === void 0 || !Array.isArray(body.lines)) return void 0;
7787
- const lines = [];
7788
- for (const raw of body.lines) {
7789
- if (typeof raw === "string") {
7790
- lines.push(raw);
7791
- continue;
7792
- }
7793
- const line2 = projectTicketProvenanceLine(raw);
7794
- if (line2 !== void 0) {
7795
- lines.push(line2);
7796
- continue;
7797
- }
7798
- const preserved = projectTicketProvenanceRaw(raw);
7799
- if (preserved === void 0) return void 0;
7800
- lines.push(preserved);
7801
- }
7802
- return { timestamp: record4.timestamp, sessions, lines };
7803
- }
7804
- async function readTicketProvenance(ticketNumber, cwd, home, runDirectory) {
7805
- const { recordFile } = ticketNumber === null ? resolveSitianRecordPath(ticketProvenanceRecordInput(null, cwd, home, runDirectory)) : resolveTicketProvenanceVolume(ticketNumber, cwd, home);
7806
- let text;
7807
- try {
7808
- text = await readFile12(recordFile, "utf8");
7809
- } catch (error) {
7810
- if (error.code === "ENOENT") {
7811
- return {
7812
- header: void 0,
7813
- lines: [],
7814
- unprojectedRaw: [],
7815
- recordFile,
7816
- sourceIdentities: /* @__PURE__ */ new Map(),
7817
- legacySourcePositions: /* @__PURE__ */ new Map()
7818
- };
7819
- }
7820
- throw error;
7821
- }
7822
- const physical = text.split("\n");
7823
- let header;
7824
- const lines = [];
7825
- const unprojectedRaw = [];
7826
- const sourceIdentities = /* @__PURE__ */ new Map();
7827
- const legacySourcePositions = /* @__PURE__ */ new Map();
7828
- const rememberIdentity = (s, identity) => {
7829
- const seen = sourceIdentities.get(s) ?? /* @__PURE__ */ new Set();
7830
- const fresh = !seen.has(identity);
7831
- seen.add(identity);
7832
- sourceIdentities.set(s, seen);
7833
- return fresh;
7834
- };
7835
- const rememberLegacyPosition = (s, position) => {
7836
- const seen = legacySourcePositions.get(s) ?? /* @__PURE__ */ new Set();
7837
- seen.add(position);
7838
- legacySourcePositions.set(s, seen);
7839
- };
7840
- const remapCoverage = (coverage, priorIndexes) => {
7841
- const normalized = /* @__PURE__ */ new Map();
7842
- for (const [s, values] of coverage) {
7843
- const target = priorIndexes[s] ?? s;
7844
- const union = normalized.get(target) ?? /* @__PURE__ */ new Set();
7845
- for (const value of values) union.add(value);
7846
- normalized.set(target, union);
7847
- }
7848
- coverage.clear();
7849
- for (const [s, values] of normalized) coverage.set(s, values);
7850
- };
7851
- let sawFirst = false;
7852
- for (let index = 0; index < physical.length; index += 1) {
7853
- const raw = physical[index];
7854
- if (!raw.trim()) continue;
7855
- let parsed;
7856
- try {
7857
- parsed = JSON.parse(raw);
7858
- } catch {
7859
- unprojectedRaw.push(raw);
7860
- continue;
7861
- }
7862
- if (!sawFirst) {
7863
- sawFirst = true;
7864
- header = projectTicketProvenanceHeader(parsed);
7865
- if (header !== void 0) continue;
7866
- }
7867
- const line2 = projectTicketProvenanceLine(parsed);
7868
- if (line2 !== void 0) {
7869
- lines.push(line2);
7870
- continue;
7871
- }
7872
- const commit = projectTicketProvenanceCommit(parsed);
7873
- if (commit !== void 0) {
7874
- const merged = mergeSessionBounds(header?.sessions, commit.sessions);
7875
- remapCoverage(sourceIdentities, merged.priorIndexes);
7876
- remapCoverage(legacySourcePositions, merged.priorIndexes);
7877
- const remapped = [];
7878
- for (const entry of commit.lines) {
7879
- if (typeof entry === "string") {
7880
- unprojectedRaw.push(entry);
7881
- continue;
7882
- }
7883
- const s = merged.incomingIndexes[entry.s] ?? merged.priorIndexes[entry.s] ?? entry.s;
7884
- if ("raw" in entry) {
7885
- if (entry.sourceIdentity !== void 0) {
7886
- if (rememberIdentity(s, entry.sourceIdentity)) unprojectedRaw.push(entry.raw);
7887
- } else {
7888
- rememberLegacyPosition(s, entry.sourcePosition);
7889
- unprojectedRaw.push(entry.raw);
7890
- }
7891
- continue;
7892
- }
7893
- remapped.push({ ...entry, s });
7894
- if (entry.id === void 0) {
7895
- if (entry.sourceIdentity !== void 0) rememberIdentity(s, entry.sourceIdentity);
7896
- else if (entry.sourcePosition !== void 0) rememberLegacyPosition(s, entry.sourcePosition);
7897
- }
7898
- }
7899
- const now = commit.timestamp;
7900
- header = {
7901
- repo: header?.repo ?? resolveBookKeyFromGit(cwd),
7902
- ticket: ticketNumber,
7903
- createdAt: header?.createdAt ?? now,
7904
- updatedAt: header?.updatedAt !== void 0 && header.updatedAt > now ? header.updatedAt : now,
7905
- sessions: merged.sessions
7906
- };
7907
- const carried = lines.map((entry) => ({
7908
- ...entry,
7909
- s: merged.priorIndexes[entry.s] ?? entry.s
7910
- }));
7911
- lines.splice(0, lines.length, ...mergeFreshIntoCarried(carried, remapped));
7912
- continue;
7913
- }
7914
- unprojectedRaw.push(raw);
7915
- }
7916
- for (const line2 of lines) {
7917
- if (line2.id !== void 0) continue;
7918
- if (line2.sourceIdentity !== void 0) rememberIdentity(line2.s, line2.sourceIdentity);
7919
- else if (line2.sourcePosition !== void 0) rememberLegacyPosition(line2.s, line2.sourcePosition);
7920
- }
7921
- return {
7922
- header,
7923
- lines,
7924
- unprojectedRaw,
7925
- recordFile,
7926
- sourceIdentities,
7927
- legacySourcePositions
7928
- };
7929
- }
7930
7564
  async function rehomeUnboundTicketProvenance(runDirectory, ticketNumber, cwd, home) {
7931
7565
  const source = join16(runDirectory, "records.jsonl");
7932
7566
  let content;
@@ -7956,110 +7590,6 @@ function resolveBoundIndex(bound, sessionLines) {
7956
7590
  }
7957
7591
  return void 0;
7958
7592
  }
7959
- function dialogueIdentity(s, id) {
7960
- return `${s}\0${id}`;
7961
- }
7962
- function rangeDeclarationKey(range) {
7963
- return JSON.stringify({
7964
- from: range.from,
7965
- to: range.to
7966
- });
7967
- }
7968
- function mergeSessionBounds(prior, incoming) {
7969
- const merged = [];
7970
- const indexByIdentity = /* @__PURE__ */ new Map();
7971
- const absorb = (sessions) => {
7972
- const indexes = [];
7973
- for (const session of sessions) {
7974
- const identity = physicalPathIdentity(session.path);
7975
- let targetIndex = indexByIdentity.get(identity);
7976
- if (targetIndex === void 0) {
7977
- targetIndex = merged.length;
7978
- indexByIdentity.set(identity, targetIndex);
7979
- merged.push({ path: session.path, ranges: [] });
7980
- }
7981
- indexes.push(targetIndex);
7982
- const target = merged[targetIndex];
7983
- const seen = new Set(target.ranges.map(rangeDeclarationKey));
7984
- for (const range of session.ranges) {
7985
- const key = rangeDeclarationKey(range);
7986
- if (seen.has(key)) continue;
7987
- seen.add(key);
7988
- target.ranges.push({ from: { ...range.from }, to: { ...range.to } });
7989
- }
7990
- }
7991
- return indexes;
7992
- };
7993
- const priorIndexes = absorb(prior ?? []);
7994
- const incomingIndexes = absorb(incoming);
7995
- return { sessions: merged, priorIndexes, incomingIndexes };
7996
- }
7997
- function undeclaredSessionRanges(prior, merged) {
7998
- const priorKeys = /* @__PURE__ */ new Map();
7999
- for (const session of prior ?? []) {
8000
- const identity = physicalPathIdentity(session.path);
8001
- let keys = priorKeys.get(identity);
8002
- if (keys === void 0) {
8003
- keys = /* @__PURE__ */ new Set();
8004
- priorKeys.set(identity, keys);
8005
- }
8006
- for (const range of session.ranges) keys.add(rangeDeclarationKey(range));
8007
- }
8008
- const out = [];
8009
- for (let s = 0; s < merged.length; s += 1) {
8010
- const session = merged[s];
8011
- const identity = physicalPathIdentity(session.path);
8012
- const declared = priorKeys.get(identity) ?? /* @__PURE__ */ new Set();
8013
- const fresh = session.ranges.filter(
8014
- (range) => !declared.has(rangeDeclarationKey(range))
8015
- );
8016
- if (fresh.length === 0) continue;
8017
- out.push({
8018
- s,
8019
- session: {
8020
- path: session.path,
8021
- ranges: fresh.map((range) => ({
8022
- from: { ...range.from },
8023
- to: { ...range.to }
8024
- }))
8025
- }
8026
- });
8027
- }
8028
- return out;
8029
- }
8030
- function mergeFreshIntoCarried(carried, fresh) {
8031
- const seenSources = /* @__PURE__ */ new Map();
8032
- const bySession = /* @__PURE__ */ new Map();
8033
- const absorb = (lines) => {
8034
- for (const line2 of lines) {
8035
- const sourceIdentity = line2.id === void 0 ? line2.sourceIdentity : `id\0${line2.id}`;
8036
- const identity = sourceIdentity === void 0 ? void 0 : `${line2.s}\0${sourceIdentity}`;
8037
- const seen = identity === void 0 ? void 0 : seenSources.get(identity);
8038
- if (seen !== void 0) {
8039
- if (line2.sourcePosition !== void 0) {
8040
- Object.assign(seen, { sourcePosition: line2.sourcePosition });
8041
- }
8042
- continue;
8043
- }
8044
- const bucket = bySession.get(line2.s) ?? [];
8045
- bucket.push({ ...line2 });
8046
- if (identity !== void 0) seenSources.set(identity, bucket.at(-1));
8047
- bySession.set(line2.s, bucket);
8048
- }
8049
- };
8050
- absorb(carried);
8051
- absorb(fresh);
8052
- return [...bySession.entries()].sort(([left], [right]) => left - right).flatMap(([, lines]) => lines.map((line2, archiveIndex) => ({ line: line2, archiveIndex })).sort((left, right) => {
8053
- const leftPosition = left.line.sourcePosition;
8054
- const rightPosition = right.line.sourcePosition;
8055
- if (leftPosition === void 0 && rightPosition === void 0) {
8056
- return left.archiveIndex - right.archiveIndex;
8057
- }
8058
- if (leftPosition === void 0) return 1;
8059
- if (rightPosition === void 0) return -1;
8060
- return leftPosition - rightPosition || left.archiveIndex - right.archiveIndex;
8061
- }).map(({ line: line2 }) => line2));
8062
- }
8063
7593
  function stableSourceFacts(sessionLines) {
8064
7594
  const positionByIdentity = /* @__PURE__ */ new Map();
8065
7595
  const facts = [];
@@ -8134,13 +7664,7 @@ async function projectSessionRanges(input) {
8134
7664
  const rows = sessionLines.map((entry) => entry.row);
8135
7665
  const dialogue = adaptSessionDialogue(rows);
8136
7666
  const sourceFacts = stableSourceFacts(sessionLines);
8137
- const sourcePositionByIdentity = /* @__PURE__ */ new Map();
8138
- for (const fact of sourceFacts) {
8139
- sourcePositionByIdentity.set(fact.identity, fact.position);
8140
- }
8141
- const seenIds = input.seenIds;
8142
- const lines = [];
8143
- const raw = [];
7667
+ const entries = [];
8144
7668
  const ranges = normalizeResolvedRanges(
8145
7669
  input.session.ranges,
8146
7670
  sessionLines,
@@ -8149,19 +7673,13 @@ async function projectSessionRanges(input) {
8149
7673
  for (const range of ranges) {
8150
7674
  for (let index = range.fromIndex; index <= range.toIndex; index += 1) {
8151
7675
  const { position: sourcePosition, identity: sourceIdentity } = sourceFacts[index];
8152
- if (input.coveredSourceIdentities.has(sourceIdentity) || input.legacyCoveredSourcePositions.has(sourcePosition)) continue;
8153
7676
  const entry = sessionLines[index];
8154
7677
  if (entry.row === void 0) {
8155
- raw.push({ raw: entry.raw, s: input.s, sourcePosition, sourceIdentity });
7678
+ entries.push({ raw: entry.raw, s: input.s, sourcePosition, sourceIdentity });
8156
7679
  continue;
8157
7680
  }
8158
7681
  for (const event of dialogue[index] ?? []) {
8159
- if (event.id !== void 0) {
8160
- const identity = dialogueIdentity(input.s, event.id);
8161
- if (seenIds.has(identity)) continue;
8162
- seenIds.add(identity);
8163
- }
8164
- lines.push({
7682
+ entries.push({
8165
7683
  speaker: event.speaker,
8166
7684
  s: input.s,
8167
7685
  sourcePosition,
@@ -8171,106 +7689,49 @@ async function projectSessionRanges(input) {
8171
7689
  }
8172
7690
  }
8173
7691
  }
8174
- return { lines, raw, sourcePositionByIdentity };
7692
+ return { entries };
8175
7693
  }
8176
7694
  async function reprojectTicketProvenance(input) {
8177
- const prior = await readTicketProvenance(input.ticketNumber, input.cwd, input.home, input.runDirectory);
7695
+ const recordInput = ticketProvenanceRecordInput(
7696
+ input.ticketNumber,
7697
+ input.cwd,
7698
+ input.home,
7699
+ input.runDirectory
7700
+ );
7701
+ const resolved = resolveSitianRecordPath(recordInput);
8178
7702
  if (input.sessions.length === 0) {
8179
- const now2 = (/* @__PURE__ */ new Date()).toISOString();
8180
7703
  return {
8181
- recordFile: prior.recordFile,
8182
- header: prior.header ?? {
8183
- repo: resolveBookKeyFromGit(input.cwd),
8184
- ticket: input.ticketNumber,
8185
- createdAt: now2,
8186
- updatedAt: now2,
8187
- sessions: []
8188
- },
8189
- lines: prior.lines
7704
+ recordFile: resolved.recordFile,
7705
+ lines: []
8190
7706
  };
8191
7707
  }
8192
- const merged = mergeSessionBounds(prior.header?.sessions, input.sessions);
8193
- const deltas = undeclaredSessionRanges(prior.header?.sessions, merged.sessions);
8194
- if (deltas.length === 0) {
8195
- const now2 = (/* @__PURE__ */ new Date()).toISOString();
8196
- return {
8197
- recordFile: prior.recordFile,
8198
- header: prior.header ?? {
8199
- repo: resolveBookKeyFromGit(input.cwd),
8200
- ticket: input.ticketNumber,
8201
- createdAt: now2,
8202
- updatedAt: now2,
8203
- sessions: merged.sessions
8204
- },
8205
- lines: prior.lines
8206
- };
8207
- }
8208
- const seenIds = new Set(
8209
- prior.lines.flatMap(
8210
- (line2) => line2.id === void 0 ? [] : [dialogueIdentity(line2.s, line2.id)]
8211
- )
8212
- );
8213
- const fresh = [];
8214
- const raw = [];
8215
- for (const delta of deltas) {
7708
+ const entries = [];
7709
+ for (let s = 0; s < input.sessions.length; s += 1) {
7710
+ const session = input.sessions[s];
8216
7711
  const projected = await projectSessionRanges({
8217
- s: delta.s,
8218
- session: delta.session,
8219
- seenIds,
8220
- coveredSourceIdentities: prior.sourceIdentities.get(delta.s) ?? /* @__PURE__ */ new Set(),
8221
- legacyCoveredSourcePositions: prior.legacySourcePositions.get(delta.s) ?? /* @__PURE__ */ new Set(),
7712
+ s,
7713
+ session,
8222
7714
  ...input.home === void 0 ? {} : { home: input.home }
8223
7715
  });
8224
- fresh.push(...prior.lines.flatMap((line2) => {
8225
- if (line2.s !== delta.s) return [];
8226
- const sourceIdentity = line2.id === void 0 ? line2.sourceIdentity : `id\0${line2.id}`;
8227
- if (sourceIdentity === void 0) return [];
8228
- const sourcePosition = projected.sourcePositionByIdentity.get(sourceIdentity);
8229
- return sourcePosition === void 0 ? [] : [{ ...line2, sourcePosition }];
8230
- }));
8231
- fresh.push(...projected.lines);
8232
- raw.push(...projected.raw);
8233
- }
8234
- const lines = mergeFreshIntoCarried(prior.lines, fresh);
8235
- const now = (/* @__PURE__ */ new Date()).toISOString();
8236
- const header = {
8237
- repo: prior.header?.repo ?? resolveBookKeyFromGit(input.cwd),
8238
- ticket: input.ticketNumber,
8239
- createdAt: prior.header?.createdAt ?? now,
8240
- updatedAt: now,
8241
- sessions: merged.sessions
8242
- };
8243
- const identityMaterial = JSON.stringify({
8244
- ticket: input.ticketNumber,
8245
- deltas: deltas.map(({ s, session }) => ({
8246
- s,
8247
- path: physicalPathIdentity(session.path),
8248
- ranges: session.ranges
8249
- })),
8250
- lines: [...fresh, ...raw]
8251
- });
8252
- const identity = `ticket-provenance:${createHash6("sha256").update(identityMaterial).digest("hex")}`;
7716
+ entries.push(...projected.entries);
7717
+ }
8253
7718
  const pointer = appendSitianRecord({
8254
- ...ticketProvenanceRecordInput(input.ticketNumber, input.cwd, input.home, input.runDirectory),
8255
- identity,
7719
+ ...recordInput,
8256
7720
  payload: {
8257
7721
  type: "ticket-provenance-append",
8258
- sessions: merged.sessions,
8259
- lines: [...fresh, ...raw]
7722
+ sessions: input.sessions,
7723
+ lines: entries
8260
7724
  }
8261
7725
  });
8262
- const folded = await readTicketProvenance(input.ticketNumber, input.cwd, input.home, input.runDirectory);
8263
7726
  return {
8264
7727
  recordFile: pointer.recordFile,
8265
- header: folded.header ?? header,
8266
- lines: folded.lines
7728
+ lines: entries.filter((entry) => "speaker" in entry)
8267
7729
  };
8268
7730
  }
8269
7731
  var TicketProvenanceInputError;
8270
7732
  var init_ticket_provenance = __esm({
8271
7733
  "src/ticket-provenance.ts"() {
8272
7734
  "use strict";
8273
- init_activation_ledger_git();
8274
7735
  init_activation_ledger_topology();
8275
7736
  init_ledger_session_read();
8276
7737
  init_run_ticket_number();
@@ -9497,7 +8958,7 @@ var init_option_definitions = __esm({
9497
8958
 
9498
8959
  // src/public-cli/invocation.ts
9499
8960
  import { execFileSync as execFileSync3 } from "node:child_process";
9500
- import { existsSync as existsSync5 } from "node:fs";
8961
+ import { existsSync as existsSync4 } from "node:fs";
9501
8962
  import {
9502
8963
  lstat as lstat3,
9503
8964
  mkdtemp as mkdtemp2,
@@ -9723,7 +9184,7 @@ async function relocateAdmittedRunToTicket(admitted, authority, heldLease) {
9723
9184
  for (const childRunId of Array.isArray(childRunIds) ? childRunIds : []) {
9724
9185
  if (typeof childRunId !== "string") continue;
9725
9186
  const childDirectory = join18(dirname13(oldRunDirectory), `${childRunId}@diarist`);
9726
- if (!existsSync5(childDirectory)) continue;
9187
+ if (!existsSync4(childDirectory)) continue;
9727
9188
  const childTarget = roleRunPlacement(ledgerHome, {
9728
9189
  bookKey: admitted.bookKey,
9729
9190
  subject: { ticketNumber: admitted.ticketNumber },
@@ -11205,7 +10666,7 @@ var init_invocation = __esm({
11205
10666
  });
11206
10667
 
11207
10668
  // src/public-cli/load-production-acp-host.ts
11208
- import { existsSync as existsSync6 } from "node:fs";
10669
+ import { existsSync as existsSync5 } from "node:fs";
11209
10670
  import { join as join19 } from "node:path";
11210
10671
  import { pathToFileURL } from "node:url";
11211
10672
  async function loadProductionAcpHostFactory(packageRoot, host) {
@@ -11215,7 +10676,7 @@ async function loadProductionAcpHostFactory(packageRoot, host) {
11215
10676
  }
11216
10677
  const built = join19(packageRoot, "dist/acp-host/production-host.js");
11217
10678
  const source = join19(packageRoot, "src/acp-host/production-host.ts");
11218
- const target = existsSync6(built) ? built : source;
10679
+ const target = existsSync5(built) ? built : source;
11219
10680
  const href = pathToFileURL(target).href;
11220
10681
  const mod = await import(href);
11221
10682
  const create = mod.createProductionAcpRoleTurnHost;
@@ -11229,7 +10690,7 @@ var init_load_production_acp_host = __esm({
11229
10690
  });
11230
10691
 
11231
10692
  // src/public-cli/load-production-headless-host.ts
11232
- import { existsSync as existsSync7 } from "node:fs";
10693
+ import { existsSync as existsSync6 } from "node:fs";
11233
10694
  import { join as join20 } from "node:path";
11234
10695
  import { pathToFileURL as pathToFileURL2 } from "node:url";
11235
10696
  async function loadProductionHeadlessHostFactory(packageRoot, host) {
@@ -11239,7 +10700,7 @@ async function loadProductionHeadlessHostFactory(packageRoot, host) {
11239
10700
  }
11240
10701
  const built = join20(packageRoot, "dist/headless-host/production-host.js");
11241
10702
  const source = join20(packageRoot, "src/headless-host/production-host.ts");
11242
- const target = existsSync7(built) ? built : source;
10703
+ const target = existsSync6(built) ? built : source;
11243
10704
  const href = pathToFileURL2(target).href;
11244
10705
  const mod = await import(href);
11245
10706
  const create = mod.createProductionHeadlessRoleTurnHost;
@@ -11376,7 +10837,7 @@ __export(host_providers_exports, {
11376
10837
  projectHostFacingProvider: () => projectHostFacingProvider,
11377
10838
  renderHostProvidersTable: () => renderHostProvidersTable
11378
10839
  });
11379
- import { readFileSync as readFileSync2 } from "node:fs";
10840
+ import { readFileSync } from "node:fs";
11380
10841
  import { join as join21 } from "node:path";
11381
10842
  function hostProvidersPath(home) {
11382
10843
  if (typeof home !== "string" || home.trim() === "") {
@@ -11424,7 +10885,7 @@ function parseHostProvidersTable(value) {
11424
10885
  function loadHostProvidersTable(home) {
11425
10886
  const path = hostProvidersPath(home);
11426
10887
  try {
11427
- const raw = readFileSync2(path, "utf8");
10888
+ const raw = readFileSync(path, "utf8");
11428
10889
  return parseHostProvidersTable(JSON.parse(raw));
11429
10890
  } catch (error) {
11430
10891
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -11442,7 +10903,7 @@ function listHermesProvidersForModel(home, seatModel) {
11442
10903
  const path = hermesProviderModelsCachePath(home);
11443
10904
  let text;
11444
10905
  try {
11445
- text = readFileSync2(path, "utf8");
10906
+ text = readFileSync(path, "utf8");
11446
10907
  } catch (error) {
11447
10908
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
11448
10909
  return [];
@@ -11542,7 +11003,7 @@ var init_host_providers = __esm({
11542
11003
  // src/analyst-gate-cycles-read.ts
11543
11004
  import { readdir as readdir4 } from "node:fs/promises";
11544
11005
  import { join as join22 } from "node:path";
11545
- function isRecord8(value) {
11006
+ function isRecord7(value) {
11546
11007
  return typeof value === "object" && value !== null && !Array.isArray(value);
11547
11008
  }
11548
11009
  function isParentAttemptBindingRow(row) {
@@ -11572,7 +11033,7 @@ function isGateTerminatingToolName(toolName) {
11572
11033
  function acceptedGateReceiptIds(rows) {
11573
11034
  const accepted = /* @__PURE__ */ new Set();
11574
11035
  for (const row of rows) {
11575
- const message = isRecord8(row.message) ? row.message : void 0;
11036
+ const message = isRecord7(row.message) ? row.message : void 0;
11576
11037
  if (message?.role !== "toolResult") continue;
11577
11038
  if (typeof message.toolCallId !== "string" || message.toolCallId.length === 0) continue;
11578
11039
  if (message.isError === false) accepted.add(message.toolCallId);
@@ -11607,7 +11068,7 @@ function nearestAttemptBindingBefore(rows, beforeIndex) {
11607
11068
  for (let i = beforeIndex - 1; i >= 0; i -= 1) {
11608
11069
  const row = rows[i];
11609
11070
  if (!isParentAttemptBindingRow(row)) continue;
11610
- if (!isRecord8(row.data) || !isRecord8(row.data.parent)) continue;
11071
+ if (!isRecord7(row.data) || !isRecord7(row.data.parent)) continue;
11611
11072
  const id = row.data.parent.attemptEntryId;
11612
11073
  const sessionFile = row.data.parent.sessionFile;
11613
11074
  return {
@@ -11622,10 +11083,10 @@ function extractAllAcceptedGateToolCalls(rows) {
11622
11083
  const out = [];
11623
11084
  for (let rowIndex = 0; rowIndex < rows.length; rowIndex += 1) {
11624
11085
  const row = rows[rowIndex];
11625
- const message = isRecord8(row.message) ? row.message : void 0;
11086
+ const message = isRecord7(row.message) ? row.message : void 0;
11626
11087
  if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
11627
11088
  for (const part of message.content) {
11628
- if (!isRecord8(part) || part.type !== "toolCall") continue;
11089
+ if (!isRecord7(part) || part.type !== "toolCall") continue;
11629
11090
  if (typeof part.id !== "string" || part.id.length === 0) continue;
11630
11091
  if (typeof part.name !== "string" || part.name.length === 0) continue;
11631
11092
  if (!isGateTerminatingToolName(part.name)) continue;
@@ -11633,7 +11094,7 @@ function extractAllAcceptedGateToolCalls(rows) {
11633
11094
  const binding = nearestAttemptBindingBefore(rows, rowIndex);
11634
11095
  out.push({
11635
11096
  toolName: part.name,
11636
- args: isRecord8(part.arguments) ? part.arguments : void 0,
11097
+ args: isRecord7(part.arguments) ? part.arguments : void 0,
11637
11098
  accepted: true,
11638
11099
  rowIndex,
11639
11100
  ...binding
@@ -11766,7 +11227,7 @@ async function resolveOfficerSessionFromPointerFile(pointerPath) {
11766
11227
  { cause: error }
11767
11228
  );
11768
11229
  }
11769
- if (!isRecord8(raw) || raw.kind !== "direct-officer-run-pointer" || raw.version !== 1) {
11230
+ if (!isRecord7(raw) || raw.kind !== "direct-officer-run-pointer" || raw.version !== 1) {
11770
11231
  throw new Error(`direct officer run pointer has unknown shape in ${pointerPath}`);
11771
11232
  }
11772
11233
  const sessionFile = raw.sessionFile;
@@ -12240,14 +11701,14 @@ var init_audit_escalation = __esm({
12240
11701
  });
12241
11702
 
12242
11703
  // src/session-opening-materials.ts
12243
- import { existsSync as existsSync8 } from "node:fs";
11704
+ import { existsSync as existsSync7 } from "node:fs";
12244
11705
  import { readFile as readFile14 } from "node:fs/promises";
12245
11706
  import { dirname as dirname14, join as join24 } from "node:path";
12246
11707
  import { fileURLToPath, pathToFileURL as pathToFileURL3 } from "node:url";
12247
11708
  function resolvePackageRootDir(moduleUrl = import.meta.url) {
12248
11709
  let dir = dirname14(fileURLToPath(moduleUrl));
12249
11710
  for (let i = 0; i < 8; i += 1) {
12250
- if (existsSync8(join24(dir, "package.json")) && existsSync8(join24(dir, "souls"))) {
11711
+ if (existsSync7(join24(dir, "package.json")) && existsSync7(join24(dir, "souls"))) {
12251
11712
  return dir;
12252
11713
  }
12253
11714
  const parent = dirname14(dir);
@@ -12470,7 +11931,7 @@ var init_serialize_thrown_value = __esm({
12470
11931
 
12471
11932
  // src/engine-detour-usage.ts
12472
11933
  import { randomUUID as randomUUID4 } from "node:crypto";
12473
- import { readFileSync as readFileSync3 } from "node:fs";
11934
+ import { readFileSync as readFileSync2 } from "node:fs";
12474
11935
  import { dirname as dirname15, join as join26 } from "node:path";
12475
11936
  function engineDetourStdoutByteLength(stdout) {
12476
11937
  return Buffer.byteLength(stdout, "utf8");
@@ -12524,11 +11985,11 @@ function reportEngineDetourCall(input) {
12524
11985
  recordPointer: pointer
12525
11986
  };
12526
11987
  }
12527
- function isRecord9(value) {
11988
+ function isRecord8(value) {
12528
11989
  return typeof value === "object" && value !== null && !Array.isArray(value);
12529
11990
  }
12530
11991
  function callFactFromSitianPayload(payload, pointer) {
12531
- if (!isRecord9(payload)) return void 0;
11992
+ if (!isRecord8(payload)) return void 0;
12532
11993
  if (payload.tool !== ENGINE_DETOUR_TOOL_NAME) return void 0;
12533
11994
  if (typeof payload.toolCallId !== "string" || payload.toolCallId.length === 0) {
12534
11995
  return void 0;
@@ -12545,11 +12006,11 @@ function callFactFromSitianPayload(payload, pointer) {
12545
12006
  };
12546
12007
  }
12547
12008
  function invocationScopeIdOfRecord(record4) {
12548
- if (isRecord9(record4.subject)) {
12009
+ if (isRecord8(record4.subject)) {
12549
12010
  const fromSubject = record4.subject.invocationScopeId;
12550
12011
  if (typeof fromSubject === "string" && fromSubject.length > 0) return fromSubject;
12551
12012
  }
12552
- if (isRecord9(record4.payload)) {
12013
+ if (isRecord8(record4.payload)) {
12553
12014
  const fromPayload = record4.payload.invocationScopeId;
12554
12015
  if (typeof fromPayload === "string" && fromPayload.length > 0) return fromPayload;
12555
12016
  }
@@ -12565,7 +12026,7 @@ async function readEngineDetourToolUsage(input) {
12565
12026
  ...input.cwd === void 0 ? {} : { cwd: input.cwd }
12566
12027
  });
12567
12028
  const { records } = await readSitianRecords(recordFile);
12568
- const calls = [];
12029
+ const callsByToolCallId = /* @__PURE__ */ new Map();
12569
12030
  for (const record4 of records) {
12570
12031
  if (record4.kind !== ENGINE_DETOUR_CALL_KIND) continue;
12571
12032
  const boundScope = invocationScopeIdOfRecord(record4);
@@ -12582,8 +12043,9 @@ async function readEngineDetourToolUsage(input) {
12582
12043
  };
12583
12044
  const fact = callFactFromSitianPayload(record4.payload, pointer);
12584
12045
  if (fact === void 0) continue;
12585
- calls.push(fact);
12046
+ callsByToolCallId.set(fact.toolCallId, fact);
12586
12047
  }
12048
+ const calls = Array.from(callsByToolCallId.values());
12587
12049
  return { callCount: calls.length, calls };
12588
12050
  }
12589
12051
  function projectEngineDetourToolUsageForPublicTerminal(usage, options) {
@@ -12607,9 +12069,9 @@ function projectEngineDetourToolUsageForPublicTerminal(usage, options) {
12607
12069
  function readInvocationRecord(runDirectory) {
12608
12070
  try {
12609
12071
  const raw = JSON.parse(
12610
- readFileSync3(join26(runDirectory, "invocation.json"), "utf8")
12072
+ readFileSync2(join26(runDirectory, "invocation.json"), "utf8")
12611
12073
  );
12612
- return isRecord9(raw) ? raw : void 0;
12074
+ return isRecord8(raw) ? raw : void 0;
12613
12075
  } catch (error) {
12614
12076
  if (error?.code === "ENOENT") return void 0;
12615
12077
  throw error;
@@ -12620,14 +12082,9 @@ async function readInvocationEngineMounted(runDirectory) {
12620
12082
  if (raw === void 0) return false;
12621
12083
  return typeof raw.engine === "string" && raw.engine.trim() !== "";
12622
12084
  }
12623
- function readInvocationSelectedHost(runDirectory) {
12624
- const raw = readInvocationRecord(runDirectory);
12625
- if (raw === void 0) return void 0;
12626
- return typeof raw.host === "string" && raw.host.trim() !== "" ? raw.host.trim() : void 0;
12627
- }
12628
12085
  function withEngineDetourToolUsageFact(outcome, usage) {
12629
12086
  if (usage === void 0) return outcome;
12630
- const prior = isRecord9(outcome.decisiveFacts) ? outcome.decisiveFacts : {};
12087
+ const prior = isRecord8(outcome.decisiveFacts) ? outcome.decisiveFacts : {};
12631
12088
  return {
12632
12089
  ...outcome,
12633
12090
  decisiveFacts: {
@@ -12669,7 +12126,7 @@ var init_engine_detour_usage = __esm({
12669
12126
  });
12670
12127
 
12671
12128
  // src/dossier-resolution.ts
12672
- import { existsSync as existsSync9, statSync as statSync2 } from "node:fs";
12129
+ import { existsSync as existsSync8, statSync as statSync2 } from "node:fs";
12673
12130
  import { resolve as resolve12 } from "node:path";
12674
12131
  function isHostContext(value) {
12675
12132
  return "sessionManager" in value;
@@ -12689,7 +12146,7 @@ function resolveAuditDossier(source) {
12689
12146
  }
12690
12147
  const runDirectory = resolve12(raw);
12691
12148
  try {
12692
- if (!existsSync9(runDirectory) || !statSync2(runDirectory).isDirectory()) {
12149
+ if (!existsSync8(runDirectory) || !statSync2(runDirectory).isDirectory()) {
12693
12150
  return { status: "incomplete", observation: { kind: "missing-dossier" } };
12694
12151
  }
12695
12152
  } catch {
@@ -12697,13 +12154,13 @@ function resolveAuditDossier(source) {
12697
12154
  }
12698
12155
  return { status: "ok", runDirectory };
12699
12156
  }
12700
- function isRecord10(value) {
12157
+ function isRecord9(value) {
12701
12158
  return typeof value === "object" && value !== null && !Array.isArray(value);
12702
12159
  }
12703
12160
  function readDoctorAuditSubjects(context) {
12704
12161
  const entries = context.sessionManager.getEntries?.() ?? [];
12705
12162
  for (const entry of entries) {
12706
- if (isRecord10(entry) && entry.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
12163
+ if (isRecord9(entry) && entry.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
12707
12164
  return { status: "ok" };
12708
12165
  }
12709
12166
  }
@@ -12736,11 +12193,11 @@ var init_dossier_resolution = __esm({
12736
12193
  });
12737
12194
 
12738
12195
  // src/receipt-delivery-policy.ts
12739
- function isRecord11(value) {
12196
+ function isRecord10(value) {
12740
12197
  return typeof value === "object" && value !== null && !Array.isArray(value);
12741
12198
  }
12742
12199
  function parseNoReceiptLifecycleFacts(input) {
12743
- if (!isRecord11(input) || typeof input.terminalToolCalled !== "boolean" || input.deliveryTurns !== RECEIPT_DELIVERY_TURN_LIMIT || input.sessionCompletion !== "settled-without-accepted-receipt" || input.acceptedReceipt !== false || typeof input.runPointer !== "string" || input.runPointer.trim() === "" || typeof input.attemptPointer !== "string" || input.attemptPointer.trim() === "" || !Array.isArray(input.rejectedReceipts) || !input.rejectedReceipts.every((item) => isRecord11(item) && typeof item.reason === "string")) {
12200
+ if (!isRecord10(input) || typeof input.terminalToolCalled !== "boolean" || input.deliveryTurns !== RECEIPT_DELIVERY_TURN_LIMIT || input.sessionCompletion !== "settled-without-accepted-receipt" || input.acceptedReceipt !== false || typeof input.runPointer !== "string" || input.runPointer.trim() === "" || typeof input.attemptPointer !== "string" || input.attemptPointer.trim() === "" || !Array.isArray(input.rejectedReceipts) || !input.rejectedReceipts.every((item) => isRecord10(item) && typeof item.reason === "string")) {
12744
12201
  throw new TypeError("malformed no-receipt lifecycle facts");
12745
12202
  }
12746
12203
  return {
@@ -13365,7 +12822,7 @@ async function readSitianRetainedAuditorProviderStop(sessionFile) {
13365
12822
  const { records } = await readSitianRecords(recordFile);
13366
12823
  for (let i = records.length - 1; i >= 0; i -= 1) {
13367
12824
  const payload = records[i]?.payload;
13368
- if (!isRecord12(payload) || !isRecord12(payload.response)) continue;
12825
+ if (!isRecord11(payload) || !isRecord11(payload.response)) continue;
13369
12826
  if (typeof payload.type === "string") continue;
13370
12827
  const stop = sessionProviderStopFromAssistant(payload.response);
13371
12828
  if (stop !== void 0) return stop;
@@ -13415,7 +12872,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
13415
12872
  throw sessionReadFailure(error, "failed to read discovered auditor session");
13416
12873
  }
13417
12874
  const header = entries.find((entry) => entry.type === "session");
13418
- if (!isRecord12(header)) continue;
12875
+ if (!isRecord11(header)) continue;
13419
12876
  const bindingIndexes = [];
13420
12877
  for (let i = 0; i < entries.length; i += 1) {
13421
12878
  const entry = entries[i];
@@ -13429,7 +12886,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
13429
12886
  end: idx + 1 < bindingIndexes.length ? bindingIndexes[idx + 1] : entries.length
13430
12887
  })) : [{ entry: void 0, start: 0, end: entries.length }];
13431
12888
  for (const { entry: bindingEntry, start, end } of bindingPasses) {
13432
- const bindingParent = bindingEntry !== void 0 && isRecord12(bindingEntry.data) && isRecord12(bindingEntry.data.parent) ? bindingEntry.data.parent : void 0;
12889
+ const bindingParent = bindingEntry !== void 0 && isRecord11(bindingEntry.data) && isRecord11(bindingEntry.data.parent) ? bindingEntry.data.parent : void 0;
13433
12890
  const attemptEntryId = typeof bindingParent?.attemptEntryId === "string" ? bindingParent.attemptEntryId : void 0;
13434
12891
  const boundSessionFile = typeof bindingParent?.sessionFile === "string" ? bindingParent.sessionFile : typeof header.parentSession === "string" ? header.parentSession : void 0;
13435
12892
  if (boundSessionFile !== sessionFile) continue;
@@ -13453,12 +12910,12 @@ function complianceFailureFromAuditorVolumes(volumes) {
13453
12910
  if (stop === void 0) continue;
13454
12911
  for (let i = entries.length - 1; i >= 0; i -= 1) {
13455
12912
  const entry = entries[i];
13456
- if (entry?.type !== "custom" || entry.customType !== AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE || !isRecord12(entry.data)) continue;
13457
- const parent = isRecord12(entry.data.parent) ? entry.data.parent : void 0;
13458
- const failure2 = isRecord12(entry.data.failure) ? entry.data.failure : void 0;
12913
+ if (entry?.type !== "custom" || entry.customType !== AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE || !isRecord11(entry.data)) continue;
12914
+ const parent = isRecord11(entry.data.parent) ? entry.data.parent : void 0;
12915
+ const failure2 = isRecord11(entry.data.failure) ? entry.data.failure : void 0;
13459
12916
  if (parent?.sessionId !== parentId || parent.sessionFile !== sessionFile || parent.attemptEntryId !== attemptEntryId) continue;
13460
12917
  if (failure2 === void 0) continue;
13461
- const identity = isRecord12(failure2.identity) ? failure2.identity : void 0;
12918
+ const identity = isRecord11(failure2.identity) ? failure2.identity : void 0;
13462
12919
  const typedCause = failure2.cause === "provider" || failure2.cause === "activation" || failure2.cause === "session" || failure2.cause === "output" || failure2.cause === "timeout" ? failure2.cause : void 0;
13463
12920
  return {
13464
12921
  ...typedCause === void 0 ? {} : { cause: typedCause },
@@ -13467,7 +12924,7 @@ function complianceFailureFromAuditorVolumes(volumes) {
13467
12924
  ...typeof identity.code === "string" || typeof identity.code === "number" ? { code: identity.code } : {}
13468
12925
  } },
13469
12926
  ...typeof failure2.diagnostic === "string" ? { diagnostic: failure2.diagnostic } : {},
13470
- ...isRecord12(failure2.details) ? { details: failure2.details } : {}
12927
+ ...isRecord11(failure2.details) ? { details: failure2.details } : {}
13471
12928
  };
13472
12929
  }
13473
12930
  }
@@ -13514,9 +12971,9 @@ function typedFailedTerminatingToolKnownFailure(entries) {
13514
12971
  if (classification.kind !== "infrastructure") continue;
13515
12972
  if (typeof message.toolCallId !== "string" || typeof message.toolName !== "string") continue;
13516
12973
  if (boundRoleToolCallForResult(attemptEntries, i, message, message.toolName) === void 0) continue;
13517
- const textPart = Array.isArray(message.content) ? message.content.find((part) => isRecord12(part) && part.type === "text" && typeof part.text === "string") : void 0;
13518
- const diagnostic = isRecord12(textPart) ? textPart.text : void 0;
13519
- const details = isRecord12(message.details) ? message.details : classification.fact;
12974
+ const textPart = Array.isArray(message.content) ? message.content.find((part) => isRecord11(part) && part.type === "text" && typeof part.text === "string") : void 0;
12975
+ const diagnostic = isRecord11(textPart) ? textPart.text : void 0;
12976
+ const details = isRecord11(message.details) ? message.details : classification.fact;
13520
12977
  return {
13521
12978
  cause: "activation",
13522
12979
  identity: { name: message.toolName, code: message.toolCallId },
@@ -13653,7 +13110,7 @@ function controlledFailureInputFromResolution(resolution) {
13653
13110
  } : {}
13654
13111
  };
13655
13112
  }
13656
- function isRecord12(value) {
13113
+ function isRecord11(value) {
13657
13114
  return typeof value === "object" && value !== null && !Array.isArray(value);
13658
13115
  }
13659
13116
  function toolResultText(message) {
@@ -13678,7 +13135,7 @@ function extractCollectorTargetBindRejection(entries) {
13678
13135
  const diagnostic = toolResultText(message);
13679
13136
  if (diagnostic.length === 0) return void 0;
13680
13137
  const details = message.details;
13681
- const code = isRecord12(details) && typeof details.code === "string" && details.code.trim() !== "" ? details.code : void 0;
13138
+ const code = isRecord11(details) && typeof details.code === "string" && details.code.trim() !== "" ? details.code : void 0;
13682
13139
  return code === void 0 ? { diagnostic } : { diagnostic, code };
13683
13140
  }
13684
13141
  return void 0;
@@ -13779,7 +13236,7 @@ function boundRoleToolCallForResult(entries, resultIndex, message, outputToolNam
13779
13236
  const candidateMessage = entries[index]?.message;
13780
13237
  if (candidateMessage?.role === "assistant" && Array.isArray(candidateMessage.content)) {
13781
13238
  for (const part of candidateMessage.content) {
13782
- if (!isRecord12(part) || part.type !== "toolCall" || part.id !== callId) {
13239
+ if (!isRecord11(part) || part.type !== "toolCall" || part.id !== callId) {
13783
13240
  continue;
13784
13241
  }
13785
13242
  if (part.name !== outputToolName) return void 0;
@@ -13850,7 +13307,7 @@ function parseNavigatorAttendanceDetails(details) {
13850
13307
  if (typeof details.prose === "string" && details.prose.trim() !== "") {
13851
13308
  prose = details.prose;
13852
13309
  } else {
13853
- const next = isRecord12(details.next) && typeof details.next.role === "string" ? details.next.role : void 0;
13310
+ const next = isRecord11(details.next) && typeof details.next.role === "string" ? details.next.role : void 0;
13854
13311
  const reason = typeof details.reason === "string" && details.reason.trim() !== "" ? details.reason : void 0;
13855
13312
  const command = typeof details.command === "string" && details.command.trim() !== "" ? details.command : void 0;
13856
13313
  if (reason !== void 0 && next !== void 0) {
@@ -13959,7 +13416,7 @@ function detourGateContext(admitted, scope) {
13959
13416
  }
13960
13417
  async function withOptionalGateProjection(base, sessionDirectory, gateContext = {}) {
13961
13418
  const secondaryEvidence = base.roleOutcome.kind === "failure" ? base.roleOutcome.decisiveFacts.secondaryEvidence : void 0;
13962
- const skipGate = isRecord12(secondaryEvidence) && secondaryEvidence.kind === "role_infrastructure_failure" && packagedSkipsGateOnInfrastructureStage(secondaryEvidence.stage);
13419
+ const skipGate = isRecord11(secondaryEvidence) && secondaryEvidence.kind === "role_infrastructure_failure" && packagedSkipsGateOnInfrastructureStage(secondaryEvidence.stage);
13963
13420
  let next = base;
13964
13421
  if (!skipGate) {
13965
13422
  const gate = await extractGateFactFromSessionDirectory(sessionDirectory, gateContext);
@@ -13972,7 +13429,7 @@ function routePlaybookFailureMessage(entries) {
13972
13429
  const entry = entries[i];
13973
13430
  if (entry?.type !== "custom" || entry.customType !== NAVIGATOR_ROUTE_PLAYBOOK_FAILURE_ENTRY) continue;
13974
13431
  const data = entry.data;
13975
- if (!isRecord12(data) || typeof data.message !== "string" || data.message.trim() === "") return void 0;
13432
+ if (!isRecord11(data) || typeof data.message !== "string" || data.message.trim() === "") return void 0;
13976
13433
  return data.message;
13977
13434
  }
13978
13435
  return void 0;
@@ -14019,7 +13476,7 @@ function extractNavigatorAttendanceFact(entries) {
14019
13476
  const entry = entries[i];
14020
13477
  if (entry?.type === "custom_message" && entry.customType === "ak-navigator-attendance") {
14021
13478
  const details = entry.message?.details ?? entry.details;
14022
- if (!isRecord12(details)) {
13479
+ if (!isRecord11(details)) {
14023
13480
  return {
14024
13481
  disposition: "unavailable",
14025
13482
  source: "unknown",
@@ -14170,7 +13627,7 @@ async function settleSealedAcceptedOrToolResidual(admitted, authority, scope, ro
14170
13627
  const residual = boundErroredToolCandidate(entries, index, message, residualToolName);
14171
13628
  if (residual === void 0) continue;
14172
13629
  const candidate = residual.candidate;
14173
- const details = isRecord12(candidate) ? candidate : { candidate };
13630
+ const details = isRecord11(candidate) ? candidate : { candidate };
14174
13631
  const failed = await settleFailureTerminalResult(
14175
13632
  admitted,
14176
13633
  {
@@ -14245,7 +13702,7 @@ function extractDoctorCandidateFacts(entries) {
14245
13702
  continue;
14246
13703
  }
14247
13704
  const data = entry.data;
14248
- if (!isRecord12(data)) return {};
13705
+ if (!isRecord11(data)) return {};
14249
13706
  return {
14250
13707
  ...data.cost === void 0 ? {} : { cost: data.cost },
14251
13708
  ...data.auditNoReceipt === void 0 ? {} : { auditNoReceipt: data.auditNoReceipt }
@@ -14330,7 +13787,7 @@ async function settleLawfulSeatAcceptedTerminalResult(admitted, authority, spec,
14330
13787
  let residual;
14331
13788
  for (let index = entries.length - 1; index >= scanStart; index -= 1) {
14332
13789
  const entry = entries[index];
14333
- if (entry?.type === "custom" && entry.customType === "ak-role-submission-closure" && isRecord12(entry.data) && entry.data.toolName === spec.toolName && classifyPackagedRoleTerminalResult(entry.data).kind === "accepted") {
13790
+ if (entry?.type === "custom" && entry.customType === "ak-role-submission-closure" && isRecord11(entry.data) && entry.data.toolName === spec.toolName && classifyPackagedRoleTerminalResult(entry.data).kind === "accepted") {
14334
13791
  thisAttemptHasSeatSuccess = true;
14335
13792
  }
14336
13793
  const message = entries[index]?.message;
@@ -14370,7 +13827,7 @@ async function settleLawfulSeatAcceptedTerminalResult(admitted, authority, spec,
14370
13827
  );
14371
13828
  }
14372
13829
  if (residual !== void 0) {
14373
- const details = isRecord12(residual.candidate) ? residual.candidate : { candidate: residual.candidate };
13830
+ const details = isRecord11(residual.candidate) ? residual.candidate : { candidate: residual.candidate };
14374
13831
  const failed = await settleFailureTerminalResult(
14375
13832
  admitted,
14376
13833
  {
@@ -14420,7 +13877,7 @@ function countersignTerminalFromEntries(entries) {
14420
13877
  return void 0;
14421
13878
  }
14422
13879
  function withCountersignTerminalFact(roleOutcome, officer) {
14423
- const prior = roleOutcome.decisiveFacts !== void 0 && isRecord12(roleOutcome.decisiveFacts) ? roleOutcome.decisiveFacts : {};
13880
+ const prior = roleOutcome.decisiveFacts !== void 0 && isRecord11(roleOutcome.decisiveFacts) ? roleOutcome.decisiveFacts : {};
14424
13881
  return {
14425
13882
  ...roleOutcome,
14426
13883
  decisiveFacts: {
@@ -14433,7 +13890,7 @@ function acceptedSecretariatDefinesOfficerProjection(roleOutcome) {
14433
13890
  const payloads = roleOutcome.payloads ?? [];
14434
13891
  for (let index = payloads.length - 1; index >= 0; index -= 1) {
14435
13892
  const payload = payloads[index];
14436
- if (!isRecord12(payload)) continue;
13893
+ if (!isRecord11(payload)) continue;
14437
13894
  const status = payload.secretariatStatus;
14438
13895
  if (typeof status !== "string") continue;
14439
13896
  return status === "converged";
@@ -14878,7 +14335,7 @@ var init_settlement = __esm({
14878
14335
  });
14879
14336
 
14880
14337
  // src/archivist-record-pointer.ts
14881
- import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
14338
+ import { mkdirSync as mkdirSync2, writeFileSync } from "node:fs";
14882
14339
  import { dirname as dirname17, join as join28 } from "node:path";
14883
14340
  function bookDirectOfficerRunPointer(options) {
14884
14341
  const nest = join28(dirname17(options.parentSessionFile), "auditor-roles");
@@ -14890,7 +14347,7 @@ function bookDirectOfficerRunPointer(options) {
14890
14347
  sessionFile: options.sessionFile,
14891
14348
  ...options.runDirectory !== void 0 && options.runDirectory.trim() !== "" ? { runDirectory: options.runDirectory } : {}
14892
14349
  };
14893
- writeFileSync2(
14350
+ writeFileSync(
14894
14351
  join28(nest, `${options.officer}.pointer.json`),
14895
14352
  `${JSON.stringify(pointer)}
14896
14353
  `,
@@ -15284,78 +14741,281 @@ var init_case_dossier_delivery = __esm({
15284
14741
  }
15285
14742
  });
15286
14743
 
15287
- // src/host-transition-prior-native.ts
15288
- import { access as access3, readdir as readdir6 } from "node:fs/promises";
14744
+ // src/public-cli/process-cancel.ts
14745
+ function processCancelSignalName(signal) {
14746
+ if (signal === void 0 || signal.aborted !== true) return void 0;
14747
+ const reason = signal.reason;
14748
+ if (reason === "SIGTERM" || reason === "SIGINT" || reason === "SIGHUP") {
14749
+ return reason;
14750
+ }
14751
+ return void 0;
14752
+ }
14753
+ function processCancelDiagnostic(signalName) {
14754
+ return `ak-role terminated by ${signalName}`;
14755
+ }
14756
+ var init_process_cancel = __esm({
14757
+ "src/public-cli/process-cancel.ts"() {
14758
+ "use strict";
14759
+ }
14760
+ });
14761
+
14762
+ // src/host-session-record.ts
14763
+ import { spawnSync } from "node:child_process";
14764
+ import {
14765
+ appendFileSync as appendFileSync2,
14766
+ copyFileSync,
14767
+ closeSync,
14768
+ existsSync as existsSync9,
14769
+ openSync,
14770
+ readFileSync as readFileSync3,
14771
+ mkdirSync as mkdirSync3,
14772
+ readdirSync as readdirSync2,
14773
+ rmSync,
14774
+ statSync as statSync3
14775
+ } from "node:fs";
14776
+ import { homedir } from "node:os";
15289
14777
  import { dirname as dirname19, join as join31 } from "node:path";
15290
- function isEnoent2(error) {
15291
- return typeof error === "object" && error !== null && error.code === "ENOENT";
14778
+ function declareHostSessionFailure(error) {
14779
+ const message = error instanceof Error ? error.stack || error.message : String(error);
14780
+ process.stderr.write(`[host-session] Dossier record failure: ${message}
14781
+ `);
15292
14782
  }
15293
- async function listPiNativeRecordPaths(sessionFile) {
14783
+ function sitianReportSafe(input) {
15294
14784
  try {
15295
- await access3(sessionFile);
15296
- return [sessionFile];
14785
+ sitianReport(input);
15297
14786
  } catch (error) {
15298
- if (isEnoent2(error)) return [];
15299
- throw error;
14787
+ declareHostSessionFailure(error);
14788
+ }
14789
+ }
14790
+ function findCodexRollout(sessionsDir, sessionId) {
14791
+ if (!existsSync9(sessionsDir)) return void 0;
14792
+ const matches = [];
14793
+ function scan(dir, depth = 0) {
14794
+ if (depth > 6) return;
14795
+ let entries;
14796
+ try {
14797
+ entries = readdirSync2(dir, { withFileTypes: true });
14798
+ } catch {
14799
+ return;
14800
+ }
14801
+ for (const entry of entries) {
14802
+ const fullPath = join31(dir, entry.name);
14803
+ if (entry.isDirectory()) {
14804
+ scan(fullPath, depth + 1);
14805
+ } else if (entry.isFile() && entry.name.endsWith(".jsonl") && entry.name.includes(sessionId)) {
14806
+ try {
14807
+ const stat2 = statSync3(fullPath);
14808
+ matches.push({ path: fullPath, mtime: stat2.mtimeMs });
14809
+ } catch {
14810
+ matches.push({ path: fullPath, mtime: 0 });
14811
+ }
14812
+ }
14813
+ }
15300
14814
  }
14815
+ scan(sessionsDir);
14816
+ if (matches.length === 0 || matches[0] === void 0) return void 0;
14817
+ matches.sort((a, b) => b.mtime - a.mtime);
14818
+ return matches[0]?.path;
15301
14819
  }
15302
- async function listSitianRecordPaths(sessionParent) {
15303
- const sessionRoot = dirname19(sessionParent);
15304
- let entries;
14820
+ function sanitizeClaudeCwd(cwd) {
14821
+ return cwd.replace(/[^a-zA-Z0-9]/g, "-");
14822
+ }
14823
+ function resolveNativeSessionPath(options) {
14824
+ const home = options.home || homedir();
14825
+ if (options.host === "claude") {
14826
+ const configDir = process.env.CLAUDE_CONFIG_DIR || join31(home, ".claude");
14827
+ const sanitizedCwd = sanitizeClaudeCwd(options.cwd);
14828
+ return join31(configDir, "projects", sanitizedCwd, `${options.sessionId}.jsonl`);
14829
+ }
14830
+ if (options.host === "codex") {
14831
+ return findCodexRollout(codexSessionsDirectory(home), options.sessionId);
14832
+ }
14833
+ if (options.host === "grok-build") {
14834
+ const grokHome = process.env.GROK_HOME || join31(home, ".grok");
14835
+ return join31(grokHome, "sessions", encodeURIComponent(options.cwd), options.sessionId);
14836
+ }
14837
+ return void 0;
14838
+ }
14839
+ function codexSessionsDirectory(home) {
14840
+ return join31(process.env.CODEX_HOME || join31(home || homedir(), ".codex"), "sessions");
14841
+ }
14842
+ function recordRunStart(runDirectory) {
14843
+ try {
14844
+ appendFileSync2(join31(runDirectory, ".run-starts"), "\n");
14845
+ } catch (error) {
14846
+ declareHostSessionFailure(error);
14847
+ }
14848
+ }
14849
+ function resolveHostDossierLandingPath(options) {
14850
+ const sanitizedModel = (options.model?.model ?? "default").replace(/[\/\\]+/g, "-");
14851
+ let maxOrdinal = 0;
14852
+ if (existsSync9(options.sessionDirectory)) {
14853
+ try {
14854
+ const entries = readdirSync2(options.sessionDirectory);
14855
+ for (const entry of entries) {
14856
+ const match = entry.match(/-(\d+)(?:\.jsonl|\.failed)?$/);
14857
+ const first = match?.[1];
14858
+ if (first !== void 0) {
14859
+ const val = parseInt(first, 10);
14860
+ if (!isNaN(val) && val > maxOrdinal) {
14861
+ maxOrdinal = val;
14862
+ }
14863
+ }
14864
+ }
14865
+ } catch {
14866
+ }
14867
+ }
14868
+ const startsPath = join31(dirname19(options.sessionDirectory), ".run-starts");
14869
+ let starts = 0;
14870
+ if (existsSync9(startsPath)) starts = readFileSync3(startsPath, "utf8").length;
14871
+ const ordinal = Math.max(maxOrdinal + 1, starts, options.continuation.kind === "resume" ? 2 : 1);
14872
+ const baseName = `${options.host}-${sanitizedModel}-${ordinal}`;
14873
+ const landingPath = options.host === "grok-build" ? join31(options.sessionDirectory, baseName) : join31(options.sessionDirectory, `${baseName}.jsonl`);
14874
+ return { landingPath, ordinal, sanitizedModel };
14875
+ }
14876
+ function recordNativeSessionPointer(options) {
14877
+ if (options.host === "pi" || options.host === "hermes") {
14878
+ return void 0;
14879
+ }
14880
+ const nativePath = options.host === "codex" ? codexSessionsDirectory(options.home) : resolveNativeSessionPath(options);
14881
+ if (nativePath === void 0) return void 0;
14882
+ sitianReportSafe({
14883
+ level: "event",
14884
+ kind: HOST_SESSION_RECORD_KIND,
14885
+ host: options.host,
14886
+ cwd: options.cwd,
14887
+ sessionParent: options.sessionParent,
14888
+ source: `${options.host}-dossier`,
14889
+ payload: {
14890
+ type: "native-session-pointer",
14891
+ nativePath,
14892
+ sessionId: options.sessionId
14893
+ }
14894
+ });
14895
+ return nativePath;
14896
+ }
14897
+ function copyFileCloneOrFallback(src, dest) {
14898
+ try {
14899
+ const res = spawnSync("cp", ["-c", src, dest]);
14900
+ if (res.status === 0) return;
14901
+ } catch {
14902
+ }
14903
+ copyFileSync(src, dest);
14904
+ }
14905
+ function copyGrokDossier(srcDir, destDir) {
14906
+ const chatHistorySrc = join31(srcDir, "chat_history.jsonl");
14907
+ if (!existsSync9(chatHistorySrc)) {
14908
+ throw new Error(`Grok native chat_history.jsonl missing at ${chatHistorySrc}`);
14909
+ }
14910
+ mkdirSync3(destDir, { recursive: true });
14911
+ const chatHistoryDest = join31(destDir, "chat_history.jsonl");
14912
+ copyFileCloneOrFallback(chatHistorySrc, chatHistoryDest);
14913
+ const usageSrc = join31(srcDir, "usage.json");
14914
+ if (!existsSync9(usageSrc)) {
14915
+ throw new Error(`Grok native usage.json missing at ${usageSrc}`);
14916
+ }
14917
+ copyFileCloneOrFallback(usageSrc, join31(destDir, "usage.json"));
14918
+ }
14919
+ function copyAndRecordHostDossier(options) {
14920
+ if (options.host === "pi" || options.host === "hermes") {
14921
+ return;
14922
+ }
14923
+ const nativePath = resolveNativeSessionPath({
14924
+ host: options.host,
14925
+ sessionId: options.sessionId,
14926
+ cwd: options.cwd,
14927
+ ...options.home !== void 0 ? { home: options.home } : {}
14928
+ });
14929
+ if (nativePath === void 0 && options.host !== "codex") return;
14930
+ let destination;
15305
14931
  try {
15306
- entries = await readdir6(sessionRoot, { withFileTypes: true });
14932
+ destination = resolveHostDossierLandingPath(options);
15307
14933
  } catch (error) {
15308
- if (isEnoent2(error)) return [];
15309
- throw error;
14934
+ sitianReportSafe({
14935
+ level: "event",
14936
+ kind: HOST_SESSION_RECORD_KIND,
14937
+ host: options.host,
14938
+ cwd: options.cwd,
14939
+ sessionParent: options.sessionParent,
14940
+ source: `${options.host}-dossier`,
14941
+ payload: {
14942
+ type: "native-session-warning",
14943
+ sessionId: options.sessionId,
14944
+ error: error instanceof Error ? error.message : String(error)
14945
+ }
14946
+ });
14947
+ return;
15310
14948
  }
15311
- const recordPaths = [];
15312
- for (const entry of entries) {
15313
- if (!entry.isDirectory()) continue;
15314
- const recordFile = join31(sessionRoot, entry.name, "records.jsonl");
14949
+ const { landingPath, ordinal, sanitizedModel } = destination;
14950
+ let lastError;
14951
+ let copySuccess = false;
14952
+ for (let attempt = 1; attempt <= 2; attempt++) {
15315
14953
  try {
15316
- await access3(recordFile);
15317
- recordPaths.push(recordFile);
14954
+ if (options.host === "grok-build") {
14955
+ copyGrokDossier(nativePath, landingPath);
14956
+ } else {
14957
+ if (nativePath === void 0 || !existsSync9(nativePath)) {
14958
+ throw new Error(`Native session file missing for ${options.host} session ${options.sessionId}`);
14959
+ }
14960
+ mkdirSync3(dirname19(landingPath), { recursive: true });
14961
+ copyFileCloneOrFallback(nativePath, landingPath);
14962
+ }
14963
+ copySuccess = true;
14964
+ break;
15318
14965
  } catch (error) {
15319
- if (!isEnoent2(error)) throw error;
14966
+ lastError = error;
15320
14967
  }
15321
14968
  }
15322
- recordPaths.sort();
15323
- return recordPaths;
15324
- }
15325
- async function projectHostTransitionPriorNative(input) {
15326
- if (input.previousHost === input.liveHost) return void 0;
15327
- if (input.previousHost === "pi") {
15328
- return {
15329
- priorNativeKind: "pi-native",
15330
- priorNativePaths: await listPiNativeRecordPaths(input.piSessionFile)
15331
- };
15332
- }
15333
- return {
15334
- priorNativeKind: "sitian",
15335
- priorNativePaths: await listSitianRecordPaths(input.piSessionFile)
15336
- };
15337
- }
15338
- var init_host_transition_prior_native = __esm({
15339
- "src/host-transition-prior-native.ts"() {
15340
- "use strict";
15341
- }
15342
- });
15343
-
15344
- // src/public-cli/process-cancel.ts
15345
- function processCancelSignalName(signal) {
15346
- if (signal === void 0 || signal.aborted !== true) return void 0;
15347
- const reason = signal.reason;
15348
- if (reason === "SIGTERM" || reason === "SIGINT" || reason === "SIGHUP") {
15349
- return reason;
14969
+ if (copySuccess) {
14970
+ sitianReportSafe({
14971
+ level: "event",
14972
+ kind: HOST_SESSION_RECORD_KIND,
14973
+ host: options.host,
14974
+ cwd: options.cwd,
14975
+ sessionParent: options.sessionParent,
14976
+ source: `${options.host}-dossier`,
14977
+ payload: {
14978
+ type: "native-session-copy",
14979
+ nativePath,
14980
+ landingPath,
14981
+ ordinal,
14982
+ sessionId: options.sessionId
14983
+ }
14984
+ });
14985
+ } else {
14986
+ try {
14987
+ rmSync(landingPath, { recursive: options.host === "grok-build", force: true });
14988
+ } catch {
14989
+ }
14990
+ try {
14991
+ mkdirSync3(options.sessionDirectory, { recursive: true });
14992
+ closeSync(openSync(join31(options.sessionDirectory, `${options.host}-${sanitizedModel}-${ordinal}.failed`), "a"));
14993
+ } catch {
14994
+ }
14995
+ sitianReportSafe({
14996
+ level: "event",
14997
+ kind: HOST_SESSION_RECORD_KIND,
14998
+ host: options.host,
14999
+ cwd: options.cwd,
15000
+ sessionParent: options.sessionParent,
15001
+ source: `${options.host}-dossier`,
15002
+ payload: {
15003
+ type: "native-session-warning",
15004
+ nativePath,
15005
+ landingPath,
15006
+ ordinal,
15007
+ sessionId: options.sessionId,
15008
+ error: lastError instanceof Error ? lastError.message : String(lastError)
15009
+ }
15010
+ });
15350
15011
  }
15351
- return void 0;
15352
- }
15353
- function processCancelDiagnostic(signalName) {
15354
- return `ak-role terminated by ${signalName}`;
15355
15012
  }
15356
- var init_process_cancel = __esm({
15357
- "src/public-cli/process-cancel.ts"() {
15013
+ var HOST_SESSION_RECORD_KIND;
15014
+ var init_host_session_record = __esm({
15015
+ "src/host-session-record.ts"() {
15358
15016
  "use strict";
15017
+ init_sitian_facade();
15018
+ HOST_SESSION_RECORD_KIND = "host-session";
15359
15019
  }
15360
15020
  });
15361
15021
 
@@ -16021,35 +15681,6 @@ async function dispatchPostAdmissionTurn(input) {
16021
15681
  }
16022
15682
  };
16023
15683
  try {
16024
- let previousHost;
16025
- const liveHost = env.host;
16026
- const principalCoordinates = admitted.principal === void 0 ? void 0 : env.principalAuthority.decode(admitted.principal);
16027
- let hostTransition;
16028
- try {
16029
- previousHost = readInvocationSelectedHost(admitted.runDirectory);
16030
- hostTransition = previousHost !== void 0 && liveHost !== void 0 && principalCoordinates !== void 0 ? await projectHostTransitionPriorNative({
16031
- previousHost,
16032
- liveHost,
16033
- piSessionFile: principalCoordinates.sessionFile
16034
- }) : void 0;
16035
- } catch (error) {
16036
- return {
16037
- ...await presentControlledFailure2(
16038
- admitted,
16039
- withEngineDetourInvocationScope({
16040
- timedOut: false,
16041
- code: null,
16042
- stderr: "",
16043
- thrown: error
16044
- }, request.invocationScopeId),
16045
- adapters,
16046
- env.principalAuthority,
16047
- io,
16048
- persistRunState
16049
- ),
16050
- ...deferredPersist
16051
- };
16052
- }
16053
15684
  await clearTypedProviderHttpObservation(admitted.runDirectory);
16054
15685
  if (adapters.beforeDispatch !== void 0) {
16055
15686
  try {
@@ -16085,11 +15716,8 @@ async function dispatchPostAdmissionTurn(input) {
16085
15716
  if (env.stationChild !== void 0) {
16086
15717
  turnRequest = { ...turnRequest, stationChild: env.stationChild };
16087
15718
  }
16088
- if (hostTransition !== void 0) {
16089
- turnRequest = { ...turnRequest, hostTransition };
16090
- }
16091
- if (typeof liveHost === "string" && liveHost.trim() !== "") {
16092
- turnRequest = { ...turnRequest, host: liveHost.trim() };
15719
+ if (typeof env.host === "string" && env.host.trim() !== "") {
15720
+ turnRequest = { ...turnRequest, host: env.host.trim() };
16093
15721
  }
16094
15722
  await deliverCaseDossierAsAttachment({
16095
15723
  ticketNumber: admitted.ticketNumber,
@@ -16106,6 +15734,7 @@ async function dispatchPostAdmissionTurn(input) {
16106
15734
  );
16107
15735
  let result;
16108
15736
  try {
15737
+ recordRunStart(admitted.runDirectory);
16109
15738
  result = await env.roleTurnHost.executeTurn(turnRequest);
16110
15739
  } catch (error) {
16111
15740
  const processCancelName = processCancelSignalName(env.signal);
@@ -16805,10 +16434,10 @@ var init_post_admission = __esm({
16805
16434
  init_packaged_role_registry();
16806
16435
  init_case_dossier_delivery();
16807
16436
  init_engine_detour_usage();
16808
- init_host_transition_prior_native();
16809
16437
  init_run_lifecycle();
16810
16438
  init_process_cancel();
16811
16439
  init_activation_ledger_topology();
16440
+ init_host_session_record();
16812
16441
  init_settlement();
16813
16442
  init_terminal();
16814
16443
  init_auto_resume();
@@ -16842,10 +16471,10 @@ var init_seat_ticket_binding = __esm({
16842
16471
  });
16843
16472
 
16844
16473
  // src/public-cli/machine-method-skills.ts
16845
- import { accessSync, constants as constants2, statSync as statSync3 } from "node:fs";
16474
+ import { accessSync, constants as constants2, statSync as statSync4 } from "node:fs";
16846
16475
  import { lstat as lstat6, mkdir as mkdir4, symlink } from "node:fs/promises";
16847
16476
  import { join as join34 } from "node:path";
16848
- import { spawnSync } from "node:child_process";
16477
+ import { spawnSync as spawnSync2 } from "node:child_process";
16849
16478
  function skillRoot(home) {
16850
16479
  return join34(home, ".agents/skills");
16851
16480
  }
@@ -16855,7 +16484,7 @@ function installedMethodSkillPath(home, name) {
16855
16484
  function installedSkillPath(root, name) {
16856
16485
  const path = join34(root, name, "SKILL.md");
16857
16486
  try {
16858
- if (!statSync3(path).isFile()) return void 0;
16487
+ if (!statSync4(path).isFile()) return void 0;
16859
16488
  accessSync(path, constants2.R_OK);
16860
16489
  return path;
16861
16490
  } catch (error) {
@@ -16896,7 +16525,7 @@ async function warnMissingMethodSkills(home, host, role, skills, stdout) {
16896
16525
  }
16897
16526
  }
16898
16527
  function runSkillsCli(args, home) {
16899
- const result = spawnSync("npx", ["--yes", "skills", ...args], {
16528
+ const result = spawnSync2("npx", ["--yes", "skills", ...args], {
16900
16529
  stdio: "inherit",
16901
16530
  env: { ...process.env, HOME: home }
16902
16531
  });
@@ -17083,11 +16712,11 @@ var init_turn_request = __esm({
17083
16712
  });
17084
16713
 
17085
16714
  // src/public-cli/countersign-run.ts
17086
- function isRecord13(value) {
16715
+ function isRecord12(value) {
17087
16716
  return typeof value === "object" && value !== null && !Array.isArray(value);
17088
16717
  }
17089
16718
  function isEscalatePayload(payload) {
17090
- if (!isRecord13(payload)) return false;
16719
+ if (!isRecord12(payload)) return false;
17091
16720
  return payload.status === "escalate";
17092
16721
  }
17093
16722
  function courtDiaristPayloadRows(roleOutcome, submissions) {
@@ -18302,13 +17931,13 @@ var init_instruction_seat_run = __esm({
18302
17931
  });
18303
17932
 
18304
17933
  // src/analyst-book-key.ts
18305
- import { statSync as statSync4 } from "node:fs";
17934
+ import { statSync as statSync5 } from "node:fs";
18306
17935
  import { isAbsolute as isAbsolute8 } from "node:path";
18307
17936
  function resolveAnalystBookKey(projectRoot) {
18308
17937
  const identity = physicalPathIdentity(projectRoot);
18309
17938
  let stats;
18310
17939
  try {
18311
- stats = statSync4(identity);
17940
+ stats = statSync5(identity);
18312
17941
  } catch (error) {
18313
17942
  const code = errnoCode(error);
18314
17943
  if (code === "ENOENT" || code === "ENOTDIR") return `root:${identity}`;
@@ -18668,7 +18297,7 @@ var init_analyst_cohort = __esm({
18668
18297
  });
18669
18298
 
18670
18299
  // src/analyst-ledger.ts
18671
- import { readdir as readdir7, readFile as readFile20 } from "node:fs/promises";
18300
+ import { readdir as readdir6, readFile as readFile20 } from "node:fs/promises";
18672
18301
  import { basename as basename9, join as join36 } from "node:path";
18673
18302
  function isMissingPathError6(error) {
18674
18303
  return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
@@ -18676,7 +18305,7 @@ function isMissingPathError6(error) {
18676
18305
  function errorText3(error) {
18677
18306
  return error instanceof Error ? error.message : String(error);
18678
18307
  }
18679
- function isRecord14(value) {
18308
+ function isRecord13(value) {
18680
18309
  return typeof value === "object" && value !== null && !Array.isArray(value);
18681
18310
  }
18682
18311
  async function readExistingRunLifecycleState(runDirectory) {
@@ -18717,7 +18346,7 @@ function parseRunDirectoryName2(name) {
18717
18346
  }
18718
18347
  async function listLedgerBookNames(booksRoot) {
18719
18348
  try {
18720
- const entries = await readdir7(booksRoot, { withFileTypes: true });
18349
+ const entries = await readdir6(booksRoot, { withFileTypes: true });
18721
18350
  return entries.filter((e) => e.isDirectory()).map((e) => e.name).sort();
18722
18351
  } catch (error) {
18723
18352
  if (isMissingPathError6(error)) return [];
@@ -18733,7 +18362,7 @@ async function readInvocationScopeFields(runDirectory) {
18733
18362
  throw error;
18734
18363
  }
18735
18364
  const parsed = JSON.parse(raw);
18736
- if (!isRecord14(parsed)) return void 0;
18365
+ if (!isRecord13(parsed)) return void 0;
18737
18366
  if (typeof parsed.projectRoot !== "string" || parsed.projectRoot.trim() === "") {
18738
18367
  return void 0;
18739
18368
  }
@@ -18762,7 +18391,7 @@ async function resolveSessionFile(runDirectory) {
18762
18391
  try {
18763
18392
  const raw = await readFile20(join36(runDirectory, "invocation.json"), "utf8");
18764
18393
  const parsed = JSON.parse(raw);
18765
- if (isRecord14(parsed) && typeof parsed.sessionFile === "string" && parsed.sessionFile.trim() !== "") {
18394
+ if (isRecord13(parsed) && typeof parsed.sessionFile === "string" && parsed.sessionFile.trim() !== "") {
18766
18395
  return parsed.sessionFile;
18767
18396
  }
18768
18397
  } catch (error) {
@@ -19100,7 +18729,7 @@ var init_analyst_ledger = __esm({
19100
18729
  });
19101
18730
 
19102
18731
  // src/analyst-metric-families/acceptance-success-rework.ts
19103
- function isRecord15(value) {
18732
+ function isRecord14(value) {
19104
18733
  return typeof value === "object" && value !== null && !Array.isArray(value);
19105
18734
  }
19106
18735
  function wallMsFromSpan(span) {
@@ -19109,21 +18738,21 @@ function wallMsFromSpan(span) {
19109
18738
  function findCollectorGroups(body) {
19110
18739
  if (Array.isArray(body.groups)) return body.groups;
19111
18740
  const receipt = body.receipt;
19112
- if (isRecord15(receipt) && Array.isArray(receipt.groups)) return receipt.groups;
18741
+ if (isRecord14(receipt) && Array.isArray(receipt.groups)) return receipt.groups;
19113
18742
  const outcome = body.outcome;
19114
- if (isRecord15(outcome)) {
18743
+ if (isRecord14(outcome)) {
19115
18744
  const facts = outcome.decisiveFacts;
19116
- if (isRecord15(facts) && Array.isArray(facts.groups)) return facts.groups;
18745
+ if (isRecord14(facts) && Array.isArray(facts.groups)) return facts.groups;
19117
18746
  }
19118
18747
  return void 0;
19119
18748
  }
19120
18749
  function extractStatus(body) {
19121
18750
  const outcome = body.outcome;
19122
- if (isRecord15(outcome) && typeof outcome.status === "string" && outcome.status.trim() !== "") {
18751
+ if (isRecord14(outcome) && typeof outcome.status === "string" && outcome.status.trim() !== "") {
19123
18752
  return outcome.status;
19124
18753
  }
19125
18754
  const receipt = body.receipt;
19126
- if (isRecord15(receipt) && typeof receipt.status === "string" && receipt.status.trim() !== "") {
18755
+ if (isRecord14(receipt) && typeof receipt.status === "string" && receipt.status.trim() !== "") {
19127
18756
  return receipt.status;
19128
18757
  }
19129
18758
  if (typeof body.status === "string" && body.status.trim() !== "") {
@@ -19749,15 +19378,15 @@ var init_leg_wall_clock = __esm({
19749
19378
  });
19750
19379
 
19751
19380
  // src/analyst-metric-families/round-timeline.ts
19752
- function isRecord16(value) {
19381
+ function isRecord15(value) {
19753
19382
  return typeof value === "object" && value !== null && !Array.isArray(value);
19754
19383
  }
19755
19384
  function wallMsFromSpan2(startedAt, endedAt) {
19756
19385
  return Date.parse(endedAt) - Date.parse(startedAt);
19757
19386
  }
19758
19387
  function readClassCount(body) {
19759
- if (!isRecord16(body.outcome)) return void 0;
19760
- if (!isRecord16(body.outcome.decisiveFacts)) return void 0;
19388
+ if (!isRecord15(body.outcome)) return void 0;
19389
+ if (!isRecord15(body.outcome.decisiveFacts)) return void 0;
19761
19390
  const classCount = body.outcome.decisiveFacts.classCount;
19762
19391
  if (typeof classCount !== "number" || !Number.isFinite(classCount)) {
19763
19392
  return void 0;
@@ -19901,7 +19530,7 @@ var init_analyst_metric_family = __esm({
19901
19530
  });
19902
19531
 
19903
19532
  // src/analyst-page.ts
19904
- import { createHash as createHash7 } from "node:crypto";
19533
+ import { createHash as createHash5 } from "node:crypto";
19905
19534
  import { dirname as dirname22, join as join37 } from "node:path";
19906
19535
  function analystIssuePageKey(address) {
19907
19536
  const parts = ["book", address.bookKey];
@@ -19910,7 +19539,7 @@ function analystIssuePageKey(address) {
19910
19539
  } else if (address.scopeRootIdentity !== void 0) {
19911
19540
  parts.push("root", physicalPathIdentity(address.scopeRootIdentity));
19912
19541
  }
19913
- return createHash7("sha256").update(parts.join("\0")).digest("hex").slice(0, 32);
19542
+ return createHash5("sha256").update(parts.join("\0")).digest("hex").slice(0, 32);
19914
19543
  }
19915
19544
  function analystIssuePagePath(ledgerHome, address) {
19916
19545
  return join37(ledgerHome, "analyst", "issues", `${analystIssuePageKey(address)}.json`);
@@ -22140,7 +21769,7 @@ __export(run_lifecycle_exports, {
22140
21769
  renderResumeCommand: () => renderResumeCommand,
22141
21770
  writeRoleRunState: () => writeRoleRunState
22142
21771
  });
22143
- import { chmod, lstat as lstat7, open as open3, readdir as readdir8, readFile as readFile23, unlink as unlink5, writeFile as writeFile10 } from "node:fs/promises";
21772
+ import { chmod, lstat as lstat7, open as open3, readdir as readdir7, readFile as readFile23, unlink as unlink5, writeFile as writeFile10 } from "node:fs/promises";
22144
21773
  import { basename as basename10, join as join41 } from "node:path";
22145
21774
  function buildAutoResumeContinuationPrompt(options) {
22146
21775
  return appendEngineSessionMaterial(
@@ -22219,7 +21848,7 @@ async function readRoleRunStateRaw(runDirectory) {
22219
21848
  try {
22220
21849
  raw = JSON.parse(await readFile23(join41(runDirectory, RUN_STATE_FILE), "utf8"));
22221
21850
  } catch (error) {
22222
- if (errorCodeOf2(error) === "ENOENT") return void 0;
21851
+ if (errorCodeOf(error) === "ENOENT") return void 0;
22223
21852
  throw error;
22224
21853
  }
22225
21854
  return raw;
@@ -22464,7 +22093,7 @@ function describeErrorIdentity(error) {
22464
22093
  const message = typeof candidate?.message === "string" && candidate.message !== "" ? `: ${candidate.message}` : "";
22465
22094
  return `${name}${code}${message}`;
22466
22095
  }
22467
- function errorCodeOf2(error) {
22096
+ function errorCodeOf(error) {
22468
22097
  return error.code;
22469
22098
  }
22470
22099
  function isProcessAlive(pid) {
@@ -22472,7 +22101,7 @@ function isProcessAlive(pid) {
22472
22101
  process.kill(pid, 0);
22473
22102
  return true;
22474
22103
  } catch (error) {
22475
- return errorCodeOf2(error) !== "ESRCH";
22104
+ return errorCodeOf(error) !== "ESRCH";
22476
22105
  }
22477
22106
  }
22478
22107
  async function autopsyWriterLock(lockPath) {
@@ -22480,7 +22109,7 @@ async function autopsyWriterLock(lockPath) {
22480
22109
  try {
22481
22110
  content = await readFile23(lockPath, "utf8");
22482
22111
  } catch (error) {
22483
- if (errorCodeOf2(error) === "ENOENT") return { verdict: "absent" };
22112
+ if (errorCodeOf(error) === "ENOENT") return { verdict: "absent" };
22484
22113
  return { verdict: "unknown", reason: "unreadable", readFailure: error };
22485
22114
  }
22486
22115
  const normalized = content.trim();
@@ -22512,8 +22141,8 @@ async function reclaimStaleWriterLock(lockPath, runDirectory) {
22512
22141
  await unlink5(lockPath);
22513
22142
  return { reclaimed: true };
22514
22143
  } catch (error) {
22515
- if (errorCodeOf2(error) === "ENOENT") return { reclaimed: false };
22516
- if (errorCodeOf2(error) !== "EACCES") throw error;
22144
+ if (errorCodeOf(error) === "ENOENT") return { reclaimed: false };
22145
+ if (errorCodeOf(error) !== "EACCES") throw error;
22517
22146
  await chmod(runDirectory, 493);
22518
22147
  return { reclaimed: false, eaccesFailure: error };
22519
22148
  }
@@ -22546,7 +22175,7 @@ async function createWriterLease(lockPath, runDirectory, reportCleanupFailure) {
22546
22175
  try {
22547
22176
  await unlink5(currentLockPath);
22548
22177
  } catch (error) {
22549
- if (errorCodeOf2(error) === "EACCES") {
22178
+ if (errorCodeOf(error) === "EACCES") {
22550
22179
  try {
22551
22180
  await chmod(currentRunDirectory, 493);
22552
22181
  await unlink5(currentLockPath);
@@ -22586,7 +22215,7 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
22586
22215
  try {
22587
22216
  return await createWriterLease(lockPath, runDirectory, reportCleanupFailure);
22588
22217
  } catch (error) {
22589
- if (errorCodeOf2(error) !== "EEXIST") throw error;
22218
+ if (errorCodeOf(error) !== "EEXIST") throw error;
22590
22219
  }
22591
22220
  lastAutopsy = await autopsyWriterLock(lockPath);
22592
22221
  if (lastAutopsy.verdict === "unknown" && lastAutopsy.reason === "unreadable") {
@@ -22637,9 +22266,9 @@ async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole) {
22637
22266
  const booksRoot = join41(ledgerHome, "books");
22638
22267
  let bookKeys;
22639
22268
  try {
22640
- bookKeys = await readdir8(booksRoot);
22269
+ bookKeys = await readdir7(booksRoot);
22641
22270
  } catch (error) {
22642
- if (errorCodeOf2(error) === "ENOENT") return void 0;
22271
+ if (errorCodeOf(error) === "ENOENT") return void 0;
22643
22272
  throw error;
22644
22273
  }
22645
22274
  const matches = [];
@@ -22650,7 +22279,7 @@ async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole) {
22650
22279
  try {
22651
22280
  runDirectories = await listBookRunDirectories(bookDir);
22652
22281
  } catch (error) {
22653
- if (errorCodeOf2(error) === "ENOENT") continue;
22282
+ if (errorCodeOf(error) === "ENOENT") continue;
22654
22283
  throw error;
22655
22284
  }
22656
22285
  for (const runDirectory of runDirectories) {
@@ -22678,7 +22307,7 @@ async function readRunParentPath(runDirectory) {
22678
22307
  await readFile23(join41(runDirectory, "admitted-request.json"), "utf8")
22679
22308
  );
22680
22309
  } catch (error) {
22681
- if (errorCodeOf2(error) === "ENOENT") return void 0;
22310
+ if (errorCodeOf(error) === "ENOENT") return void 0;
22682
22311
  throw error;
22683
22312
  }
22684
22313
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
@@ -22701,7 +22330,7 @@ async function runHasFormedSessionPrincipal(runDirectory) {
22701
22330
  const stat2 = await lstat7(sessionFile);
22702
22331
  return stat2.isFile() && !stat2.isSymbolicLink();
22703
22332
  } catch (error) {
22704
- if (errorCodeOf2(error) === "ENOENT") return false;
22333
+ if (errorCodeOf(error) === "ENOENT") return false;
22705
22334
  throw error;
22706
22335
  }
22707
22336
  }
@@ -22717,7 +22346,7 @@ async function findLatestRunIdForSeatTicket(input) {
22717
22346
  input.ticketNumber === void 0 ? bookDir : join41(bookDir, String(input.ticketNumber))
22718
22347
  );
22719
22348
  } catch (error) {
22720
- if (errorCodeOf2(error) === "ENOENT") return void 0;
22349
+ if (errorCodeOf(error) === "ENOENT") return void 0;
22721
22350
  throw error;
22722
22351
  }
22723
22352
  const suffix = `@${input.role}`;
@@ -23348,7 +22977,7 @@ var init_run_lifecycle = __esm({
23348
22977
  });
23349
22978
 
23350
22979
  // src/archivist-record-topology.ts
23351
- import { createHash as createHash8 } from "node:crypto";
22980
+ import { createHash as createHash6 } from "node:crypto";
23352
22981
  import { join as join42 } from "node:path";
23353
22982
  function resolveNavigatorWorkSubjectPlacement(input) {
23354
22983
  let ledgerHome;
@@ -23359,7 +22988,7 @@ function resolveNavigatorWorkSubjectPlacement(input) {
23359
22988
  }
23360
22989
  }
23361
22990
  ledgerHome ??= resolveActivationLedgerHome(input.home);
23362
- const digest = createHash8("sha256").update(input.subject).digest("hex").slice(0, 32);
22991
+ const digest = createHash6("sha256").update(input.subject).digest("hex").slice(0, 32);
23363
22992
  return {
23364
22993
  ledgerHome,
23365
22994
  sessionDir: join42(
@@ -23424,15 +23053,15 @@ __export(archivist_record_entry_exports, {
23424
23053
  resolveNavigatorWorkSubjectPlacement: () => resolveNavigatorWorkSubjectPlacement
23425
23054
  });
23426
23055
  import {
23427
- closeSync,
23056
+ closeSync as closeSync2,
23428
23057
  existsSync as existsSync12,
23429
- openSync,
23430
- readdirSync as readdirSync2,
23058
+ openSync as openSync2,
23059
+ readdirSync as readdirSync3,
23431
23060
  readFileSync as readFileSync4,
23432
23061
  readSync,
23433
23062
  realpathSync as realpathSync3,
23434
- statSync as statSync5,
23435
- writeFileSync as writeFileSync3
23063
+ statSync as statSync6,
23064
+ writeFileSync as writeFileSync2
23436
23065
  } from "node:fs";
23437
23066
  import { dirname as dirname23, resolve as resolve16, join as join43 } from "node:path";
23438
23067
  import { StringDecoder } from "node:string_decoder";
@@ -23454,7 +23083,7 @@ function readCurrentSession(sessionDir) {
23454
23083
  function writeCurrentSession(sessionDir, sessionFile) {
23455
23084
  const ledger = join43(sessionDir, CURRENT_SESSION_LEDGER);
23456
23085
  try {
23457
- writeFileSync3(ledger, `${JSON.stringify({ sessionFile })}
23086
+ writeFileSync2(ledger, `${JSON.stringify({ sessionFile })}
23458
23087
  `, { flag: "wx" });
23459
23088
  } catch (error) {
23460
23089
  throw new ActivationLedgerError(
@@ -23471,7 +23100,7 @@ function currentSessionLedgerPath(sessionDir) {
23471
23100
  return join43(sessionDir, CURRENT_SESSION_LEDGER);
23472
23101
  }
23473
23102
  function readBoundedSessionHeader(filePath) {
23474
- const fd = openSync(filePath, "r");
23103
+ const fd = openSync2(filePath, "r");
23475
23104
  try {
23476
23105
  const buffer = Buffer.allocUnsafe(SESSION_HEADER_CHUNK_BYTES);
23477
23106
  const decoder2 = new StringDecoder("utf8");
@@ -23519,7 +23148,7 @@ function readBoundedSessionHeader(filePath) {
23519
23148
  }
23520
23149
  return void 0;
23521
23150
  } finally {
23522
- closeSync(fd);
23151
+ closeSync2(fd);
23523
23152
  }
23524
23153
  }
23525
23154
  function parseSessionHeaderLine(line2) {
@@ -23545,7 +23174,7 @@ function mostRecentNavigatorSessionFile(sessionDir, cwd) {
23545
23174
  const absoluteCwd = resolve16(cwd);
23546
23175
  let names;
23547
23176
  try {
23548
- names = readdirSync2(absoluteSessionDir);
23177
+ names = readdirSync3(absoluteSessionDir);
23549
23178
  } catch (error) {
23550
23179
  throw new ActivationLedgerError(
23551
23180
  `archivist navigator nest is not readable (${sessionDir}): ${errorText(error)}`,
@@ -23558,7 +23187,7 @@ function mostRecentNavigatorSessionFile(sessionDir, cwd) {
23558
23187
  const filePath = join43(absoluteSessionDir, name);
23559
23188
  let st;
23560
23189
  try {
23561
- st = statSync5(filePath);
23190
+ st = statSync6(filePath);
23562
23191
  } catch (error) {
23563
23192
  throw new ActivationLedgerError(
23564
23193
  `archivist navigator session file is not stat-able (${filePath}): ${errorText(error)}`,
@@ -23699,7 +23328,7 @@ function createRecordSessionOpen(options, host = piRecordSessionHost) {
23699
23328
  if (file !== void 0 && !existsSync12(file)) {
23700
23329
  const header = session.getHeader();
23701
23330
  if (header !== null && header.type === "session") {
23702
- writeFileSync3(file, `${JSON.stringify(header)}
23331
+ writeFileSync2(file, `${JSON.stringify(header)}
23703
23332
  `, { flag: "wx" });
23704
23333
  session.setSessionFile(file);
23705
23334
  }
@@ -23739,7 +23368,7 @@ import { readFile as readFile26 } from "node:fs/promises";
23739
23368
  import { join as join47 } from "node:path";
23740
23369
 
23741
23370
  // src/navigator-attendance.ts
23742
- import { createHash as createHash9 } from "node:crypto";
23371
+ import { createHash as createHash7 } from "node:crypto";
23743
23372
  init_navigator_invocation_identity();
23744
23373
  init_packaged_role_registry();
23745
23374
  init_activation_ledger_topology();
@@ -23943,7 +23572,7 @@ init_packaged_role_registry();
23943
23572
 
23944
23573
  // src/navigator-work-base.ts
23945
23574
  init_atomic_write();
23946
- import { existsSync as existsSync4, realpathSync as realpathSync2 } from "node:fs";
23575
+ import { existsSync as existsSync3, realpathSync as realpathSync2 } from "node:fs";
23947
23576
  import { readFile as readFile6 } from "node:fs/promises";
23948
23577
  import { basename as basename3, dirname as dirname7, join as join7, resolve as resolve5 } from "node:path";
23949
23578
  var NAVIGATOR_WORK_CONTEXT_BASENAME = "work-context.json";
@@ -23967,7 +23596,7 @@ function canonicalNavigatorWorkContextFile(path) {
23967
23596
  }
23968
23597
  }
23969
23598
  async function persistNavigatorWorkBase(sessionDir, body) {
23970
- if (sessionDir.trim() === "" || !existsSync4(sessionDir)) return void 0;
23599
+ if (sessionDir.trim() === "" || !existsSync3(sessionDir)) return void 0;
23971
23600
  if (body.authority.trim() === "") return void 0;
23972
23601
  const path = navigatorWorkContextFile(sessionDir);
23973
23602
  const next = `${JSON.stringify({ subject: body.subject, authority: body.authority })}
@@ -24300,7 +23929,7 @@ function navigatorSubjectKey(subjectRoot, subject, provenance = "role_input") {
24300
23929
  if (provenance === "placeholder") return subjectRoot;
24301
23930
  const normalized = subject.trim().replace(/\s+/g, " ");
24302
23931
  if (normalized === "") return subjectRoot;
24303
- return `${subjectRoot}#${createHash9("sha256").update(normalized).digest("hex").slice(0, 32)}`;
23932
+ return `${subjectRoot}#${createHash7("sha256").update(normalized).digest("hex").slice(0, 32)}`;
24304
23933
  }
24305
23934
  function navigatorSubjectKeyForInput(subjectRoot, reference, cwd = process.cwd()) {
24306
23935
  if (issueRoot(subjectRoot) !== void 0 || !subjectRoot.includes("/.ak/work/")) return subjectRoot;
@@ -24851,8 +24480,8 @@ init_activation_ledger_topology();
24851
24480
  import {
24852
24481
  lstatSync as lstatSync2,
24853
24482
  realpathSync as realpathSync4,
24854
- statSync as statSync6,
24855
- writeFileSync as writeFileSync4
24483
+ statSync as statSync7,
24484
+ writeFileSync as writeFileSync3
24856
24485
  } from "node:fs";
24857
24486
  import { isAbsolute as isAbsolute11, resolve as resolve19 } from "node:path";
24858
24487
  var ActivationSessionFileMissingError = class extends Error {
@@ -24873,7 +24502,7 @@ function materializeDeferredSessionFile(sessionManager, resolvedFile) {
24873
24502
  throw new ActivationSessionFileMissingError(resolvedFile);
24874
24503
  }
24875
24504
  try {
24876
- writeFileSync4(resolvedFile, `${JSON.stringify(header)}
24505
+ writeFileSync3(resolvedFile, `${JSON.stringify(header)}
24877
24506
  `, { flag: "wx" });
24878
24507
  } catch (error) {
24879
24508
  if (errnoCode(error) !== "EEXIST") {
@@ -24926,7 +24555,7 @@ function durableSessionPointer(sessionManager) {
24926
24555
  }
24927
24556
  let info;
24928
24557
  try {
24929
- info = statSync6(realFile);
24558
+ info = statSync7(realFile);
24930
24559
  } catch (error) {
24931
24560
  throw new Error(
24932
24561
  `Workflow role activation failed to stat durable session file (${realFile}): ${errorText(error)}`,
@@ -26358,7 +25987,7 @@ init_worker_submission_contracts();
26358
25987
  init_submission_errors();
26359
25988
  init_worker_submission_contracts();
26360
25989
  import { execFileSync as execFileSync4 } from "node:child_process";
26361
- import { existsSync as existsSync14, lstatSync as lstatSync3, readdirSync as readdirSync3, readFileSync as readFileSync5, rmdirSync, rmSync } from "node:fs";
25990
+ import { existsSync as existsSync14, lstatSync as lstatSync3, readdirSync as readdirSync4, readFileSync as readFileSync5, rmdirSync, rmSync as rmSync2 } from "node:fs";
26362
25991
  import { resolve as resolve20 } from "node:path";
26363
25992
  var WORKER_SUBMISSION_GATE_RECORD_KIND = WORKER_SUBMISSION_GATE_KIND;
26364
25993
  var WORKER_COMMIT_BASELINE_ENTRY_TYPE = "commit-baseline";
@@ -26424,13 +26053,13 @@ function unsetOwnedHooksPath(file) {
26424
26053
  function rmOwnedDir(dir) {
26425
26054
  const hookPath = resolve20(dir, HOOK_FILE);
26426
26055
  if (!ownedHook(hookPath)) return;
26427
- rmSync(hookPath, { force: true });
26428
- if (existsSync14(dir) && readdirSync3(dir).length === 0) rmdirSync(dir);
26056
+ rmSync2(hookPath, { force: true });
26057
+ if (existsSync14(dir) && readdirSync4(dir).length === 0) rmdirSync(dir);
26429
26058
  }
26430
26059
  function linkedGitDirs(commonDir) {
26431
26060
  const root = resolve20(commonDir, "worktrees");
26432
26061
  if (!existsSync14(root)) return [];
26433
- return readdirSync3(root).map((name) => resolve20(root, name)).filter((dir) => lstatSync3(dir).isDirectory());
26062
+ return readdirSync4(root).map((name) => resolve20(root, name)).filter((dir) => lstatSync3(dir).isDirectory());
26434
26063
  }
26435
26064
  function uninstallPackageWorkerHooks(cwd) {
26436
26065
  let inside;
@@ -26448,13 +26077,13 @@ function uninstallPackageWorkerHooks(cwd) {
26448
26077
  clear(resolve20(commonDir, "config.worktree"));
26449
26078
  rmOwnedDir(resolve20(commonDir, HOOKS_DIR));
26450
26079
  const legacy = resolve20(commonDir, "hooks", HOOK_FILE);
26451
- if (ownedHook(legacy)) rmSync(legacy, { force: true });
26080
+ if (ownedHook(legacy)) rmSync2(legacy, { force: true });
26452
26081
  for (const gitDir of linkedGitDirs(commonDir)) {
26453
26082
  clear(resolve20(gitDir, "config.worktree"));
26454
26083
  rmOwnedDir(resolve20(gitDir, HOOKS_DIR));
26455
26084
  }
26456
26085
  }
26457
- function isRecord17(value) {
26086
+ function isRecord16(value) {
26458
26087
  return typeof value === "object" && value !== null && !Array.isArray(value);
26459
26088
  }
26460
26089
  function unfinishedReasonPresent(details) {
@@ -26470,7 +26099,7 @@ function readGateState(session) {
26470
26099
  if (entry.type !== "custom") continue;
26471
26100
  if (entry.customType === WORKER_COMMIT_BASELINE_ENTRY_TYPE) {
26472
26101
  const data = entry.data;
26473
- if (isRecord17(data) && (data.head === null || typeof data.head === "string")) {
26102
+ if (isRecord16(data) && (data.head === null || typeof data.head === "string")) {
26474
26103
  baseline = data.head;
26475
26104
  }
26476
26105
  } else if (entry.customType === WORKER_COMMIT_REMINDER_BOUNCE_ENTRY_TYPE) {
@@ -26663,11 +26292,11 @@ var FIXER_PHASES = ["plan", "apply"];
26663
26292
  function isWorkerPhase(value) {
26664
26293
  return typeof value === "string" && FIXER_PHASES.includes(value);
26665
26294
  }
26666
- function isRecord18(value) {
26295
+ function isRecord17(value) {
26667
26296
  return typeof value === "object" && value !== null && !Array.isArray(value);
26668
26297
  }
26669
26298
  function workerStatusOf(output) {
26670
- return isRecord18(output) && typeof output.status === "string" ? output.status : void 0;
26299
+ return isRecord17(output) && typeof output.status === "string" ? output.status : void 0;
26671
26300
  }
26672
26301
  function deepFreeze2(value) {
26673
26302
  if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
@@ -29164,30 +28793,19 @@ function headlessMcpConfigDocument(mcpServers) {
29164
28793
  }
29165
28794
 
29166
28795
  // src/headless-host/role-turn-host.ts
29167
- import { spawn as spawn4, spawnSync as spawnSync2 } from "node:child_process";
28796
+ import { spawn as spawn4, spawnSync as spawnSync3 } from "node:child_process";
29168
28797
  import { randomUUID as randomUUID10 } from "node:crypto";
29169
28798
  import { existsSync as existsSync15 } from "node:fs";
29170
28799
  import { writeFile as writeFile12 } from "node:fs/promises";
29171
28800
  import { dirname as dirname26, isAbsolute as isAbsolute12, join as join50, resolve as resolve21 } from "node:path";
29172
28801
 
29173
28802
  // src/external-host-turn-loop.ts
29174
- init_packaged_role_registry();
29175
28803
  var EXTERNAL_ROLE_TURN_ROUND_LIMIT = 8;
29176
28804
  function mergeRoleTurnAbortSignals(prepared, request) {
29177
28805
  if (request === void 0) return prepared;
29178
28806
  if (prepared === void 0) return request;
29179
28807
  return AbortSignal.any([prepared, request]);
29180
28808
  }
29181
- function promptWithPriorNativePaths(basePrompt, request) {
29182
- if (request.continuation.kind !== "resume") return basePrompt;
29183
- if (request.stationChild === true && isOfficerReviewSeat(request.activation.role)) {
29184
- return basePrompt;
29185
- }
29186
- const paths = request.hostTransition?.priorNativePaths;
29187
- if (paths === void 0 || paths.length === 0) return basePrompt;
29188
- return `${basePrompt}
29189
- ${paths.join("\n")}`;
29190
- }
29191
28809
  function isHostAbortedError(error) {
29192
28810
  return typeof error === "object" && error !== null && error.code === "host-aborted";
29193
28811
  }
@@ -29207,7 +28825,7 @@ async function settleHostAborted(prepared, sessionId) {
29207
28825
  });
29208
28826
  }
29209
28827
  async function driveExternalRoleTurnRounds(prepared, request, driver) {
29210
- let prompt = promptWithPriorNativePaths(prepared.prompt, request);
28828
+ let prompt = prepared.prompt;
29211
28829
  const abortSignal = mergeRoleTurnAbortSignals(prepared.abortSignal, request.signal);
29212
28830
  let stderr = "";
29213
28831
  for (let attempt = 0; attempt < EXTERNAL_ROLE_TURN_ROUND_LIMIT; attempt += 1) {
@@ -29262,31 +28880,8 @@ function renderSystemPromptOverride(authority) {
29262
28880
  return renderAgentStartMaterials(authority.body, authority.materials);
29263
28881
  }
29264
28882
 
29265
- // src/host-session-record.ts
29266
- init_sitian_facade();
29267
- var HOST_SESSION_RECORD_KIND = "host-session";
29268
- function eventField(event, key) {
29269
- if (typeof event !== "object" || event === null || Array.isArray(event)) return void 0;
29270
- const value = event[key];
29271
- return typeof value === "string" && value.length > 0 ? value : void 0;
29272
- }
29273
- function reportHostSessionEvent(input) {
29274
- const identity = input.identity ?? eventField(input.event, "uuid");
29275
- const timestamp2 = input.timestamp ?? eventField(input.event, "timestamp");
29276
- sitianReport({
29277
- level: "event",
29278
- kind: HOST_SESSION_RECORD_KIND,
29279
- host: input.host,
29280
- cwd: input.cwd,
29281
- sessionParent: input.sessionParent,
29282
- source: input.source,
29283
- payload: input.event,
29284
- ...identity === void 0 ? {} : { identity },
29285
- ...timestamp2 === void 0 ? {} : { timestamp: timestamp2 }
29286
- });
29287
- }
29288
-
29289
28883
  // src/headless-host/role-turn-host.ts
28884
+ init_host_session_record();
29290
28885
  init_navigator_output();
29291
28886
  function failure(cause, name, code, details, diagnostic) {
29292
28887
  return {
@@ -29398,7 +28993,7 @@ function resolveGitCommonDir(cwd) {
29398
28993
  if (!cwdIsGitWorkTree(cwd)) return void 0;
29399
28994
  let result;
29400
28995
  try {
29401
- result = spawnSync2("git", ["rev-parse", "--git-common-dir"], {
28996
+ result = spawnSync3("git", ["rev-parse", "--git-common-dir"], {
29402
28997
  cwd,
29403
28998
  encoding: "utf8"
29404
28999
  });
@@ -29484,8 +29079,15 @@ function spawnHeadlessTurn(options) {
29484
29079
  lineBuffer = "";
29485
29080
  }
29486
29081
  };
29082
+ let aborted = false;
29487
29083
  const settle = (code) => {
29488
29084
  if (settled) return;
29085
+ if (aborted) {
29086
+ settled = true;
29087
+ if (timer !== void 0) clearTimeout(timer);
29088
+ reject(hostAbortedError("headless host aborted"));
29089
+ return;
29090
+ }
29489
29091
  flushStdoutLines("", true);
29490
29092
  if (settled) return;
29491
29093
  settled = true;
@@ -29498,11 +29100,9 @@ function spawnHeadlessTurn(options) {
29498
29100
  resolve22({ code, stdout: resultStdout, stderr, timedOut });
29499
29101
  };
29500
29102
  const onAbort = () => {
29501
- child.kill("SIGTERM");
29502
29103
  if (settled) return;
29503
- settled = true;
29504
- if (timer !== void 0) clearTimeout(timer);
29505
- reject(hostAbortedError("headless host aborted"));
29104
+ aborted = true;
29105
+ child.kill("SIGTERM");
29506
29106
  };
29507
29107
  child.stdout.setEncoding("utf8").on("data", (chunk) => {
29508
29108
  flushStdoutLines(chunk, false);
@@ -29517,7 +29117,10 @@ function spawnHeadlessTurn(options) {
29517
29117
  options.signal?.removeEventListener("abort", onAbort);
29518
29118
  reject(error);
29519
29119
  });
29520
- child.on("close", (code) => settle(code));
29120
+ child.on("close", (code) => {
29121
+ options.onClose?.();
29122
+ settle(code);
29123
+ });
29521
29124
  options.signal?.addEventListener("abort", onAbort, { once: true });
29522
29125
  if (options.timeoutMs !== void 0 && options.timeoutMs > 0) {
29523
29126
  timer = setTimeout(() => {
@@ -29620,236 +29223,268 @@ function createHeadlessRoleTurnHost(config) {
29620
29223
  );
29621
29224
  }
29622
29225
  const sessionParent = config.sessionIdentity.resolveSessionFile(request.principal);
29623
- outcome = await driveExternalRoleTurnRounds(prepared, request, {
29624
- roundLimitName: "HeadlessRoundLimit",
29625
- currentSessionId: () => sessionId,
29626
- afterRetry() {
29627
- sessionKind = "resume";
29628
- },
29629
- async runRound({ prompt, abortSignal }) {
29630
- let args;
29631
- try {
29632
- const gitCommonDir = codex ? resolveGitCommonDir(request.cwd) : void 0;
29633
- args = buildTurnArgs({
29634
- description: config.description,
29635
- systemPromptPath,
29636
- // #959: navigator prose exit — no closed JSON schema on claude either.
29637
- ...prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME ? {} : { jsonSchema: prepared.jsonSchema },
29638
- mcpServers: prepared.mcpServers,
29639
- ...mcpConfigPath === void 0 ? {} : { mcpConfigPath },
29640
- ...outputSchemaPath === void 0 ? {} : { outputSchemaPath },
29641
- ...request.model?.model !== void 0 ? { model: request.model.model } : {},
29642
- ...request.model?.thinking !== void 0 ? { effort: request.model.thinking } : {},
29643
- sessionId,
29644
- sessionKind,
29645
- cwd: request.cwd,
29646
- ...gitCommonDir === void 0 ? {} : { writableRoots: [gitCommonDir] }
29647
- });
29648
- } catch (error) {
29649
- const message = error instanceof Error ? error.message : String(error);
29650
- return {
29651
- status: "terminal",
29652
- result: failure("session", "HeadlessArgvFailure", "argv-failed", { diagnostic: message }, message)
29653
- };
29654
- }
29655
- const codexObserver = codex ? createCodexExecTurnObserver() : void 0;
29656
- let spawned;
29657
- try {
29658
- spawned = await spawnHeadlessTurn({
29659
- binary: config.binary,
29660
- args,
29661
- cwd: request.cwd,
29662
- env,
29663
- stdin: prompt,
29664
- ...abortSignal === void 0 ? {} : { signal: abortSignal },
29665
- ...request.timeoutMs === void 0 ? {} : { timeoutMs: request.timeoutMs },
29666
- onStdoutLine(line2) {
29667
- const trimmed = line2.trim();
29668
- if (trimmed === "") return;
29669
- let event;
29670
- try {
29671
- event = JSON.parse(trimmed);
29672
- } catch {
29673
- return;
29674
- }
29675
- codexObserver?.observe(event);
29676
- reportHostSessionEvent({
29677
- host: config.hostName,
29678
- cwd: request.cwd,
29679
- sessionParent,
29680
- source: "headless-host",
29681
- event
29682
- });
29683
- }
29684
- });
29685
- } catch (error) {
29686
- if (isHostAbortedError(error)) throw error;
29687
- const message = error instanceof Error ? error.message : String(error);
29688
- const observedHostFailure = codexObserver?.result().failureDiagnostic;
29689
- if (observedHostFailure !== void 0) {
29226
+ let exitedSessionId;
29227
+ try {
29228
+ outcome = await driveExternalRoleTurnRounds(prepared, request, {
29229
+ roundLimitName: "HeadlessRoundLimit",
29230
+ currentSessionId: () => sessionId,
29231
+ afterRetry() {
29232
+ sessionKind = "resume";
29233
+ },
29234
+ async runRound({ prompt, abortSignal }) {
29235
+ let args;
29236
+ try {
29237
+ const gitCommonDir = codex ? resolveGitCommonDir(request.cwd) : void 0;
29238
+ args = buildTurnArgs({
29239
+ description: config.description,
29240
+ systemPromptPath,
29241
+ // #959: navigator prose exit — no closed JSON schema on claude either.
29242
+ ...prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME ? {} : { jsonSchema: prepared.jsonSchema },
29243
+ mcpServers: prepared.mcpServers,
29244
+ ...mcpConfigPath === void 0 ? {} : { mcpConfigPath },
29245
+ ...outputSchemaPath === void 0 ? {} : { outputSchemaPath },
29246
+ ...request.model?.model !== void 0 ? { model: request.model.model } : {},
29247
+ ...request.model?.thinking !== void 0 ? { effort: request.model.thinking } : {},
29248
+ sessionId,
29249
+ sessionKind,
29250
+ cwd: request.cwd,
29251
+ ...gitCommonDir === void 0 ? {} : { writableRoots: [gitCommonDir] }
29252
+ });
29253
+ } catch (error) {
29254
+ const message = error instanceof Error ? error.message : String(error);
29690
29255
  return {
29691
29256
  status: "terminal",
29692
- result: failure("output", "HeadlessCliError", "codex-turn-failed", {
29693
- diagnostic: observedHostFailure,
29694
- sessionRecordDiagnostic: message,
29695
- sessionId
29696
- }, observedHostFailure)
29257
+ result: failure("session", "HeadlessArgvFailure", "argv-failed", { diagnostic: message }, message)
29697
29258
  };
29698
29259
  }
29699
- const isRecordFailure = typeof error === "object" && error !== null && (error.knownCause === "session" || error.name === "SitianInfrastructureError");
29700
- if (isRecordFailure) {
29260
+ const codexObserver = codex ? createCodexExecTurnObserver() : void 0;
29261
+ let pointerRecorded = false;
29262
+ let codexIdObserved = false;
29263
+ if (sessionId !== void 0 && sessionId !== "") {
29264
+ pointerRecorded = recordNativeSessionPointer({
29265
+ host: config.hostName,
29266
+ sessionId,
29267
+ cwd: request.cwd,
29268
+ sessionParent,
29269
+ home: request.home
29270
+ }) !== void 0;
29271
+ }
29272
+ let spawned;
29273
+ let childExited = false;
29274
+ try {
29275
+ spawned = await spawnHeadlessTurn({
29276
+ onClose() {
29277
+ childExited = true;
29278
+ },
29279
+ binary: config.binary,
29280
+ args,
29281
+ cwd: request.cwd,
29282
+ env,
29283
+ stdin: prompt,
29284
+ ...abortSignal === void 0 ? {} : { signal: abortSignal },
29285
+ ...request.timeoutMs === void 0 ? {} : { timeoutMs: request.timeoutMs },
29286
+ onStdoutLine(line2) {
29287
+ const trimmed = line2.trim();
29288
+ if (trimmed === "") return;
29289
+ let event;
29290
+ try {
29291
+ event = JSON.parse(trimmed);
29292
+ } catch {
29293
+ return;
29294
+ }
29295
+ codexObserver?.observe(event);
29296
+ if (!codex && typeof event === "object" && event !== null && "session_id" in event && typeof event.session_id === "string" && event.session_id !== "" && event.session_id !== sessionId) {
29297
+ sessionId = event.session_id;
29298
+ recordNativeSessionPointer({ host: config.hostName, sessionId, cwd: request.cwd, sessionParent, home: request.home });
29299
+ }
29300
+ if (codex && !codexIdObserved) {
29301
+ const tid = codexObserver?.result().threadId;
29302
+ if (tid !== void 0 && tid !== "") {
29303
+ codexIdObserved = true;
29304
+ pointerRecorded = recordNativeSessionPointer({
29305
+ host: config.hostName,
29306
+ sessionId: tid,
29307
+ cwd: request.cwd,
29308
+ sessionParent,
29309
+ home: request.home
29310
+ }) !== void 0;
29311
+ }
29312
+ }
29313
+ }
29314
+ });
29315
+ const roundSessionId = (codex ? codexObserver?.result().threadId : void 0) ?? sessionId;
29316
+ exitedSessionId = roundSessionId;
29317
+ if (codex && roundSessionId !== void 0 && roundSessionId !== "" && !pointerRecorded) {
29318
+ recordNativeSessionPointer({ host: config.hostName, sessionId: roundSessionId, cwd: request.cwd, sessionParent, home: request.home });
29319
+ }
29320
+ } catch (error) {
29321
+ if (childExited) exitedSessionId = (codex ? codexObserver?.result().threadId : void 0) ?? sessionId;
29322
+ if (isHostAbortedError(error)) throw error;
29323
+ const message = error instanceof Error ? error.message : String(error);
29324
+ const observedHostFailure = codexObserver?.result().failureDiagnostic;
29325
+ if (observedHostFailure !== void 0) {
29326
+ return {
29327
+ status: "terminal",
29328
+ result: failure("output", "HeadlessCliError", "codex-turn-failed", {
29329
+ diagnostic: observedHostFailure,
29330
+ sessionRecordDiagnostic: message,
29331
+ sessionId
29332
+ }, observedHostFailure)
29333
+ };
29334
+ }
29701
29335
  return {
29702
29336
  status: "terminal",
29703
- result: failure(
29704
- "session",
29705
- "HostSessionRecordFailure",
29706
- "host-session-record-failed",
29707
- { diagnostic: message, sessionId },
29708
- message
29709
- )
29337
+ result: failure("activation", "HeadlessSpawnFailure", "spawn-failed", {
29338
+ diagnostic: message,
29339
+ binary: config.binary
29340
+ }, message)
29710
29341
  };
29711
29342
  }
29712
- return {
29713
- status: "terminal",
29714
- result: failure("activation", "HeadlessSpawnFailure", "spawn-failed", {
29715
- diagnostic: message,
29716
- binary: config.binary
29717
- }, message)
29718
- };
29719
- }
29720
- if (spawned.timedOut) {
29721
- return terminalFromSpawned(spawned, {
29722
- cause: "timeout",
29723
- identity: { name: "HeadlessTimeout", code: "timeout" },
29724
- details: { sessionId }
29725
- });
29726
- }
29727
- if (codex) {
29728
- const observation = codexObserver.result();
29729
- if (observation.threadId !== void 0 && observation.threadId !== "") {
29730
- sessionId = observation.threadId;
29731
- }
29732
- let sessionBindingDiagnostic;
29733
- const hostFailed = observation.failureDiagnostic !== void 0 || spawned.code !== 0 && spawned.code !== null;
29734
- if (hostFailed && observation.threadId !== void 0 && observation.threadId !== "") {
29735
- try {
29736
- await config.sessionIdentity.bind(request.principal, observation.threadId);
29737
- } catch (error) {
29738
- sessionBindingDiagnostic = error instanceof Error ? error.message : String(error);
29739
- }
29740
- }
29741
- if (observation.failureDiagnostic !== void 0) {
29343
+ if (spawned.timedOut) {
29742
29344
  return terminalFromSpawned(spawned, {
29743
- cause: "output",
29744
- identity: { name: "HeadlessCliError", code: "codex-turn-failed" },
29745
- diagnostic: observation.failureDiagnostic,
29746
- details: {
29747
- sessionId,
29748
- exitCode: spawned.code,
29749
- ...sessionBindingDiagnostic === void 0 ? {} : { sessionBindingDiagnostic }
29750
- }
29345
+ cause: "timeout",
29346
+ identity: { name: "HeadlessTimeout", code: "timeout" },
29347
+ details: { sessionId }
29751
29348
  });
29752
29349
  }
29753
- if (spawned.code !== 0 && spawned.code !== null) {
29754
- return terminalFromSpawned(spawned, {
29755
- cause: "output",
29756
- identity: { name: "HeadlessCliError", code: "codex-nonzero-exit" },
29757
- diagnostic: spawned.stderr.trim() || `codex exec exited ${String(spawned.code)}`,
29758
- details: {
29759
- sessionId,
29760
- exitCode: spawned.code,
29761
- ...sessionBindingDiagnostic === void 0 ? {} : { sessionBindingDiagnostic }
29350
+ if (codex) {
29351
+ const observation = codexObserver.result();
29352
+ if (observation.threadId !== void 0 && observation.threadId !== "") {
29353
+ sessionId = observation.threadId;
29354
+ }
29355
+ let sessionBindingDiagnostic;
29356
+ const hostFailed = observation.failureDiagnostic !== void 0 || spawned.code !== 0 && spawned.code !== null;
29357
+ if (hostFailed && observation.threadId !== void 0 && observation.threadId !== "") {
29358
+ try {
29359
+ await config.sessionIdentity.bind(request.principal, observation.threadId);
29360
+ } catch (error) {
29361
+ sessionBindingDiagnostic = error instanceof Error ? error.message : String(error);
29762
29362
  }
29763
- });
29764
- }
29765
- if (observation.threadId === void 0 || observation.threadId === "") {
29766
- return terminalFromSpawned(spawned, {
29767
- cause: "session",
29768
- identity: { name: "HeadlessMissingThreadId", code: "missing-thread-id" },
29769
- diagnostic: "codex exec emitted no thread.started thread_id",
29770
- details: { sessionId, exitCode: spawned.code }
29771
- });
29772
- }
29773
- sessionId = observation.threadId;
29774
- await config.sessionIdentity.bind(request.principal, sessionId);
29775
- if (!observation.turnCompleted) {
29776
- return terminalFromSpawned(spawned, {
29777
- cause: "output",
29778
- identity: { name: "HeadlessCliError", code: "codex-missing-terminal-event" },
29779
- diagnostic: "codex exec exited without turn.completed",
29780
- details: { sessionId, exitCode: spawned.code }
29781
- });
29782
- }
29783
- if (observation.finalMessage === void 0) {
29784
- return terminalFromSpawned(spawned, {
29785
- cause: "output",
29786
- identity: { name: "HeadlessEmptyOutput", code: "empty-stdout" },
29787
- diagnostic: spawned.stderr.trim() || "codex exec produced no agent_message",
29788
- details: { sessionId, exitCode: spawned.code }
29789
- });
29790
- }
29791
- if (prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME) {
29792
- if (observation.finalMessage.trim() === "") {
29363
+ }
29364
+ if (observation.failureDiagnostic !== void 0) {
29365
+ return terminalFromSpawned(spawned, {
29366
+ cause: "output",
29367
+ identity: { name: "HeadlessCliError", code: "codex-turn-failed" },
29368
+ diagnostic: observation.failureDiagnostic,
29369
+ details: {
29370
+ sessionId,
29371
+ exitCode: spawned.code,
29372
+ ...sessionBindingDiagnostic === void 0 ? {} : { sessionBindingDiagnostic }
29373
+ }
29374
+ });
29375
+ }
29376
+ if (spawned.code !== 0 && spawned.code !== null) {
29377
+ return terminalFromSpawned(spawned, {
29378
+ cause: "output",
29379
+ identity: { name: "HeadlessCliError", code: "codex-nonzero-exit" },
29380
+ diagnostic: spawned.stderr.trim() || `codex exec exited ${String(spawned.code)}`,
29381
+ details: {
29382
+ sessionId,
29383
+ exitCode: spawned.code,
29384
+ ...sessionBindingDiagnostic === void 0 ? {} : { sessionBindingDiagnostic }
29385
+ }
29386
+ });
29387
+ }
29388
+ if (observation.threadId === void 0 || observation.threadId === "") {
29389
+ return terminalFromSpawned(spawned, {
29390
+ cause: "session",
29391
+ identity: { name: "HeadlessMissingThreadId", code: "missing-thread-id" },
29392
+ diagnostic: "codex exec emitted no thread.started thread_id",
29393
+ details: { sessionId, exitCode: spawned.code }
29394
+ });
29395
+ }
29396
+ sessionId = observation.threadId;
29397
+ await config.sessionIdentity.bind(request.principal, sessionId);
29398
+ if (!observation.turnCompleted) {
29399
+ return terminalFromSpawned(spawned, {
29400
+ cause: "output",
29401
+ identity: { name: "HeadlessCliError", code: "codex-missing-terminal-event" },
29402
+ diagnostic: "codex exec exited without turn.completed",
29403
+ details: { sessionId, exitCode: spawned.code }
29404
+ });
29405
+ }
29406
+ if (observation.finalMessage === void 0) {
29793
29407
  return terminalFromSpawned(spawned, {
29794
29408
  cause: "output",
29795
29409
  identity: { name: "HeadlessEmptyOutput", code: "empty-stdout" },
29796
- diagnostic: spawned.stderr.trim() || "codex exec produced empty agent_message",
29410
+ diagnostic: spawned.stderr.trim() || "codex exec produced no agent_message",
29411
+ details: { sessionId, exitCode: spawned.code }
29412
+ });
29413
+ }
29414
+ if (prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME) {
29415
+ if (observation.finalMessage.trim() === "") {
29416
+ return terminalFromSpawned(spawned, {
29417
+ cause: "output",
29418
+ identity: { name: "HeadlessEmptyOutput", code: "empty-stdout" },
29419
+ diagnostic: spawned.stderr.trim() || "codex exec produced empty agent_message",
29420
+ details: { sessionId, exitCode: spawned.code }
29421
+ });
29422
+ }
29423
+ await prepared.ingestStructuredOutput({ prose: observation.finalMessage });
29424
+ return { status: "delivered", stderr: spawned.stderr };
29425
+ }
29426
+ let receipt;
29427
+ try {
29428
+ receipt = JSON.parse(observation.finalMessage);
29429
+ } catch {
29430
+ return terminalFromSpawned(spawned, {
29431
+ cause: "output",
29432
+ identity: { name: "HeadlessEmptyOutput", code: "unparseable-final-message" },
29433
+ diagnostic: "codex final agent_message was not JSON",
29797
29434
  details: { sessionId, exitCode: spawned.code }
29798
29435
  });
29799
29436
  }
29800
- await prepared.ingestStructuredOutput({ prose: observation.finalMessage });
29437
+ await prepared.ingestStructuredOutput(receipt);
29801
29438
  return { status: "delivered", stderr: spawned.stderr };
29802
29439
  }
29803
- let receipt;
29804
- try {
29805
- receipt = JSON.parse(observation.finalMessage);
29806
- } catch {
29440
+ const envelope = parseHeadlessCliStdout(spawned.stdout);
29441
+ if (envelope === void 0) {
29807
29442
  return terminalFromSpawned(spawned, {
29808
29443
  cause: "output",
29809
- identity: { name: "HeadlessEmptyOutput", code: "unparseable-final-message" },
29810
- diagnostic: "codex final agent_message was not JSON",
29444
+ identity: { name: "HeadlessEmptyOutput", code: "empty-stdout" },
29445
+ diagnostic: spawned.stderr.length > 0 ? spawned.stderr : "headless CLI produced no parseable result",
29811
29446
  details: { sessionId, exitCode: spawned.code }
29812
29447
  });
29813
29448
  }
29814
- await prepared.ingestStructuredOutput(receipt);
29449
+ if (typeof envelope.session_id === "string" && envelope.session_id !== "") {
29450
+ sessionId = envelope.session_id;
29451
+ await config.sessionIdentity.bind(request.principal, sessionId);
29452
+ }
29453
+ if (envelope.is_error === true || typeof envelope.subtype === "string" && envelope.subtype.startsWith("error_")) {
29454
+ const errorCode = typeof envelope.subtype === "string" && envelope.subtype.startsWith("error_") ? envelope.subtype : envelope.is_error === true ? "is_error" : "cli-error";
29455
+ const diagnostic = typeof envelope.result === "string" ? envelope.result : Array.isArray(envelope.errors) ? envelope.errors.map(String).join("\n") : spawned.stderr.length > 0 ? spawned.stderr : "headless CLI reported is_error";
29456
+ return terminalFromSpawned(spawned, {
29457
+ cause: "output",
29458
+ identity: { name: "HeadlessCliError", code: errorCode },
29459
+ diagnostic,
29460
+ details: {
29461
+ sessionId,
29462
+ subtype: envelope.subtype,
29463
+ errors: envelope.errors,
29464
+ exitCode: spawned.code
29465
+ }
29466
+ });
29467
+ }
29468
+ if (envelope.structured_output !== void 0) {
29469
+ await prepared.ingestStructuredOutput(envelope.structured_output);
29470
+ } else if (prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME && typeof envelope.result === "string" && envelope.result.trim() !== "") {
29471
+ await prepared.ingestStructuredOutput({ prose: envelope.result });
29472
+ }
29815
29473
  return { status: "delivered", stderr: spawned.stderr };
29816
29474
  }
29817
- const envelope = parseHeadlessCliStdout(spawned.stdout);
29818
- if (envelope === void 0) {
29819
- return terminalFromSpawned(spawned, {
29820
- cause: "output",
29821
- identity: { name: "HeadlessEmptyOutput", code: "empty-stdout" },
29822
- diagnostic: spawned.stderr.length > 0 ? spawned.stderr : "headless CLI produced no parseable result",
29823
- details: { sessionId, exitCode: spawned.code }
29824
- });
29825
- }
29826
- if (typeof envelope.session_id === "string" && envelope.session_id !== "") {
29827
- sessionId = envelope.session_id;
29828
- await config.sessionIdentity.bind(request.principal, sessionId);
29829
- }
29830
- if (envelope.is_error === true || typeof envelope.subtype === "string" && envelope.subtype.startsWith("error_")) {
29831
- const errorCode = typeof envelope.subtype === "string" && envelope.subtype.startsWith("error_") ? envelope.subtype : envelope.is_error === true ? "is_error" : "cli-error";
29832
- 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";
29833
- return terminalFromSpawned(spawned, {
29834
- cause: "output",
29835
- identity: { name: "HeadlessCliError", code: errorCode },
29836
- diagnostic,
29837
- details: {
29838
- sessionId,
29839
- subtype: envelope.subtype,
29840
- errors: envelope.errors,
29841
- exitCode: spawned.code
29842
- }
29843
- });
29844
- }
29845
- if (envelope.structured_output !== void 0) {
29846
- await prepared.ingestStructuredOutput(envelope.structured_output);
29847
- } else if (prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME && typeof envelope.result === "string" && envelope.result.trim() !== "") {
29848
- await prepared.ingestStructuredOutput({ prose: envelope.result });
29849
- }
29850
- return { status: "delivered", stderr: spawned.stderr };
29851
- }
29852
- });
29475
+ });
29476
+ } finally {
29477
+ if (exitedSessionId !== void 0 && exitedSessionId !== "") copyAndRecordHostDossier({
29478
+ host: config.hostName,
29479
+ sessionId: exitedSessionId,
29480
+ cwd: request.cwd,
29481
+ sessionDirectory: join50(request.runDirectory, "session"),
29482
+ sessionParent,
29483
+ continuation: request.continuation,
29484
+ ...request.model !== void 0 ? { model: request.model } : {},
29485
+ ...request.home !== void 0 ? { home: request.home } : {}
29486
+ });
29487
+ }
29853
29488
  } finally {
29854
29489
  try {
29855
29490
  await prepared.dispose?.();