@akagilnc/pi-workflow-roles 0.1.5216 → 0.1.5235

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4224,57 +4224,15 @@ var init_sitian_contracts = __esm({
4224
4224
  });
4225
4225
 
4226
4226
  // src/sitian-appender.ts
4227
- import { createHash as createHash4, randomUUID } from "node:crypto";
4228
- import {
4229
- appendFileSync,
4230
- existsSync,
4231
- readFileSync,
4232
- unlinkSync,
4233
- writeFileSync
4234
- } from "node:fs";
4227
+ import { randomUUID } from "node:crypto";
4228
+ import { appendFileSync } from "node:fs";
4235
4229
  import { dirname as dirname3, join as join4 } from "node:path";
4236
- function isRecord3(value) {
4237
- return typeof value === "object" && value !== null && !Array.isArray(value);
4238
- }
4239
- function errorCodeOf(error) {
4240
- return error.code;
4241
- }
4242
- function identityClaimPath(recordFile, identity) {
4243
- const digest = createHash4("sha256").update(identity, "utf8").digest("hex");
4244
- return `${recordFile}.id-${digest}`;
4245
- }
4246
- function createExclusiveFile(path, contents) {
4247
- writeFileSync(path, contents, { encoding: "utf8", flag: "wx" });
4248
- }
4249
- function sealTornTail(recordFile) {
4250
- if (!existsSync(recordFile)) return;
4251
- const buffer = readFileSync(recordFile);
4252
- if (buffer.length > 0 && buffer[buffer.length - 1] !== 10) {
4253
- appendFileSync(recordFile, "\n", "utf8");
4254
- }
4255
- }
4256
4230
  function appendSitianRecordBlock(input, block) {
4257
4231
  if (block === "") return;
4258
4232
  try {
4259
4233
  const { sessionDir, recordFile, ledgerHome } = resolveSitianRecordPath(input);
4260
4234
  ensureRealDirectoryTree(ledgerHome, sessionDir);
4261
- appendFileSync(recordFile, "", "utf8");
4262
- sealTornTail(recordFile);
4263
- const identityOf = (line2) => {
4264
- try {
4265
- const row = JSON.parse(line2);
4266
- return isRecord3(row) && typeof row.identity === "string" ? row.identity : void 0;
4267
- } catch {
4268
- return void 0;
4269
- }
4270
- };
4271
- const identities = new Set(readFileSync(recordFile, "utf8").split("\n").map(identityOf).filter((id) => id !== void 0));
4272
- for (const line2 of block.match(/[^\n]*\n|[^\n]+$/g) ?? []) {
4273
- const identity = identityOf(line2);
4274
- if (identity !== void 0 && identities.has(identity)) continue;
4275
- appendFileSync(recordFile, line2, "utf8");
4276
- if (identity !== void 0) identities.add(identity);
4277
- }
4235
+ appendFileSync(recordFile, block, "utf8");
4278
4236
  } catch (error) {
4279
4237
  if (error instanceof SitianInfrastructureError) throw error;
4280
4238
  throw new SitianInfrastructureError(
@@ -4283,106 +4241,6 @@ function appendSitianRecordBlock(input, block) {
4283
4241
  );
4284
4242
  }
4285
4243
  }
4286
- function findIdentityPointer(recordFile, identity, kind, level) {
4287
- if (!existsSync(recordFile)) return void 0;
4288
- const text = readFileSync(recordFile, "utf8");
4289
- for (const line2 of text.split("\n")) {
4290
- const trimmed = line2.trim();
4291
- if (!trimmed) continue;
4292
- try {
4293
- const parsed = JSON.parse(trimmed);
4294
- if (isRecord3(parsed) && parsed.identity === identity) {
4295
- return { identity, recordFile, kind, level };
4296
- }
4297
- } catch {
4298
- }
4299
- }
4300
- return void 0;
4301
- }
4302
- function unlinkAbsentOk(path) {
4303
- try {
4304
- unlinkSync(path);
4305
- return void 0;
4306
- } catch (error) {
4307
- if (errorCodeOf(error) === "ENOENT") return void 0;
4308
- return error instanceof Error ? error : new Error(errorText(error));
4309
- }
4310
- }
4311
- function appendWithIdentityClaim(recordFile, record4, row) {
4312
- sealTornTail(recordFile);
4313
- const claimPath = identityClaimPath(recordFile, record4.identity);
4314
- const existing = findIdentityPointer(
4315
- recordFile,
4316
- record4.identity,
4317
- record4.kind,
4318
- record4.level
4319
- );
4320
- if (existing !== void 0) {
4321
- unlinkAbsentOk(claimPath);
4322
- return existing;
4323
- }
4324
- try {
4325
- createExclusiveFile(claimPath, "");
4326
- } catch (error) {
4327
- if (errorCodeOf(error) !== "EEXIST") throw error;
4328
- sealTornTail(recordFile);
4329
- const published = findIdentityPointer(
4330
- recordFile,
4331
- record4.identity,
4332
- record4.kind,
4333
- record4.level
4334
- );
4335
- if (published !== void 0) {
4336
- unlinkAbsentOk(claimPath);
4337
- return published;
4338
- }
4339
- throw new SitianInfrastructureError(
4340
- `Sitian identity claim at ${claimPath} already exists for identity ${record4.identity}`,
4341
- { cause: error }
4342
- );
4343
- }
4344
- let primaryFailure;
4345
- let result;
4346
- let cleanupFailure;
4347
- try {
4348
- sealTornTail(recordFile);
4349
- const raced = findIdentityPointer(
4350
- recordFile,
4351
- record4.identity,
4352
- record4.kind,
4353
- record4.level
4354
- );
4355
- if (raced !== void 0) {
4356
- result = raced;
4357
- } else {
4358
- appendFileSync(recordFile, row, "utf8");
4359
- result = {
4360
- identity: record4.identity,
4361
- recordFile,
4362
- kind: record4.kind,
4363
- level: record4.level
4364
- };
4365
- }
4366
- } catch (error) {
4367
- primaryFailure = error;
4368
- } finally {
4369
- cleanupFailure = unlinkAbsentOk(claimPath);
4370
- }
4371
- if (primaryFailure !== void 0) {
4372
- if (primaryFailure instanceof SitianInfrastructureError) throw primaryFailure;
4373
- throw new SitianInfrastructureError(
4374
- `Sitian appender persistence failure: ${errorText(primaryFailure)}`,
4375
- { cause: primaryFailure }
4376
- );
4377
- }
4378
- if (cleanupFailure !== void 0) {
4379
- throw new SitianInfrastructureError(
4380
- `Sitian identity claim at ${claimPath} could not be released after append for identity ${record4.identity}: ${errorText(cleanupFailure)}`,
4381
- { cause: cleanupFailure }
4382
- );
4383
- }
4384
- return result;
4385
- }
4386
4244
  function resolveSitianVolumeCategory(kind) {
4387
4245
  if (S4_SUBMISSION_LEDGER_KINDS.has(kind)) {
4388
4246
  return "submission-ledger";
@@ -4455,7 +4313,13 @@ function appendSitianRecord(input) {
4455
4313
  };
4456
4314
  const row = `${JSON.stringify(record4)}
4457
4315
  `;
4458
- return appendWithIdentityClaim(recordFile, record4, row);
4316
+ appendFileSync(recordFile, row, "utf8");
4317
+ return {
4318
+ identity: record4.identity,
4319
+ recordFile,
4320
+ kind: record4.kind,
4321
+ level: record4.level
4322
+ };
4459
4323
  } catch (error) {
4460
4324
  if (error instanceof SitianInfrastructureError) throw error;
4461
4325
  throw new SitianInfrastructureError(
@@ -4483,13 +4347,13 @@ var init_sitian_appender = __esm({
4483
4347
  });
4484
4348
 
4485
4349
  // src/sitian-reader.ts
4486
- import { existsSync as existsSync2 } from "node:fs";
4350
+ import { existsSync } from "node:fs";
4487
4351
  import { readFile as readFile3 } from "node:fs/promises";
4488
- function isRecord4(value) {
4352
+ function isRecord3(value) {
4489
4353
  return typeof value === "object" && value !== null && !Array.isArray(value);
4490
4354
  }
4491
4355
  async function readSitianRecords(recordFile) {
4492
- if (!existsSync2(recordFile)) {
4356
+ if (!existsSync(recordFile)) {
4493
4357
  return { records: [], diagnostics: [] };
4494
4358
  }
4495
4359
  const text = await readFile3(recordFile, "utf8");
@@ -4501,7 +4365,7 @@ async function readSitianRecords(recordFile) {
4501
4365
  if (!line2.trim()) continue;
4502
4366
  try {
4503
4367
  const parsed = JSON.parse(line2);
4504
- if (isRecord4(parsed)) {
4368
+ if (isRecord3(parsed)) {
4505
4369
  records.push(parsed);
4506
4370
  } else {
4507
4371
  const typeDesc = parsed === null ? "null" : Array.isArray(parsed) ? "array" : typeof parsed;
@@ -4642,14 +4506,14 @@ function isMissingPathError2(error) {
4642
4506
  function errorText2(error) {
4643
4507
  return error instanceof Error ? error.message : String(error);
4644
4508
  }
4645
- function isRecord5(value) {
4509
+ function isRecord4(value) {
4646
4510
  return typeof value === "object" && value !== null && !Array.isArray(value);
4647
4511
  }
4648
4512
  function readUsableTerminalArtifactBody(body) {
4649
4513
  if (body === null) {
4650
4514
  return { ok: false, reason: "terminal artifact JSON value is null" };
4651
4515
  }
4652
- if (!isRecord5(body)) {
4516
+ if (!isRecord4(body)) {
4653
4517
  return {
4654
4518
  ok: false,
4655
4519
  reason: `terminal artifact JSON value is not a typed object (${Array.isArray(body) ? "array" : typeof body})`
@@ -5340,7 +5204,7 @@ var init_session_assistant_usage = __esm({
5340
5204
  });
5341
5205
 
5342
5206
  // src/package-resources/engine-material.ts
5343
- import { existsSync as existsSync3, readdirSync } from "node:fs";
5207
+ import { existsSync as existsSync2, readdirSync } from "node:fs";
5344
5208
  import { join as join10 } from "node:path";
5345
5209
  function pickEngineAxis(source) {
5346
5210
  return {
@@ -5383,7 +5247,7 @@ function engineSessionMaterialFromOptions(options) {
5383
5247
  const model = options.engineModel === void 0 ? void 0 : assertLegalEngineModel(options.engineModel);
5384
5248
  const materialPath = resolveEngineMaterialPath(options.packageRoot, name);
5385
5249
  const modelField = model === void 0 ? {} : { model };
5386
- if (existsSync3(materialPath)) {
5250
+ if (existsSync2(materialPath)) {
5387
5251
  return Object.freeze({ name, materialPath, ...modelField });
5388
5252
  }
5389
5253
  return Object.freeze({ name, ...modelField });
@@ -5750,19 +5614,7 @@ function createPiRoleTurnHost(config) {
5750
5614
  });
5751
5615
  return {
5752
5616
  async executeTurn(request) {
5753
- let turnRequest = request;
5754
- const officerStationChild = request.stationChild === true && isOfficerReviewSeat(request.activation.role);
5755
- const paths = !officerStationChild && request.hostTransition?.priorNativeKind === "sitian" ? request.hostTransition.priorNativePaths : void 0;
5756
- if (request.continuation.kind === "resume" && paths !== void 0 && paths.length > 0) {
5757
- turnRequest = {
5758
- ...request,
5759
- continuation: {
5760
- ...request.continuation,
5761
- prompt: `${request.continuation.prompt}
5762
- ${paths.join("\n")}`
5763
- }
5764
- };
5765
- }
5617
+ const turnRequest = request;
5766
5618
  const roleEntry = await realpath(resolveInternalRoleEntrypoint(config.packageRoot));
5767
5619
  const extraArgs = buildPiTurnExtraArgs(
5768
5620
  turnRequest,
@@ -5842,7 +5694,6 @@ var init_role_turn_host = __esm({
5842
5694
  "src/pi/role-turn-host.ts"() {
5843
5695
  "use strict";
5844
5696
  init_host_contracts();
5845
- init_packaged_role_registry();
5846
5697
  init_engine_detour();
5847
5698
  init_role_activation_flags();
5848
5699
  init_user_dialogue_stdin();
@@ -5962,9 +5813,9 @@ var init_host_descriptions = __esm({
5962
5813
  });
5963
5814
 
5964
5815
  // src/sha256.ts
5965
- import { createHash as createHash5 } from "node:crypto";
5816
+ import { createHash as createHash4 } from "node:crypto";
5966
5817
  function sha256Hex(bytes) {
5967
- return createHash5("sha256").update(bytes).digest("hex");
5818
+ return createHash4("sha256").update(bytes).digest("hex");
5968
5819
  }
5969
5820
  var init_sha256 = __esm({
5970
5821
  "src/sha256.ts"() {
@@ -6464,7 +6315,7 @@ var init_merger_git_state = __esm({
6464
6315
 
6465
6316
  // src/ledger-session-read.ts
6466
6317
  import { readFile as readFile9 } from "node:fs/promises";
6467
- function isRecord6(value) {
6318
+ function isRecord5(value) {
6468
6319
  return typeof value === "object" && value !== null && !Array.isArray(value);
6469
6320
  }
6470
6321
  async function readLedgerSessionJsonlLines(path) {
@@ -6489,7 +6340,7 @@ async function readLedgerSessionJsonlLines(path) {
6489
6340
  });
6490
6341
  continue;
6491
6342
  }
6492
- if (!isRecord6(row)) {
6343
+ if (!isRecord5(row)) {
6493
6344
  const kind = row === null ? "null" : Array.isArray(row) ? "array" : typeof row;
6494
6345
  out.push({
6495
6346
  line: lineNumber,
@@ -6542,7 +6393,7 @@ function extractSessionModelSequence(rows) {
6542
6393
  if (row.type === "model_change" && typeof row.modelId === "string") {
6543
6394
  push(row.modelId);
6544
6395
  }
6545
- const message = isRecord6(row.message) ? row.message : void 0;
6396
+ const message = isRecord5(row.message) ? row.message : void 0;
6546
6397
  if (message?.role === "assistant" && typeof message.model === "string") {
6547
6398
  push(message.model);
6548
6399
  }
@@ -6558,11 +6409,11 @@ function extractSessionToolIntervals(rows) {
6558
6409
  const openById = /* @__PURE__ */ new Map();
6559
6410
  for (const row of rows) {
6560
6411
  const rowTimestamp = typeof row.timestamp === "string" ? row.timestamp : void 0;
6561
- const message = isRecord6(row.message) ? row.message : void 0;
6412
+ const message = isRecord5(row.message) ? row.message : void 0;
6562
6413
  if (message?.role === "assistant" && Array.isArray(message.content)) {
6563
6414
  const callTimestamp = typeof message.timestamp === "string" && message.timestamp ? message.timestamp : rowTimestamp;
6564
6415
  for (const part of message.content) {
6565
- if (!isRecord6(part) || part.type !== "toolCall") continue;
6416
+ if (!isRecord5(part) || part.type !== "toolCall") continue;
6566
6417
  if (typeof part.id !== "string" || part.id.length === 0) {
6567
6418
  throw new Error("toolCall frame missing string id");
6568
6419
  }
@@ -6575,7 +6426,7 @@ function extractSessionToolIntervals(rows) {
6575
6426
  if (openById.has(part.id)) {
6576
6427
  throw new Error(`duplicate toolCall id ${part.id}`);
6577
6428
  }
6578
- const args = isRecord6(part.arguments) ? part.arguments : void 0;
6429
+ const args = isRecord5(part.arguments) ? part.arguments : void 0;
6579
6430
  const command = part.name === "bash" && args !== void 0 && typeof args.command === "string" ? bashCommandFirstLine(args.command) : void 0;
6580
6431
  const interval = {
6581
6432
  toolCallId: part.id,
@@ -6659,7 +6510,7 @@ var init_ledger_session_read = __esm({
6659
6510
  });
6660
6511
 
6661
6512
  // src/session-dialogue.ts
6662
- function isRecord7(value) {
6513
+ function isRecord6(value) {
6663
6514
  return typeof value === "object" && value !== null && !Array.isArray(value);
6664
6515
  }
6665
6516
  function nativeEventId(row) {
@@ -6669,7 +6520,7 @@ function nativeEventId(row) {
6669
6520
  }
6670
6521
  for (const nestKey of ["message", "payload"]) {
6671
6522
  const nested = row[nestKey];
6672
- if (!isRecord7(nested)) continue;
6523
+ if (!isRecord6(nested)) continue;
6673
6524
  for (const key of ["uuid", "id"]) {
6674
6525
  const value = nested[key];
6675
6526
  if (typeof value === "string" && value !== "") return value;
@@ -6682,19 +6533,19 @@ function textParts(content) {
6682
6533
  if (!Array.isArray(content)) return [];
6683
6534
  const out = [];
6684
6535
  for (const part of content) {
6685
- if (!isRecord7(part) || !SPEAKER_TEXT_PART_TYPES.has(String(part.type))) continue;
6536
+ if (!isRecord6(part) || !SPEAKER_TEXT_PART_TYPES.has(String(part.type))) continue;
6686
6537
  const text = part.text;
6687
6538
  if (typeof text === "string" && text !== "") out.push(text);
6688
6539
  }
6689
6540
  return out;
6690
6541
  }
6691
6542
  function responseItemMessage(row) {
6692
- if (row.type !== "response_item" || !isRecord7(row.payload)) return void 0;
6543
+ if (row.type !== "response_item" || !isRecord6(row.payload)) return void 0;
6693
6544
  if (row.payload.type !== "message") return void 0;
6694
6545
  return row.payload;
6695
6546
  }
6696
6547
  function messageBody(row) {
6697
- if (isRecord7(row.message)) return row.message;
6548
+ if (isRecord6(row.message)) return row.message;
6698
6549
  return responseItemMessage(row);
6699
6550
  }
6700
6551
  function speakerOf(message) {
@@ -6704,7 +6555,7 @@ function speakerOf(message) {
6704
6555
  }
6705
6556
  function codexContentItemKinds(message) {
6706
6557
  const pass = message.internal_chat_message_metadata_passthrough;
6707
- if (!isRecord7(pass) || !Array.isArray(pass.content_item_kinds)) return void 0;
6558
+ if (!isRecord6(pass) || !Array.isArray(pass.content_item_kinds)) return void 0;
6708
6559
  const kinds = [];
6709
6560
  for (const kind of pass.content_item_kinds) {
6710
6561
  if (typeof kind === "string" && kind !== "") kinds.push(kind);
@@ -6733,7 +6584,7 @@ function isFixedNonOwnerEnqueueShape(content) {
6733
6584
  return hasFixedOpenTagPrefix(content, TASK_NOTIFICATION_OPEN_TAG);
6734
6585
  }
6735
6586
  function materializationOriginKind(row) {
6736
- if (!isRecord7(row.origin)) return void 0;
6587
+ if (!isRecord6(row.origin)) return void 0;
6737
6588
  const kind = row.origin.kind;
6738
6589
  return typeof kind === "string" && kind !== "" ? kind : void 0;
6739
6590
  }
@@ -8326,7 +8177,7 @@ var init_option_definitions = __esm({
8326
8177
 
8327
8178
  // src/public-cli/invocation.ts
8328
8179
  import { execFileSync as execFileSync3 } from "node:child_process";
8329
- import { existsSync as existsSync4 } from "node:fs";
8180
+ import { existsSync as existsSync3 } from "node:fs";
8330
8181
  import {
8331
8182
  lstat as lstat3,
8332
8183
  mkdtemp as mkdtemp2,
@@ -8552,7 +8403,7 @@ async function relocateAdmittedRunToTicket(admitted, authority, heldLease) {
8552
8403
  for (const childRunId of Array.isArray(childRunIds) ? childRunIds : []) {
8553
8404
  if (typeof childRunId !== "string") continue;
8554
8405
  const childDirectory = join15(dirname10(oldRunDirectory), `${childRunId}@diarist`);
8555
- if (!existsSync4(childDirectory)) continue;
8406
+ if (!existsSync3(childDirectory)) continue;
8556
8407
  const childTarget = roleRunPlacement(ledgerHome, {
8557
8408
  bookKey: admitted.bookKey,
8558
8409
  subject: { ticketNumber: admitted.ticketNumber },
@@ -10034,7 +9885,7 @@ var init_invocation = __esm({
10034
9885
  });
10035
9886
 
10036
9887
  // src/public-cli/load-production-acp-host.ts
10037
- import { existsSync as existsSync5 } from "node:fs";
9888
+ import { existsSync as existsSync4 } from "node:fs";
10038
9889
  import { join as join16 } from "node:path";
10039
9890
  import { pathToFileURL } from "node:url";
10040
9891
  async function loadProductionAcpHostFactory(packageRoot, host) {
@@ -10044,7 +9895,7 @@ async function loadProductionAcpHostFactory(packageRoot, host) {
10044
9895
  }
10045
9896
  const built = join16(packageRoot, "dist/acp-host/production-host.js");
10046
9897
  const source = join16(packageRoot, "src/acp-host/production-host.ts");
10047
- const target = existsSync5(built) ? built : source;
9898
+ const target = existsSync4(built) ? built : source;
10048
9899
  const href = pathToFileURL(target).href;
10049
9900
  const mod = await import(href);
10050
9901
  const create = mod.createProductionAcpRoleTurnHost;
@@ -10058,7 +9909,7 @@ var init_load_production_acp_host = __esm({
10058
9909
  });
10059
9910
 
10060
9911
  // src/public-cli/load-production-headless-host.ts
10061
- import { existsSync as existsSync6 } from "node:fs";
9912
+ import { existsSync as existsSync5 } from "node:fs";
10062
9913
  import { join as join17 } from "node:path";
10063
9914
  import { pathToFileURL as pathToFileURL2 } from "node:url";
10064
9915
  async function loadProductionHeadlessHostFactory(packageRoot, host) {
@@ -10068,7 +9919,7 @@ async function loadProductionHeadlessHostFactory(packageRoot, host) {
10068
9919
  }
10069
9920
  const built = join17(packageRoot, "dist/headless-host/production-host.js");
10070
9921
  const source = join17(packageRoot, "src/headless-host/production-host.ts");
10071
- const target = existsSync6(built) ? built : source;
9922
+ const target = existsSync5(built) ? built : source;
10072
9923
  const href = pathToFileURL2(target).href;
10073
9924
  const mod = await import(href);
10074
9925
  const create = mod.createProductionHeadlessRoleTurnHost;
@@ -10754,7 +10605,7 @@ __export(host_providers_exports, {
10754
10605
  projectHostFacingProvider: () => projectHostFacingProvider,
10755
10606
  renderHostProvidersTable: () => renderHostProvidersTable
10756
10607
  });
10757
- import { readFileSync as readFileSync2 } from "node:fs";
10608
+ import { readFileSync } from "node:fs";
10758
10609
  import { join as join19 } from "node:path";
10759
10610
  function hostProvidersPath(home) {
10760
10611
  if (typeof home !== "string" || home.trim() === "") {
@@ -10802,7 +10653,7 @@ function parseHostProvidersTable(value) {
10802
10653
  function loadHostProvidersTable(home) {
10803
10654
  const path = hostProvidersPath(home);
10804
10655
  try {
10805
- const raw = readFileSync2(path, "utf8");
10656
+ const raw = readFileSync(path, "utf8");
10806
10657
  return parseHostProvidersTable(JSON.parse(raw));
10807
10658
  } catch (error) {
10808
10659
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
@@ -10820,7 +10671,7 @@ function listHermesProvidersForModel(home, seatModel) {
10820
10671
  const path = hermesProviderModelsCachePath(home);
10821
10672
  let text;
10822
10673
  try {
10823
- text = readFileSync2(path, "utf8");
10674
+ text = readFileSync(path, "utf8");
10824
10675
  } catch (error) {
10825
10676
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
10826
10677
  return [];
@@ -10920,7 +10771,7 @@ var init_host_providers = __esm({
10920
10771
  // src/analyst-gate-cycles-read.ts
10921
10772
  import { readdir as readdir4 } from "node:fs/promises";
10922
10773
  import { join as join20 } from "node:path";
10923
- function isRecord8(value) {
10774
+ function isRecord7(value) {
10924
10775
  return typeof value === "object" && value !== null && !Array.isArray(value);
10925
10776
  }
10926
10777
  function isParentAttemptBindingRow(row) {
@@ -10950,7 +10801,7 @@ function isGateTerminatingToolName(toolName) {
10950
10801
  function acceptedGateReceiptIds(rows) {
10951
10802
  const accepted = /* @__PURE__ */ new Set();
10952
10803
  for (const row of rows) {
10953
- const message = isRecord8(row.message) ? row.message : void 0;
10804
+ const message = isRecord7(row.message) ? row.message : void 0;
10954
10805
  if (message?.role !== "toolResult") continue;
10955
10806
  if (typeof message.toolCallId !== "string" || message.toolCallId.length === 0) continue;
10956
10807
  if (message.isError === false) accepted.add(message.toolCallId);
@@ -10985,7 +10836,7 @@ function nearestAttemptBindingBefore(rows, beforeIndex) {
10985
10836
  for (let i = beforeIndex - 1; i >= 0; i -= 1) {
10986
10837
  const row = rows[i];
10987
10838
  if (!isParentAttemptBindingRow(row)) continue;
10988
- if (!isRecord8(row.data) || !isRecord8(row.data.parent)) continue;
10839
+ if (!isRecord7(row.data) || !isRecord7(row.data.parent)) continue;
10989
10840
  const id = row.data.parent.attemptEntryId;
10990
10841
  const sessionFile = row.data.parent.sessionFile;
10991
10842
  return {
@@ -11000,10 +10851,10 @@ function extractAllAcceptedGateToolCalls(rows) {
11000
10851
  const out = [];
11001
10852
  for (let rowIndex = 0; rowIndex < rows.length; rowIndex += 1) {
11002
10853
  const row = rows[rowIndex];
11003
- const message = isRecord8(row.message) ? row.message : void 0;
10854
+ const message = isRecord7(row.message) ? row.message : void 0;
11004
10855
  if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
11005
10856
  for (const part of message.content) {
11006
- if (!isRecord8(part) || part.type !== "toolCall") continue;
10857
+ if (!isRecord7(part) || part.type !== "toolCall") continue;
11007
10858
  if (typeof part.id !== "string" || part.id.length === 0) continue;
11008
10859
  if (typeof part.name !== "string" || part.name.length === 0) continue;
11009
10860
  if (!isGateTerminatingToolName(part.name)) continue;
@@ -11011,7 +10862,7 @@ function extractAllAcceptedGateToolCalls(rows) {
11011
10862
  const binding = nearestAttemptBindingBefore(rows, rowIndex);
11012
10863
  out.push({
11013
10864
  toolName: part.name,
11014
- args: isRecord8(part.arguments) ? part.arguments : void 0,
10865
+ args: isRecord7(part.arguments) ? part.arguments : void 0,
11015
10866
  accepted: true,
11016
10867
  rowIndex,
11017
10868
  ...binding
@@ -11144,7 +10995,7 @@ async function resolveOfficerSessionFromPointerFile(pointerPath) {
11144
10995
  { cause: error }
11145
10996
  );
11146
10997
  }
11147
- if (!isRecord8(raw) || raw.kind !== "direct-officer-run-pointer" || raw.version !== 1) {
10998
+ if (!isRecord7(raw) || raw.kind !== "direct-officer-run-pointer" || raw.version !== 1) {
11148
10999
  throw new Error(`direct officer run pointer has unknown shape in ${pointerPath}`);
11149
11000
  }
11150
11001
  const sessionFile = raw.sessionFile;
@@ -11219,14 +11070,14 @@ var init_audit_escalation = __esm({
11219
11070
  });
11220
11071
 
11221
11072
  // src/session-opening-materials.ts
11222
- import { existsSync as existsSync7 } from "node:fs";
11073
+ import { existsSync as existsSync6 } from "node:fs";
11223
11074
  import { readFile as readFile13 } from "node:fs/promises";
11224
11075
  import { dirname as dirname12, join as join21 } from "node:path";
11225
11076
  import { fileURLToPath, pathToFileURL as pathToFileURL3 } from "node:url";
11226
11077
  function resolvePackageRootDir(moduleUrl = import.meta.url) {
11227
11078
  let dir = dirname12(fileURLToPath(moduleUrl));
11228
11079
  for (let i = 0; i < 8; i += 1) {
11229
- if (existsSync7(join21(dir, "package.json")) && existsSync7(join21(dir, "souls"))) {
11080
+ if (existsSync6(join21(dir, "package.json")) && existsSync6(join21(dir, "souls"))) {
11230
11081
  return dir;
11231
11082
  }
11232
11083
  const parent = dirname12(dir);
@@ -11449,7 +11300,7 @@ var init_serialize_thrown_value = __esm({
11449
11300
 
11450
11301
  // src/engine-detour-usage.ts
11451
11302
  import { randomUUID as randomUUID3 } from "node:crypto";
11452
- import { readFileSync as readFileSync3 } from "node:fs";
11303
+ import { readFileSync as readFileSync2 } from "node:fs";
11453
11304
  import { dirname as dirname13, join as join23 } from "node:path";
11454
11305
  function engineDetourStdoutByteLength(stdout) {
11455
11306
  return Buffer.byteLength(stdout, "utf8");
@@ -11503,11 +11354,11 @@ function reportEngineDetourCall(input) {
11503
11354
  recordPointer: pointer
11504
11355
  };
11505
11356
  }
11506
- function isRecord9(value) {
11357
+ function isRecord8(value) {
11507
11358
  return typeof value === "object" && value !== null && !Array.isArray(value);
11508
11359
  }
11509
11360
  function callFactFromSitianPayload(payload, pointer) {
11510
- if (!isRecord9(payload)) return void 0;
11361
+ if (!isRecord8(payload)) return void 0;
11511
11362
  if (payload.tool !== ENGINE_DETOUR_TOOL_NAME) return void 0;
11512
11363
  if (typeof payload.toolCallId !== "string" || payload.toolCallId.length === 0) {
11513
11364
  return void 0;
@@ -11524,11 +11375,11 @@ function callFactFromSitianPayload(payload, pointer) {
11524
11375
  };
11525
11376
  }
11526
11377
  function invocationScopeIdOfRecord(record4) {
11527
- if (isRecord9(record4.subject)) {
11378
+ if (isRecord8(record4.subject)) {
11528
11379
  const fromSubject = record4.subject.invocationScopeId;
11529
11380
  if (typeof fromSubject === "string" && fromSubject.length > 0) return fromSubject;
11530
11381
  }
11531
- if (isRecord9(record4.payload)) {
11382
+ if (isRecord8(record4.payload)) {
11532
11383
  const fromPayload = record4.payload.invocationScopeId;
11533
11384
  if (typeof fromPayload === "string" && fromPayload.length > 0) return fromPayload;
11534
11385
  }
@@ -11544,7 +11395,7 @@ async function readEngineDetourToolUsage(input) {
11544
11395
  ...input.cwd === void 0 ? {} : { cwd: input.cwd }
11545
11396
  });
11546
11397
  const { records } = await readSitianRecords(recordFile);
11547
- const calls = [];
11398
+ const callsByToolCallId = /* @__PURE__ */ new Map();
11548
11399
  for (const record4 of records) {
11549
11400
  if (record4.kind !== ENGINE_DETOUR_CALL_KIND) continue;
11550
11401
  const boundScope = invocationScopeIdOfRecord(record4);
@@ -11561,8 +11412,9 @@ async function readEngineDetourToolUsage(input) {
11561
11412
  };
11562
11413
  const fact = callFactFromSitianPayload(record4.payload, pointer);
11563
11414
  if (fact === void 0) continue;
11564
- calls.push(fact);
11415
+ callsByToolCallId.set(fact.toolCallId, fact);
11565
11416
  }
11417
+ const calls = Array.from(callsByToolCallId.values());
11566
11418
  return { callCount: calls.length, calls };
11567
11419
  }
11568
11420
  function projectEngineDetourToolUsageForPublicTerminal(usage, options) {
@@ -11586,9 +11438,9 @@ function projectEngineDetourToolUsageForPublicTerminal(usage, options) {
11586
11438
  function readInvocationRecord(runDirectory) {
11587
11439
  try {
11588
11440
  const raw = JSON.parse(
11589
- readFileSync3(join23(runDirectory, "invocation.json"), "utf8")
11441
+ readFileSync2(join23(runDirectory, "invocation.json"), "utf8")
11590
11442
  );
11591
- return isRecord9(raw) ? raw : void 0;
11443
+ return isRecord8(raw) ? raw : void 0;
11592
11444
  } catch (error) {
11593
11445
  if (error?.code === "ENOENT") return void 0;
11594
11446
  throw error;
@@ -11599,14 +11451,9 @@ async function readInvocationEngineMounted(runDirectory) {
11599
11451
  if (raw === void 0) return false;
11600
11452
  return typeof raw.engine === "string" && raw.engine.trim() !== "";
11601
11453
  }
11602
- function readInvocationSelectedHost(runDirectory) {
11603
- const raw = readInvocationRecord(runDirectory);
11604
- if (raw === void 0) return void 0;
11605
- return typeof raw.host === "string" && raw.host.trim() !== "" ? raw.host.trim() : void 0;
11606
- }
11607
11454
  function withEngineDetourToolUsageFact(outcome, usage) {
11608
11455
  if (usage === void 0) return outcome;
11609
- const prior = isRecord9(outcome.decisiveFacts) ? outcome.decisiveFacts : {};
11456
+ const prior = isRecord8(outcome.decisiveFacts) ? outcome.decisiveFacts : {};
11610
11457
  return {
11611
11458
  ...outcome,
11612
11459
  decisiveFacts: {
@@ -11648,7 +11495,7 @@ var init_engine_detour_usage = __esm({
11648
11495
  });
11649
11496
 
11650
11497
  // src/dossier-resolution.ts
11651
- import { existsSync as existsSync8, statSync as statSync2 } from "node:fs";
11498
+ import { existsSync as existsSync7, statSync as statSync2 } from "node:fs";
11652
11499
  import { resolve as resolve10 } from "node:path";
11653
11500
  function isHostContext(value) {
11654
11501
  return "sessionManager" in value;
@@ -11668,7 +11515,7 @@ function resolveAuditDossier(source) {
11668
11515
  }
11669
11516
  const runDirectory = resolve10(raw);
11670
11517
  try {
11671
- if (!existsSync8(runDirectory) || !statSync2(runDirectory).isDirectory()) {
11518
+ if (!existsSync7(runDirectory) || !statSync2(runDirectory).isDirectory()) {
11672
11519
  return { status: "incomplete", observation: { kind: "missing-dossier" } };
11673
11520
  }
11674
11521
  } catch {
@@ -11676,13 +11523,13 @@ function resolveAuditDossier(source) {
11676
11523
  }
11677
11524
  return { status: "ok", runDirectory };
11678
11525
  }
11679
- function isRecord10(value) {
11526
+ function isRecord9(value) {
11680
11527
  return typeof value === "object" && value !== null && !Array.isArray(value);
11681
11528
  }
11682
11529
  function readDoctorAuditSubjects(context) {
11683
11530
  const entries = context.sessionManager.getEntries?.() ?? [];
11684
11531
  for (const entry of entries) {
11685
- if (isRecord10(entry) && entry.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
11532
+ if (isRecord9(entry) && entry.type === "custom" && entry.customType === DOCTOR_CANDIDATE_ENTRY_TYPE) {
11686
11533
  return { status: "ok" };
11687
11534
  }
11688
11535
  }
@@ -11926,11 +11773,11 @@ var init_navigator_invocation_identity = __esm({
11926
11773
  });
11927
11774
 
11928
11775
  // src/receipt-delivery-policy.ts
11929
- function isRecord11(value) {
11776
+ function isRecord10(value) {
11930
11777
  return typeof value === "object" && value !== null && !Array.isArray(value);
11931
11778
  }
11932
11779
  function parseNoReceiptLifecycleFacts(input) {
11933
- 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")) {
11780
+ 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")) {
11934
11781
  throw new TypeError("malformed no-receipt lifecycle facts");
11935
11782
  }
11936
11783
  return {
@@ -12555,7 +12402,7 @@ async function readSitianRetainedAuditorProviderStop(sessionFile) {
12555
12402
  const { records } = await readSitianRecords(recordFile);
12556
12403
  for (let i = records.length - 1; i >= 0; i -= 1) {
12557
12404
  const payload = records[i]?.payload;
12558
- if (!isRecord12(payload) || !isRecord12(payload.response)) continue;
12405
+ if (!isRecord11(payload) || !isRecord11(payload.response)) continue;
12559
12406
  if (typeof payload.type === "string") continue;
12560
12407
  const stop = sessionProviderStopFromAssistant(payload.response);
12561
12408
  if (stop !== void 0) return stop;
@@ -12605,7 +12452,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
12605
12452
  throw sessionReadFailure(error, "failed to read discovered auditor session");
12606
12453
  }
12607
12454
  const header = entries.find((entry) => entry.type === "session");
12608
- if (!isRecord12(header)) continue;
12455
+ if (!isRecord11(header)) continue;
12609
12456
  const bindingIndexes = [];
12610
12457
  for (let i = 0; i < entries.length; i += 1) {
12611
12458
  const entry = entries[i];
@@ -12619,7 +12466,7 @@ async function loadBoundAuditorVolumes(sessionFile) {
12619
12466
  end: idx + 1 < bindingIndexes.length ? bindingIndexes[idx + 1] : entries.length
12620
12467
  })) : [{ entry: void 0, start: 0, end: entries.length }];
12621
12468
  for (const { entry: bindingEntry, start, end } of bindingPasses) {
12622
- const bindingParent = bindingEntry !== void 0 && isRecord12(bindingEntry.data) && isRecord12(bindingEntry.data.parent) ? bindingEntry.data.parent : void 0;
12469
+ const bindingParent = bindingEntry !== void 0 && isRecord11(bindingEntry.data) && isRecord11(bindingEntry.data.parent) ? bindingEntry.data.parent : void 0;
12623
12470
  const attemptEntryId = typeof bindingParent?.attemptEntryId === "string" ? bindingParent.attemptEntryId : void 0;
12624
12471
  const boundSessionFile = typeof bindingParent?.sessionFile === "string" ? bindingParent.sessionFile : typeof header.parentSession === "string" ? header.parentSession : void 0;
12625
12472
  if (boundSessionFile !== sessionFile) continue;
@@ -12643,12 +12490,12 @@ function complianceFailureFromAuditorVolumes(volumes) {
12643
12490
  if (stop === void 0) continue;
12644
12491
  for (let i = entries.length - 1; i >= 0; i -= 1) {
12645
12492
  const entry = entries[i];
12646
- if (entry?.type !== "custom" || entry.customType !== AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE || !isRecord12(entry.data)) continue;
12647
- const parent = isRecord12(entry.data.parent) ? entry.data.parent : void 0;
12648
- const failure2 = isRecord12(entry.data.failure) ? entry.data.failure : void 0;
12493
+ if (entry?.type !== "custom" || entry.customType !== AUDITOR_COMPLIANCE_FAILURE_ENTRY_TYPE || !isRecord11(entry.data)) continue;
12494
+ const parent = isRecord11(entry.data.parent) ? entry.data.parent : void 0;
12495
+ const failure2 = isRecord11(entry.data.failure) ? entry.data.failure : void 0;
12649
12496
  if (parent?.sessionId !== parentId || parent.sessionFile !== sessionFile || parent.attemptEntryId !== attemptEntryId) continue;
12650
12497
  if (failure2 === void 0) continue;
12651
- const identity = isRecord12(failure2.identity) ? failure2.identity : void 0;
12498
+ const identity = isRecord11(failure2.identity) ? failure2.identity : void 0;
12652
12499
  const typedCause = failure2.cause === "provider" || failure2.cause === "activation" || failure2.cause === "session" || failure2.cause === "output" || failure2.cause === "timeout" ? failure2.cause : void 0;
12653
12500
  return {
12654
12501
  ...typedCause === void 0 ? {} : { cause: typedCause },
@@ -12657,7 +12504,7 @@ function complianceFailureFromAuditorVolumes(volumes) {
12657
12504
  ...typeof identity.code === "string" || typeof identity.code === "number" ? { code: identity.code } : {}
12658
12505
  } },
12659
12506
  ...typeof failure2.diagnostic === "string" ? { diagnostic: failure2.diagnostic } : {},
12660
- ...isRecord12(failure2.details) ? { details: failure2.details } : {}
12507
+ ...isRecord11(failure2.details) ? { details: failure2.details } : {}
12661
12508
  };
12662
12509
  }
12663
12510
  }
@@ -12704,9 +12551,9 @@ function typedFailedTerminatingToolKnownFailure(entries) {
12704
12551
  if (classification.kind !== "infrastructure") continue;
12705
12552
  if (typeof message.toolCallId !== "string" || typeof message.toolName !== "string") continue;
12706
12553
  if (boundRoleToolCallForResult(attemptEntries, i, message, message.toolName) === void 0) continue;
12707
- const textPart = Array.isArray(message.content) ? message.content.find((part) => isRecord12(part) && part.type === "text" && typeof part.text === "string") : void 0;
12708
- const diagnostic = isRecord12(textPart) ? textPart.text : void 0;
12709
- const details = isRecord12(message.details) ? message.details : classification.fact;
12554
+ const textPart = Array.isArray(message.content) ? message.content.find((part) => isRecord11(part) && part.type === "text" && typeof part.text === "string") : void 0;
12555
+ const diagnostic = isRecord11(textPart) ? textPart.text : void 0;
12556
+ const details = isRecord11(message.details) ? message.details : classification.fact;
12710
12557
  return {
12711
12558
  cause: "activation",
12712
12559
  identity: { name: message.toolName, code: message.toolCallId },
@@ -12843,7 +12690,7 @@ function controlledFailureInputFromResolution(resolution) {
12843
12690
  } : {}
12844
12691
  };
12845
12692
  }
12846
- function isRecord12(value) {
12693
+ function isRecord11(value) {
12847
12694
  return typeof value === "object" && value !== null && !Array.isArray(value);
12848
12695
  }
12849
12696
  function toolResultText(message) {
@@ -12868,7 +12715,7 @@ function extractCollectorTargetBindRejection(entries) {
12868
12715
  const diagnostic = toolResultText(message);
12869
12716
  if (diagnostic.length === 0) return void 0;
12870
12717
  const details = message.details;
12871
- const code = isRecord12(details) && typeof details.code === "string" && details.code.trim() !== "" ? details.code : void 0;
12718
+ const code = isRecord11(details) && typeof details.code === "string" && details.code.trim() !== "" ? details.code : void 0;
12872
12719
  return code === void 0 ? { diagnostic } : { diagnostic, code };
12873
12720
  }
12874
12721
  return void 0;
@@ -12969,7 +12816,7 @@ function boundRoleToolCallForResult(entries, resultIndex, message, outputToolNam
12969
12816
  const candidateMessage = entries[index]?.message;
12970
12817
  if (candidateMessage?.role === "assistant" && Array.isArray(candidateMessage.content)) {
12971
12818
  for (const part of candidateMessage.content) {
12972
- if (!isRecord12(part) || part.type !== "toolCall" || part.id !== callId) {
12819
+ if (!isRecord11(part) || part.type !== "toolCall" || part.id !== callId) {
12973
12820
  continue;
12974
12821
  }
12975
12822
  if (part.name !== outputToolName) return void 0;
@@ -13040,7 +12887,7 @@ function parseNavigatorAttendanceDetails(details) {
13040
12887
  if (typeof details.prose === "string" && details.prose.trim() !== "") {
13041
12888
  prose = details.prose;
13042
12889
  } else {
13043
- const next = isRecord12(details.next) && typeof details.next.role === "string" ? details.next.role : void 0;
12890
+ const next = isRecord11(details.next) && typeof details.next.role === "string" ? details.next.role : void 0;
13044
12891
  const reason = typeof details.reason === "string" && details.reason.trim() !== "" ? details.reason : void 0;
13045
12892
  const command = typeof details.command === "string" && details.command.trim() !== "" ? details.command : void 0;
13046
12893
  if (reason !== void 0 && next !== void 0) {
@@ -13149,7 +12996,7 @@ function detourGateContext(admitted, scope) {
13149
12996
  }
13150
12997
  async function withOptionalGateProjection(base, sessionDirectory, gateContext = {}) {
13151
12998
  const secondaryEvidence = base.roleOutcome.kind === "failure" ? base.roleOutcome.decisiveFacts.secondaryEvidence : void 0;
13152
- const skipGate = isRecord12(secondaryEvidence) && secondaryEvidence.kind === "role_infrastructure_failure" && packagedSkipsGateOnInfrastructureStage(secondaryEvidence.stage);
12999
+ const skipGate = isRecord11(secondaryEvidence) && secondaryEvidence.kind === "role_infrastructure_failure" && packagedSkipsGateOnInfrastructureStage(secondaryEvidence.stage);
13153
13000
  let next = base;
13154
13001
  if (!skipGate) {
13155
13002
  const gate = await extractGateFactFromSessionDirectory(sessionDirectory, gateContext);
@@ -13162,7 +13009,7 @@ function routePlaybookFailureMessage(entries) {
13162
13009
  const entry = entries[i];
13163
13010
  if (entry?.type !== "custom" || entry.customType !== NAVIGATOR_ROUTE_PLAYBOOK_FAILURE_ENTRY) continue;
13164
13011
  const data = entry.data;
13165
- if (!isRecord12(data) || typeof data.message !== "string" || data.message.trim() === "") return void 0;
13012
+ if (!isRecord11(data) || typeof data.message !== "string" || data.message.trim() === "") return void 0;
13166
13013
  return data.message;
13167
13014
  }
13168
13015
  return void 0;
@@ -13209,7 +13056,7 @@ function extractNavigatorAttendanceFact(entries) {
13209
13056
  const entry = entries[i];
13210
13057
  if (entry?.type === "custom_message" && entry.customType === "ak-navigator-attendance") {
13211
13058
  const details = entry.message?.details ?? entry.details;
13212
- if (!isRecord12(details)) {
13059
+ if (!isRecord11(details)) {
13213
13060
  return {
13214
13061
  disposition: "unavailable",
13215
13062
  source: "unknown",
@@ -13360,7 +13207,7 @@ async function settleSealedAcceptedOrToolResidual(admitted, authority, scope, ro
13360
13207
  const residual = boundErroredToolCandidate(entries, index, message, residualToolName);
13361
13208
  if (residual === void 0) continue;
13362
13209
  const candidate = residual.candidate;
13363
- const details = isRecord12(candidate) ? candidate : { candidate };
13210
+ const details = isRecord11(candidate) ? candidate : { candidate };
13364
13211
  const failed = await settleFailureTerminalResult(
13365
13212
  admitted,
13366
13213
  {
@@ -13435,7 +13282,7 @@ function extractDoctorCandidateFacts(entries) {
13435
13282
  continue;
13436
13283
  }
13437
13284
  const data = entry.data;
13438
- if (!isRecord12(data)) return {};
13285
+ if (!isRecord11(data)) return {};
13439
13286
  return {
13440
13287
  ...data.cost === void 0 ? {} : { cost: data.cost },
13441
13288
  ...data.auditNoReceipt === void 0 ? {} : { auditNoReceipt: data.auditNoReceipt }
@@ -13520,7 +13367,7 @@ async function settleLawfulSeatAcceptedTerminalResult(admitted, authority, spec,
13520
13367
  let residual;
13521
13368
  for (let index = entries.length - 1; index >= scanStart; index -= 1) {
13522
13369
  const entry = entries[index];
13523
- if (entry?.type === "custom" && entry.customType === "ak-role-submission-closure" && isRecord12(entry.data) && entry.data.toolName === spec.toolName && classifyPackagedRoleTerminalResult(entry.data).kind === "accepted") {
13370
+ if (entry?.type === "custom" && entry.customType === "ak-role-submission-closure" && isRecord11(entry.data) && entry.data.toolName === spec.toolName && classifyPackagedRoleTerminalResult(entry.data).kind === "accepted") {
13524
13371
  thisAttemptHasSeatSuccess = true;
13525
13372
  }
13526
13373
  const message = entries[index]?.message;
@@ -13560,7 +13407,7 @@ async function settleLawfulSeatAcceptedTerminalResult(admitted, authority, spec,
13560
13407
  );
13561
13408
  }
13562
13409
  if (residual !== void 0) {
13563
- const details = isRecord12(residual.candidate) ? residual.candidate : { candidate: residual.candidate };
13410
+ const details = isRecord11(residual.candidate) ? residual.candidate : { candidate: residual.candidate };
13564
13411
  const failed = await settleFailureTerminalResult(
13565
13412
  admitted,
13566
13413
  {
@@ -13610,7 +13457,7 @@ function countersignTerminalFromEntries(entries) {
13610
13457
  return void 0;
13611
13458
  }
13612
13459
  function withCountersignTerminalFact(roleOutcome, officer) {
13613
- const prior = roleOutcome.decisiveFacts !== void 0 && isRecord12(roleOutcome.decisiveFacts) ? roleOutcome.decisiveFacts : {};
13460
+ const prior = roleOutcome.decisiveFacts !== void 0 && isRecord11(roleOutcome.decisiveFacts) ? roleOutcome.decisiveFacts : {};
13614
13461
  return {
13615
13462
  ...roleOutcome,
13616
13463
  decisiveFacts: {
@@ -13623,7 +13470,7 @@ function acceptedSecretariatDefinesOfficerProjection(roleOutcome) {
13623
13470
  const payloads = roleOutcome.payloads ?? [];
13624
13471
  for (let index = payloads.length - 1; index >= 0; index -= 1) {
13625
13472
  const payload = payloads[index];
13626
- if (!isRecord12(payload)) continue;
13473
+ if (!isRecord11(payload)) continue;
13627
13474
  const status = payload.secretariatStatus;
13628
13475
  if (typeof status !== "string") continue;
13629
13476
  return status === "converged";
@@ -14068,7 +13915,7 @@ var init_settlement = __esm({
14068
13915
  });
14069
13916
 
14070
13917
  // src/archivist-record-pointer.ts
14071
- import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
13918
+ import { mkdirSync as mkdirSync2, writeFileSync } from "node:fs";
14072
13919
  import { dirname as dirname15, join as join25 } from "node:path";
14073
13920
  function bookDirectOfficerRunPointer(options) {
14074
13921
  const nest = join25(dirname15(options.parentSessionFile), "auditor-roles");
@@ -14080,7 +13927,7 @@ function bookDirectOfficerRunPointer(options) {
14080
13927
  sessionFile: options.sessionFile,
14081
13928
  ...options.runDirectory !== void 0 && options.runDirectory.trim() !== "" ? { runDirectory: options.runDirectory } : {}
14082
13929
  };
14083
- writeFileSync2(
13930
+ writeFileSync(
14084
13931
  join25(nest, `${options.officer}.pointer.json`),
14085
13932
  `${JSON.stringify(pointer)}
14086
13933
  `,
@@ -14474,78 +14321,281 @@ var init_case_dossier_delivery = __esm({
14474
14321
  }
14475
14322
  });
14476
14323
 
14477
- // src/host-transition-prior-native.ts
14478
- import { access as access3, readdir as readdir6 } from "node:fs/promises";
14324
+ // src/public-cli/process-cancel.ts
14325
+ function processCancelSignalName(signal) {
14326
+ if (signal === void 0 || signal.aborted !== true) return void 0;
14327
+ const reason = signal.reason;
14328
+ if (reason === "SIGTERM" || reason === "SIGINT" || reason === "SIGHUP") {
14329
+ return reason;
14330
+ }
14331
+ return void 0;
14332
+ }
14333
+ function processCancelDiagnostic(signalName) {
14334
+ return `ak-role terminated by ${signalName}`;
14335
+ }
14336
+ var init_process_cancel = __esm({
14337
+ "src/public-cli/process-cancel.ts"() {
14338
+ "use strict";
14339
+ }
14340
+ });
14341
+
14342
+ // src/host-session-record.ts
14343
+ import { spawnSync } from "node:child_process";
14344
+ import {
14345
+ appendFileSync as appendFileSync2,
14346
+ copyFileSync,
14347
+ closeSync,
14348
+ existsSync as existsSync8,
14349
+ openSync,
14350
+ readFileSync as readFileSync3,
14351
+ mkdirSync as mkdirSync3,
14352
+ readdirSync as readdirSync2,
14353
+ rmSync,
14354
+ statSync as statSync3
14355
+ } from "node:fs";
14356
+ import { homedir } from "node:os";
14479
14357
  import { dirname as dirname17, join as join28 } from "node:path";
14480
- function isEnoent2(error) {
14481
- return typeof error === "object" && error !== null && error.code === "ENOENT";
14358
+ function declareHostSessionFailure(error) {
14359
+ const message = error instanceof Error ? error.stack || error.message : String(error);
14360
+ process.stderr.write(`[host-session] Dossier record failure: ${message}
14361
+ `);
14482
14362
  }
14483
- async function listPiNativeRecordPaths(sessionFile) {
14363
+ function sitianReportSafe(input) {
14484
14364
  try {
14485
- await access3(sessionFile);
14486
- return [sessionFile];
14365
+ sitianReport(input);
14487
14366
  } catch (error) {
14488
- if (isEnoent2(error)) return [];
14489
- throw error;
14367
+ declareHostSessionFailure(error);
14368
+ }
14369
+ }
14370
+ function findCodexRollout(sessionsDir, sessionId) {
14371
+ if (!existsSync8(sessionsDir)) return void 0;
14372
+ const matches = [];
14373
+ function scan(dir, depth = 0) {
14374
+ if (depth > 6) return;
14375
+ let entries;
14376
+ try {
14377
+ entries = readdirSync2(dir, { withFileTypes: true });
14378
+ } catch {
14379
+ return;
14380
+ }
14381
+ for (const entry of entries) {
14382
+ const fullPath = join28(dir, entry.name);
14383
+ if (entry.isDirectory()) {
14384
+ scan(fullPath, depth + 1);
14385
+ } else if (entry.isFile() && entry.name.endsWith(".jsonl") && entry.name.includes(sessionId)) {
14386
+ try {
14387
+ const stat2 = statSync3(fullPath);
14388
+ matches.push({ path: fullPath, mtime: stat2.mtimeMs });
14389
+ } catch {
14390
+ matches.push({ path: fullPath, mtime: 0 });
14391
+ }
14392
+ }
14393
+ }
14490
14394
  }
14395
+ scan(sessionsDir);
14396
+ if (matches.length === 0 || matches[0] === void 0) return void 0;
14397
+ matches.sort((a, b) => b.mtime - a.mtime);
14398
+ return matches[0]?.path;
14399
+ }
14400
+ function sanitizeClaudeCwd(cwd) {
14401
+ return cwd.replace(/[^a-zA-Z0-9]/g, "-");
14402
+ }
14403
+ function resolveNativeSessionPath(options) {
14404
+ const home = options.home || homedir();
14405
+ if (options.host === "claude") {
14406
+ const configDir = process.env.CLAUDE_CONFIG_DIR || join28(home, ".claude");
14407
+ const sanitizedCwd = sanitizeClaudeCwd(options.cwd);
14408
+ return join28(configDir, "projects", sanitizedCwd, `${options.sessionId}.jsonl`);
14409
+ }
14410
+ if (options.host === "codex") {
14411
+ return findCodexRollout(codexSessionsDirectory(home), options.sessionId);
14412
+ }
14413
+ if (options.host === "grok-build") {
14414
+ const grokHome = process.env.GROK_HOME || join28(home, ".grok");
14415
+ return join28(grokHome, "sessions", encodeURIComponent(options.cwd), options.sessionId);
14416
+ }
14417
+ return void 0;
14418
+ }
14419
+ function codexSessionsDirectory(home) {
14420
+ return join28(process.env.CODEX_HOME || join28(home || homedir(), ".codex"), "sessions");
14491
14421
  }
14492
- async function listSitianRecordPaths(sessionParent) {
14493
- const sessionRoot = dirname17(sessionParent);
14494
- let entries;
14422
+ function recordRunStart(runDirectory) {
14495
14423
  try {
14496
- entries = await readdir6(sessionRoot, { withFileTypes: true });
14424
+ appendFileSync2(join28(runDirectory, ".run-starts"), "\n");
14497
14425
  } catch (error) {
14498
- if (isEnoent2(error)) return [];
14499
- throw error;
14426
+ declareHostSessionFailure(error);
14500
14427
  }
14501
- const recordPaths = [];
14502
- for (const entry of entries) {
14503
- if (!entry.isDirectory()) continue;
14504
- const recordFile = join28(sessionRoot, entry.name, "records.jsonl");
14428
+ }
14429
+ function resolveHostDossierLandingPath(options) {
14430
+ const sanitizedModel = (options.model?.model ?? "default").replace(/[\/\\]+/g, "-");
14431
+ let maxOrdinal = 0;
14432
+ if (existsSync8(options.sessionDirectory)) {
14505
14433
  try {
14506
- await access3(recordFile);
14507
- recordPaths.push(recordFile);
14508
- } catch (error) {
14509
- if (!isEnoent2(error)) throw error;
14434
+ const entries = readdirSync2(options.sessionDirectory);
14435
+ for (const entry of entries) {
14436
+ const match = entry.match(/-(\d+)(?:\.jsonl|\.failed)?$/);
14437
+ const first = match?.[1];
14438
+ if (first !== void 0) {
14439
+ const val = parseInt(first, 10);
14440
+ if (!isNaN(val) && val > maxOrdinal) {
14441
+ maxOrdinal = val;
14442
+ }
14443
+ }
14444
+ }
14445
+ } catch {
14510
14446
  }
14511
14447
  }
14512
- recordPaths.sort();
14513
- return recordPaths;
14448
+ const startsPath = join28(dirname17(options.sessionDirectory), ".run-starts");
14449
+ let starts = 0;
14450
+ if (existsSync8(startsPath)) starts = readFileSync3(startsPath, "utf8").length;
14451
+ const ordinal = Math.max(maxOrdinal + 1, starts, options.continuation.kind === "resume" ? 2 : 1);
14452
+ const baseName = `${options.host}-${sanitizedModel}-${ordinal}`;
14453
+ const landingPath = options.host === "grok-build" ? join28(options.sessionDirectory, baseName) : join28(options.sessionDirectory, `${baseName}.jsonl`);
14454
+ return { landingPath, ordinal, sanitizedModel };
14514
14455
  }
14515
- async function projectHostTransitionPriorNative(input) {
14516
- if (input.previousHost === input.liveHost) return void 0;
14517
- if (input.previousHost === "pi") {
14518
- return {
14519
- priorNativeKind: "pi-native",
14520
- priorNativePaths: await listPiNativeRecordPaths(input.piSessionFile)
14521
- };
14456
+ function recordNativeSessionPointer(options) {
14457
+ if (options.host === "pi" || options.host === "hermes") {
14458
+ return void 0;
14522
14459
  }
14523
- return {
14524
- priorNativeKind: "sitian",
14525
- priorNativePaths: await listSitianRecordPaths(input.piSessionFile)
14526
- };
14460
+ const nativePath = options.host === "codex" ? codexSessionsDirectory(options.home) : resolveNativeSessionPath(options);
14461
+ if (nativePath === void 0) return void 0;
14462
+ sitianReportSafe({
14463
+ level: "event",
14464
+ kind: HOST_SESSION_RECORD_KIND,
14465
+ host: options.host,
14466
+ cwd: options.cwd,
14467
+ sessionParent: options.sessionParent,
14468
+ source: `${options.host}-dossier`,
14469
+ payload: {
14470
+ type: "native-session-pointer",
14471
+ nativePath,
14472
+ sessionId: options.sessionId
14473
+ }
14474
+ });
14475
+ return nativePath;
14527
14476
  }
14528
- var init_host_transition_prior_native = __esm({
14529
- "src/host-transition-prior-native.ts"() {
14530
- "use strict";
14477
+ function copyFileCloneOrFallback(src, dest) {
14478
+ try {
14479
+ const res = spawnSync("cp", ["-c", src, dest]);
14480
+ if (res.status === 0) return;
14481
+ } catch {
14531
14482
  }
14532
- });
14533
-
14534
- // src/public-cli/process-cancel.ts
14535
- function processCancelSignalName(signal) {
14536
- if (signal === void 0 || signal.aborted !== true) return void 0;
14537
- const reason = signal.reason;
14538
- if (reason === "SIGTERM" || reason === "SIGINT" || reason === "SIGHUP") {
14539
- return reason;
14483
+ copyFileSync(src, dest);
14484
+ }
14485
+ function copyGrokDossier(srcDir, destDir) {
14486
+ const chatHistorySrc = join28(srcDir, "chat_history.jsonl");
14487
+ if (!existsSync8(chatHistorySrc)) {
14488
+ throw new Error(`Grok native chat_history.jsonl missing at ${chatHistorySrc}`);
14540
14489
  }
14541
- return void 0;
14490
+ mkdirSync3(destDir, { recursive: true });
14491
+ const chatHistoryDest = join28(destDir, "chat_history.jsonl");
14492
+ copyFileCloneOrFallback(chatHistorySrc, chatHistoryDest);
14493
+ const usageSrc = join28(srcDir, "usage.json");
14494
+ if (!existsSync8(usageSrc)) {
14495
+ throw new Error(`Grok native usage.json missing at ${usageSrc}`);
14496
+ }
14497
+ copyFileCloneOrFallback(usageSrc, join28(destDir, "usage.json"));
14542
14498
  }
14543
- function processCancelDiagnostic(signalName) {
14544
- return `ak-role terminated by ${signalName}`;
14499
+ function copyAndRecordHostDossier(options) {
14500
+ if (options.host === "pi" || options.host === "hermes") {
14501
+ return;
14502
+ }
14503
+ const nativePath = resolveNativeSessionPath({
14504
+ host: options.host,
14505
+ sessionId: options.sessionId,
14506
+ cwd: options.cwd,
14507
+ ...options.home !== void 0 ? { home: options.home } : {}
14508
+ });
14509
+ if (nativePath === void 0 && options.host !== "codex") return;
14510
+ let destination;
14511
+ try {
14512
+ destination = resolveHostDossierLandingPath(options);
14513
+ } catch (error) {
14514
+ sitianReportSafe({
14515
+ level: "event",
14516
+ kind: HOST_SESSION_RECORD_KIND,
14517
+ host: options.host,
14518
+ cwd: options.cwd,
14519
+ sessionParent: options.sessionParent,
14520
+ source: `${options.host}-dossier`,
14521
+ payload: {
14522
+ type: "native-session-warning",
14523
+ sessionId: options.sessionId,
14524
+ error: error instanceof Error ? error.message : String(error)
14525
+ }
14526
+ });
14527
+ return;
14528
+ }
14529
+ const { landingPath, ordinal, sanitizedModel } = destination;
14530
+ let lastError;
14531
+ let copySuccess = false;
14532
+ for (let attempt = 1; attempt <= 2; attempt++) {
14533
+ try {
14534
+ if (options.host === "grok-build") {
14535
+ copyGrokDossier(nativePath, landingPath);
14536
+ } else {
14537
+ if (nativePath === void 0 || !existsSync8(nativePath)) {
14538
+ throw new Error(`Native session file missing for ${options.host} session ${options.sessionId}`);
14539
+ }
14540
+ mkdirSync3(dirname17(landingPath), { recursive: true });
14541
+ copyFileCloneOrFallback(nativePath, landingPath);
14542
+ }
14543
+ copySuccess = true;
14544
+ break;
14545
+ } catch (error) {
14546
+ lastError = error;
14547
+ }
14548
+ }
14549
+ if (copySuccess) {
14550
+ sitianReportSafe({
14551
+ level: "event",
14552
+ kind: HOST_SESSION_RECORD_KIND,
14553
+ host: options.host,
14554
+ cwd: options.cwd,
14555
+ sessionParent: options.sessionParent,
14556
+ source: `${options.host}-dossier`,
14557
+ payload: {
14558
+ type: "native-session-copy",
14559
+ nativePath,
14560
+ landingPath,
14561
+ ordinal,
14562
+ sessionId: options.sessionId
14563
+ }
14564
+ });
14565
+ } else {
14566
+ try {
14567
+ rmSync(landingPath, { recursive: options.host === "grok-build", force: true });
14568
+ } catch {
14569
+ }
14570
+ try {
14571
+ mkdirSync3(options.sessionDirectory, { recursive: true });
14572
+ closeSync(openSync(join28(options.sessionDirectory, `${options.host}-${sanitizedModel}-${ordinal}.failed`), "a"));
14573
+ } catch {
14574
+ }
14575
+ sitianReportSafe({
14576
+ level: "event",
14577
+ kind: HOST_SESSION_RECORD_KIND,
14578
+ host: options.host,
14579
+ cwd: options.cwd,
14580
+ sessionParent: options.sessionParent,
14581
+ source: `${options.host}-dossier`,
14582
+ payload: {
14583
+ type: "native-session-warning",
14584
+ nativePath,
14585
+ landingPath,
14586
+ ordinal,
14587
+ sessionId: options.sessionId,
14588
+ error: lastError instanceof Error ? lastError.message : String(lastError)
14589
+ }
14590
+ });
14591
+ }
14545
14592
  }
14546
- var init_process_cancel = __esm({
14547
- "src/public-cli/process-cancel.ts"() {
14593
+ var HOST_SESSION_RECORD_KIND;
14594
+ var init_host_session_record = __esm({
14595
+ "src/host-session-record.ts"() {
14548
14596
  "use strict";
14597
+ init_sitian_facade();
14598
+ HOST_SESSION_RECORD_KIND = "host-session";
14549
14599
  }
14550
14600
  });
14551
14601
 
@@ -15211,35 +15261,6 @@ async function dispatchPostAdmissionTurn(input) {
15211
15261
  }
15212
15262
  };
15213
15263
  try {
15214
- let previousHost;
15215
- const liveHost = env.host;
15216
- const principalCoordinates = admitted.principal === void 0 ? void 0 : env.principalAuthority.decode(admitted.principal);
15217
- let hostTransition;
15218
- try {
15219
- previousHost = readInvocationSelectedHost(admitted.runDirectory);
15220
- hostTransition = previousHost !== void 0 && liveHost !== void 0 && principalCoordinates !== void 0 ? await projectHostTransitionPriorNative({
15221
- previousHost,
15222
- liveHost,
15223
- piSessionFile: principalCoordinates.sessionFile
15224
- }) : void 0;
15225
- } catch (error) {
15226
- return {
15227
- ...await presentControlledFailure2(
15228
- admitted,
15229
- withEngineDetourInvocationScope({
15230
- timedOut: false,
15231
- code: null,
15232
- stderr: "",
15233
- thrown: error
15234
- }, request.invocationScopeId),
15235
- adapters,
15236
- env.principalAuthority,
15237
- io,
15238
- persistRunState
15239
- ),
15240
- ...deferredPersist
15241
- };
15242
- }
15243
15264
  await clearTypedProviderHttpObservation(admitted.runDirectory);
15244
15265
  if (adapters.beforeDispatch !== void 0) {
15245
15266
  try {
@@ -15275,11 +15296,8 @@ async function dispatchPostAdmissionTurn(input) {
15275
15296
  if (env.stationChild !== void 0) {
15276
15297
  turnRequest = { ...turnRequest, stationChild: env.stationChild };
15277
15298
  }
15278
- if (hostTransition !== void 0) {
15279
- turnRequest = { ...turnRequest, hostTransition };
15280
- }
15281
- if (typeof liveHost === "string" && liveHost.trim() !== "") {
15282
- turnRequest = { ...turnRequest, host: liveHost.trim() };
15299
+ if (typeof env.host === "string" && env.host.trim() !== "") {
15300
+ turnRequest = { ...turnRequest, host: env.host.trim() };
15283
15301
  }
15284
15302
  await deliverCaseDossierAsAttachment({
15285
15303
  ticketNumber: admitted.ticketNumber,
@@ -15296,6 +15314,7 @@ async function dispatchPostAdmissionTurn(input) {
15296
15314
  );
15297
15315
  let result;
15298
15316
  try {
15317
+ recordRunStart(admitted.runDirectory);
15299
15318
  result = await env.roleTurnHost.executeTurn(turnRequest);
15300
15319
  } catch (error) {
15301
15320
  const processCancelName = processCancelSignalName(env.signal);
@@ -15995,10 +16014,10 @@ var init_post_admission = __esm({
15995
16014
  init_packaged_role_registry();
15996
16015
  init_case_dossier_delivery();
15997
16016
  init_engine_detour_usage();
15998
- init_host_transition_prior_native();
15999
16017
  init_run_lifecycle();
16000
16018
  init_process_cancel();
16001
16019
  init_activation_ledger_topology();
16020
+ init_host_session_record();
16002
16021
  init_settlement();
16003
16022
  init_terminal();
16004
16023
  init_auto_resume();
@@ -16032,10 +16051,10 @@ var init_seat_ticket_binding = __esm({
16032
16051
  });
16033
16052
 
16034
16053
  // src/public-cli/machine-method-skills.ts
16035
- import { accessSync, constants as constants2, statSync as statSync3 } from "node:fs";
16054
+ import { accessSync, constants as constants2, statSync as statSync4 } from "node:fs";
16036
16055
  import { lstat as lstat6, mkdir as mkdir4, symlink } from "node:fs/promises";
16037
16056
  import { join as join31 } from "node:path";
16038
- import { spawnSync } from "node:child_process";
16057
+ import { spawnSync as spawnSync2 } from "node:child_process";
16039
16058
  function skillRoot(home) {
16040
16059
  return join31(home, ".agents/skills");
16041
16060
  }
@@ -16045,7 +16064,7 @@ function installedMethodSkillPath(home, name) {
16045
16064
  function installedSkillPath(root, name) {
16046
16065
  const path = join31(root, name, "SKILL.md");
16047
16066
  try {
16048
- if (!statSync3(path).isFile()) return void 0;
16067
+ if (!statSync4(path).isFile()) return void 0;
16049
16068
  accessSync(path, constants2.R_OK);
16050
16069
  return path;
16051
16070
  } catch (error) {
@@ -16086,7 +16105,7 @@ async function warnMissingMethodSkills(home, host, role, skills, stdout) {
16086
16105
  }
16087
16106
  }
16088
16107
  function runSkillsCli(args, home) {
16089
- const result = spawnSync("npx", ["--yes", "skills", ...args], {
16108
+ const result = spawnSync2("npx", ["--yes", "skills", ...args], {
16090
16109
  stdio: "inherit",
16091
16110
  env: { ...process.env, HOME: home }
16092
16111
  });
@@ -16273,11 +16292,11 @@ var init_turn_request = __esm({
16273
16292
  });
16274
16293
 
16275
16294
  // src/public-cli/countersign-run.ts
16276
- function isRecord13(value) {
16295
+ function isRecord12(value) {
16277
16296
  return typeof value === "object" && value !== null && !Array.isArray(value);
16278
16297
  }
16279
16298
  function isEscalatePayload(payload) {
16280
- if (!isRecord13(payload)) return false;
16299
+ if (!isRecord12(payload)) return false;
16281
16300
  return payload.status === "escalate";
16282
16301
  }
16283
16302
  function courtDiaristPayloadRows(roleOutcome, submissions) {
@@ -17492,13 +17511,13 @@ var init_instruction_seat_run = __esm({
17492
17511
  });
17493
17512
 
17494
17513
  // src/analyst-book-key.ts
17495
- import { statSync as statSync4 } from "node:fs";
17514
+ import { statSync as statSync5 } from "node:fs";
17496
17515
  import { isAbsolute as isAbsolute8 } from "node:path";
17497
17516
  function resolveAnalystBookKey(projectRoot) {
17498
17517
  const identity = physicalPathIdentity(projectRoot);
17499
17518
  let stats;
17500
17519
  try {
17501
- stats = statSync4(identity);
17520
+ stats = statSync5(identity);
17502
17521
  } catch (error) {
17503
17522
  const code = errnoCode(error);
17504
17523
  if (code === "ENOENT" || code === "ENOTDIR") return `root:${identity}`;
@@ -17879,7 +17898,7 @@ var init_analyst_cohort = __esm({
17879
17898
  });
17880
17899
 
17881
17900
  // src/analyst-ledger.ts
17882
- import { readdir as readdir7, readFile as readFile19 } from "node:fs/promises";
17901
+ import { readdir as readdir6, readFile as readFile19 } from "node:fs/promises";
17883
17902
  import { basename as basename8, join as join34 } from "node:path";
17884
17903
  function isMissingPathError6(error) {
17885
17904
  return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
@@ -17887,7 +17906,7 @@ function isMissingPathError6(error) {
17887
17906
  function errorText3(error) {
17888
17907
  return error instanceof Error ? error.message : String(error);
17889
17908
  }
17890
- function isRecord14(value) {
17909
+ function isRecord13(value) {
17891
17910
  return typeof value === "object" && value !== null && !Array.isArray(value);
17892
17911
  }
17893
17912
  async function readExistingRunLifecycleState(runDirectory) {
@@ -17928,7 +17947,7 @@ function parseRunDirectoryName2(name) {
17928
17947
  }
17929
17948
  async function listLedgerBookNames(booksRoot) {
17930
17949
  try {
17931
- const entries = await readdir7(booksRoot, { withFileTypes: true });
17950
+ const entries = await readdir6(booksRoot, { withFileTypes: true });
17932
17951
  return entries.filter((e) => e.isDirectory()).map((e) => e.name).sort();
17933
17952
  } catch (error) {
17934
17953
  if (isMissingPathError6(error)) return [];
@@ -17944,7 +17963,7 @@ async function readInvocationScopeFields(runDirectory) {
17944
17963
  throw error;
17945
17964
  }
17946
17965
  const parsed = JSON.parse(raw);
17947
- if (!isRecord14(parsed)) return void 0;
17966
+ if (!isRecord13(parsed)) return void 0;
17948
17967
  if (typeof parsed.projectRoot !== "string" || parsed.projectRoot.trim() === "") {
17949
17968
  return void 0;
17950
17969
  }
@@ -17973,7 +17992,7 @@ async function resolveSessionFile(runDirectory) {
17973
17992
  try {
17974
17993
  const raw = await readFile19(join34(runDirectory, "invocation.json"), "utf8");
17975
17994
  const parsed = JSON.parse(raw);
17976
- if (isRecord14(parsed) && typeof parsed.sessionFile === "string" && parsed.sessionFile.trim() !== "") {
17995
+ if (isRecord13(parsed) && typeof parsed.sessionFile === "string" && parsed.sessionFile.trim() !== "") {
17977
17996
  return parsed.sessionFile;
17978
17997
  }
17979
17998
  } catch (error) {
@@ -18311,7 +18330,7 @@ var init_analyst_ledger = __esm({
18311
18330
  });
18312
18331
 
18313
18332
  // src/analyst-metric-families/acceptance-success-rework.ts
18314
- function isRecord15(value) {
18333
+ function isRecord14(value) {
18315
18334
  return typeof value === "object" && value !== null && !Array.isArray(value);
18316
18335
  }
18317
18336
  function wallMsFromSpan(span) {
@@ -18320,21 +18339,21 @@ function wallMsFromSpan(span) {
18320
18339
  function findCollectorGroups(body) {
18321
18340
  if (Array.isArray(body.groups)) return body.groups;
18322
18341
  const receipt = body.receipt;
18323
- if (isRecord15(receipt) && Array.isArray(receipt.groups)) return receipt.groups;
18342
+ if (isRecord14(receipt) && Array.isArray(receipt.groups)) return receipt.groups;
18324
18343
  const outcome = body.outcome;
18325
- if (isRecord15(outcome)) {
18344
+ if (isRecord14(outcome)) {
18326
18345
  const facts = outcome.decisiveFacts;
18327
- if (isRecord15(facts) && Array.isArray(facts.groups)) return facts.groups;
18346
+ if (isRecord14(facts) && Array.isArray(facts.groups)) return facts.groups;
18328
18347
  }
18329
18348
  return void 0;
18330
18349
  }
18331
18350
  function extractStatus(body) {
18332
18351
  const outcome = body.outcome;
18333
- if (isRecord15(outcome) && typeof outcome.status === "string" && outcome.status.trim() !== "") {
18352
+ if (isRecord14(outcome) && typeof outcome.status === "string" && outcome.status.trim() !== "") {
18334
18353
  return outcome.status;
18335
18354
  }
18336
18355
  const receipt = body.receipt;
18337
- if (isRecord15(receipt) && typeof receipt.status === "string" && receipt.status.trim() !== "") {
18356
+ if (isRecord14(receipt) && typeof receipt.status === "string" && receipt.status.trim() !== "") {
18338
18357
  return receipt.status;
18339
18358
  }
18340
18359
  if (typeof body.status === "string" && body.status.trim() !== "") {
@@ -18960,15 +18979,15 @@ var init_leg_wall_clock = __esm({
18960
18979
  });
18961
18980
 
18962
18981
  // src/analyst-metric-families/round-timeline.ts
18963
- function isRecord16(value) {
18982
+ function isRecord15(value) {
18964
18983
  return typeof value === "object" && value !== null && !Array.isArray(value);
18965
18984
  }
18966
18985
  function wallMsFromSpan2(startedAt, endedAt) {
18967
18986
  return Date.parse(endedAt) - Date.parse(startedAt);
18968
18987
  }
18969
18988
  function readClassCount(body) {
18970
- if (!isRecord16(body.outcome)) return void 0;
18971
- if (!isRecord16(body.outcome.decisiveFacts)) return void 0;
18989
+ if (!isRecord15(body.outcome)) return void 0;
18990
+ if (!isRecord15(body.outcome.decisiveFacts)) return void 0;
18972
18991
  const classCount = body.outcome.decisiveFacts.classCount;
18973
18992
  if (typeof classCount !== "number" || !Number.isFinite(classCount)) {
18974
18993
  return void 0;
@@ -19112,7 +19131,7 @@ var init_analyst_metric_family = __esm({
19112
19131
  });
19113
19132
 
19114
19133
  // src/analyst-page.ts
19115
- import { createHash as createHash6 } from "node:crypto";
19134
+ import { createHash as createHash5 } from "node:crypto";
19116
19135
  import { dirname as dirname21, join as join35 } from "node:path";
19117
19136
  function analystIssuePageKey(address) {
19118
19137
  const parts = ["book", address.bookKey];
@@ -19121,7 +19140,7 @@ function analystIssuePageKey(address) {
19121
19140
  } else if (address.scopeRootIdentity !== void 0) {
19122
19141
  parts.push("root", physicalPathIdentity(address.scopeRootIdentity));
19123
19142
  }
19124
- return createHash6("sha256").update(parts.join("\0")).digest("hex").slice(0, 32);
19143
+ return createHash5("sha256").update(parts.join("\0")).digest("hex").slice(0, 32);
19125
19144
  }
19126
19145
  function analystIssuePagePath(ledgerHome, address) {
19127
19146
  return join35(ledgerHome, "analyst", "issues", `${analystIssuePageKey(address)}.json`);
@@ -21351,7 +21370,7 @@ __export(run_lifecycle_exports, {
21351
21370
  renderResumeCommand: () => renderResumeCommand,
21352
21371
  writeRoleRunState: () => writeRoleRunState
21353
21372
  });
21354
- import { chmod, lstat as lstat7, open as open3, readdir as readdir8, readFile as readFile22, unlink as unlink5, writeFile as writeFile10 } from "node:fs/promises";
21373
+ import { chmod, lstat as lstat7, open as open3, readdir as readdir7, readFile as readFile22, unlink as unlink5, writeFile as writeFile10 } from "node:fs/promises";
21355
21374
  import { basename as basename9, join as join39 } from "node:path";
21356
21375
  function buildAutoResumeContinuationPrompt(options) {
21357
21376
  return appendEngineSessionMaterial(
@@ -21430,7 +21449,7 @@ async function readRoleRunStateRaw(runDirectory) {
21430
21449
  try {
21431
21450
  raw = JSON.parse(await readFile22(join39(runDirectory, RUN_STATE_FILE), "utf8"));
21432
21451
  } catch (error) {
21433
- if (errorCodeOf2(error) === "ENOENT") return void 0;
21452
+ if (errorCodeOf(error) === "ENOENT") return void 0;
21434
21453
  throw error;
21435
21454
  }
21436
21455
  return raw;
@@ -21675,7 +21694,7 @@ function describeErrorIdentity(error) {
21675
21694
  const message = typeof candidate?.message === "string" && candidate.message !== "" ? `: ${candidate.message}` : "";
21676
21695
  return `${name}${code}${message}`;
21677
21696
  }
21678
- function errorCodeOf2(error) {
21697
+ function errorCodeOf(error) {
21679
21698
  return error.code;
21680
21699
  }
21681
21700
  function isProcessAlive(pid) {
@@ -21683,7 +21702,7 @@ function isProcessAlive(pid) {
21683
21702
  process.kill(pid, 0);
21684
21703
  return true;
21685
21704
  } catch (error) {
21686
- return errorCodeOf2(error) !== "ESRCH";
21705
+ return errorCodeOf(error) !== "ESRCH";
21687
21706
  }
21688
21707
  }
21689
21708
  async function autopsyWriterLock(lockPath) {
@@ -21691,7 +21710,7 @@ async function autopsyWriterLock(lockPath) {
21691
21710
  try {
21692
21711
  content = await readFile22(lockPath, "utf8");
21693
21712
  } catch (error) {
21694
- if (errorCodeOf2(error) === "ENOENT") return { verdict: "absent" };
21713
+ if (errorCodeOf(error) === "ENOENT") return { verdict: "absent" };
21695
21714
  return { verdict: "unknown", reason: "unreadable", readFailure: error };
21696
21715
  }
21697
21716
  const normalized = content.trim();
@@ -21723,8 +21742,8 @@ async function reclaimStaleWriterLock(lockPath, runDirectory) {
21723
21742
  await unlink5(lockPath);
21724
21743
  return { reclaimed: true };
21725
21744
  } catch (error) {
21726
- if (errorCodeOf2(error) === "ENOENT") return { reclaimed: false };
21727
- if (errorCodeOf2(error) !== "EACCES") throw error;
21745
+ if (errorCodeOf(error) === "ENOENT") return { reclaimed: false };
21746
+ if (errorCodeOf(error) !== "EACCES") throw error;
21728
21747
  await chmod(runDirectory, 493);
21729
21748
  return { reclaimed: false, eaccesFailure: error };
21730
21749
  }
@@ -21757,7 +21776,7 @@ async function createWriterLease(lockPath, runDirectory, reportCleanupFailure) {
21757
21776
  try {
21758
21777
  await unlink5(currentLockPath);
21759
21778
  } catch (error) {
21760
- if (errorCodeOf2(error) === "EACCES") {
21779
+ if (errorCodeOf(error) === "EACCES") {
21761
21780
  try {
21762
21781
  await chmod(currentRunDirectory, 493);
21763
21782
  await unlink5(currentLockPath);
@@ -21797,7 +21816,7 @@ async function acquireRunWriterLease(runDirectory, onCleanupFailure) {
21797
21816
  try {
21798
21817
  return await createWriterLease(lockPath, runDirectory, reportCleanupFailure);
21799
21818
  } catch (error) {
21800
- if (errorCodeOf2(error) !== "EEXIST") throw error;
21819
+ if (errorCodeOf(error) !== "EEXIST") throw error;
21801
21820
  }
21802
21821
  lastAutopsy = await autopsyWriterLock(lockPath);
21803
21822
  if (lastAutopsy.verdict === "unknown" && lastAutopsy.reason === "unreadable") {
@@ -21848,9 +21867,9 @@ async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole) {
21848
21867
  const booksRoot = join39(ledgerHome, "books");
21849
21868
  let bookKeys;
21850
21869
  try {
21851
- bookKeys = await readdir8(booksRoot);
21870
+ bookKeys = await readdir7(booksRoot);
21852
21871
  } catch (error) {
21853
- if (errorCodeOf2(error) === "ENOENT") return void 0;
21872
+ if (errorCodeOf(error) === "ENOENT") return void 0;
21854
21873
  throw error;
21855
21874
  }
21856
21875
  const matches = [];
@@ -21861,7 +21880,7 @@ async function findRunDirectoryById(home, runId, onlyBookKey, onlyRole) {
21861
21880
  try {
21862
21881
  runDirectories = await listBookRunDirectories(bookDir);
21863
21882
  } catch (error) {
21864
- if (errorCodeOf2(error) === "ENOENT") continue;
21883
+ if (errorCodeOf(error) === "ENOENT") continue;
21865
21884
  throw error;
21866
21885
  }
21867
21886
  for (const runDirectory of runDirectories) {
@@ -21889,7 +21908,7 @@ async function readRunParentPath(runDirectory) {
21889
21908
  await readFile22(join39(runDirectory, "admitted-request.json"), "utf8")
21890
21909
  );
21891
21910
  } catch (error) {
21892
- if (errorCodeOf2(error) === "ENOENT") return void 0;
21911
+ if (errorCodeOf(error) === "ENOENT") return void 0;
21893
21912
  throw error;
21894
21913
  }
21895
21914
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
@@ -21912,7 +21931,7 @@ async function runHasFormedSessionPrincipal(runDirectory) {
21912
21931
  const stat2 = await lstat7(sessionFile);
21913
21932
  return stat2.isFile() && !stat2.isSymbolicLink();
21914
21933
  } catch (error) {
21915
- if (errorCodeOf2(error) === "ENOENT") return false;
21934
+ if (errorCodeOf(error) === "ENOENT") return false;
21916
21935
  throw error;
21917
21936
  }
21918
21937
  }
@@ -21928,7 +21947,7 @@ async function findLatestRunIdForSeatTicket(input) {
21928
21947
  input.ticketNumber === void 0 ? bookDir : join39(bookDir, String(input.ticketNumber))
21929
21948
  );
21930
21949
  } catch (error) {
21931
- if (errorCodeOf2(error) === "ENOENT") return void 0;
21950
+ if (errorCodeOf(error) === "ENOENT") return void 0;
21932
21951
  throw error;
21933
21952
  }
21934
21953
  const suffix = `@${input.role}`;
@@ -22958,7 +22977,7 @@ var init_submission_ledger = __esm({
22958
22977
  });
22959
22978
 
22960
22979
  // src/archivist-record-topology.ts
22961
- import { createHash as createHash7 } from "node:crypto";
22980
+ import { createHash as createHash6 } from "node:crypto";
22962
22981
  import { join as join43 } from "node:path";
22963
22982
  function resolveNavigatorWorkSubjectPlacement(input) {
22964
22983
  let ledgerHome;
@@ -22969,7 +22988,7 @@ function resolveNavigatorWorkSubjectPlacement(input) {
22969
22988
  }
22970
22989
  }
22971
22990
  ledgerHome ??= resolveActivationLedgerHome(input.home);
22972
- const digest = createHash7("sha256").update(input.subject).digest("hex").slice(0, 32);
22991
+ const digest = createHash6("sha256").update(input.subject).digest("hex").slice(0, 32);
22973
22992
  return {
22974
22993
  ledgerHome,
22975
22994
  sessionDir: join43(
@@ -23034,15 +23053,15 @@ __export(archivist_record_entry_exports, {
23034
23053
  resolveNavigatorWorkSubjectPlacement: () => resolveNavigatorWorkSubjectPlacement
23035
23054
  });
23036
23055
  import {
23037
- closeSync,
23056
+ closeSync as closeSync2,
23038
23057
  existsSync as existsSync12,
23039
- openSync,
23040
- readdirSync as readdirSync2,
23058
+ openSync as openSync2,
23059
+ readdirSync as readdirSync3,
23041
23060
  readFileSync as readFileSync4,
23042
23061
  readSync,
23043
23062
  realpathSync as realpathSync4,
23044
- statSync as statSync6,
23045
- writeFileSync as writeFileSync4
23063
+ statSync as statSync7,
23064
+ writeFileSync as writeFileSync3
23046
23065
  } from "node:fs";
23047
23066
  import { dirname as dirname23, resolve as resolve17, join as join44 } from "node:path";
23048
23067
  import { StringDecoder } from "node:string_decoder";
@@ -23064,7 +23083,7 @@ function readCurrentSession(sessionDir) {
23064
23083
  function writeCurrentSession(sessionDir, sessionFile) {
23065
23084
  const ledger = join44(sessionDir, CURRENT_SESSION_LEDGER);
23066
23085
  try {
23067
- writeFileSync4(ledger, `${JSON.stringify({ sessionFile })}
23086
+ writeFileSync3(ledger, `${JSON.stringify({ sessionFile })}
23068
23087
  `, { flag: "wx" });
23069
23088
  } catch (error) {
23070
23089
  throw new ActivationLedgerError(
@@ -23081,7 +23100,7 @@ function currentSessionLedgerPath(sessionDir) {
23081
23100
  return join44(sessionDir, CURRENT_SESSION_LEDGER);
23082
23101
  }
23083
23102
  function readBoundedSessionHeader(filePath) {
23084
- const fd = openSync(filePath, "r");
23103
+ const fd = openSync2(filePath, "r");
23085
23104
  try {
23086
23105
  const buffer = Buffer.allocUnsafe(SESSION_HEADER_CHUNK_BYTES);
23087
23106
  const decoder2 = new StringDecoder("utf8");
@@ -23129,7 +23148,7 @@ function readBoundedSessionHeader(filePath) {
23129
23148
  }
23130
23149
  return void 0;
23131
23150
  } finally {
23132
- closeSync(fd);
23151
+ closeSync2(fd);
23133
23152
  }
23134
23153
  }
23135
23154
  function parseSessionHeaderLine(line2) {
@@ -23155,7 +23174,7 @@ function mostRecentNavigatorSessionFile(sessionDir, cwd) {
23155
23174
  const absoluteCwd = resolve17(cwd);
23156
23175
  let names;
23157
23176
  try {
23158
- names = readdirSync2(absoluteSessionDir);
23177
+ names = readdirSync3(absoluteSessionDir);
23159
23178
  } catch (error) {
23160
23179
  throw new ActivationLedgerError(
23161
23180
  `archivist navigator nest is not readable (${sessionDir}): ${errorText(error)}`,
@@ -23168,7 +23187,7 @@ function mostRecentNavigatorSessionFile(sessionDir, cwd) {
23168
23187
  const filePath = join44(absoluteSessionDir, name);
23169
23188
  let st;
23170
23189
  try {
23171
- st = statSync6(filePath);
23190
+ st = statSync7(filePath);
23172
23191
  } catch (error) {
23173
23192
  throw new ActivationLedgerError(
23174
23193
  `archivist navigator session file is not stat-able (${filePath}): ${errorText(error)}`,
@@ -23309,7 +23328,7 @@ function createRecordSessionOpen(options, host = piRecordSessionHost) {
23309
23328
  if (file !== void 0 && !existsSync12(file)) {
23310
23329
  const header = session.getHeader();
23311
23330
  if (header !== null && header.type === "session") {
23312
- writeFileSync4(file, `${JSON.stringify(header)}
23331
+ writeFileSync3(file, `${JSON.stringify(header)}
23313
23332
  `, { flag: "wx" });
23314
23333
  session.setSessionFile(file);
23315
23334
  }
@@ -23406,8 +23425,8 @@ init_activation_ledger_topology();
23406
23425
  import {
23407
23426
  lstatSync as lstatSync2,
23408
23427
  realpathSync as realpathSync2,
23409
- statSync as statSync5,
23410
- writeFileSync as writeFileSync3
23428
+ statSync as statSync6,
23429
+ writeFileSync as writeFileSync2
23411
23430
  } from "node:fs";
23412
23431
  import { isAbsolute as isAbsolute11, resolve as resolve15 } from "node:path";
23413
23432
  var ActivationSessionFileMissingError = class extends Error {
@@ -23428,7 +23447,7 @@ function materializeDeferredSessionFile(sessionManager, resolvedFile) {
23428
23447
  throw new ActivationSessionFileMissingError(resolvedFile);
23429
23448
  }
23430
23449
  try {
23431
- writeFileSync3(resolvedFile, `${JSON.stringify(header)}
23450
+ writeFileSync2(resolvedFile, `${JSON.stringify(header)}
23432
23451
  `, { flag: "wx" });
23433
23452
  } catch (error) {
23434
23453
  if (errnoCode(error) !== "EEXIST") {
@@ -23481,7 +23500,7 @@ function durableSessionPointer(sessionManager) {
23481
23500
  }
23482
23501
  let info;
23483
23502
  try {
23484
- info = statSync5(realFile);
23503
+ info = statSync6(realFile);
23485
23504
  } catch (error) {
23486
23505
  throw new Error(
23487
23506
  `Workflow role activation failed to stat durable session file (${realFile}): ${errorText(error)}`,
@@ -24823,7 +24842,7 @@ var AUDITOR_TOOL_SPEC = {
24823
24842
  };
24824
24843
 
24825
24844
  // src/navigator-attendance.ts
24826
- import { createHash as createHash8 } from "node:crypto";
24845
+ import { createHash as createHash7 } from "node:crypto";
24827
24846
  init_navigator_invocation_identity();
24828
24847
  init_packaged_role_registry();
24829
24848
  init_activation_ledger_topology();
@@ -25384,7 +25403,7 @@ function navigatorSubjectKey(subjectRoot, subject, provenance = "role_input") {
25384
25403
  if (provenance === "placeholder") return subjectRoot;
25385
25404
  const normalized = subject.trim().replace(/\s+/g, " ");
25386
25405
  if (normalized === "") return subjectRoot;
25387
- return `${subjectRoot}#${createHash8("sha256").update(normalized).digest("hex").slice(0, 32)}`;
25406
+ return `${subjectRoot}#${createHash7("sha256").update(normalized).digest("hex").slice(0, 32)}`;
25388
25407
  }
25389
25408
  function navigatorSubjectKeyForInput(subjectRoot, reference, cwd = process.cwd()) {
25390
25409
  if (issueRoot(subjectRoot) !== void 0 || !subjectRoot.includes("/.ak/work/")) return subjectRoot;
@@ -25873,7 +25892,7 @@ init_worker_submission_contracts();
25873
25892
  init_submission_errors();
25874
25893
  init_worker_submission_contracts();
25875
25894
  import { execFileSync as execFileSync4 } from "node:child_process";
25876
- import { existsSync as existsSync14, lstatSync as lstatSync3, readdirSync as readdirSync3, readFileSync as readFileSync5, rmdirSync, rmSync } from "node:fs";
25895
+ import { existsSync as existsSync14, lstatSync as lstatSync3, readdirSync as readdirSync4, readFileSync as readFileSync5, rmdirSync, rmSync as rmSync2 } from "node:fs";
25877
25896
  import { resolve as resolve19 } from "node:path";
25878
25897
  var WORKER_SUBMISSION_GATE_RECORD_KIND = WORKER_SUBMISSION_GATE_KIND;
25879
25898
  var WORKER_COMMIT_BASELINE_ENTRY_TYPE = "commit-baseline";
@@ -25939,13 +25958,13 @@ function unsetOwnedHooksPath(file) {
25939
25958
  function rmOwnedDir(dir) {
25940
25959
  const hookPath = resolve19(dir, HOOK_FILE);
25941
25960
  if (!ownedHook(hookPath)) return;
25942
- rmSync(hookPath, { force: true });
25943
- if (existsSync14(dir) && readdirSync3(dir).length === 0) rmdirSync(dir);
25961
+ rmSync2(hookPath, { force: true });
25962
+ if (existsSync14(dir) && readdirSync4(dir).length === 0) rmdirSync(dir);
25944
25963
  }
25945
25964
  function linkedGitDirs(commonDir) {
25946
25965
  const root = resolve19(commonDir, "worktrees");
25947
25966
  if (!existsSync14(root)) return [];
25948
- return readdirSync3(root).map((name) => resolve19(root, name)).filter((dir) => lstatSync3(dir).isDirectory());
25967
+ return readdirSync4(root).map((name) => resolve19(root, name)).filter((dir) => lstatSync3(dir).isDirectory());
25949
25968
  }
25950
25969
  function uninstallPackageWorkerHooks(cwd) {
25951
25970
  let inside;
@@ -25963,13 +25982,13 @@ function uninstallPackageWorkerHooks(cwd) {
25963
25982
  clear(resolve19(commonDir, "config.worktree"));
25964
25983
  rmOwnedDir(resolve19(commonDir, HOOKS_DIR));
25965
25984
  const legacy = resolve19(commonDir, "hooks", HOOK_FILE);
25966
- if (ownedHook(legacy)) rmSync(legacy, { force: true });
25985
+ if (ownedHook(legacy)) rmSync2(legacy, { force: true });
25967
25986
  for (const gitDir of linkedGitDirs(commonDir)) {
25968
25987
  clear(resolve19(gitDir, "config.worktree"));
25969
25988
  rmOwnedDir(resolve19(gitDir, HOOKS_DIR));
25970
25989
  }
25971
25990
  }
25972
- function isRecord17(value) {
25991
+ function isRecord16(value) {
25973
25992
  return typeof value === "object" && value !== null && !Array.isArray(value);
25974
25993
  }
25975
25994
  function unfinishedReasonPresent(details) {
@@ -25985,7 +26004,7 @@ function readGateState(session) {
25985
26004
  if (entry.type !== "custom") continue;
25986
26005
  if (entry.customType === WORKER_COMMIT_BASELINE_ENTRY_TYPE) {
25987
26006
  const data = entry.data;
25988
- if (isRecord17(data) && (data.head === null || typeof data.head === "string")) {
26007
+ if (isRecord16(data) && (data.head === null || typeof data.head === "string")) {
25989
26008
  baseline = data.head;
25990
26009
  }
25991
26010
  } else if (entry.customType === WORKER_COMMIT_REMINDER_BOUNCE_ENTRY_TYPE) {
@@ -26178,11 +26197,11 @@ var FIXER_PHASES = ["plan", "apply"];
26178
26197
  function isWorkerPhase(value) {
26179
26198
  return typeof value === "string" && FIXER_PHASES.includes(value);
26180
26199
  }
26181
- function isRecord18(value) {
26200
+ function isRecord17(value) {
26182
26201
  return typeof value === "object" && value !== null && !Array.isArray(value);
26183
26202
  }
26184
26203
  function workerStatusOf(output) {
26185
- return isRecord18(output) && typeof output.status === "string" ? output.status : void 0;
26204
+ return isRecord17(output) && typeof output.status === "string" ? output.status : void 0;
26186
26205
  }
26187
26206
  function deepFreeze2(value) {
26188
26207
  if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
@@ -28527,27 +28546,17 @@ function acpModelId(modelPassing, model) {
28527
28546
  }
28528
28547
 
28529
28548
  // src/acp-host/role-turn-host.ts
28549
+ import { join as join50 } from "node:path";
28530
28550
  import { spawn as spawn4 } from "node:child_process";
28531
28551
  import { createInterface } from "node:readline";
28532
28552
 
28533
28553
  // src/external-host-turn-loop.ts
28534
- init_packaged_role_registry();
28535
28554
  var EXTERNAL_ROLE_TURN_ROUND_LIMIT = 8;
28536
28555
  function mergeRoleTurnAbortSignals(prepared, request) {
28537
28556
  if (request === void 0) return prepared;
28538
28557
  if (prepared === void 0) return request;
28539
28558
  return AbortSignal.any([prepared, request]);
28540
28559
  }
28541
- function promptWithPriorNativePaths(basePrompt, request) {
28542
- if (request.continuation.kind !== "resume") return basePrompt;
28543
- if (request.stationChild === true && isOfficerReviewSeat(request.activation.role)) {
28544
- return basePrompt;
28545
- }
28546
- const paths = request.hostTransition?.priorNativePaths;
28547
- if (paths === void 0 || paths.length === 0) return basePrompt;
28548
- return `${basePrompt}
28549
- ${paths.join("\n")}`;
28550
- }
28551
28560
  function isHostAbortedError(error) {
28552
28561
  return typeof error === "object" && error !== null && error.code === "host-aborted";
28553
28562
  }
@@ -28596,7 +28605,7 @@ async function settleHostAborted(prepared, sessionId) {
28596
28605
  });
28597
28606
  }
28598
28607
  async function driveExternalRoleTurnRounds(prepared, request, driver) {
28599
- let prompt = promptWithPriorNativePaths(prepared.prompt, request);
28608
+ let prompt = prepared.prompt;
28600
28609
  const abortSignal = mergeRoleTurnAbortSignals(prepared.abortSignal, request.signal);
28601
28610
  let stderr = "";
28602
28611
  for (let attempt = 0; attempt < EXTERNAL_ROLE_TURN_ROUND_LIMIT; attempt += 1) {
@@ -28640,31 +28649,8 @@ function createSerializedRoleTurnHost(execute) {
28640
28649
  };
28641
28650
  }
28642
28651
 
28643
- // src/host-session-record.ts
28644
- init_sitian_facade();
28645
- var HOST_SESSION_RECORD_KIND = "host-session";
28646
- function eventField(event, key) {
28647
- if (typeof event !== "object" || event === null || Array.isArray(event)) return void 0;
28648
- const value = event[key];
28649
- return typeof value === "string" && value.length > 0 ? value : void 0;
28650
- }
28651
- function reportHostSessionEvent(input) {
28652
- const identity = input.identity ?? eventField(input.event, "uuid");
28653
- const timestamp2 = input.timestamp ?? eventField(input.event, "timestamp");
28654
- sitianReport({
28655
- level: "event",
28656
- kind: HOST_SESSION_RECORD_KIND,
28657
- host: input.host,
28658
- cwd: input.cwd,
28659
- sessionParent: input.sessionParent,
28660
- source: input.source,
28661
- payload: input.event,
28662
- ...identity === void 0 ? {} : { identity },
28663
- ...timestamp2 === void 0 ? {} : { timestamp: timestamp2 }
28664
- });
28665
- }
28666
-
28667
28652
  // src/acp-host/role-turn-host.ts
28653
+ init_host_session_record();
28668
28654
  init_navigator_output();
28669
28655
 
28670
28656
  // src/agent-start-materials.ts
@@ -28679,18 +28665,6 @@ function renderSystemPromptOverride(authority) {
28679
28665
  }
28680
28666
 
28681
28667
  // src/acp-host/role-turn-host.ts
28682
- var GROK_BUILD_HOST = "grok-build";
28683
- function acpPromptResultHasUsage(result) {
28684
- const meta = result._meta;
28685
- if (typeof meta !== "object" || meta === null || Array.isArray(meta)) return false;
28686
- return Object.prototype.hasOwnProperty.call(meta, "usage");
28687
- }
28688
- function isAcpAutoCompactCompletedNotification(method, params) {
28689
- if (method !== "_x.ai/session_notification") return false;
28690
- const update = params.update;
28691
- if (typeof update !== "object" || update === null || Array.isArray(update)) return false;
28692
- return update.sessionUpdate === "auto_compact_completed";
28693
- }
28694
28668
  function acpAgentTextChunk(params) {
28695
28669
  let kind;
28696
28670
  let content;
@@ -28862,189 +28836,142 @@ function createAcpRoleTurnHost(config) {
28862
28836
  const systemPromptOverride = renderSystemPromptOverride(prepared.systemPrompt);
28863
28837
  let connection;
28864
28838
  let sessionId;
28839
+ let sessionOpened = false;
28865
28840
  let accepted = false;
28841
+ const sessionParent = config.sessionIdentity.resolveSessionFile(request.principal);
28866
28842
  let outcome = failure("session", "AcpNoOutcome", "no-outcome");
28867
28843
  try {
28868
28844
  if (prepared.mcpServers.length === 0) {
28869
28845
  outcome = failure("activation", "UncontrolledAcpSession", "ak-config-missing");
28870
28846
  } else {
28871
28847
  connection = await config.connect(request);
28872
- const sessionParent = config.sessionIdentity.resolveSessionFile(request.principal);
28873
- const recordAbort = new AbortController();
28874
- let hostSessionRecordFailure;
28875
- const hostSessionRecordResult = () => ({
28876
- code: null,
28877
- stderr: "",
28878
- timedOut: false,
28879
- knownFailure: hostSessionRecordFailure
28880
- });
28881
- const noteHostSessionRecordFailure = (error) => {
28882
- if (hostSessionRecordFailure !== void 0) return;
28883
- hostSessionRecordFailure = {
28884
- cause: "session",
28885
- identity: { name: "HostSessionRecordFailure", code: "host-session-record-failed" },
28886
- diagnostic: error instanceof Error ? error.message : String(error)
28887
- };
28888
- try {
28889
- recordAbort.abort();
28890
- } catch {
28891
- }
28892
- };
28893
- const rpc = (method, params) => raceAgainstHostAbort(connection.request(method, params), recordAbort.signal, "host-session-record-failed");
28848
+ const rpc = (method, params) => connection.request(method, params);
28894
28849
  const agentProseChunks = [];
28895
28850
  let collectAgentProse = false;
28896
- const ledgerGrokBuildObservability = config.hostName === GROK_BUILD_HOST;
28897
28851
  connection.onNotification?.((method, params) => {
28898
- if (hostSessionRecordFailure !== void 0) return;
28899
28852
  const isSessionUpdate = method === "session/update";
28900
- const isAutoCompact = ledgerGrokBuildObservability && isAcpAutoCompactCompletedNotification(method, params);
28901
- if (!isSessionUpdate && !isAutoCompact) return;
28902
- if (isSessionUpdate && collectAgentProse) {
28853
+ if (!isSessionUpdate) return;
28854
+ if (collectAgentProse) {
28903
28855
  const chunk = acpAgentTextChunk(params);
28904
28856
  if (chunk !== void 0) agentProseChunks.push(chunk);
28905
28857
  }
28906
- try {
28907
- reportHostSessionEvent({
28858
+ });
28859
+ const initialized = await rpc("initialize", {
28860
+ protocolVersion: 1,
28861
+ clientCapabilities: {}
28862
+ });
28863
+ const initializeMeta = initialized._meta;
28864
+ const availableModels = Array.isArray(initializeMeta?.modelState?.availableModels) ? initializeMeta.modelState.availableModels : void 0;
28865
+ if (request.model !== void 0 && availableModels !== void 0 && !availableModels.some((entry) => typeof entry === "object" && entry !== null && entry.modelId === acpModelId(config.modelPassing, request.model))) {
28866
+ outcome = failure("activation", "AcpHostModelMismatch", "host-model-mismatch", {
28867
+ provider: request.model.provider,
28868
+ model: request.model.model
28869
+ });
28870
+ } else {
28871
+ const sessionBindParams = {
28872
+ cwd: request.cwd,
28873
+ mcpServers: prepared.mcpServers,
28874
+ _meta: { systemPromptOverride, yoloMode: false }
28875
+ };
28876
+ const loadSession = async (bindSessionId) => {
28877
+ const loaded = await rpc("session/load", {
28878
+ sessionId: bindSessionId,
28879
+ ...sessionBindParams
28880
+ });
28881
+ const loadedId = typeof loaded.sessionId === "string" && loaded.sessionId !== "" ? loaded.sessionId : bindSessionId;
28882
+ if (config.hostName !== "hermes") recordNativeSessionPointer({
28908
28883
  host: config.hostName,
28884
+ sessionId: loadedId,
28909
28885
  cwd: request.cwd,
28910
28886
  sessionParent,
28911
- source: "acp-host",
28912
- event: { method, params }
28887
+ home: request.home
28913
28888
  });
28914
- } catch (error) {
28915
- noteHostSessionRecordFailure(error);
28889
+ return loadedId;
28890
+ };
28891
+ if (request.continuation.kind === "resume" && config.boundResume === "session/load") {
28892
+ const explicitHostSessionId = request.continuation.hostSessionId;
28893
+ const boundSessionId = explicitHostSessionId !== void 0 && explicitHostSessionId !== "" ? explicitHostSessionId : await config.sessionIdentity.load(request.principal);
28894
+ if (boundSessionId !== void 0 && boundSessionId !== "") {
28895
+ sessionId = boundSessionId;
28896
+ sessionId = await loadSession(boundSessionId);
28897
+ sessionOpened = true;
28898
+ }
28916
28899
  }
28917
- });
28918
- try {
28919
- const initialized = await rpc("initialize", {
28920
- protocolVersion: 1,
28921
- clientCapabilities: {}
28922
- });
28923
- const initializeMeta = initialized._meta;
28924
- const availableModels = Array.isArray(initializeMeta?.modelState?.availableModels) ? initializeMeta.modelState.availableModels : void 0;
28925
- if (request.model !== void 0 && availableModels !== void 0 && !availableModels.some((entry) => typeof entry === "object" && entry !== null && entry.modelId === acpModelId(config.modelPassing, request.model))) {
28926
- outcome = failure("activation", "AcpHostModelMismatch", "host-model-mismatch", {
28927
- provider: request.model.provider,
28928
- model: request.model.model
28929
- });
28930
- } else {
28931
- const sessionBindParams = {
28932
- cwd: request.cwd,
28933
- mcpServers: prepared.mcpServers,
28934
- _meta: { systemPromptOverride, yoloMode: false }
28935
- };
28936
- const loadSession = async (bindSessionId) => {
28937
- const loaded = await rpc("session/load", {
28938
- sessionId: bindSessionId,
28939
- ...sessionBindParams
28900
+ let sessionReady = true;
28901
+ if (sessionId === void 0) {
28902
+ const session = await rpc("session/new", sessionBindParams);
28903
+ sessionId = typeof session.sessionId === "string" ? session.sessionId : void 0;
28904
+ if (sessionId === void 0 || sessionId === "") {
28905
+ outcome = failure("session", "AcpSessionFailure", "session-id-missing");
28906
+ sessionReady = false;
28907
+ } else {
28908
+ if (config.hostName !== "hermes") recordNativeSessionPointer({
28909
+ host: config.hostName,
28910
+ sessionId,
28911
+ cwd: request.cwd,
28912
+ sessionParent,
28913
+ home: request.home
28940
28914
  });
28941
- return typeof loaded.sessionId === "string" && loaded.sessionId !== "" ? loaded.sessionId : bindSessionId;
28942
- };
28943
- if (request.continuation.kind === "resume" && config.boundResume === "session/load") {
28944
- const explicitHostSessionId = request.continuation.hostSessionId;
28945
- const boundSessionId = explicitHostSessionId !== void 0 && explicitHostSessionId !== "" ? explicitHostSessionId : await config.sessionIdentity.load(request.principal);
28946
- if (boundSessionId !== void 0 && boundSessionId !== "") {
28947
- sessionId = await loadSession(boundSessionId);
28948
- }
28915
+ sessionOpened = true;
28916
+ await config.sessionIdentity.bind(request.principal, sessionId);
28949
28917
  }
28950
- let sessionReady = true;
28951
- if (sessionId === void 0) {
28952
- const session = await rpc("session/new", sessionBindParams);
28953
- sessionId = typeof session.sessionId === "string" ? session.sessionId : void 0;
28954
- if (sessionId === void 0 || sessionId === "") {
28955
- outcome = failure("session", "AcpSessionFailure", "session-id-missing");
28956
- sessionReady = false;
28957
- } else {
28958
- await config.sessionIdentity.bind(request.principal, sessionId);
28959
- }
28918
+ }
28919
+ if (sessionReady) {
28920
+ if (config.modelPassing === "set_model" && request.model !== void 0 && sessionId !== void 0) {
28921
+ await rpc("session/set_model", {
28922
+ sessionId,
28923
+ modelId: acpModelId(config.modelPassing, request.model)
28924
+ });
28925
+ sessionId = await loadSession(sessionId);
28960
28926
  }
28961
- if (sessionReady) {
28962
- if (config.modelPassing === "set_model" && request.model !== void 0 && sessionId !== void 0) {
28963
- await rpc("session/set_model", {
28964
- sessionId,
28965
- modelId: acpModelId(config.modelPassing, request.model)
28966
- });
28967
- sessionId = await loadSession(sessionId);
28968
- }
28969
- const activeConnection = connection;
28970
- const activeSessionId = sessionId;
28971
- const turnResult = await driveExternalRoleTurnRounds(prepared, request, {
28972
- roundLimitName: "AcpRoundLimit",
28973
- currentSessionId: () => sessionId,
28974
- async runRound({ prompt, abortSignal }) {
28975
- if (hostSessionRecordFailure !== void 0) return { status: "terminal", result: hostSessionRecordResult() };
28976
- const abortParts = [recordAbort.signal];
28977
- if (abortSignal !== void 0) abortParts.push(abortSignal);
28978
- const combinedAbort = AbortSignal.any(abortParts);
28979
- let result;
28980
- agentProseChunks.length = 0;
28981
- collectAgentProse = prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME;
28982
- try {
28983
- result = await raceAgainstHostAbort(
28984
- activeConnection.request("session/prompt", {
28985
- sessionId: activeSessionId,
28986
- prompt: [{ type: "text", text: prompt }]
28987
- }),
28988
- combinedAbort,
28989
- "ACP host aborted"
28990
- );
28991
- } catch (error) {
28992
- collectAgentProse = false;
28993
- agentProseChunks.length = 0;
28994
- if (hostSessionRecordFailure !== void 0) {
28995
- return { status: "terminal", result: hostSessionRecordResult() };
28996
- }
28997
- throw error;
28998
- }
28927
+ const activeConnection = connection;
28928
+ const activeSessionId = sessionId;
28929
+ const turnResult = await driveExternalRoleTurnRounds(prepared, request, {
28930
+ roundLimitName: "AcpRoundLimit",
28931
+ currentSessionId: () => sessionId,
28932
+ async runRound({ prompt, abortSignal }) {
28933
+ let result;
28934
+ agentProseChunks.length = 0;
28935
+ collectAgentProse = prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME;
28936
+ try {
28937
+ result = await raceAgainstHostAbort(
28938
+ activeConnection.request("session/prompt", {
28939
+ sessionId: activeSessionId,
28940
+ prompt: [{ type: "text", text: prompt }]
28941
+ }),
28942
+ abortSignal,
28943
+ "ACP host aborted"
28944
+ );
28945
+ } catch (error) {
28999
28946
  collectAgentProse = false;
29000
- if (ledgerGrokBuildObservability && acpPromptResultHasUsage(result)) {
29001
- try {
29002
- reportHostSessionEvent({
29003
- host: config.hostName,
29004
- cwd: request.cwd,
29005
- sessionParent,
29006
- source: "acp-host",
29007
- event: { method: "session/prompt", result }
29008
- });
29009
- } catch (error) {
29010
- noteHostSessionRecordFailure(error);
29011
- return { status: "terminal", result: hostSessionRecordResult() };
29012
- }
29013
- }
29014
- if (hostSessionRecordFailure !== void 0) {
29015
- return { status: "terminal", result: hostSessionRecordResult() };
29016
- }
29017
- if (result.stopReason === "refusal") {
29018
- agentProseChunks.length = 0;
29019
- return {
29020
- status: "terminal",
29021
- result: failure("output", "AcpRefusal", "refusal", { sessionId })
29022
- };
29023
- }
29024
- if (prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME) {
29025
- const prose = agentProseChunks.join("");
29026
- agentProseChunks.length = 0;
29027
- if (navigatorProseFromUnknown(prose) !== void 0) {
29028
- await prepared.ingestStructuredOutput({ prose });
29029
- }
29030
- } else {
29031
- agentProseChunks.length = 0;
28947
+ agentProseChunks.length = 0;
28948
+ throw error;
28949
+ }
28950
+ collectAgentProse = false;
28951
+ if (result.stopReason === "refusal") {
28952
+ agentProseChunks.length = 0;
28953
+ return {
28954
+ status: "terminal",
28955
+ result: failure("output", "AcpRefusal", "refusal", { sessionId })
28956
+ };
28957
+ }
28958
+ if (prepared.terminatingToolName === NAVIGATOR_OUTPUT_TOOL_NAME) {
28959
+ const prose = agentProseChunks.join("");
28960
+ agentProseChunks.length = 0;
28961
+ if (navigatorProseFromUnknown(prose) !== void 0) {
28962
+ await prepared.ingestStructuredOutput({ prose });
29032
28963
  }
29033
- return { status: "delivered", stderr: activeConnection.stderr?.() ?? "" };
29034
- },
29035
- async afterAccepted() {
29036
- await rpc("session/close", { sessionId: activeSessionId });
29037
- accepted = true;
28964
+ } else {
28965
+ agentProseChunks.length = 0;
29038
28966
  }
29039
- });
29040
- outcome = hostSessionRecordFailure !== void 0 ? hostSessionRecordResult() : turnResult;
29041
- }
29042
- }
29043
- } catch (error) {
29044
- if (hostSessionRecordFailure !== void 0) {
29045
- outcome = hostSessionRecordResult();
29046
- } else {
29047
- throw error;
28967
+ return { status: "delivered", stderr: activeConnection.stderr?.() ?? "" };
28968
+ },
28969
+ async afterAccepted() {
28970
+ await rpc("session/close", { sessionId: activeSessionId });
28971
+ accepted = true;
28972
+ }
28973
+ });
28974
+ outcome = turnResult;
29048
28975
  }
29049
28976
  }
29050
28977
  }
@@ -29061,6 +28988,18 @@ function createAcpRoleTurnHost(config) {
29061
28988
  } catch {
29062
28989
  }
29063
28990
  }
28991
+ if (config.hostName !== "hermes" && sessionOpened && sessionId !== void 0) {
28992
+ copyAndRecordHostDossier({
28993
+ host: config.hostName,
28994
+ sessionId,
28995
+ cwd: request.cwd,
28996
+ sessionDirectory: join50(request.runDirectory, "session"),
28997
+ sessionParent,
28998
+ continuation: request.continuation,
28999
+ ...request.model !== void 0 ? { model: request.model } : {},
29000
+ ...request.home !== void 0 ? { home: request.home } : {}
29001
+ });
29002
+ }
29064
29003
  try {
29065
29004
  await prepared.dispose?.();
29066
29005
  } catch (cleanupError) {
@@ -29073,17 +29012,17 @@ function createAcpRoleTurnHost(config) {
29073
29012
 
29074
29013
  // src/acp-host/seat-profile-soul.ts
29075
29014
  import { constants as constants3 } from "node:fs";
29076
- import { access as access4, copyFile, lstat as lstat8, mkdir as mkdir6, readlink, symlink as symlink2, unlink as unlink6 } from "node:fs/promises";
29077
- import { dirname as dirname26, join as join50, relative as relative3, resolve as resolve21 } from "node:path";
29015
+ import { access as access3, copyFile, lstat as lstat8, mkdir as mkdir6, readlink, symlink as symlink2, unlink as unlink6 } from "node:fs/promises";
29016
+ import { dirname as dirname26, join as join51, relative as relative3, resolve as resolve21 } from "node:path";
29078
29017
  function seatProfileName(spec, role) {
29079
29018
  return `${spec.namePrefix}${role}`;
29080
29019
  }
29081
29020
  function packageRoleSoulPath(packageRoot, role) {
29082
- return join50(packageRoot, "souls", `${role}.md`);
29021
+ return join51(packageRoot, "souls", `${role}.md`);
29083
29022
  }
29084
29023
  async function pathExists2(path) {
29085
29024
  try {
29086
- await access4(path, constants3.F_OK);
29025
+ await access3(path, constants3.F_OK);
29087
29026
  return true;
29088
29027
  } catch {
29089
29028
  return false;
@@ -29096,16 +29035,16 @@ async function ensureSeatProfileSoul(options) {
29096
29035
  if (!await pathExists2(soulTarget)) {
29097
29036
  throw new Error(`packaged role soul missing: ${soulTarget}`);
29098
29037
  }
29099
- const profilesRoot = join50(operatorHome, ...spec.profilesRootFromHome);
29100
- const profileDir = join50(profilesRoot, profileName);
29038
+ const profilesRoot = join51(operatorHome, ...spec.profilesRootFromHome);
29039
+ const profileDir = join51(profilesRoot, profileName);
29101
29040
  const hostRoot = dirname26(profilesRoot);
29102
- const soulPath = join50(profileDir, spec.soulFileName);
29041
+ const soulPath = join51(profileDir, spec.soulFileName);
29103
29042
  if (!await pathExists2(profileDir)) {
29104
29043
  await mkdir6(profileDir, { recursive: true });
29105
29044
  for (const name of ["auth.json", ".env", "config.yaml"]) {
29106
- const source = join50(hostRoot, name);
29045
+ const source = join51(hostRoot, name);
29107
29046
  if (!await pathExists2(source)) continue;
29108
- await copyFile(source, join50(profileDir, name));
29047
+ await copyFile(source, join51(profileDir, name));
29109
29048
  }
29110
29049
  } else {
29111
29050
  await mkdir6(profileDir, { recursive: true });