@akagilnc/pi-workflow-roles 0.1.5614 → 0.1.5650

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/acp-host/production-host.js +960 -465
  2. package/dist/activation-ledger-topology.js +12 -0
  3. package/dist/external-host-turn-loop.js +281 -0
  4. package/dist/headless-host/production-host.js +900 -406
  5. package/dist/migrate-book-topology.js +8 -5
  6. package/dist/pi/role-turn-host.js +33 -3
  7. package/dist/public-cli/instruction-seat-run.js +177 -46
  8. package/dist/public-cli/invocation.js +5 -12
  9. package/dist/public-cli/main.js +541 -165
  10. package/dist/public-cli/post-admission.js +171 -18
  11. package/dist/public-cli/settlement.js +20 -10
  12. package/dist/report-ticket-tool.js +136 -0
  13. package/dist/role-run-placement.js +1 -2
  14. package/dist/role-run-relocation.js +24 -4
  15. package/package.json +1 -1
  16. package/resources/engine-dispatch.md +6 -3
  17. package/resources/engines/claude-code.md +4 -5
  18. package/resources/missing-ticket-reask.md +1 -0
  19. package/src/acp-host/role-turn-host.ts +41 -31
  20. package/src/activation-ledger-topology.ts +16 -0
  21. package/src/external-host-turn-loop.ts +103 -12
  22. package/src/headless-host/role-turn-host.ts +41 -25
  23. package/src/pi/role-turn-host.ts +37 -3
  24. package/src/public-cli/instruction-seat-run.ts +248 -50
  25. package/src/public-cli/invocation.ts +15 -27
  26. package/src/public-cli/post-admission.ts +250 -33
  27. package/src/public-cli/run-lifecycle.ts +5 -5
  28. package/src/public-cli/settlement.ts +38 -11
  29. package/src/public-cli/terminal.ts +6 -0
  30. package/src/report-ticket-tool.ts +176 -0
  31. package/src/role-envelope.ts +28 -3
  32. package/src/role-run-placement.ts +0 -2
  33. package/src/role-run-relocation.ts +45 -4
  34. package/src/role-runtime.ts +6 -0
  35. package/src/worker-submission-gates.ts +26 -3
@@ -572,6 +572,7 @@ __export(activation_ledger_topology_exports, {
572
572
  physicallyContainedIn: () => physicallyContainedIn,
573
573
  resolveActivationLedgerHome: () => resolveActivationLedgerHome,
574
574
  resolveActivationLedgerHomeForPath: () => resolveActivationLedgerHomeForPath,
575
+ tryBookKeyFromAkRolesPath: () => tryBookKeyFromAkRolesPath,
575
576
  tryHomeFromAkRolesPath: () => tryHomeFromAkRolesPath
576
577
  });
577
578
  import {
@@ -593,6 +594,17 @@ function tryHomeFromAkRolesPath(path) {
593
594
  }
594
595
  return path.slice(0, match.index);
595
596
  }
597
+ function tryBookKeyFromAkRolesPath(path) {
598
+ const home = tryHomeFromAkRolesPath(path);
599
+ if (home === void 0 || home.length === 0) return void 0;
600
+ const booksRoot = join2(resolveActivationLedgerHome(home), "books");
601
+ const rel = relative(booksRoot, resolve2(path));
602
+ if (rel === "" || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute2(rel)) {
603
+ return void 0;
604
+ }
605
+ const bookKey = rel.split(sep)[0];
606
+ return bookKey === void 0 || bookKey === "" ? void 0 : bookKey;
607
+ }
596
608
  function homeFromRunDirectory(runDirectory) {
597
609
  const home = tryHomeFromAkRolesPath(runDirectory);
598
610
  if (home === void 0 || home.length === 0) {
@@ -1483,8 +1495,7 @@ function roleRunPlacement(ledgerHome, input) {
1483
1495
  return {
1484
1496
  runDirectory,
1485
1497
  sessionDirectory,
1486
- sessionFile: sessionFileIn(sessionDirectory),
1487
- attachmentsDirectory: join6(runDirectory, "attachments")
1498
+ sessionFile: sessionFileIn(sessionDirectory)
1488
1499
  };
1489
1500
  }
1490
1501
  function isUnboundRunDirectory(runDirectory) {
@@ -14937,15 +14948,9 @@ async function relocateAdmittedRunToTicket(admitted, authority, heldLease) {
14937
14948
  }
14938
14949
  await rename(oldRunDirectory, target.runDirectory);
14939
14950
  heldLease?.relocate(target.runDirectory);
14940
- const admittedRecord = admitted;
14941
- rewriteRunDirectoryPathFields(
14942
- admittedRecord,
14943
- [
14944
- "runDirectory",
14945
- "mergerInputPath"
14946
- ],
14947
- oldRunDirectory,
14948
- target.runDirectory
14951
+ rewriteAdmittedRoleRunPage(
14952
+ admitted,
14953
+ [{ oldRunDirectory, newRunDirectory: target.runDirectory }]
14949
14954
  );
14950
14955
  admitted.principal = principal;
14951
14956
  renderCurrentSync(target.runDirectory);
@@ -15576,7 +15581,6 @@ async function placeRoleAdmission(options) {
15576
15581
  sessionDirectory,
15577
15582
  sessionFile,
15578
15583
  runDirectory,
15579
- attachmentsDirectory,
15580
15584
  ledgerHome,
15581
15585
  bookKey
15582
15586
  } = issueAdmissionPlacement(options.principalAuthority, {
@@ -15597,7 +15601,6 @@ async function placeRoleAdmission(options) {
15597
15601
  sessionDirectory,
15598
15602
  sessionFile,
15599
15603
  attachments,
15600
- attachmentsDirectory,
15601
15604
  ledgerHome,
15602
15605
  ticketFields
15603
15606
  };
@@ -16322,19 +16325,24 @@ function roleOutcomeFromRows(role, rows) {
16322
16325
  if (terminal.length === 0) return void 0;
16323
16326
  const payloads = mine.map((row) => row.accepted);
16324
16327
  const latest = terminal[terminal.length - 1];
16328
+ const submissionToolCallId = typeof latest.toolCallId === "string" && latest.toolCallId.length > 0 ? latest.toolCallId : void 0;
16329
+ const belonging = submissionToolCallId === void 0 ? {} : { submissionToolCallId };
16325
16330
  if (latest.kind === "audit-escalation") {
16326
16331
  return {
16327
- kind: "audit_escalation",
16328
- role,
16329
- status: "audit_escalation",
16330
- payloads,
16331
- ...Object.hasOwn(latest, "auditReceipt") ? { decisiveFacts: {
16332
- auditEscalationReceipt: latest.auditReceipt,
16333
- ...Object.hasOwn(latest, "auditOfficer") ? { auditEscalationOfficer: latest.auditOfficer } : {}
16334
- } } : {}
16332
+ outcome: {
16333
+ kind: "audit_escalation",
16334
+ role,
16335
+ status: "audit_escalation",
16336
+ payloads,
16337
+ ...Object.hasOwn(latest, "auditReceipt") ? { decisiveFacts: {
16338
+ auditEscalationReceipt: latest.auditReceipt,
16339
+ ...Object.hasOwn(latest, "auditOfficer") ? { auditEscalationOfficer: latest.auditOfficer } : {}
16340
+ } } : {}
16341
+ },
16342
+ ...belonging
16335
16343
  };
16336
16344
  }
16337
- return { kind: "accepted", role, payloads };
16345
+ return { outcome: { kind: "accepted", role, payloads }, ...belonging };
16338
16346
  }
16339
16347
  async function sealedLedgerOutcome(admitted, role, scope) {
16340
16348
  const home = sealedLedgerHome(admitted);
@@ -16969,8 +16977,8 @@ function entriesOf(read) {
16969
16977
  }
16970
16978
  async function settleSealedSeat(admitted, authority, scope, options) {
16971
16979
  const coordinates = coordinatesFromAdmitted(authority, admitted);
16972
- const roleOutcome = await sealedLedgerOutcome(admitted, admitted.role, scope);
16973
- if (roleOutcome === void 0 || options.acceptedOnly && roleOutcome.kind !== "accepted") {
16980
+ const settled = await sealedLedgerOutcome(admitted, admitted.role, scope);
16981
+ if (settled === void 0 || options.acceptedOnly && settled.outcome.kind !== "accepted") {
16974
16982
  return void 0;
16975
16983
  }
16976
16984
  const read = await readLawfulSettlementEntries(coordinates.sessionFile);
@@ -16981,15 +16989,23 @@ async function settleSealedSeat(admitted, authority, scope, options) {
16981
16989
  `session read failed beside lawful terminal: ${describeErrorIdentity(read.error)}`
16982
16990
  );
16983
16991
  }
16984
- return finishLawfulSeat(admitted, coordinates, entriesOf(read), roleOutcome, scope);
16992
+ return finishLawfulSeat(
16993
+ admitted,
16994
+ coordinates,
16995
+ entriesOf(read),
16996
+ settled.outcome,
16997
+ scope,
16998
+ settled.submissionToolCallId
16999
+ );
16985
17000
  }
16986
- async function finishLawfulSeat(admitted, coordinates, entries, roleOutcome, scope) {
17001
+ async function finishLawfulSeat(admitted, coordinates, entries, roleOutcome, scope, submissionToolCallId) {
16987
17002
  const artifacts = scope?.previewOnly === true ? [] : await publishDeclaredSeatTerminal(admitted, roleOutcome, coordinates, entries, scope);
16988
17003
  const terminal = await attachEngineDetourToolUsage({
16989
17004
  roleOutcome,
16990
17005
  navigator: extractNavigatorFact(entries),
16991
17006
  artifacts,
16992
- runId: admitted.runId
17007
+ runId: admitted.runId,
17008
+ ...submissionToolCallId === void 0 || submissionToolCallId.length === 0 ? {} : { submissionToolCallId }
16993
17009
  }, coordinates.sessionDirectory, detourUsageContext(admitted, scope));
16994
17010
  return attachRecordedSubmissions(admitted, terminal, scope);
16995
17011
  }
@@ -17341,6 +17357,77 @@ var init_settlement = __esm({
17341
17357
  }
17342
17358
  });
17343
17359
 
17360
+ // src/external-host-turn-loop.ts
17361
+ import { existsSync as existsSync5 } from "node:fs";
17362
+ import { basename as basename8 } from "node:path";
17363
+ async function resolveLiveRunDirectoryPath(recordedPath, home) {
17364
+ if (existsSync5(recordedPath)) return recordedPath;
17365
+ const parsed = parseRunLeaf(basename8(recordedPath));
17366
+ const bookKey = tryBookKeyFromAkRolesPath(recordedPath);
17367
+ if (parsed === void 0 || bookKey === void 0) return void 0;
17368
+ return await findRunDirectoryById(
17369
+ home,
17370
+ parsed.runId,
17371
+ bookKey,
17372
+ parsed.role
17373
+ );
17374
+ }
17375
+ async function syncTurnRequestLivePlacement(request) {
17376
+ const live = await resolveLiveRunDirectoryPath(request.runDirectory, request.home);
17377
+ if (live === void 0) {
17378
+ const parsed = parseRunLeaf(basename8(request.runDirectory));
17379
+ throw new Error(
17380
+ `admitted run ${parsed?.runId ?? "(unparseable)"} missing after host turn; not found under ${request.home}`
17381
+ );
17382
+ }
17383
+ if (live !== request.runDirectory) {
17384
+ projectTurnRequestLiveRunDirectory(
17385
+ request,
17386
+ live
17387
+ );
17388
+ }
17389
+ return live;
17390
+ }
17391
+ async function trySyncTurnRequestLivePlacement(request) {
17392
+ try {
17393
+ return { runDirectory: await syncTurnRequestLivePlacement(request) };
17394
+ } catch (resolveError) {
17395
+ return { resolveError };
17396
+ }
17397
+ }
17398
+ async function retainPackageFaultBesideLivePlacement(request, input) {
17399
+ const live = await trySyncTurnRequestLivePlacement(request);
17400
+ if ("resolveError" in live) {
17401
+ const resolveDiagnostic = `live run path resolve failed beside fault: ${describeErrorIdentity(live.resolveError)}`;
17402
+ try {
17403
+ process.stderr.write(`${input.diagnostic}
17404
+ `);
17405
+ process.stderr.write(`${resolveDiagnostic}
17406
+ `);
17407
+ } catch {
17408
+ }
17409
+ return;
17410
+ }
17411
+ await retainPackageFault({
17412
+ runDirectory: live.runDirectory,
17413
+ diagnostic: input.diagnostic,
17414
+ ...Object.hasOwn(input, "error") ? { error: input.error } : {}
17415
+ });
17416
+ }
17417
+ var init_external_host_turn_loop = __esm({
17418
+ "src/external-host-turn-loop.ts"() {
17419
+ "use strict";
17420
+ init_activation_ledger_topology();
17421
+ init_settlement();
17422
+ init_run_lifecycle();
17423
+ init_receipt_delivery_policy();
17424
+ init_role_run_placement();
17425
+ init_role_run_relocation();
17426
+ init_sitian_facade();
17427
+ init_submission_errors();
17428
+ }
17429
+ });
17430
+
17344
17431
  // src/session-identity.ts
17345
17432
  import { dirname as dirname11, join as join15 } from "node:path";
17346
17433
  function createSessionIdentityAuthority(authority, hostName) {
@@ -17420,6 +17507,7 @@ __export(role_turn_host_exports, {
17420
17507
  });
17421
17508
  import { execFile as execFile2, spawn } from "node:child_process";
17422
17509
  import { constants as constants2 } from "node:fs";
17510
+ import { existsSync as existsSync6 } from "node:fs";
17423
17511
  import { access as access2, appendFile, realpath as realpath4 } from "node:fs/promises";
17424
17512
  import { delimiter as delimiter2, dirname as dirname12, isAbsolute as isAbsolute6, join as join16, resolve as resolve10 } from "node:path";
17425
17513
  import { platform } from "node:process";
@@ -17605,7 +17693,32 @@ function createDefaultPiSpawnRunner(options) {
17605
17693
  if (stdinDeliveryError !== void 0) packageErrors.push(stdinDeliveryError);
17606
17694
  for (const error of packageErrors) {
17607
17695
  const diagnostic = `Pi transport handling failed beside host terminal: ${describeErrorIdentity(error)}`;
17608
- const runDirectory = spawnOptions.env.AK_ROLE_RUN_DIR;
17696
+ const spawnDir = spawnOptions.env.AK_ROLE_RUN_DIR;
17697
+ let runDirectory;
17698
+ if (typeof spawnDir === "string" && spawnDir.trim() !== "") {
17699
+ try {
17700
+ runDirectory = await resolveLiveRunDirectoryPath(
17701
+ spawnDir,
17702
+ homeFromRunDirectory(spawnDir)
17703
+ );
17704
+ } catch (resolveError) {
17705
+ runDirectory = existsSync6(spawnDir) ? spawnDir : void 0;
17706
+ const resolveDiagnostic = `live run path resolve failed beside Pi transport fault: ${describeErrorIdentity(resolveError)}`;
17707
+ if (runDirectory !== void 0) {
17708
+ await retainPackageFault({
17709
+ runDirectory,
17710
+ diagnostic: resolveDiagnostic,
17711
+ error: resolveError
17712
+ });
17713
+ } else {
17714
+ try {
17715
+ process.stderr.write(`${resolveDiagnostic}
17716
+ `);
17717
+ } catch {
17718
+ }
17719
+ }
17720
+ }
17721
+ }
17609
17722
  if (runDirectory !== void 0) {
17610
17723
  await retainPackageFault({ runDirectory, diagnostic, error });
17611
17724
  } else {
@@ -17687,6 +17800,7 @@ function createPiRoleTurnHost(config) {
17687
17800
  ...request.signal === void 0 ? {} : { signal: request.signal }
17688
17801
  });
17689
17802
  try {
17803
+ await syncTurnRequestLivePlacement(request);
17690
17804
  const { sessionFile, sessionDirectory } = config.principalAuthority.decode(request.principal);
17691
17805
  const sessionId = await readPiSessionHeaderId(sessionFile);
17692
17806
  if (sessionId !== void 0) {
@@ -17704,8 +17818,7 @@ function createPiRoleTurnHost(config) {
17704
17818
  });
17705
17819
  }
17706
17820
  } catch (error) {
17707
- await retainPackageFault({
17708
- runDirectory: request.runDirectory,
17821
+ await retainPackageFaultBesideLivePlacement(request, {
17709
17822
  diagnostic: `pi host dossier record failed beside host terminal: ${describeErrorIdentity(error)}`,
17710
17823
  error
17711
17824
  });
@@ -17774,6 +17887,8 @@ var init_role_turn_host = __esm({
17774
17887
  init_user_dialogue_stdin();
17775
17888
  init_ledger_session_read();
17776
17889
  init_host_session_record();
17890
+ init_external_host_turn_loop();
17891
+ init_activation_ledger_topology();
17777
17892
  init_settlement();
17778
17893
  init_run_lifecycle();
17779
17894
  init_receipt_delivery_policy();
@@ -17793,7 +17908,7 @@ var init_role_turn_host = __esm({
17793
17908
  });
17794
17909
 
17795
17910
  // src/public-cli/load-production-acp-host.ts
17796
- import { existsSync as existsSync5 } from "node:fs";
17911
+ import { existsSync as existsSync7 } from "node:fs";
17797
17912
  import { join as join17 } from "node:path";
17798
17913
  import { pathToFileURL } from "node:url";
17799
17914
  async function loadProductionAcpHostFactory(packageRoot2, host) {
@@ -17803,7 +17918,7 @@ async function loadProductionAcpHostFactory(packageRoot2, host) {
17803
17918
  }
17804
17919
  const built = join17(packageRoot2, "dist/acp-host/production-host.js");
17805
17920
  const source = join17(packageRoot2, "src/acp-host/production-host.ts");
17806
- const target = existsSync5(built) ? built : source;
17921
+ const target = existsSync7(built) ? built : source;
17807
17922
  const href = pathToFileURL(target).href;
17808
17923
  const mod = await import(href);
17809
17924
  const create = mod.createProductionAcpRoleTurnHost;
@@ -17817,7 +17932,7 @@ var init_load_production_acp_host = __esm({
17817
17932
  });
17818
17933
 
17819
17934
  // src/public-cli/load-production-headless-host.ts
17820
- import { existsSync as existsSync6 } from "node:fs";
17935
+ import { existsSync as existsSync8 } from "node:fs";
17821
17936
  import { join as join18 } from "node:path";
17822
17937
  import { pathToFileURL as pathToFileURL2 } from "node:url";
17823
17938
  async function loadProductionHeadlessHostFactory(packageRoot2, host) {
@@ -17827,7 +17942,7 @@ async function loadProductionHeadlessHostFactory(packageRoot2, host) {
17827
17942
  }
17828
17943
  const built = join18(packageRoot2, "dist/headless-host/production-host.js");
17829
17944
  const source = join18(packageRoot2, "src/headless-host/production-host.ts");
17830
- const target = existsSync6(built) ? built : source;
17945
+ const target = existsSync8(built) ? built : source;
17831
17946
  const href = pathToFileURL2(target).href;
17832
17947
  const mod = await import(href);
17833
17948
  const create = mod.createProductionHeadlessRoleTurnHost;
@@ -17993,8 +18108,78 @@ var init_role_seat_runtime = __esm({
17993
18108
  }
17994
18109
  });
17995
18110
 
18111
+ // src/report-ticket-tool.ts
18112
+ var reportTicketArgsSchema, MISSING_TICKET_REASK_MATERIAL;
18113
+ var init_report_ticket_tool = __esm({
18114
+ "src/report-ticket-tool.ts"() {
18115
+ "use strict";
18116
+ init_build();
18117
+ init_host_contracts();
18118
+ init_durable_principal();
18119
+ init_invocation();
18120
+ init_role_run_placement();
18121
+ init_run_dossier();
18122
+ init_run_ticket_number();
18123
+ init_unknown_value();
18124
+ reportTicketArgsSchema = typebox_exports.Object(
18125
+ {
18126
+ ticketNumber: typebox_exports.Unknown({
18127
+ description: "\u672C\u7968\u53F7\uFF08\u6B63\u6574\u6570\u3001\u6570\u5B57\u4E32\u6216\u524D\u5BFC #N\uFF09\u3002\u5DF2\u77E5\u7968\u53F7\u65F6\u5F00\u5DE5\u5373\u62A5\uFF1B\u5C1A\u65E0\u7968\u53F7\u65F6\u4E0D\u8981\u8C03\u7528\u3002"
18128
+ })
18129
+ },
18130
+ { additionalProperties: true }
18131
+ );
18132
+ MISSING_TICKET_REASK_MATERIAL = "resources/missing-ticket-reask.md";
18133
+ }
18134
+ });
18135
+
18136
+ // src/session-opening-materials.ts
18137
+ import { existsSync as existsSync9 } from "node:fs";
18138
+ import { readFile as readFile9 } from "node:fs/promises";
18139
+ import { dirname as dirname13, join as join19 } from "node:path";
18140
+ import { fileURLToPath, pathToFileURL as pathToFileURL3 } from "node:url";
18141
+ function resolvePackageRootDir(moduleUrl = import.meta.url) {
18142
+ let dir = dirname13(fileURLToPath(moduleUrl));
18143
+ for (let i = 0; i < 8; i += 1) {
18144
+ if (existsSync9(join19(dir, "package.json")) && existsSync9(join19(dir, "souls"))) {
18145
+ return dir;
18146
+ }
18147
+ const parent = dirname13(dir);
18148
+ if (parent === dir) break;
18149
+ dir = parent;
18150
+ }
18151
+ return fileURLToPath(new URL("..", moduleUrl));
18152
+ }
18153
+ async function readPackageMaterial(relativePath) {
18154
+ return readFile9(fileURLToPath(new URL(relativePath, packageRootUrl)), "utf8");
18155
+ }
18156
+ async function joinPackageMaterials(relativePaths) {
18157
+ const chunks = [];
18158
+ for (const relativePath of relativePaths) chunks.push(await readPackageMaterial(relativePath));
18159
+ return chunks.join("\n\n");
18160
+ }
18161
+ var packageRootUrl, MAIN_ROLE_SESSION_MATERIALS, GATEKEEPER_SESSION_MATERIALS;
18162
+ var init_session_opening_materials = __esm({
18163
+ "src/session-opening-materials.ts"() {
18164
+ "use strict";
18165
+ init_packaged_role_registry();
18166
+ packageRootUrl = pathToFileURL3(resolvePackageRootDir() + "/").href;
18167
+ MAIN_ROLE_SESSION_MATERIALS = {
18168
+ ...Object.fromEntries(
18169
+ PUBLIC_ROLE_RECORDS.map((record) => [record.role, record.sessionMaterials])
18170
+ )
18171
+ };
18172
+ GATEKEEPER_SESSION_MATERIALS = {
18173
+ // #639: single authority — the public gatekeeper record owns the province list.
18174
+ gatekeeper: packagedRoleSessionMaterials("gatekeeper"),
18175
+ inspector: INSPECTOR_SESSION_MATERIALS,
18176
+ notary: NOTARY_SESSION_MATERIALS
18177
+ };
18178
+ }
18179
+ });
18180
+
17996
18181
  // src/archivist-record-pointer.ts
17997
- import { basename as basename8, join as join19 } from "node:path";
18182
+ import { basename as basename9, join as join20 } from "node:path";
17998
18183
  function bookDirectOfficerRunPointer(options) {
17999
18184
  const submissionToolCallId = options.submissionToolCallId?.trim() ?? "";
18000
18185
  const pointer = {
@@ -18020,7 +18205,7 @@ async function resolveOfficerPointer(raw, parentRunDirectory) {
18020
18205
  let runDirectory = typeof raw.runDirectory === "string" && raw.runDirectory.trim() !== "" ? raw.runDirectory : void 0;
18021
18206
  let sessionFile = raw.sessionFile;
18022
18207
  const recordedRunDirectory = runDirectory ?? runDirectoryOfSessionFile(sessionFile);
18023
- const leaf = parseRunLeaf(basename8(recordedRunDirectory));
18208
+ const leaf = parseRunLeaf(basename9(recordedRunDirectory));
18024
18209
  const parentIdentity = await readRoleRunIdentity(parentRunDirectory);
18025
18210
  if (leaf !== void 0 && parentIdentity !== void 0) {
18026
18211
  const currentRunDirectory = await findRunDirectoryById(
@@ -18043,7 +18228,7 @@ async function resolveOfficerPointer(raw, parentRunDirectory) {
18043
18228
  };
18044
18229
  }
18045
18230
  async function readBookedOfficerPointers(parentRunDirectory) {
18046
- const { records, diagnostics } = await readSitianRecords(join19(parentRunDirectory, RUN_HISTORY_FILE));
18231
+ const { records, diagnostics } = await readSitianRecords(join20(parentRunDirectory, RUN_HISTORY_FILE));
18047
18232
  if (diagnostics.length > 0) {
18048
18233
  throw new Error(
18049
18234
  `${RUN_HISTORY_FILE} has ${diagnostics.length} malformed row(s); officer pointers unreadable: ${parentRunDirectory}`
@@ -18334,51 +18519,6 @@ var init_submission_gate = __esm({
18334
18519
  }
18335
18520
  });
18336
18521
 
18337
- // src/session-opening-materials.ts
18338
- import { existsSync as existsSync7 } from "node:fs";
18339
- import { readFile as readFile9 } from "node:fs/promises";
18340
- import { dirname as dirname13, join as join20 } from "node:path";
18341
- import { fileURLToPath, pathToFileURL as pathToFileURL3 } from "node:url";
18342
- function resolvePackageRootDir(moduleUrl = import.meta.url) {
18343
- let dir = dirname13(fileURLToPath(moduleUrl));
18344
- for (let i = 0; i < 8; i += 1) {
18345
- if (existsSync7(join20(dir, "package.json")) && existsSync7(join20(dir, "souls"))) {
18346
- return dir;
18347
- }
18348
- const parent = dirname13(dir);
18349
- if (parent === dir) break;
18350
- dir = parent;
18351
- }
18352
- return fileURLToPath(new URL("..", moduleUrl));
18353
- }
18354
- async function readPackageMaterial(relativePath) {
18355
- return readFile9(fileURLToPath(new URL(relativePath, packageRootUrl)), "utf8");
18356
- }
18357
- async function joinPackageMaterials(relativePaths) {
18358
- const chunks = [];
18359
- for (const relativePath of relativePaths) chunks.push(await readPackageMaterial(relativePath));
18360
- return chunks.join("\n\n");
18361
- }
18362
- var packageRootUrl, MAIN_ROLE_SESSION_MATERIALS, GATEKEEPER_SESSION_MATERIALS;
18363
- var init_session_opening_materials = __esm({
18364
- "src/session-opening-materials.ts"() {
18365
- "use strict";
18366
- init_packaged_role_registry();
18367
- packageRootUrl = pathToFileURL3(resolvePackageRootDir() + "/").href;
18368
- MAIN_ROLE_SESSION_MATERIALS = {
18369
- ...Object.fromEntries(
18370
- PUBLIC_ROLE_RECORDS.map((record) => [record.role, record.sessionMaterials])
18371
- )
18372
- };
18373
- GATEKEEPER_SESSION_MATERIALS = {
18374
- // #639: single authority — the public gatekeeper record owns the province list.
18375
- gatekeeper: packagedRoleSessionMaterials("gatekeeper"),
18376
- inspector: INSPECTOR_SESSION_MATERIALS,
18377
- notary: NOTARY_SESSION_MATERIALS
18378
- };
18379
- }
18380
- });
18381
-
18382
18522
  // src/auditor-soul.ts
18383
18523
  var auditor_soul_exports = {};
18384
18524
  __export(auditor_soul_exports, {
@@ -18394,7 +18534,7 @@ __export(auditor_soul_exports, {
18394
18534
  readAuditorResumeBinding: () => readAuditorResumeBinding,
18395
18535
  resolveAuditorSubject: () => resolveAuditorSubject
18396
18536
  });
18397
- import { basename as basename9 } from "node:path";
18537
+ import { basename as basename10 } from "node:path";
18398
18538
  function auditorSoulRelativePath(role) {
18399
18539
  return `souls/${role}-auditor.md`;
18400
18540
  }
@@ -18430,7 +18570,7 @@ function loadAuditorReferenceMaterialsFromSubjectInput(raw) {
18430
18570
  return loadAuditorReferenceMaterials(resolveAuditorSubject(raw));
18431
18571
  }
18432
18572
  function subjectFromSourceDirectory(sourceRunDirectory) {
18433
- const role = parseRunLeaf(basename9(sourceRunDirectory))?.role;
18573
+ const role = parseRunLeaf(basename10(sourceRunDirectory))?.role;
18434
18574
  return isAuditorSoulRole(role) ? role : void 0;
18435
18575
  }
18436
18576
  async function readAuditorResumeBinding(runDirectory) {
@@ -18977,10 +19117,14 @@ function unreadablePostSubmissionStatus(admitted, terminal) {
18977
19117
  const status = receivedDiscriminator(payload, "status");
18978
19118
  return typeof status === "string" && route.statuses.has(status) ? void 0 : route.reask ?? officerConclusionReask(status);
18979
19119
  }
19120
+ function withoutSoftTicketReaskTurn(env) {
19121
+ const { softTicketReaskTurn: _softTicketReaskTurn, ...rest } = env;
19122
+ return rest;
19123
+ }
18980
19124
  function withUnreadableReask(env) {
18981
19125
  const spent = env.unreadableReasksSpent ?? 0;
18982
19126
  if (spent >= deliveryLimitFromConfig(env.autoResumeLimit)) return void 0;
18983
- return { ...env, unreadableReasksSpent: spent + 1 };
19127
+ return { ...withoutSoftTicketReaskTurn(env), unreadableReasksSpent: spent + 1 };
18984
19128
  }
18985
19129
  function isUnreadableReaskExhausted(value) {
18986
19130
  return value === UNREADABLE_REASK_EXHAUSTED;
@@ -19039,6 +19183,110 @@ async function reaskUnreadablePostSubmissionStatus(admitted, terminal, env, io,
19039
19183
  io
19040
19184
  );
19041
19185
  }
19186
+ async function reaskMissingTicketOnce(admitted, terminal, env, io) {
19187
+ if ((env.ticketReasksSpent ?? 0) >= 1) return { kind: "none" };
19188
+ if (admitted.ticketNumber !== void 0) return { kind: "none" };
19189
+ if (!isUnboundRunDirectory(admitted.runDirectory)) return { kind: "none" };
19190
+ if (terminal?.roleOutcome.kind !== "accepted" && terminal?.roleOutcome.kind !== "audit_escalation") {
19191
+ return { kind: "none" };
19192
+ }
19193
+ const payloads = terminal.roleOutcome.payloads ?? [];
19194
+ if (payloads.length === 0) return { kind: "none" };
19195
+ const instruction = (await readPackageMaterial(MISSING_TICKET_REASK_MATERIAL)).trim();
19196
+ const softTicketReaskOwnership = { sealedSubstitute: false };
19197
+ const softReaskEnv = {
19198
+ ...env,
19199
+ ticketReasksSpent: 1,
19200
+ softTicketReaskTurn: true,
19201
+ softTicketReaskOwnership
19202
+ };
19203
+ const result = await runPublicInstructionSeatResume(
19204
+ { runId: admitted.runId, summons: { instruction } },
19205
+ softReaskEnv,
19206
+ io
19207
+ );
19208
+ if (softTicketReaskOwnership.sealedSubstitute || terminalCarriesSealedSubmission(result.terminal)) {
19209
+ return { kind: "nested_owns", result };
19210
+ }
19211
+ return { kind: "no_substitute", result };
19212
+ }
19213
+ function envForCourtContinue(env) {
19214
+ return { ...withoutSoftTicketReaskTurn(env), unreadableReasksSpent: 0 };
19215
+ }
19216
+ function terminalCarriesSealedSubmission(terminal) {
19217
+ const kind = terminal?.roleOutcome.kind;
19218
+ if (kind !== "accepted" && kind !== "audit_escalation") return false;
19219
+ return (terminal?.roleOutcome.payloads ?? []).length > 0;
19220
+ }
19221
+ function projectKeptOriginalArtifactsOntoLiveAdmitted(original, kept) {
19222
+ const oldRunDirectory = original.admitted?.runDirectory;
19223
+ const newRunDirectory = kept.admitted?.runDirectory;
19224
+ if (oldRunDirectory === void 0 || newRunDirectory === void 0 || oldRunDirectory === newRunDirectory || kept.terminal === void 0) {
19225
+ return;
19226
+ }
19227
+ for (const artifact of kept.terminal.artifacts) {
19228
+ artifact.path = rewriteRunDirectoryPathValue(
19229
+ artifact.path,
19230
+ oldRunDirectory,
19231
+ newRunDirectory
19232
+ );
19233
+ }
19234
+ }
19235
+ function mergeMissingTicketReaskKeepOriginal(original, ticketReask) {
19236
+ if (ticketReask.exitCode !== 0) return ticketReask;
19237
+ const admitted = ticketReask.admitted ?? original.admitted;
19238
+ if (admitted === void 0) return { ...original };
19239
+ const kept = { ...original, admitted };
19240
+ projectKeptOriginalArtifactsOntoLiveAdmitted(original, kept);
19241
+ return kept;
19242
+ }
19243
+ async function continueAfterPostSubmissionGuards(result, admittedRole, env, io, held) {
19244
+ const live = result.admitted;
19245
+ if (live === void 0) {
19246
+ await presentOriginalVolume(held, result.terminal, io);
19247
+ return result;
19248
+ }
19249
+ const unreadableReask = await reaskUnreadablePostSubmissionStatus(
19250
+ live,
19251
+ result.terminal,
19252
+ env,
19253
+ io
19254
+ );
19255
+ let afterStatus = result;
19256
+ if (isUnreadableReaskExhausted(unreadableReask)) {
19257
+ const terminal = result.terminal === void 0 ? void 0 : withUnsettledDirection(result.terminal);
19258
+ afterStatus = terminal === void 0 ? { ...result, admitted: live } : { ...result, admitted: live, terminal };
19259
+ } else if (unreadableReask !== void 0) {
19260
+ return unreadableReask;
19261
+ }
19262
+ const forTicket = afterStatus.admitted ?? live;
19263
+ const softReask = await reaskMissingTicketOnce(
19264
+ forTicket,
19265
+ afterStatus.terminal ?? result.terminal,
19266
+ env,
19267
+ io
19268
+ );
19269
+ if (softReask.kind === "nested_owns") {
19270
+ return softReask.result;
19271
+ }
19272
+ const continued = softReask.kind === "none" ? afterStatus : mergeMissingTicketReaskKeepOriginal(afterStatus, softReask.result);
19273
+ const continuedAdmitted = continued.admitted ?? live;
19274
+ const continuedEnv = softReask.kind !== "none" ? { ...env, ticketReasksSpent: 1 } : env;
19275
+ if (AUDITED_ROLES.has(admittedRole) && continued.terminal?.roleOutcome.kind === "accepted") {
19276
+ return auditSubmittedRole(
19277
+ { ...continued, admitted: continuedAdmitted },
19278
+ continuedEnv,
19279
+ io
19280
+ );
19281
+ }
19282
+ await presentOriginalVolume(
19283
+ held,
19284
+ continued.terminal,
19285
+ io,
19286
+ continuedAdmitted.runDirectory
19287
+ );
19288
+ return { ...continued, admitted: continuedAdmitted };
19289
+ }
19042
19290
  function roleRecord(role) {
19043
19291
  const record = packagedRoleMetadata(role);
19044
19292
  if (record === void 0) {
@@ -19213,23 +19461,14 @@ async function dispatchAdmitted(admitted, env, io) {
19213
19461
  });
19214
19462
  };
19215
19463
  const result = await execute(env);
19216
- const unreadableReask = await reaskUnreadablePostSubmissionStatus(
19217
- admitted,
19218
- result.terminal,
19464
+ const live = result.admitted ?? admitted;
19465
+ return continueAfterPostSubmissionGuards(
19466
+ { ...result, admitted: live },
19467
+ admitted.role,
19219
19468
  env,
19220
- io
19469
+ io,
19470
+ held
19221
19471
  );
19222
- if (isUnreadableReaskExhausted(unreadableReask)) {
19223
- const terminal = result.terminal === void 0 ? void 0 : withUnsettledDirection(result.terminal);
19224
- await presentOriginalVolume(held, terminal, io, admitted.runDirectory);
19225
- return terminal === void 0 ? result : { ...result, terminal };
19226
- }
19227
- if (unreadableReask !== void 0) return unreadableReask;
19228
- if (AUDITED_ROLES.has(admitted.role) && result.terminal?.roleOutcome.kind === "accepted") {
19229
- return auditSubmittedRole(result, env, io);
19230
- }
19231
- await presentOriginalVolume(held, result.terminal, io, admitted.runDirectory);
19232
- return result;
19233
19472
  }
19234
19473
  async function runOmittedLensBatch(argv2, parsed, env, io) {
19235
19474
  const { summonParallelReviewerLenses: summonParallelReviewerLenses2 } = await Promise.resolve().then(() => (init_public_role_summons(), public_role_summons_exports));
@@ -19415,9 +19654,7 @@ async function runPublicInstructionSeat(argv2, env, io, role, parseArgv2) {
19415
19654
  stdout: (value) => held.push(value),
19416
19655
  stderr: io.stderr
19417
19656
  });
19418
- if (result.terminal?.roleOutcome.kind === "accepted") return auditSubmittedRole(result, env, io);
19419
- await presentOriginalVolume(held, result.terminal, io, result.admitted?.runDirectory);
19420
- return result;
19657
+ return continueAfterPostSubmissionGuards(result, "countersign", env, io, held);
19421
19658
  }
19422
19659
  if ("parallelLenses" in record && record.parallelLenses === true) {
19423
19660
  if (parsed.baseRevision === void 0) {
@@ -19691,23 +19928,17 @@ async function runPublicInstructionSeatResume(request, env, io) {
19691
19928
  },
19692
19929
  ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
19693
19930
  });
19694
- const unreadableReask = result.admitted === void 0 ? void 0 : await reaskUnreadablePostSubmissionStatus(
19695
- result.admitted,
19696
- result.terminal,
19931
+ if (result.admitted === void 0) {
19932
+ await presentOriginalVolume(held, result.terminal, io);
19933
+ return result;
19934
+ }
19935
+ return continueAfterPostSubmissionGuards(
19936
+ result,
19937
+ result.admitted.role,
19697
19938
  env,
19698
- io
19939
+ io,
19940
+ held
19699
19941
  );
19700
- if (isUnreadableReaskExhausted(unreadableReask)) {
19701
- const terminal = result.terminal === void 0 ? void 0 : withUnsettledDirection(result.terminal);
19702
- await presentOriginalVolume(held, terminal, io, result.admitted?.runDirectory);
19703
- return terminal === void 0 ? result : { ...result, terminal };
19704
- }
19705
- if (unreadableReask !== void 0) return unreadableReask;
19706
- if (result.admitted !== void 0 && AUDITED_ROLES.has(result.admitted.role) && result.terminal?.roleOutcome.kind === "accepted") {
19707
- return auditSubmittedRole(result, env, io);
19708
- }
19709
- await presentOriginalVolume(held, result.terminal, io, result.admitted?.runDirectory);
19710
- return result;
19711
19942
  };
19712
19943
  let binding;
19713
19944
  try {
@@ -19740,7 +19971,7 @@ async function queueConclusionFromChild(child, env, io) {
19740
19971
  return { stop: { exitCode: 0, ...terminal === void 0 ? {} : { terminal } } };
19741
19972
  }
19742
19973
  let current = child;
19743
- let budgetEnv = { ...env, unreadableReasksSpent: 0 };
19974
+ let budgetEnv = envForCourtContinue(env);
19744
19975
  for (; ; ) {
19745
19976
  const terminal = await trySettlePublicSeat(
19746
19977
  current,
@@ -19811,7 +20042,7 @@ async function continueParentAfterChild(parentRunId, child, env, io) {
19811
20042
  return runPublicInstructionSeatResume({
19812
20043
  runId: parentRunId,
19813
20044
  summons: { instruction: readableGateItem(latestQueuePayload(resolved.terminal)) }
19814
- }, { ...env, unreadableReasksSpent: 0 }, io);
20045
+ }, envForCourtContinue(env), io);
19815
20046
  }
19816
20047
  const result = await dispatchAdmitted(admitted, env, { ...io, omitFailureStderrDiagnostic: true });
19817
20048
  showResumeErrorPointer(io, result.exitCode, result.terminal);
@@ -19841,6 +20072,7 @@ async function officerPassedCurrentSubmission(input) {
19841
20072
  return latestQueueStatus(terminal) === "converged";
19842
20073
  }
19843
20074
  async function auditSubmittedRole(turn, env, io, resumedOfficer, passedReceipt) {
20075
+ env = withoutSoftTicketReaskTurn(env);
19844
20076
  const admitted = turn.admitted;
19845
20077
  if (admitted === void 0 || !AUDITED_ROLES.has(admitted.role) || turn.terminal?.roleOutcome.kind !== "accepted") return turn;
19846
20078
  const accepted = turn.terminal.roleOutcome.payloads?.at(-1);
@@ -19874,10 +20106,10 @@ async function auditSubmittedRole(turn, env, io, resumedOfficer, passedReceipt)
19874
20106
  await presentTerminal(turn.terminal, { ...io, omitFailureStderrDiagnostic: true }, admitted.runDirectory);
19875
20107
  return turn;
19876
20108
  }
19877
- const rows = await readRecordedSubmissionRows(admitted.projectRoot, admitted.runId, env.home);
19878
- const acceptedRow = [...rows].reverse().find((row) => row.role === admitted.role && row.kind === "accepted");
19879
- const toolCallId = acceptedRow?.toolCallId;
19880
- if (toolCallId === void 0) throw new Error("accepted submission has no tool call identity");
20109
+ const toolCallId = turn.terminal.submissionToolCallId;
20110
+ if (toolCallId === void 0 || toolCallId.length === 0) {
20111
+ throw new Error("accepted submission has no tool call identity");
20112
+ }
19881
20113
  const sessionFile = env.principalAuthority.decode(admitted.principal).sessionFile;
19882
20114
  const entries = admitted.role === "doctor" ? await readBoundSessionEntries(sessionFile) : [];
19883
20115
  const context = {
@@ -19943,7 +20175,7 @@ async function auditSubmittedRole(turn, env, io, resumedOfficer, passedReceipt)
19943
20175
  return runPublicInstructionSeatResume({
19944
20176
  runId: admitted.runId,
19945
20177
  summons: { instruction: readableGateItem(decision.receipt ?? decision.violations) }
19946
- }, { ...env, unreadableReasksSpent: 0 }, io);
20178
+ }, envForCourtContinue(env), io);
19947
20179
  }
19948
20180
  if (decision.status === "received") {
19949
20181
  if (lastSummon?.terminal === void 0) {
@@ -20043,7 +20275,7 @@ async function auditSubmittedRole(turn, env, io, resumedOfficer, passedReceipt)
20043
20275
  return runPublicInstructionSeatResume({
20044
20276
  runId: admitted.runId,
20045
20277
  summons: { instruction: readableGateItem(chain.passes.at(-1)?.receipt) }
20046
- }, { ...env, unreadableReasksSpent: 0 }, io);
20278
+ }, envForCourtContinue(env), io);
20047
20279
  }
20048
20280
  if (admitted.role === "secretariat") {
20049
20281
  const pass = chain.passes.at(-1);
@@ -20072,7 +20304,10 @@ var AUDITED_ROLES, SECRETARIAT_STATUS_REASK, WORKER_ROUTING_STATUSES, WORKER_STA
20072
20304
  var init_instruction_seat_run = __esm({
20073
20305
  "src/public-cli/instruction-seat-run.ts"() {
20074
20306
  "use strict";
20307
+ init_report_ticket_tool();
20075
20308
  init_role_run_placement();
20309
+ init_role_run_relocation();
20310
+ init_session_opening_materials();
20076
20311
  init_archivist_record_pointer();
20077
20312
  init_doctor_auditor();
20078
20313
  init_gatekeeper_role();
@@ -20155,7 +20390,7 @@ __export(public_role_summons_exports, {
20155
20390
  summonPublicRole: () => summonPublicRole
20156
20391
  });
20157
20392
  import { execFile as execFile3 } from "node:child_process";
20158
- import { existsSync as existsSync8 } from "node:fs";
20393
+ import { existsSync as existsSync10 } from "node:fs";
20159
20394
  import { realpath as realpath5 } from "node:fs/promises";
20160
20395
  import { join as join22 } from "node:path";
20161
20396
  import { promisify as promisify3 } from "node:util";
@@ -20181,7 +20416,7 @@ function parentDir(path) {
20181
20416
  function walkPackageRoot(start) {
20182
20417
  let dir = start;
20183
20418
  for (let i = 0; i < 12; i += 1) {
20184
- if (existsSync8(join22(dir, "package.json")) && existsSync8(join22(dir, "souls"))) {
20419
+ if (existsSync10(join22(dir, "package.json")) && existsSync10(join22(dir, "souls"))) {
20185
20420
  return dir;
20186
20421
  }
20187
20422
  const parent = parentDir(dir);
@@ -20843,6 +21078,24 @@ function rewriteRunDirectoryPathFields(record, fields, oldRunDirectory, newRunDi
20843
21078
  { oldRunDirectory, newRunDirectory }
20844
21079
  ]);
20845
21080
  }
21081
+ function rewritePrincipalSessionPaths(principal, oldRunDirectory, newRunDirectory) {
21082
+ rewriteRunDirectoryPathFields(
21083
+ principal,
21084
+ PRINCIPAL_SESSION_PATH_FIELDS,
21085
+ oldRunDirectory,
21086
+ newRunDirectory
21087
+ );
21088
+ }
21089
+ function projectTurnRequestLiveRunDirectory(request, newRunDirectory) {
21090
+ const old = request.runDirectory;
21091
+ if (old === newRunDirectory) return;
21092
+ request.runDirectory = newRunDirectory;
21093
+ rewritePrincipalSessionPaths(
21094
+ request.principal,
21095
+ old,
21096
+ newRunDirectory
21097
+ );
21098
+ }
20846
21099
  function rewriteRunDirectoryPathFieldsAgainstRewrites(record, fields, rewrites) {
20847
21100
  for (const field of fields) {
20848
21101
  if (field in record) {
@@ -20867,12 +21120,12 @@ function rewriteAdmittedRoleRunPage(page, rewrites) {
20867
21120
  if (isRecord(page.principal)) {
20868
21121
  rewriteRunDirectoryPathFieldsAgainstRewrites(
20869
21122
  page.principal,
20870
- ["sessionDirectory", "sessionFile"],
21123
+ PRINCIPAL_SESSION_PATH_FIELDS,
20871
21124
  rewrites
20872
21125
  );
20873
21126
  }
20874
21127
  }
20875
- var ADMITTED_PAGE_FIELDS, SOURCE_RUN_LOCATOR_FIELDS;
21128
+ var ADMITTED_PAGE_FIELDS, PRINCIPAL_SESSION_PATH_FIELDS, SOURCE_RUN_LOCATOR_FIELDS;
20876
21129
  var init_role_run_relocation = __esm({
20877
21130
  "src/role-run-relocation.ts"() {
20878
21131
  "use strict";
@@ -20894,6 +21147,10 @@ var init_role_run_relocation = __esm({
20894
21147
  "mergerInputPath",
20895
21148
  "sourceRunPath"
20896
21149
  ];
21150
+ PRINCIPAL_SESSION_PATH_FIELDS = [
21151
+ "sessionDirectory",
21152
+ "sessionFile"
21153
+ ];
20897
21154
  SOURCE_RUN_LOCATOR_FIELDS = ["runDirectory"];
20898
21155
  }
20899
21156
  });
@@ -20924,7 +21181,7 @@ __export(run_lifecycle_exports, {
20924
21181
  writeRoleRunState: () => writeRoleRunState
20925
21182
  });
20926
21183
  import { chmod, lstat as lstat3, open, readdir as readdir3, readFile as readFile10, unlink } from "node:fs/promises";
20927
- import { basename as basename10, join as join24 } from "node:path";
21184
+ import { basename as basename11, join as join24 } from "node:path";
20928
21185
  function buildAutoResumeContinuationPrompt() {
20929
21186
  return RESUME_TRANSPORT_ENVELOPE;
20930
21187
  }
@@ -21371,7 +21628,7 @@ async function findLatestRunIdForSeatTicket(input) {
21371
21628
  }
21372
21629
  let best;
21373
21630
  for (const runDirectory of runDirectories) {
21374
- const parsed = parseRunLeaf(basename10(runDirectory));
21631
+ const parsed = parseRunLeaf(basename11(runDirectory));
21375
21632
  if (parsed === void 0 || parsed.role !== input.role) continue;
21376
21633
  const runId = parsed.runId;
21377
21634
  const parentPath = await readRunParentPath(runDirectory);
@@ -21566,7 +21823,7 @@ async function loadResumableRunRecord(home, runId, authority) {
21566
21823
  );
21567
21824
  }
21568
21825
  }
21569
- const sourceRunLeaf = parseRunLeaf(basename10(sourceRunPath ?? ""));
21826
+ const sourceRunLeaf = parseRunLeaf(basename11(sourceRunPath ?? ""));
21570
21827
  const referencedRunId = sourceRun?.runId ?? sourceRunLeaf?.runId;
21571
21828
  const referencedRole = sourceRun?.role ?? sourceRunLeaf?.role;
21572
21829
  if (referencedRunId !== void 0 && referencedRunId !== "") {
@@ -21883,6 +22140,7 @@ var init_run_lifecycle = __esm({
21883
22140
 
21884
22141
  // src/public-cli/post-admission.ts
21885
22142
  import { randomUUID as randomUUID5 } from "node:crypto";
22143
+ import { existsSync as existsSync11 } from "node:fs";
21886
22144
  function describeCaughtError(error) {
21887
22145
  if (error instanceof Error) {
21888
22146
  const code = error.code;
@@ -21915,6 +22173,91 @@ function projectRelocatedTurnIdentity(request, result, admitted, relocation) {
21915
22173
  }
21916
22174
  }
21917
22175
  }
22176
+ async function refreshAdmittedPlacementAfterHostTurn(admitted, authority, heldLease) {
22177
+ const home = homeFromRunDirectory(admitted.runDirectory);
22178
+ const found = await findRunDirectoryById(home, admitted.runId, admitted.bookKey, admitted.role);
22179
+ if (found === void 0 && !existsSync11(admitted.runDirectory)) {
22180
+ throw new Error(
22181
+ `admitted run ${admitted.runId} missing after host turn; not found under ${home}`
22182
+ );
22183
+ }
22184
+ let relocation;
22185
+ if (found !== void 0 && found !== admitted.runDirectory) {
22186
+ const oldRunDirectory = admitted.runDirectory;
22187
+ const coords = { ...authority.decode(admitted.principal) };
22188
+ rewritePrincipalSessionPaths(
22189
+ coords,
22190
+ oldRunDirectory,
22191
+ found
22192
+ );
22193
+ const principal = authority.seal(coords);
22194
+ rewriteAdmittedRoleRunPage(
22195
+ admitted,
22196
+ [{ oldRunDirectory, newRunDirectory: found }]
22197
+ );
22198
+ admitted.principal = principal;
22199
+ heldLease?.relocate(found);
22200
+ relocation = { oldRunDirectory, newRunDirectory: found };
22201
+ }
22202
+ if (admitted.ticketNumber === void 0) {
22203
+ const boardTicket = await readBoardTicketNumber(found ?? admitted.runDirectory);
22204
+ if (boardTicket !== void 0) {
22205
+ admitted.ticketNumber = boardTicket;
22206
+ }
22207
+ }
22208
+ return relocation;
22209
+ }
22210
+ function applyRefreshedPlacementToTurn(request, turnRequest, admitted, refreshed) {
22211
+ projectRelocatedTurnIdentity(request, {}, admitted, refreshed);
22212
+ return {
22213
+ ...turnRequest,
22214
+ runDirectory: admitted.runDirectory,
22215
+ principal: admitted.principal
22216
+ };
22217
+ }
22218
+ async function settleHostThrowAfterLivePlacementRefresh(input) {
22219
+ let refreshError;
22220
+ let turnRequest = input.turnRequest;
22221
+ try {
22222
+ const refreshed = await refreshAdmittedPlacementAfterHostTurn(
22223
+ input.admitted,
22224
+ input.env.principalAuthority,
22225
+ input.lease
22226
+ );
22227
+ if (refreshed !== void 0) {
22228
+ turnRequest = applyRefreshedPlacementToTurn(
22229
+ input.request,
22230
+ turnRequest,
22231
+ input.admitted,
22232
+ refreshed
22233
+ );
22234
+ }
22235
+ } catch (err) {
22236
+ refreshError = err;
22237
+ }
22238
+ const processCancelName = processCancelSignalName(input.env.signal);
22239
+ const hostThrowSecondary = refreshError !== void 0 && input.hostTurnCompleted === false ? { knownDetails: { hostThrow: describeCaughtError(input.hostError) } } : {};
22240
+ const settled = await settleAfterTurnStarted(
22241
+ input.admitted,
22242
+ withEngineDetourInvocationScope({
22243
+ timedOut: false,
22244
+ code: null,
22245
+ stderr: "",
22246
+ // Prefer the refresh failure when the live path is gone; otherwise the
22247
+ // host throw remains the cause (失败诚实:不在旧 unbound 上结算写回).
22248
+ ...processCancelName === void 0 ? {} : { cancelName: processCancelName },
22249
+ thrown: refreshError ?? input.hostError,
22250
+ ...hostThrowSecondary
22251
+ }, input.request.invocationScopeId),
22252
+ input.adapters,
22253
+ input.env.principalAuthority,
22254
+ input.io,
22255
+ input.persistRunState,
22256
+ input.notePackageFault,
22257
+ input.courtAttemptId
22258
+ );
22259
+ return { settled, turnRequest };
22260
+ }
21918
22261
  function withProcessCancelSkipAutoResume(result, signal) {
21919
22262
  if (processCancelSignalName(signal) === void 0) {
21920
22263
  return result;
@@ -22301,6 +22644,12 @@ async function dispatchPostAdmissionTurn(input) {
22301
22644
  }
22302
22645
  if (pendingSettlement !== void 0 && pendingTerminal !== void 0 && result.terminal === pendingTerminal) {
22303
22646
  try {
22647
+ const softTicketReaskNoSeal = pendingSettlement !== "sealed" && env.softTicketReaskTurn === true;
22648
+ const noSealScope = softTicketReaskNoSeal ? {
22649
+ ...courtScope,
22650
+ previewOnly: true,
22651
+ recordAttemptHistory: true
22652
+ } : { ...courtScope, recordAttemptHistory: true };
22304
22653
  const terminal = pendingSettlement === "sealed" ? await adapters.trySettle(
22305
22654
  admitted,
22306
22655
  env.principalAuthority,
@@ -22310,13 +22659,16 @@ async function dispatchPostAdmissionTurn(input) {
22310
22659
  await settleHostEndedNoReceipt(
22311
22660
  admitted,
22312
22661
  env.principalAuthority,
22313
- { ...courtScope, recordAttemptHistory: true },
22662
+ noSealScope,
22314
22663
  receiptDelivery.issuedDeliveryRequests()
22315
22664
  ),
22316
- courtScope
22665
+ noSealScope
22317
22666
  );
22318
22667
  if (terminal === void 0) throw new Error("settled host attempt vanished before publication");
22319
22668
  result = { ...result, terminal, exitCode: exitCodeForTerminalOutcome(terminal.roleOutcome) };
22669
+ if (pendingSettlement === "sealed" && env.softTicketReaskTurn === true && env.softTicketReaskOwnership !== void 0) {
22670
+ env.softTicketReaskOwnership.sealedSubstitute = true;
22671
+ }
22320
22672
  if (pendingSettlement === "sealed" && terminal.roleOutcome.kind === "accepted" && request.courtAttemptId !== void 0 && request.courtAttemptId.length > 0) {
22321
22673
  try {
22322
22674
  await clearCurrentCourt(admitted.runDirectory, request.courtAttemptId);
@@ -22426,32 +22778,38 @@ async function dispatchPostAdmissionTurn(input) {
22426
22778
  env.engineModel
22427
22779
  );
22428
22780
  let result;
22781
+ let hostTurnCompleted = false;
22429
22782
  try {
22430
22783
  turnDispatched = true;
22431
22784
  result = await env.roleTurnHost.executeTurn(turnRequest);
22785
+ hostTurnCompleted = true;
22786
+ const refreshed = await refreshAdmittedPlacementAfterHostTurn(
22787
+ admitted,
22788
+ env.principalAuthority,
22789
+ lease
22790
+ );
22791
+ if (refreshed !== void 0) {
22792
+ turnRequest = applyRefreshedPlacementToTurn(request, turnRequest, admitted, refreshed);
22793
+ }
22432
22794
  } catch (error) {
22433
- const processCancelName = processCancelSignalName(env.signal);
22434
- const settled = await settleAfterTurnStarted(
22795
+ const thrown = await settleHostThrowAfterLivePlacementRefresh({
22435
22796
  admitted,
22436
- withEngineDetourInvocationScope({
22437
- timedOut: false,
22438
- code: null,
22439
- stderr: "",
22440
- // The thrown value is the host's report. A cancel received on this
22441
- // call is a second fact; it must not become a new Error in its place.
22442
- ...processCancelName === void 0 ? {} : { cancelName: processCancelName },
22443
- thrown: error
22444
- }, request.invocationScopeId),
22797
+ hostError: error,
22798
+ hostTurnCompleted,
22799
+ request,
22800
+ turnRequest,
22801
+ lease,
22445
22802
  adapters,
22446
- env.principalAuthority,
22803
+ env,
22447
22804
  io,
22448
22805
  persistRunState,
22449
- courtScope.notePackageFault,
22450
- courtScope.courtAttemptId
22451
- );
22806
+ notePackageFault: courtScope.notePackageFault,
22807
+ ...courtScope.courtAttemptId === void 0 ? {} : { courtAttemptId: courtScope.courtAttemptId }
22808
+ });
22809
+ turnRequest = thrown.turnRequest;
22452
22810
  return await finishAfterTurn(
22453
22811
  withProcessCancelSkipAutoResume(
22454
- { ...settled, turnDispatched: true, ...deferredPersist },
22812
+ { ...thrown.settled, turnDispatched: true, ...deferredPersist },
22455
22813
  env.signal
22456
22814
  )
22457
22815
  );
@@ -22477,6 +22835,7 @@ async function dispatchPostAdmissionTurn(input) {
22477
22835
  while (akSeamDeliversReceipt && receiptDelivery.nextAction() === "request-delivery") {
22478
22836
  let deliveryResult;
22479
22837
  let deliveryTurnRequest;
22838
+ let deliveryHostTurnCompleted = false;
22480
22839
  try {
22481
22840
  const deliveryRequest = buildReceiptDeliveryRequest({
22482
22841
  request: turnRequest,
@@ -22490,24 +22849,40 @@ async function dispatchPostAdmissionTurn(input) {
22490
22849
  };
22491
22850
  receiptDelivery.recordDeliveryRequest();
22492
22851
  deliveryResult = await env.roleTurnHost.executeTurn(deliveryTurnRequest);
22852
+ deliveryHostTurnCompleted = true;
22853
+ const refreshed = await refreshAdmittedPlacementAfterHostTurn(
22854
+ admitted,
22855
+ env.principalAuthority,
22856
+ lease
22857
+ );
22858
+ if (refreshed !== void 0) {
22859
+ turnRequest = applyRefreshedPlacementToTurn(request, turnRequest, admitted, refreshed);
22860
+ deliveryTurnRequest = {
22861
+ ...deliveryTurnRequest,
22862
+ runDirectory: admitted.runDirectory,
22863
+ principal: admitted.principal
22864
+ };
22865
+ }
22493
22866
  } catch (error) {
22494
- const settled = await settleAfterTurnStarted(
22867
+ const thrown = await settleHostThrowAfterLivePlacementRefresh({
22495
22868
  admitted,
22496
- withEngineDetourInvocationScope(
22497
- { timedOut: false, code: null, stderr: "", thrown: error },
22498
- request.invocationScopeId
22499
- ),
22869
+ hostError: error,
22870
+ hostTurnCompleted: deliveryHostTurnCompleted,
22871
+ request,
22872
+ turnRequest,
22873
+ lease,
22500
22874
  adapters,
22501
- env.principalAuthority,
22875
+ env,
22502
22876
  io,
22503
22877
  persistRunState,
22504
- courtScope.notePackageFault,
22505
- courtScope.courtAttemptId
22506
- );
22878
+ notePackageFault: courtScope.notePackageFault,
22879
+ ...courtScope.courtAttemptId === void 0 ? {} : { courtAttemptId: courtScope.courtAttemptId }
22880
+ });
22881
+ turnRequest = thrown.turnRequest;
22507
22882
  return await finishAfterTurn(
22508
22883
  withProcessCancelSkipAutoResume(
22509
22884
  {
22510
- ...settled,
22885
+ ...thrown.settled,
22511
22886
  turnDispatched: true,
22512
22887
  ...deferredPersist
22513
22888
  },
@@ -23023,6 +23398,7 @@ var init_post_admission = __esm({
23023
23398
  init_invocation();
23024
23399
  init_submission_ledger();
23025
23400
  init_run_ticket_number();
23401
+ init_activation_ledger_topology();
23026
23402
  init_session_identity();
23027
23403
  init_sitian_facade();
23028
23404
  init_receipt_delivery_policy();
@@ -29586,7 +29962,7 @@ var init_analyst_gate_cycles_read = __esm({
29586
29962
 
29587
29963
  // src/analyst-ledger.ts
29588
29964
  import { readdir as readdir4 } from "node:fs/promises";
29589
- import { basename as basename11, join as join27 } from "node:path";
29965
+ import { basename as basename12, join as join27 } from "node:path";
29590
29966
  async function readExistingRunLifecycleState(runDirectory) {
29591
29967
  return (await readRoleRunIdentity(runDirectory))?.state;
29592
29968
  }
@@ -29938,7 +30314,7 @@ async function scanAnalystIssueRuns(input) {
29938
30314
  throw error;
29939
30315
  }
29940
30316
  for (const runDirectory of runDirectories) {
29941
- const runName = basename11(runDirectory);
30317
+ const runName = basename12(runDirectory);
29942
30318
  const parsed = parseRunLeaf(runName);
29943
30319
  if (parsed === void 0) continue;
29944
30320
  let scopeFields;
@@ -32221,7 +32597,7 @@ var init_cli = __esm({
32221
32597
  });
32222
32598
 
32223
32599
  // src/public-cli/main.ts
32224
- import { existsSync as existsSync9 } from "node:fs";
32600
+ import { existsSync as existsSync12 } from "node:fs";
32225
32601
  import { dirname as dirname19, join as join29 } from "node:path";
32226
32602
  import { fileURLToPath as fileURLToPath2 } from "node:url";
32227
32603
 
@@ -32312,7 +32688,7 @@ function linkPackage(packageRoot2, name, targetDir) {
32312
32688
  var here = dirname19(fileURLToPath2(import.meta.url));
32313
32689
  function resolvePackageRoot(binDir) {
32314
32690
  const canonical = join29(binDir, "..", "..");
32315
- if (existsSync9(join29(canonical, "package.json"))) {
32691
+ if (existsSync12(join29(canonical, "package.json"))) {
32316
32692
  return canonical;
32317
32693
  }
32318
32694
  return binDir;