@akagilnc/pi-workflow-roles 0.1.4363 → 0.1.4387

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 (43) hide show
  1. package/README.md +4 -1
  2. package/README.zh-CN.md +5 -1
  3. package/dist/acp-host/production-host.js +1262 -523
  4. package/dist/engine-detour-tool.js +2 -8
  5. package/dist/gatekeeper-role.js +4 -19
  6. package/dist/headless-host/production-host.js +2538 -1799
  7. package/dist/migrate-book-topology.js +21 -1
  8. package/dist/package-contracts/terminating-tools.js +6 -0
  9. package/dist/packaged-role-registry.js +20 -1
  10. package/dist/public-cli/countersign-run.js +439 -0
  11. package/dist/public-cli/invocation.js +10 -0
  12. package/dist/public-cli/main.js +317 -12
  13. package/dist/public-cli/option-definitions.js +14 -0
  14. package/dist/public-cli/post-admission.js +3 -8
  15. package/dist/public-cli/run-lifecycle.js +13 -1
  16. package/dist/public-cli/settlement.js +11 -0
  17. package/dist/public-role-summons.js +14 -0
  18. package/dist/secretariat-contracts.js +8 -0
  19. package/extensions/role-runtime.ts +1 -0
  20. package/package.json +1 -1
  21. package/scripts/build-package.mjs +1 -0
  22. package/souls/secretariat.md +26 -0
  23. package/souls/ticket-law.md +9 -0
  24. package/src/engine-detour-tool.ts +3 -9
  25. package/src/gatekeeper-pass-envelope.ts +35 -2
  26. package/src/gatekeeper-role.ts +8 -31
  27. package/src/host-contracts.ts +2 -1
  28. package/src/package-contracts/terminating-tools.ts +9 -1
  29. package/src/packaged-role-registry.ts +20 -1
  30. package/src/public-cli/cli.ts +10 -0
  31. package/src/public-cli/countersign-run.ts +29 -5
  32. package/src/public-cli/invocation.ts +28 -2
  33. package/src/public-cli/option-definitions.ts +17 -0
  34. package/src/public-cli/post-admission.ts +3 -8
  35. package/src/public-cli/run-lifecycle.ts +29 -2
  36. package/src/public-cli/secretariat-run.ts +266 -0
  37. package/src/public-cli/settlement.ts +28 -2
  38. package/src/public-cli/terminal.ts +2 -1
  39. package/src/public-role-summons.ts +23 -1
  40. package/src/role-runtime-dependencies.ts +1 -0
  41. package/src/role-runtime.ts +203 -18
  42. package/src/secretariat-contracts.ts +27 -0
  43. package/src/secretariat-role.ts +210 -0
@@ -1354,9 +1354,268 @@ var init_gatekeeper_output = __esm({
1354
1354
  }
1355
1355
  });
1356
1356
 
1357
+ // src/gatekeeper-role.ts
1358
+ function gateSeatLabel(stage) {
1359
+ if (stage === "inspector") return "\u53F0\u9662";
1360
+ if (stage === "auditor") return "\u5BA1\u5211\u9662";
1361
+ return "\u7B26\u5B9D\u90CE";
1362
+ }
1363
+ function gateOfficerForSubject(subject) {
1364
+ if (subject.kind === "worker_completion") return "inspector";
1365
+ if (subject.kind === "judge_compliance") return "auditor";
1366
+ return "notary";
1367
+ }
1368
+ function failureReason(error) {
1369
+ if (error instanceof AggregateError) return error.errors.map(failureReason).join("; ");
1370
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
1371
+ }
1372
+ function retainedReceipt(decision) {
1373
+ return decision;
1374
+ }
1375
+ function readRecord(value) {
1376
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
1377
+ return value;
1378
+ }
1379
+ function projectOfficerDecision(officer, decision, fallbackStatus) {
1380
+ const receipt = retainedReceipt(decision);
1381
+ const record4 = readRecord(decision);
1382
+ const status = (record4 !== void 0 && typeof record4.status === "string" ? record4.status : void 0) ?? fallbackStatus;
1383
+ if (status === "pass") {
1384
+ return { status: "pass", officer, receipt };
1385
+ }
1386
+ if (status === "bounce" || status === "escalate") {
1387
+ return { status, officer, receipt };
1388
+ }
1389
+ return { status: "needs_reask", officer, receipt };
1390
+ }
1391
+ function thisCourtOfficerPayloads(terminal) {
1392
+ const outcome = terminal?.roleOutcome;
1393
+ if (outcome !== void 0 && (outcome.kind === "accepted" || outcome.kind === "audit_escalation")) {
1394
+ if (outcome.payloads !== void 0 && outcome.payloads.length > 0) return outcome.payloads;
1395
+ }
1396
+ if (outcome?.kind === "failure" && outcome.payloads !== void 0 && outcome.payloads.length > 0) {
1397
+ return outcome.payloads;
1398
+ }
1399
+ return [];
1400
+ }
1401
+ function officerFailurePayloads(terminal) {
1402
+ const outcome = terminal?.roleOutcome;
1403
+ if (outcome?.kind === "failure") return outcome.payloads ?? terminal?.submissions ?? [];
1404
+ return terminal?.submissions ?? [];
1405
+ }
1406
+ function projectOfficerPayloads(officer, payloads, fallbackStatus) {
1407
+ if (payloads.length === 0) {
1408
+ return projectOfficerDecision(officer, void 0, fallbackStatus);
1409
+ }
1410
+ return projectOfficerDecision(officer, payloads[payloads.length - 1], fallbackStatus);
1411
+ }
1412
+ function projectOfficerTerminal(officer, summoned) {
1413
+ const terminal = summoned.terminal;
1414
+ const outcome = terminal?.roleOutcome;
1415
+ const thisCourt = thisCourtOfficerPayloads(terminal);
1416
+ if (outcome === void 0) {
1417
+ const detail = summoned.stderr ?? "";
1418
+ const failurePayloads = officerFailurePayloads(terminal);
1419
+ return {
1420
+ status: "transport_failure",
1421
+ stage: officer,
1422
+ reason: detail.length > 0 ? `${gateSeatLabel(officer)} public summon exit ${summoned.exitCode}: ${detail}` : `${gateSeatLabel(officer)} public summon produced no terminal (exit ${summoned.exitCode})`,
1423
+ submission: failurePayloads.length > 0 ? failurePayloads : summoned
1424
+ };
1425
+ }
1426
+ if (outcome.kind === "no_receipt") {
1427
+ return {
1428
+ status: "no_receipt",
1429
+ stage: officer,
1430
+ reason: typeof outcome.status === "string" && outcome.status.length > 0 ? outcome.status : "no_receipt",
1431
+ facts: outcome
1432
+ };
1433
+ }
1434
+ if (outcome.kind === "failure") {
1435
+ const failurePayloads = officerFailurePayloads(terminal);
1436
+ return {
1437
+ status: "transport_failure",
1438
+ stage: officer,
1439
+ reason: outcome.diagnostic,
1440
+ submission: failurePayloads.length > 0 ? failurePayloads : outcome.decisiveFacts
1441
+ };
1442
+ }
1443
+ if (outcome.kind === "audit_escalation") {
1444
+ return {
1445
+ status: "escalate",
1446
+ officer,
1447
+ // This-court receipt only (#879) — historical rows remain on terminal.submissions.
1448
+ receipt: thisCourt.length > 0 ? thisCourt[thisCourt.length - 1] : retainedReceipt(outcome)
1449
+ };
1450
+ }
1451
+ if (outcome.kind === "accepted") {
1452
+ return projectOfficerPayloads(officer, thisCourt, outcome.status);
1453
+ }
1454
+ return {
1455
+ status: "needs_reask",
1456
+ officer,
1457
+ // This-court receipt only (#879).
1458
+ receipt: thisCourt.length > 0 ? thisCourt[thisCourt.length - 1] : retainedReceipt(outcome)
1459
+ };
1460
+ }
1461
+ async function projectGatekeeperRun(options) {
1462
+ const officer = gateOfficerForSubject(options.subject);
1463
+ const runDirectory = options.runDirectory ?? auditorRunDirectory(options.context);
1464
+ if (runDirectory === void 0) {
1465
+ return {
1466
+ officer,
1467
+ result: {
1468
+ status: "transport_failure",
1469
+ stage: officer,
1470
+ reason: `${gateSeatLabel(officer)} requires a parent run directory pointer`
1471
+ }
1472
+ };
1473
+ }
1474
+ let summoned;
1475
+ try {
1476
+ summoned = await options.summonOfficer(
1477
+ officer,
1478
+ runDirectory,
1479
+ options.signal,
1480
+ options.reask,
1481
+ options.submission
1482
+ );
1483
+ } catch (error) {
1484
+ return {
1485
+ officer,
1486
+ result: { status: "transport_failure", stage: officer, reason: failureReason(error) }
1487
+ };
1488
+ }
1489
+ return {
1490
+ officer,
1491
+ result: projectOfficerTerminal(officer, summoned),
1492
+ summoned
1493
+ };
1494
+ }
1495
+ var GATEKEEPER_TOOL_SPEC, OFFICER_CONCLUSION_REASK;
1496
+ var init_gatekeeper_role = __esm({
1497
+ "src/gatekeeper-role.ts"() {
1498
+ "use strict";
1499
+ init_auditor_dossier_tool();
1500
+ init_submission_errors();
1501
+ init_inspector_contracts();
1502
+ init_gatekeeper_output();
1503
+ init_submission_errors();
1504
+ GATEKEEPER_TOOL_SPEC = {
1505
+ name: GATEKEEPER_OUTPUT_TOOL_NAME,
1506
+ label: "\u95E8\u4E0B\u7701\u51B3\u8BAE",
1507
+ description: "\u95E8\u4E0B\u7701\u7EC8\u5C40\u51B3\u8BAE\uFF0C\u72B6\u6001\u4E3A dispatch \u6216 pass\u3002",
1508
+ promptSnippet: "\u95E8\u4E0B\u7701\u51B3\u8BAE",
1509
+ parameters: gatekeeperOutputSchema
1510
+ };
1511
+ OFFICER_CONCLUSION_REASK = "\u4E0A\u6B21\u4EA4\u5377\u7684\u7ED3\u8BBA\u4E0D\u662F pass\u3001bounce\u3001escalate \u4E09\u6001\u4E4B\u4E00\u3002\u8BF7\u91CD\u65B0\u8F93\u51FA\uFF0C\u7ED3\u8BBA\u5B57\u6BB5\u5199\u660E\u5176\u4E00\uFF1B\u6253\u56DE\u6216\u4E0A\u5448\u7684\u8BDD\u5C31\u662F\u7ED9\u5BF9\u65B9\u770B\u7684\u539F\u6587\u3002";
1512
+ }
1513
+ });
1514
+
1515
+ // src/session-assistant-usage.ts
1516
+ var session_assistant_usage_exports = {};
1517
+ __export(session_assistant_usage_exports, {
1518
+ readAssistantUsageFromSessionFile: () => readAssistantUsageFromSessionFile,
1519
+ sessionFileFromPublicSummon: () => sessionFileFromPublicSummon,
1520
+ usageFromPublicSummon: () => usageFromPublicSummon
1521
+ });
1522
+ import { join as join8 } from "node:path";
1523
+ async function readAssistantUsageFromSessionFile(sessionFile) {
1524
+ const { readFile: readFile25 } = await import("node:fs/promises");
1525
+ let text;
1526
+ try {
1527
+ text = await readFile25(sessionFile, "utf8");
1528
+ } catch (error) {
1529
+ if (error?.code === "ENOENT") return void 0;
1530
+ throw error;
1531
+ }
1532
+ let rows;
1533
+ try {
1534
+ rows = text.trim().split("\n").filter(Boolean).map((line2) => JSON.parse(line2));
1535
+ } catch (error) {
1536
+ throw new Error(
1537
+ `session usage parse failed (${sessionFile}): ${error instanceof Error ? error.message : String(error)}`,
1538
+ { cause: error }
1539
+ );
1540
+ }
1541
+ let total = 0;
1542
+ let input = 0;
1543
+ let output = 0;
1544
+ let cacheRead = 0;
1545
+ let cacheWrite = 0;
1546
+ let costInput = 0;
1547
+ let costOutput = 0;
1548
+ let costCacheRead = 0;
1549
+ let costCacheWrite = 0;
1550
+ let costTotal = 0;
1551
+ let sawCost = false;
1552
+ for (const row of rows) {
1553
+ if (row.type !== "message" || row.message?.role !== "assistant") continue;
1554
+ const usage = row.message.usage;
1555
+ if (usage === void 0) continue;
1556
+ total += usage.totalTokens ?? 0;
1557
+ input += usage.input ?? 0;
1558
+ output += usage.output ?? 0;
1559
+ cacheRead += usage.cacheRead ?? 0;
1560
+ cacheWrite += usage.cacheWrite ?? 0;
1561
+ if (usage.cost !== void 0) {
1562
+ sawCost = true;
1563
+ costInput += usage.cost.input ?? 0;
1564
+ costOutput += usage.cost.output ?? 0;
1565
+ costCacheRead += usage.cost.cacheRead ?? 0;
1566
+ costCacheWrite += usage.cost.cacheWrite ?? 0;
1567
+ costTotal += usage.cost.total ?? 0;
1568
+ }
1569
+ }
1570
+ if (total <= 0 && input <= 0 && output <= 0) return void 0;
1571
+ const base = {
1572
+ input,
1573
+ output,
1574
+ cacheRead,
1575
+ cacheWrite,
1576
+ totalTokens: total > 0 ? total : input + output + cacheRead + cacheWrite
1577
+ };
1578
+ if (!sawCost) return base;
1579
+ return {
1580
+ ...base,
1581
+ cost: {
1582
+ input: costInput,
1583
+ output: costOutput,
1584
+ cacheRead: costCacheRead,
1585
+ cacheWrite: costCacheWrite,
1586
+ total: costTotal
1587
+ }
1588
+ };
1589
+ }
1590
+ function sessionFileFromPublicSummon(summoned) {
1591
+ if (typeof summoned.runDirectory === "string" && summoned.runDirectory.trim() !== "") {
1592
+ return join8(summoned.runDirectory, "session", "session.jsonl");
1593
+ }
1594
+ const fromArtifacts = summoned.terminal?.artifacts?.map((a) => a.path).find((p) => typeof p === "string" && p.endsWith("session.jsonl"));
1595
+ if (fromArtifacts !== void 0) return fromArtifacts;
1596
+ const outcome = summoned.terminal?.roleOutcome;
1597
+ if (outcome === void 0) return void 0;
1598
+ const facts = outcome.decisiveFacts;
1599
+ const pointer = facts?.runPointer;
1600
+ if (typeof pointer === "string" && pointer.trim() !== "") {
1601
+ return join8(pointer, "session", "session.jsonl");
1602
+ }
1603
+ return void 0;
1604
+ }
1605
+ async function usageFromPublicSummon(summoned) {
1606
+ const sessionFile = sessionFileFromPublicSummon(summoned);
1607
+ if (sessionFile === void 0) return void 0;
1608
+ return readAssistantUsageFromSessionFile(sessionFile);
1609
+ }
1610
+ var init_session_assistant_usage = __esm({
1611
+ "src/session-assistant-usage.ts"() {
1612
+ "use strict";
1613
+ }
1614
+ });
1615
+
1357
1616
  // src/package-resources/engine-material.ts
1358
1617
  import { existsSync as existsSync2, readdirSync as readdirSync2 } from "node:fs";
1359
- import { join as join8 } from "node:path";
1618
+ import { join as join9 } from "node:path";
1360
1619
  function pickEngineAxis(source) {
1361
1620
  return {
1362
1621
  ...source.engine === void 0 ? {} : { engine: source.engine },
@@ -1377,11 +1636,11 @@ function isEngineNameSyntax(name) {
1377
1636
  return true;
1378
1637
  }
1379
1638
  function resolveEngineMaterialDirectory(packageRoot) {
1380
- return join8(packageRoot, ENGINE_MATERIAL_RELATIVE_ROOT);
1639
+ return join9(packageRoot, ENGINE_MATERIAL_RELATIVE_ROOT);
1381
1640
  }
1382
1641
  function resolveEngineMaterialPath(packageRoot, name) {
1383
1642
  const legal = assertLegalEngineName(name);
1384
- return join8(resolveEngineMaterialDirectory(packageRoot), `${legal}.md`);
1643
+ return join9(resolveEngineMaterialDirectory(packageRoot), `${legal}.md`);
1385
1644
  }
1386
1645
  function assertLegalEngineName(name) {
1387
1646
  if (!isEngineNameSyntax(name)) {
@@ -1439,7 +1698,7 @@ __export(durable_principal_exports, {
1439
1698
  piDurablePrincipalAuthority: () => piDurablePrincipalAuthority
1440
1699
  });
1441
1700
  import { lstat } from "node:fs/promises";
1442
- import { join as join9 } from "node:path";
1701
+ import { join as join10 } from "node:path";
1443
1702
  function encode(coordinates) {
1444
1703
  return coordinates;
1445
1704
  }
@@ -1489,7 +1748,7 @@ var init_durable_principal = __esm({
1489
1748
  }
1490
1749
  return {
1491
1750
  sessionDirectory: record4.sessionDirectory,
1492
- sessionFile: typeof record4.sessionFile === "string" && record4.sessionFile.trim() !== "" ? record4.sessionFile : join9(record4.sessionDirectory, "session.jsonl")
1751
+ sessionFile: typeof record4.sessionFile === "string" && record4.sessionFile.trim() !== "" ? record4.sessionFile : join10(record4.sessionDirectory, "session.jsonl")
1493
1752
  };
1494
1753
  },
1495
1754
  async isAvailable(principal) {
@@ -2259,6 +2518,17 @@ var init_diarist_contracts = __esm({
2259
2518
  }
2260
2519
  });
2261
2520
 
2521
+ // src/secretariat-contracts.ts
2522
+ var SECRETARIAT_OUTPUT_TOOL_NAME, SECRETARIAT_SUMMON_COUNTERSIGN_TOOL_NAME, SECRETARIAT_ACCEPTED_TEXT;
2523
+ var init_secretariat_contracts = __esm({
2524
+ "src/secretariat-contracts.ts"() {
2525
+ "use strict";
2526
+ SECRETARIAT_OUTPUT_TOOL_NAME = "ak_secretariat_output";
2527
+ SECRETARIAT_SUMMON_COUNTERSIGN_TOOL_NAME = "ak_secretariat_summon_countersign";
2528
+ SECRETARIAT_ACCEPTED_TEXT = "\u4E2D\u4E66\u7701\u56DE\u6267\u5DF2\u63A5\u53D7";
2529
+ }
2530
+ });
2531
+
2262
2532
  // src/packaged-role-registry.ts
2263
2533
  function packagedRoleMetadata(role) {
2264
2534
  return PACKAGED_ROLE_REGISTRY.find((entry) => entry.role === role);
@@ -2290,10 +2560,12 @@ var init_packaged_role_registry = __esm({
2290
2560
  init_inspector_contracts();
2291
2561
  init_auditor_output();
2292
2562
  init_diarist_contracts();
2563
+ init_secretariat_contracts();
2293
2564
  NOTARY_SESSION_MATERIALS = [
2294
2565
  "CLAUDE.md",
2295
2566
  "souls/notary.md",
2296
2567
  "souls/audit-law.md",
2568
+ "souls/ticket-law.md",
2297
2569
  "souls/gate-output-guide.md"
2298
2570
  ];
2299
2571
  INSPECTOR_SESSION_MATERIALS = [
@@ -2416,7 +2688,24 @@ var init_packaged_role_registry = __esm({
2416
2688
  inputFlag: void 0,
2417
2689
  phaseFlag: void 0,
2418
2690
  activationStage: "load-and-install",
2419
- sessionMaterials: ["CLAUDE.md", "souls/countersign.md"]
2691
+ // #924: 公用《票面法》三席同装
2692
+ sessionMaterials: ["CLAUDE.md", "souls/countersign.md", "souls/ticket-law.md"]
2693
+ },
2694
+ {
2695
+ role: "secretariat",
2696
+ phases: [null],
2697
+ outputTool: SECRETARIAT_OUTPUT_TOOL_NAME,
2698
+ inputFlag: void 0,
2699
+ phaseFlag: void 0,
2700
+ activationStage: "load-and-install",
2701
+ // #924: owner-finalized Soul + 票面法 + 给事中/符宝郎行为指南
2702
+ sessionMaterials: [
2703
+ "CLAUDE.md",
2704
+ "souls/secretariat.md",
2705
+ "souls/ticket-law.md",
2706
+ "souls/countersign.md",
2707
+ "souls/notary.md"
2708
+ ]
2420
2709
  },
2421
2710
  {
2422
2711
  role: "gleaner-left",
@@ -2582,7 +2871,7 @@ import {
2582
2871
  unlinkSync,
2583
2872
  writeFileSync as writeFileSync2
2584
2873
  } from "node:fs";
2585
- import { dirname as dirname5, join as join10 } from "node:path";
2874
+ import { dirname as dirname5, join as join11 } from "node:path";
2586
2875
  function isRecord2(value) {
2587
2876
  return typeof value === "object" && value !== null && !Array.isArray(value);
2588
2877
  }
@@ -2710,8 +2999,8 @@ function resolveSitianVolumeCategory(kind) {
2710
2999
  return kind;
2711
3000
  }
2712
3001
  function ticketProvenanceUnderBookPaths(ledgerHome, bookKey, ticketId) {
2713
- const sessionDir = join10(activationBookDirectory(ledgerHome, bookKey), ticketId);
2714
- return { sessionDir, recordFile: join10(sessionDir, SITIAN_RECORDS_LEAF) };
3002
+ const sessionDir = join11(activationBookDirectory(ledgerHome, bookKey), ticketId);
3003
+ return { sessionDir, recordFile: join11(sessionDir, SITIAN_RECORDS_LEAF) };
2715
3004
  }
2716
3005
  function resolveSitianRecordPathInLedger(input, ledgerHome) {
2717
3006
  const category = resolveSitianVolumeCategory(input.kind);
@@ -2730,14 +3019,14 @@ function resolveSitianRecordPathInLedger(input, ledgerHome) {
2730
3019
  if (input.sessionParent === void 0 || input.sessionParent.length === 0 || !physicallyContainedIn(ledgerHome, input.sessionParent)) {
2731
3020
  throw new Error("Sitian record ownership requires a parent session inside the ledger home");
2732
3021
  }
2733
- sessionDir = join10(dirname5(input.sessionParent), category);
2734
- recordFile = join10(sessionDir, SITIAN_RECORDS_LEAF);
3022
+ sessionDir = join11(dirname5(input.sessionParent), category);
3023
+ recordFile = join11(sessionDir, SITIAN_RECORDS_LEAF);
2735
3024
  }
2736
3025
  return { sessionDir, recordFile, ledgerHome };
2737
3026
  }
2738
3027
  function projectTicketRecordsPathShape() {
2739
3028
  const { recordFile } = ticketProvenanceUnderBookPaths(
2740
- join10("~", ".ak-roles"),
3029
+ join11("~", ".ak-roles"),
2741
3030
  "<\u7C3F>",
2742
3031
  "<\u7968\u53F7>"
2743
3032
  );
@@ -2873,12 +3162,12 @@ __export(role_turn_host_exports, {
2873
3162
  import { execFile, spawn as spawn2 } from "node:child_process";
2874
3163
  import { constants } from "node:fs";
2875
3164
  import { access, appendFile, readFile as readFile3, realpath } from "node:fs/promises";
2876
- import { basename as basename3, delimiter, dirname as dirname6, isAbsolute as isAbsolute3, join as join11, resolve as resolve5 } from "node:path";
3165
+ import { basename as basename3, delimiter, dirname as dirname6, isAbsolute as isAbsolute3, join as join12, resolve as resolve5 } from "node:path";
2877
3166
  import { platform } from "node:process";
2878
3167
  import { promisify } from "node:util";
2879
3168
  import { randomUUID as randomUUID2 } from "node:crypto";
2880
3169
  function resolveInternalRoleEntrypoint(packageRoot) {
2881
- return join11(packageRoot, INTERNAL_ROLE_ENTRYPOINT_RELATIVE);
3170
+ return join12(packageRoot, INTERNAL_ROLE_ENTRYPOINT_RELATIVE);
2882
3171
  }
2883
3172
  function buildExplicitInternalActivationArgs(selectedRoleEntry, extraArgs = []) {
2884
3173
  return ["--no-extensions", "-e", selectedRoleEntry, ...extraArgs];
@@ -3269,155 +3558,54 @@ var init_host_descriptions = __esm({
3269
3558
  modelPassing: "set_model",
3270
3559
  boundResume: "session/load",
3271
3560
  sessionBindingFile: "hermes-acp-session.json",
3272
- childEnv: Object.freeze({}),
3273
- seatProfileSoul: Object.freeze({
3274
- flag: "-p",
3275
- namePrefix: "ak-",
3276
- profilesRootFromHome: Object.freeze([".hermes", "profiles"]),
3277
- soulFileName: "SOUL.md"
3278
- })
3279
- })
3280
- });
3281
- HEADLESS_HOST_DESCRIPTIONS = Object.freeze({
3282
- "claude": Object.freeze({
3283
- protocol: "claude-print",
3284
- binaryFromHome: Object.freeze([".local", "bin", "claude"]),
3285
- sessionBindingFile: "claude-headless-session.json",
3286
- fixedArgs: Object.freeze([
3287
- // Live NDJSON events → sitian host-session records (#811); last line is the result receipt.
3288
- "--output-format",
3289
- "stream-json",
3290
- // Intermediate assistant/tool/system events require verbose with stream-json.
3291
- "--verbose",
3292
- "--permission-mode",
3293
- "bypassPermissions",
3294
- // Empty sources: no user/project/local operator surface (envelope owns materials).
3295
- "--setting-sources",
3296
- "",
3297
- // With adapter-supplied --mcp-config only (AK relay); drops operator + claude.ai MCP.
3298
- "--strict-mcp-config"
3299
- ]),
3300
- promptFlag: "-p",
3301
- modelFlag: "--model",
3302
- effortFlag: "--effort",
3303
- // File path keeps large role envelopes off ARG_MAX.
3304
- systemPromptFlag: "--system-prompt-file",
3305
- jsonSchemaFlag: "--json-schema",
3306
- mcpConfigFlag: "--mcp-config",
3307
- sessionIdFlag: "--session-id",
3308
- resumeFlag: "--resume"
3309
- }),
3310
- /**
3311
- * Codex headless (#646). Binary under operator home; auth stays in CODEX_HOME.
3312
- * Argv/parse/schema-close are codex-exec helpers — not Claude flag mapping.
3313
- */
3314
- "codex": Object.freeze({
3315
- protocol: "codex-exec",
3316
- binaryFromHome: Object.freeze([".local", "bin", "codex"]),
3317
- sessionBindingFile: "codex-headless-session.json"
3318
- })
3319
- });
3320
- }
3321
- });
3322
-
3323
- // src/session-assistant-usage.ts
3324
- var session_assistant_usage_exports = {};
3325
- __export(session_assistant_usage_exports, {
3326
- readAssistantUsageFromSessionFile: () => readAssistantUsageFromSessionFile,
3327
- sessionFileFromPublicSummon: () => sessionFileFromPublicSummon,
3328
- usageFromPublicSummon: () => usageFromPublicSummon
3329
- });
3330
- import { join as join12 } from "node:path";
3331
- async function readAssistantUsageFromSessionFile(sessionFile) {
3332
- const { readFile: readFile25 } = await import("node:fs/promises");
3333
- let text;
3334
- try {
3335
- text = await readFile25(sessionFile, "utf8");
3336
- } catch (error) {
3337
- if (error?.code === "ENOENT") return void 0;
3338
- throw error;
3339
- }
3340
- let rows;
3341
- try {
3342
- rows = text.trim().split("\n").filter(Boolean).map((line2) => JSON.parse(line2));
3343
- } catch (error) {
3344
- throw new Error(
3345
- `session usage parse failed (${sessionFile}): ${error instanceof Error ? error.message : String(error)}`,
3346
- { cause: error }
3347
- );
3348
- }
3349
- let total = 0;
3350
- let input = 0;
3351
- let output = 0;
3352
- let cacheRead = 0;
3353
- let cacheWrite = 0;
3354
- let costInput = 0;
3355
- let costOutput = 0;
3356
- let costCacheRead = 0;
3357
- let costCacheWrite = 0;
3358
- let costTotal = 0;
3359
- let sawCost = false;
3360
- for (const row of rows) {
3361
- if (row.type !== "message" || row.message?.role !== "assistant") continue;
3362
- const usage = row.message.usage;
3363
- if (usage === void 0) continue;
3364
- total += usage.totalTokens ?? 0;
3365
- input += usage.input ?? 0;
3366
- output += usage.output ?? 0;
3367
- cacheRead += usage.cacheRead ?? 0;
3368
- cacheWrite += usage.cacheWrite ?? 0;
3369
- if (usage.cost !== void 0) {
3370
- sawCost = true;
3371
- costInput += usage.cost.input ?? 0;
3372
- costOutput += usage.cost.output ?? 0;
3373
- costCacheRead += usage.cost.cacheRead ?? 0;
3374
- costCacheWrite += usage.cost.cacheWrite ?? 0;
3375
- costTotal += usage.cost.total ?? 0;
3376
- }
3377
- }
3378
- if (total <= 0 && input <= 0 && output <= 0) return void 0;
3379
- const base = {
3380
- input,
3381
- output,
3382
- cacheRead,
3383
- cacheWrite,
3384
- totalTokens: total > 0 ? total : input + output + cacheRead + cacheWrite
3385
- };
3386
- if (!sawCost) return base;
3387
- return {
3388
- ...base,
3389
- cost: {
3390
- input: costInput,
3391
- output: costOutput,
3392
- cacheRead: costCacheRead,
3393
- cacheWrite: costCacheWrite,
3394
- total: costTotal
3395
- }
3396
- };
3397
- }
3398
- function sessionFileFromPublicSummon(summoned) {
3399
- if (typeof summoned.runDirectory === "string" && summoned.runDirectory.trim() !== "") {
3400
- return join12(summoned.runDirectory, "session", "session.jsonl");
3401
- }
3402
- const fromArtifacts = summoned.terminal?.artifacts?.map((a) => a.path).find((p) => typeof p === "string" && p.endsWith("session.jsonl"));
3403
- if (fromArtifacts !== void 0) return fromArtifacts;
3404
- const outcome = summoned.terminal?.roleOutcome;
3405
- if (outcome === void 0) return void 0;
3406
- const facts = outcome.decisiveFacts;
3407
- const pointer = facts?.runPointer;
3408
- if (typeof pointer === "string" && pointer.trim() !== "") {
3409
- return join12(pointer, "session", "session.jsonl");
3410
- }
3411
- return void 0;
3412
- }
3413
- async function usageFromPublicSummon(summoned) {
3414
- const sessionFile = sessionFileFromPublicSummon(summoned);
3415
- if (sessionFile === void 0) return void 0;
3416
- return readAssistantUsageFromSessionFile(sessionFile);
3417
- }
3418
- var init_session_assistant_usage = __esm({
3419
- "src/session-assistant-usage.ts"() {
3420
- "use strict";
3561
+ childEnv: Object.freeze({}),
3562
+ seatProfileSoul: Object.freeze({
3563
+ flag: "-p",
3564
+ namePrefix: "ak-",
3565
+ profilesRootFromHome: Object.freeze([".hermes", "profiles"]),
3566
+ soulFileName: "SOUL.md"
3567
+ })
3568
+ })
3569
+ });
3570
+ HEADLESS_HOST_DESCRIPTIONS = Object.freeze({
3571
+ "claude": Object.freeze({
3572
+ protocol: "claude-print",
3573
+ binaryFromHome: Object.freeze([".local", "bin", "claude"]),
3574
+ sessionBindingFile: "claude-headless-session.json",
3575
+ fixedArgs: Object.freeze([
3576
+ // Live NDJSON events → sitian host-session records (#811); last line is the result receipt.
3577
+ "--output-format",
3578
+ "stream-json",
3579
+ // Intermediate assistant/tool/system events require verbose with stream-json.
3580
+ "--verbose",
3581
+ "--permission-mode",
3582
+ "bypassPermissions",
3583
+ // Empty sources: no user/project/local operator surface (envelope owns materials).
3584
+ "--setting-sources",
3585
+ "",
3586
+ // With adapter-supplied --mcp-config only (AK relay); drops operator + claude.ai MCP.
3587
+ "--strict-mcp-config"
3588
+ ]),
3589
+ promptFlag: "-p",
3590
+ modelFlag: "--model",
3591
+ effortFlag: "--effort",
3592
+ // File path keeps large role envelopes off ARG_MAX.
3593
+ systemPromptFlag: "--system-prompt-file",
3594
+ jsonSchemaFlag: "--json-schema",
3595
+ mcpConfigFlag: "--mcp-config",
3596
+ sessionIdFlag: "--session-id",
3597
+ resumeFlag: "--resume"
3598
+ }),
3599
+ /**
3600
+ * Codex headless (#646). Binary under operator home; auth stays in CODEX_HOME.
3601
+ * Argv/parse/schema-close are codex-exec helpers — not Claude flag mapping.
3602
+ */
3603
+ "codex": Object.freeze({
3604
+ protocol: "codex-exec",
3605
+ binaryFromHome: Object.freeze([".local", "bin", "codex"]),
3606
+ sessionBindingFile: "codex-headless-session.json"
3607
+ })
3608
+ });
3421
3609
  }
3422
3610
  });
3423
3611
 
@@ -3985,6 +4173,8 @@ function acceptedFacts(toolName, details) {
3985
4173
  return typeof record4.judgeStatus === "string" ? { status: record4.judgeStatus } : {};
3986
4174
  case COUNTERSIGN_OUTPUT_TOOL_NAME:
3987
4175
  return typeof record4.countersignStatus === "string" ? { status: record4.countersignStatus } : {};
4176
+ case SECRETARIAT_OUTPUT_TOOL_NAME:
4177
+ return typeof record4.secretariatStatus === "string" ? { status: record4.secretariatStatus } : {};
3988
4178
  case MERGER_OUTPUT_TOOL_NAME: {
3989
4179
  const status = typeof record4.status === "string" ? record4.status : void 0;
3990
4180
  return {
@@ -4016,6 +4206,7 @@ var init_terminating_tools = __esm({
4016
4206
  init_gleaner_left_contracts();
4017
4207
  init_inspector_contracts();
4018
4208
  init_diarist_contracts();
4209
+ init_secretariat_contracts();
4019
4210
  init_worker_output();
4020
4211
  TERMINATING_TOOL_NAMES = [
4021
4212
  CODER_OUTPUT_TOOL_NAME,
@@ -4032,7 +4223,8 @@ var init_terminating_tools = __esm({
4032
4223
  GATEKEEPER_OUTPUT_TOOL_NAME,
4033
4224
  NAVIGATOR_OUTPUT_TOOL_NAME,
4034
4225
  AUDITOR_OUTPUT_TOOL_NAME,
4035
- DIARIST_OUTPUT_TOOL_NAME
4226
+ DIARIST_OUTPUT_TOOL_NAME,
4227
+ SECRETARIAT_OUTPUT_TOOL_NAME
4036
4228
  ];
4037
4229
  AcceptedDetailsContractError = class extends CorrectableSubmissionError {
4038
4230
  code = "accepted_details_contract";
@@ -5352,7 +5544,7 @@ async function readRoleRunStateDisk(runDirectory) {
5352
5544
  if (typeof record4.runId !== "string" || record4.runId.trim() === "") {
5353
5545
  return void 0;
5354
5546
  }
5355
- if (record4.role !== "judge" && record4.role !== "coder" && record4.role !== "fixer" && record4.role !== "collector" && record4.role !== "doctor" && record4.role !== "reviewer" && record4.role !== "merger" && record4.role !== "notary" && record4.role !== "countersign" && record4.role !== "gleaner-left" && record4.role !== "inspector" && record4.role !== "gatekeeper" && record4.role !== "navigator" && record4.role !== "auditor" && record4.role !== "diarist") {
5547
+ if (record4.role !== "judge" && record4.role !== "coder" && record4.role !== "fixer" && record4.role !== "collector" && record4.role !== "doctor" && record4.role !== "reviewer" && record4.role !== "merger" && record4.role !== "notary" && record4.role !== "countersign" && record4.role !== "gleaner-left" && record4.role !== "inspector" && record4.role !== "gatekeeper" && record4.role !== "navigator" && record4.role !== "auditor" && record4.role !== "diarist" && record4.role !== "secretariat") {
5356
5548
  return void 0;
5357
5549
  }
5358
5550
  if (record4.state !== "admitted" && record4.state !== "running" && record4.state !== "resumable" && record4.state !== "terminal") {
@@ -6165,6 +6357,24 @@ async function loadResumableJudgeRun(home, runId, authority) {
6165
6357
  };
6166
6358
  return seatLoadedResult(loaded, admitted);
6167
6359
  }
6360
+ async function loadResumableCountersignRun(home, runId, authority) {
6361
+ const loaded = await loadResumableRunRecord(home, runId, authority);
6362
+ if (loaded.run.role !== "countersign") {
6363
+ throw new CliUsageError(
6364
+ `role run ${runId} belongs to ${loaded.run.role}, not countersign`
6365
+ );
6366
+ }
6367
+ const base = resumedBaseAdmitted(loaded);
6368
+ const admitted = {
6369
+ role: "countersign",
6370
+ ...base,
6371
+ ...base.courtTicketNumbers === void 0 ? {} : { courtTicketNumbers: base.courtTicketNumbers },
6372
+ ...loaded.admittedFields.courtTicketNumbersDamage === void 0 ? {} : {
6373
+ courtTicketNumbersDamage: loaded.admittedFields.courtTicketNumbersDamage
6374
+ }
6375
+ };
6376
+ return seatLoadedResult(loaded, admitted);
6377
+ }
6168
6378
  async function loadResumableInstructionSeatRun(home, runId, authority) {
6169
6379
  const loaded = await loadResumableRunRecord(home, runId, authority);
6170
6380
  if (loaded.run.role !== "gatekeeper" && loaded.run.role !== "navigator" && loaded.run.role !== "auditor") {
@@ -6610,7 +6820,7 @@ function createTypedOptionConsumer(definitions) {
6610
6820
  }
6611
6821
  };
6612
6822
  }
6613
- var ANALYST_REQUIRE_ANY_OF, ANALYST_DEFAULT_MODE, REJECTED_PUBLIC_SPELLINGS, GLOBAL_OPTIONS, SHARED_PROJECT_SEMANTICS, SHARED_ATTACH_SEMANTICS, JUDGE_OPTIONS, GLEANER_LEFT_OPTIONS, INSPECTOR_OPTIONS, GATEKEEPER_OPTIONS, NAVIGATOR_OPTIONS, AUDITOR_OPTIONS, COUNTERSIGN_OPTIONS, DIARIST_OPTIONS, CODER_OPTIONS, FIXER_OPTIONS, REVIEWER_OPTIONS, COLLECTOR_OPTIONS, DOCTOR_OPTIONS, NOTARY_OPTIONS, MERGER_OPTIONS, ANALYST_OPTIONS, PUBLIC_OPTION_TABLE, TOP_LEVEL_HELP, ROLE_COMMAND_HELP, SUPPORT_COMMAND_HELP, PUBLIC_COMMAND_HELP;
6823
+ var ANALYST_REQUIRE_ANY_OF, ANALYST_DEFAULT_MODE, REJECTED_PUBLIC_SPELLINGS, GLOBAL_OPTIONS, SHARED_PROJECT_SEMANTICS, SHARED_ATTACH_SEMANTICS, JUDGE_OPTIONS, GLEANER_LEFT_OPTIONS, INSPECTOR_OPTIONS, GATEKEEPER_OPTIONS, NAVIGATOR_OPTIONS, AUDITOR_OPTIONS, COUNTERSIGN_OPTIONS, DIARIST_OPTIONS, SECRETARIAT_OPTIONS, CODER_OPTIONS, FIXER_OPTIONS, REVIEWER_OPTIONS, COLLECTOR_OPTIONS, DOCTOR_OPTIONS, NOTARY_OPTIONS, MERGER_OPTIONS, ANALYST_OPTIONS, PUBLIC_OPTION_TABLE, TOP_LEVEL_HELP, ROLE_COMMAND_HELP, SUPPORT_COMMAND_HELP, PUBLIC_COMMAND_HELP;
6614
6824
  var init_option_definitions = __esm({
6615
6825
  "src/public-cli/option-definitions.ts"() {
6616
6826
  "use strict";
@@ -6823,6 +7033,10 @@ var init_option_definitions = __esm({
6823
7033
  bindOwner("diarist", SHARED_PROJECT_SEMANTICS),
6824
7034
  bindOwner("diarist", SHARED_ATTACH_SEMANTICS)
6825
7035
  ];
7036
+ SECRETARIAT_OPTIONS = [
7037
+ bindOwner("secretariat", SHARED_PROJECT_SEMANTICS),
7038
+ bindOwner("secretariat", SHARED_ATTACH_SEMANTICS)
7039
+ ];
6826
7040
  CODER_OPTIONS = [
6827
7041
  {
6828
7042
  id: "phase",
@@ -7185,6 +7399,7 @@ var init_option_definitions = __esm({
7185
7399
  navigator: NAVIGATOR_OPTIONS,
7186
7400
  auditor: AUDITOR_OPTIONS,
7187
7401
  diarist: DIARIST_OPTIONS,
7402
+ secretariat: SECRETARIAT_OPTIONS,
7188
7403
  analyst: ANALYST_OPTIONS
7189
7404
  };
7190
7405
  TOP_LEVEL_HELP = {
@@ -7321,6 +7536,14 @@ var init_option_definitions = __esm({
7321
7536
  'ak-role diarist --attach ./design.md "\u8865\u5F55\u672C\u8F6E\u8BBE\u8BA1\u4FEE\u8BA2\u3002"'
7322
7537
  ]
7323
7538
  },
7539
+ secretariat: {
7540
+ command: "secretariat",
7541
+ summary: "Secretariat (\u4E2D\u4E66\u7701): rewrite ticket per \u7968\u9762\u6CD5 and drive countersign to converged or escalate.",
7542
+ usage: ["ak-role secretariat [options] [instruction]"],
7543
+ examples: [
7544
+ 'ak-role secretariat "\u6574\u7406 #924 \u7968\u9762\u5E76\u9001\u5EAD\u3002"'
7545
+ ]
7546
+ },
7324
7547
  notary: {
7325
7548
  command: "notary",
7326
7549
  summary: "Direct Notary document check (quote fidelity + ticket alignment); zero prompt/attachment.",
@@ -7431,6 +7654,7 @@ __export(invocation_exports, {
7431
7654
  admitNavigatorInvocation: () => admitNavigatorInvocation,
7432
7655
  admitNotaryInvocation: () => admitNotaryInvocation,
7433
7656
  admitReviewerInvocation: () => admitReviewerInvocation,
7657
+ admitSecretariatInvocation: () => admitSecretariatInvocation,
7434
7658
  bindAdmittedTicketNumber: () => bindAdmittedTicketNumber,
7435
7659
  bindCourtTicketNumbersOnAdmitted: () => bindCourtTicketNumbersOnAdmitted,
7436
7660
  bindTicketNumberOnRunDirectory: () => bindTicketNumberOnRunDirectory,
@@ -7446,6 +7670,7 @@ __export(invocation_exports, {
7446
7670
  buildMergerTransportPrompt: () => buildMergerTransportPrompt,
7447
7671
  buildNotaryTransportPrompt: () => buildNotaryTransportPrompt,
7448
7672
  buildReviewerTransportPrompt: () => buildReviewerTransportPrompt,
7673
+ buildSecretariatTransportPrompt: () => buildSecretariatTransportPrompt,
7449
7674
  deriveMergerEnvelopeFromActiveMerge: () => deriveMergerEnvelopeFromActiveMerge,
7450
7675
  ensureRunArtifactsDir: () => ensureRunArtifactsDir,
7451
7676
  freezeAttachmentsIntoRun: () => freezeAttachmentsIntoRun,
@@ -7473,6 +7698,7 @@ __export(invocation_exports, {
7473
7698
  parseNotaryArgv: () => parseNotaryArgv,
7474
7699
  parsePositiveTicketNumber: () => parsePositiveTicketNumber,
7475
7700
  parseReviewerArgv: () => parseReviewerArgv,
7701
+ parseSecretariatArgv: () => parseSecretariatArgv,
7476
7702
  persistAdmittedSourceRunPath: () => persistAdmittedSourceRunPath,
7477
7703
  recordEffectiveInvocationModel: () => recordEffectiveInvocationModel,
7478
7704
  recordLaunchedPiIdentity: () => recordLaunchedPiIdentity,
@@ -7902,6 +8128,9 @@ function parseAuditorArgv(args) {
7902
8128
  function parseDiaristArgv(args) {
7903
8129
  return parseInstructionArgv(args, "diarist");
7904
8130
  }
8131
+ function parseSecretariatArgv(args) {
8132
+ return parseInstructionArgv(args, "secretariat");
8133
+ }
7905
8134
  function parseCoderArgv(args) {
7906
8135
  const attachmentPaths = [];
7907
8136
  let project;
@@ -8135,6 +8364,9 @@ async function admitAuditorInvocation(options) {
8135
8364
  async function admitDiaristInvocation(options) {
8136
8365
  return admitStandardMaterialInvocation("diarist", options);
8137
8366
  }
8367
+ async function admitSecretariatInvocation(options) {
8368
+ return admitStandardMaterialInvocation("secretariat", options);
8369
+ }
8138
8370
  function buildInstructionTransportPrompt(admitted, engineMaterial) {
8139
8371
  const lines = [admitted.instructionEmpty ? "" : admitted.instruction];
8140
8372
  if (admitted.attachments.length > 0) {
@@ -8149,6 +8381,9 @@ function buildInstructionTransportPrompt(admitted, engineMaterial) {
8149
8381
  function buildJudgeTransportPrompt(admitted, engineMaterial) {
8150
8382
  return buildInstructionTransportPrompt(admitted, engineMaterial);
8151
8383
  }
8384
+ function buildSecretariatTransportPrompt(admitted, engineMaterial) {
8385
+ return buildInstructionTransportPrompt(admitted, engineMaterial);
8386
+ }
8152
8387
  function buildInspectorTransportPrompt(admitted, engineMaterial) {
8153
8388
  return buildInstructionTransportPrompt(admitted, engineMaterial);
8154
8389
  }
@@ -14327,6 +14562,7 @@ __export(settlement_exports, {
14327
14562
  trySettleNavigatorTerminalResult: () => trySettleNavigatorTerminalResult,
14328
14563
  trySettleNotaryTerminalResult: () => trySettleNotaryTerminalResult,
14329
14564
  trySettleReviewerTerminalResult: () => trySettleReviewerTerminalResult,
14565
+ trySettleSecretariatTerminalResult: () => trySettleSecretariatTerminalResult,
14330
14566
  withSubmissions: () => withSubmissions
14331
14567
  });
14332
14568
  import { randomUUID as randomUUID4 } from "node:crypto";
@@ -16165,6 +16401,15 @@ async function settleLawfulDiaristTerminalResult(admitted, authority, scope) {
16165
16401
  async function trySettleDiaristTerminalResult(admitted, authority, scope) {
16166
16402
  return settleLawfulDiaristTerminalResult(admitted, authority, scope);
16167
16403
  }
16404
+ async function settleLawfulSecretariatTerminalResult(admitted, authority, scope) {
16405
+ return settleLawfulSeatAcceptedTerminalResult(admitted, authority, {
16406
+ role: "secretariat",
16407
+ toolName: SECRETARIAT_OUTPUT_TOOL_NAME
16408
+ }, scope);
16409
+ }
16410
+ async function trySettleSecretariatTerminalResult(admitted, authority, scope) {
16411
+ return settleLawfulSecretariatTerminalResult(admitted, authority, scope);
16412
+ }
16168
16413
  async function settleLawfulInspectorTerminalResult(admitted, authority, scope) {
16169
16414
  return settleLawfulSeatAcceptedTerminalResult(admitted, authority, {
16170
16415
  role: "inspector",
@@ -16791,6 +17036,7 @@ var init_settlement = __esm({
16791
17036
  init_countersign_contracts();
16792
17037
  init_gleaner_left_contracts();
16793
17038
  init_diarist_contracts();
17039
+ init_secretariat_contracts();
16794
17040
  init_inspector_contracts();
16795
17041
  init_gatekeeper_output();
16796
17042
  init_navigator_output();
@@ -18590,7 +18836,7 @@ function resumeTurnRequestProjectionOptions(admitted, request, env, summonsPrepa
18590
18836
  ...env.model === void 0 ? {} : { model: env.model },
18591
18837
  ...pickEngineAxis(env),
18592
18838
  ...env.timeoutMs === void 0 ? {} : { timeoutMs: env.timeoutMs },
18593
- ...admitted.correlationId === void 0 && env.correlationId === void 0 ? {} : { correlationId: admitted.correlationId ?? env.correlationId },
18839
+ ...env.correlationId === void 0 && admitted.correlationId === void 0 ? {} : { correlationId: env.correlationId ?? admitted.correlationId },
18594
18840
  continuation: {
18595
18841
  kind: "resume",
18596
18842
  prompt
@@ -18747,10 +18993,7 @@ async function runPostAdmissionSeatResume(input) {
18747
18993
  dispatch: async (turnRequest) => {
18748
18994
  const result = await dispatchPostAdmissionTurn({
18749
18995
  admitted: loaded.admitted,
18750
- env: {
18751
- ...input.env,
18752
- ...loaded.admitted.correlationId === void 0 ? {} : { correlationId: loaded.admitted.correlationId }
18753
- },
18996
+ env: input.env,
18754
18997
  io: attemptIo,
18755
18998
  request: turnRequest,
18756
18999
  lease,
@@ -19845,12 +20088,294 @@ function diaristAdapters(env) {
19845
20088
  afterDispatch: async (admitted, lease) => {
19846
20089
  await bindAndRelocateDiaristIfBoardBound(admitted, env.principalAuthority, lease);
19847
20090
  }
19848
- };
20091
+ };
20092
+ }
20093
+ async function runPublicDiarist(argv, env, io, parseDiaristArgv2) {
20094
+ let parsed;
20095
+ try {
20096
+ parsed = parseDiaristArgv2(argv);
20097
+ } catch (error) {
20098
+ if (error instanceof CliUsageError) {
20099
+ presentStructuralRejection(error, io);
20100
+ return { exitCode: 2 };
20101
+ }
20102
+ throw error;
20103
+ }
20104
+ const projectRoot = parsed.project ?? env.cwd;
20105
+ const handoffTicket = env.boundTicketNumber;
20106
+ if (typeof handoffTicket === "number" && Number.isSafeInteger(handoffTicket) && handoffTicket >= 1) {
20107
+ const summons = {
20108
+ instruction: parsed.instruction,
20109
+ instructionEmpty: parsed.instruction.trim() === "",
20110
+ attachmentPaths: parsed.attachmentPaths
20111
+ };
20112
+ const resumed = await tryResumeSameTicketSeatRun({
20113
+ home: env.home,
20114
+ projectRoot,
20115
+ role: "diarist",
20116
+ ticketNumber: handoffTicket,
20117
+ freshSummons: env.freshSummons,
20118
+ summons,
20119
+ resume: (runId, materials) => runPublicDiaristResume(
20120
+ { runId, ...materials === void 0 ? {} : { summons: materials } },
20121
+ env,
20122
+ io
20123
+ )
20124
+ });
20125
+ if (resumed !== void 0) return resumed;
20126
+ }
20127
+ let admitted;
20128
+ try {
20129
+ admitted = await admitDiaristInvocation({
20130
+ home: env.home,
20131
+ principalAuthority: env.principalAuthority,
20132
+ cwd: env.cwd,
20133
+ instruction: parsed.instruction,
20134
+ attachmentPaths: parsed.attachmentPaths,
20135
+ ...parsed.project === void 0 ? {} : { project: parsed.project },
20136
+ ...env.createRunId === void 0 ? {} : { createRunId: env.createRunId },
20137
+ ...env.model === void 0 ? {} : { model: env.model },
20138
+ ...env.correlationId === void 0 ? {} : { correlationId: env.correlationId },
20139
+ ...handoffTicket === void 0 ? {} : { assertedTicketNumber: handoffTicket }
20140
+ });
20141
+ } catch (error) {
20142
+ if (error instanceof CliUsageError) {
20143
+ presentStructuralRejection(error, io);
20144
+ return { exitCode: 2 };
20145
+ }
20146
+ throw error;
20147
+ }
20148
+ await markRunAdmitted(admitted, env.principalAuthority);
20149
+ const turnProjection = {
20150
+ packageRoot: env.packageRoot,
20151
+ home: env.home,
20152
+ agentDir: env.agentDir,
20153
+ ...env.model === void 0 ? {} : { model: env.model },
20154
+ ...pickEngineAxis(env),
20155
+ ...env.timeoutMs === void 0 ? {} : { timeoutMs: env.timeoutMs },
20156
+ ...env.correlationId === void 0 || env.correlationId.trim() === "" ? {} : { correlationId: env.correlationId },
20157
+ continuation: {
20158
+ kind: "initial",
20159
+ prompt: buildInstructionTransportPrompt(
20160
+ admitted,
20161
+ engineSessionMaterialFromOptions({
20162
+ ...pickEngineAxis(env),
20163
+ packageRoot: env.packageRoot
20164
+ })
20165
+ )
20166
+ }
20167
+ };
20168
+ const turnRequest = buildDiaristTurnRequest(admitted, turnProjection);
20169
+ return await runPostAdmissionOneShot({
20170
+ admitted,
20171
+ env,
20172
+ io,
20173
+ request: turnRequest,
20174
+ adapters: diaristAdapters(env),
20175
+ ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
20176
+ });
20177
+ }
20178
+ async function runPublicDiaristResume(request, env, io) {
20179
+ return await runPostAdmissionSeatResume({
20180
+ request,
20181
+ env,
20182
+ io,
20183
+ load: (effective) => loadResumableDiaristRun(env.home, effective.runId, env.principalAuthority),
20184
+ buildTurnRequest: async (admitted, effective) => {
20185
+ const summonsPrepared = await prepareSummonsResumeMaterials(
20186
+ admitted.runDirectory,
20187
+ effective.summons
20188
+ );
20189
+ return buildDiaristTurnRequest(
20190
+ admitted,
20191
+ resumeTurnRequestProjectionOptions(
20192
+ admitted,
20193
+ effective,
20194
+ env,
20195
+ summonsPrepared
20196
+ )
20197
+ );
20198
+ },
20199
+ adapters: diaristAdapters(env),
20200
+ ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
20201
+ });
20202
+ }
20203
+ var init_diarist_run = __esm({
20204
+ "src/public-cli/diarist-run.ts"() {
20205
+ "use strict";
20206
+ init_engine_material();
20207
+ init_cli_errors();
20208
+ init_invocation();
20209
+ init_post_admission();
20210
+ init_run_lifecycle();
20211
+ init_seat_ticket_binding();
20212
+ init_settlement();
20213
+ init_turn_request();
20214
+ init_run_ticket_number();
20215
+ }
20216
+ });
20217
+
20218
+ // src/public-cli/countersign-run.ts
20219
+ var countersign_run_exports = {};
20220
+ __export(countersign_run_exports, {
20221
+ buildCountersignTurnRequest: () => buildCountersignTurnRequest,
20222
+ invokeCourtDiarist: () => invokeCourtDiarist,
20223
+ runCountersignCourtDiaristStation: () => runCountersignCourtDiaristStation,
20224
+ runPublicCountersign: () => runPublicCountersign,
20225
+ runPublicCountersignResume: () => runPublicCountersignResume
20226
+ });
20227
+ function buildCountersignTurnRequest(admitted, options) {
20228
+ return projectRoleTurnRequest(
20229
+ admitted,
20230
+ {
20231
+ activation: {
20232
+ role: "countersign",
20233
+ // Admitted typed binding rides the turn activation seam to the Notary gate.
20234
+ ...admitted.ticketNumber === void 0 ? {} : { ticketNumber: admitted.ticketNumber }
20235
+ }
20236
+ },
20237
+ options
20238
+ );
20239
+ }
20240
+ function courtTicketNumbersFromOutcome(roleOutcome, principalTicket) {
20241
+ if (roleOutcome === void 0) return void 0;
20242
+ const payloads = roleOutcome.kind === "accepted" || roleOutcome.kind === "audit_escalation" || roleOutcome.kind === "failure" ? roleOutcome.payloads ?? [] : [];
20243
+ let latest;
20244
+ for (const payload of payloads) {
20245
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
20246
+ continue;
20247
+ }
20248
+ const record4 = payload;
20249
+ if (!Object.hasOwn(record4, "courtTicketNumbers")) continue;
20250
+ const raw = record4.courtTicketNumbers;
20251
+ if (!Array.isArray(raw)) continue;
20252
+ const members = projectCourtTicketNumbers(raw);
20253
+ if (members === null) continue;
20254
+ if (members.length === 0) {
20255
+ if (raw.length === 0) {
20256
+ latest = projectCourtTicketNumbers([], { principalTicket }) ?? void 0;
20257
+ }
20258
+ continue;
20259
+ }
20260
+ latest = projectCourtTicketNumbers(raw, { principalTicket }) ?? void 0;
20261
+ }
20262
+ return latest;
20263
+ }
20264
+ function courtDiaristEscalated(roleOutcome) {
20265
+ if (roleOutcome === void 0) return false;
20266
+ if (roleOutcome.kind === "audit_escalation") return true;
20267
+ if (roleOutcome.kind !== "accepted") return false;
20268
+ return (roleOutcome.payloads ?? []).some((payload) => {
20269
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return false;
20270
+ const record4 = payload;
20271
+ return record4.status === "escalate" || record4.countersignStatus === "escalate";
20272
+ });
20273
+ }
20274
+ async function invokeCourtDiarist(input, env, io) {
20275
+ const quietIo = {
20276
+ stdout() {
20277
+ },
20278
+ stderr(text) {
20279
+ if (text.trim() !== "") io.stderr(text);
20280
+ }
20281
+ };
20282
+ const { summonPublicRole: summonPublicRole2 } = await Promise.resolve().then(() => (init_public_role_summons(), public_role_summons_exports));
20283
+ const result = await summonPublicRole2({
20284
+ role: "diarist",
20285
+ argv: [
20286
+ "--project",
20287
+ input.projectRoot,
20288
+ ...(input.attachmentPaths ?? []).flatMap((path) => ["--attach", path]),
20289
+ "--",
20290
+ input.instruction
20291
+ ],
20292
+ cwd: env.cwd,
20293
+ home: env.home,
20294
+ agentDir: env.agentDir,
20295
+ packageRoot: env.packageRoot,
20296
+ io: quietIo,
20297
+ ...env.credentials === void 0 ? {} : { credentials: env.credentials },
20298
+ ...env.signal === void 0 ? {} : { signal: env.signal },
20299
+ ...input.correlationId === void 0 ? {} : { correlationId: input.correlationId },
20300
+ ...input.boundTicketNumber === void 0 ? {} : { boundTicketNumber: input.boundTicketNumber },
20301
+ // Child seat selects from the composition-root table. Do not pass the
20302
+ // already-selected parent adapter (#840 / ADR 0082: --host 旗标>席位配置>缺省 pi).
20303
+ ...env.hostAdapters === void 0 ? {} : { hostAdapters: env.hostAdapters }
20304
+ });
20305
+ const roleOutcome = result.terminal?.roleOutcome;
20306
+ if (courtDiaristEscalated(roleOutcome)) {
20307
+ return {
20308
+ identity: { kind: "escalate" }
20309
+ };
20310
+ }
20311
+ if (result.exitCode !== 0) {
20312
+ const diagnostic = roleOutcome?.kind === "failure" ? roleOutcome.diagnostic : result.stderr?.trim() || `exit ${result.exitCode}`;
20313
+ return {
20314
+ identity: { kind: "unbound" },
20315
+ failedWithoutEscalate: {
20316
+ diagnostic: `court diarist station failed for ${input.failureLabel}: ${diagnostic}`
20317
+ }
20318
+ };
20319
+ }
20320
+ const asserted = result.admitted?.ticketNumber;
20321
+ if (isSafePositiveTicketNumber(asserted)) {
20322
+ const courtTicketNumbers = courtTicketNumbersFromOutcome(roleOutcome, asserted);
20323
+ return {
20324
+ identity: {
20325
+ kind: "ticket",
20326
+ ticketNumber: asserted,
20327
+ ...courtTicketNumbers === void 0 ? {} : { courtTicketNumbers }
20328
+ }
20329
+ };
20330
+ }
20331
+ return {
20332
+ identity: { kind: "unbound" }
20333
+ };
20334
+ }
20335
+ async function runCountersignCourtDiaristStation(admitted, env, io) {
20336
+ if (env.runCourtDiaristStation !== void 0) {
20337
+ await env.runCourtDiaristStation(admitted);
20338
+ return;
20339
+ }
20340
+ if (admitted.ticketNumber === void 0) return;
20341
+ let refreshTickets;
20342
+ if (admitted.courtTicketNumbers !== void 0) {
20343
+ if (admitted.courtTicketNumbers.length === 0 || !admitted.courtTicketNumbers.includes(admitted.ticketNumber)) {
20344
+ throw new StationChildExhaustedError(
20345
+ `court diarist station: courtTicketNumbers is damaged (empty or missing principal #${admitted.ticketNumber})`
20346
+ );
20347
+ }
20348
+ refreshTickets = admitted.courtTicketNumbers;
20349
+ } else {
20350
+ refreshTickets = [admitted.ticketNumber];
20351
+ }
20352
+ for (const ticketNumber of refreshTickets) {
20353
+ const outcome = await invokeCourtDiarist(
20354
+ {
20355
+ instruction: `\u6574\u7406 #${ticketNumber} \u7684\u672C\u6848\u4F9D\u636E\u3002`,
20356
+ projectRoot: admitted.projectRoot,
20357
+ failureLabel: `ticket #${ticketNumber}`,
20358
+ correlationId: admitted.runId,
20359
+ // Refresh holds a typed key — hand it off so identity is bound before turn.
20360
+ boundTicketNumber: ticketNumber
20361
+ },
20362
+ env,
20363
+ io
20364
+ );
20365
+ if (outcome.identity.kind === "escalate") {
20366
+ throw new StationChildExhaustedError(
20367
+ "court diarist station escalated (cannot identify court target)"
20368
+ );
20369
+ }
20370
+ if (outcome.failedWithoutEscalate !== void 0) {
20371
+ throw new StationChildExhaustedError(outcome.failedWithoutEscalate.diagnostic);
20372
+ }
20373
+ }
19849
20374
  }
19850
- async function runPublicDiarist(argv, env, io, parseDiaristArgv2) {
20375
+ async function runPublicCountersign(argv, env, io, parseCountersignArgv2) {
19851
20376
  let parsed;
19852
20377
  try {
19853
- parsed = parseDiaristArgv2(argv);
20378
+ parsed = parseCountersignArgv2(argv);
19854
20379
  } catch (error) {
19855
20380
  if (error instanceof CliUsageError) {
19856
20381
  presentStructuralRejection(error, io);
@@ -19858,32 +20383,9 @@ async function runPublicDiarist(argv, env, io, parseDiaristArgv2) {
19858
20383
  }
19859
20384
  throw error;
19860
20385
  }
19861
- const projectRoot = parsed.project ?? env.cwd;
19862
- const handoffTicket = env.boundTicketNumber;
19863
- if (typeof handoffTicket === "number" && Number.isSafeInteger(handoffTicket) && handoffTicket >= 1) {
19864
- const summons = {
19865
- instruction: parsed.instruction,
19866
- instructionEmpty: parsed.instruction.trim() === "",
19867
- attachmentPaths: parsed.attachmentPaths
19868
- };
19869
- const resumed = await tryResumeSameTicketSeatRun({
19870
- home: env.home,
19871
- projectRoot,
19872
- role: "diarist",
19873
- ticketNumber: handoffTicket,
19874
- freshSummons: env.freshSummons,
19875
- summons,
19876
- resume: (runId, materials) => runPublicDiaristResume(
19877
- { runId, ...materials === void 0 ? {} : { summons: materials } },
19878
- env,
19879
- io
19880
- )
19881
- });
19882
- if (resumed !== void 0) return resumed;
19883
- }
19884
20386
  let admitted;
19885
20387
  try {
19886
- admitted = await admitDiaristInvocation({
20388
+ admitted = await admitCountersignInvocation({
19887
20389
  home: env.home,
19888
20390
  principalAuthority: env.principalAuthority,
19889
20391
  cwd: env.cwd,
@@ -19892,8 +20394,7 @@ async function runPublicDiarist(argv, env, io, parseDiaristArgv2) {
19892
20394
  ...parsed.project === void 0 ? {} : { project: parsed.project },
19893
20395
  ...env.createRunId === void 0 ? {} : { createRunId: env.createRunId },
19894
20396
  ...env.model === void 0 ? {} : { model: env.model },
19895
- ...env.correlationId === void 0 ? {} : { correlationId: env.correlationId },
19896
- ...handoffTicket === void 0 ? {} : { assertedTicketNumber: handoffTicket }
20397
+ ...env.correlationId === void 0 ? {} : { correlationId: env.correlationId }
19897
20398
  });
19898
20399
  } catch (error) {
19899
20400
  if (error instanceof CliUsageError) {
@@ -19903,6 +20404,112 @@ async function runPublicDiarist(argv, env, io, parseDiaristArgv2) {
19903
20404
  throw error;
19904
20405
  }
19905
20406
  await markRunAdmitted(admitted, env.principalAuthority);
20407
+ let typedTicket;
20408
+ let typedCourtTicketNumbers;
20409
+ let identityDiaristRan = false;
20410
+ if (env.runCourtDiaristStation === void 0) {
20411
+ const outcome = await invokeCourtDiarist(
20412
+ {
20413
+ instruction: parsed.instruction,
20414
+ projectRoot: admitted.projectRoot,
20415
+ failureLabel: "unbound summons",
20416
+ correlationId: admitted.runId
20417
+ },
20418
+ env,
20419
+ io
20420
+ );
20421
+ identityDiaristRan = true;
20422
+ if (outcome.identity.kind === "escalate") {
20423
+ return await presentControlledFailure2(
20424
+ admitted,
20425
+ {
20426
+ timedOut: false,
20427
+ code: null,
20428
+ stderr: "",
20429
+ thrown: new Error(
20430
+ "court diarist station escalated (cannot identify court target)"
20431
+ )
20432
+ },
20433
+ countersignAdapters(),
20434
+ env.principalAuthority,
20435
+ io
20436
+ );
20437
+ }
20438
+ if (outcome.failedWithoutEscalate !== void 0) {
20439
+ return await presentControlledFailure2(
20440
+ admitted,
20441
+ {
20442
+ timedOut: false,
20443
+ code: null,
20444
+ stderr: "",
20445
+ thrown: new Error(outcome.failedWithoutEscalate.diagnostic)
20446
+ },
20447
+ countersignAdapters(),
20448
+ env.principalAuthority,
20449
+ io
20450
+ );
20451
+ }
20452
+ if (outcome.identity.kind === "ticket") {
20453
+ const assertedTicket = outcome.identity.ticketNumber;
20454
+ typedTicket = assertedTicket;
20455
+ typedCourtTicketNumbers = outcome.identity.courtTicketNumbers;
20456
+ const summons = {
20457
+ instruction: parsed.instruction,
20458
+ instructionEmpty: parsed.instruction.trim() === "",
20459
+ attachmentPaths: parsed.attachmentPaths
20460
+ };
20461
+ const resumed = await tryResumeSameTicketSeatRun({
20462
+ home: env.home,
20463
+ projectRoot: admitted.projectRoot,
20464
+ role: "countersign",
20465
+ ticketNumber: typedTicket,
20466
+ freshSummons: env.freshSummons,
20467
+ summons,
20468
+ resume: async (runId, materials) => {
20469
+ await bindAdmittedTicketNumber(admitted, assertedTicket);
20470
+ await relocateAdmittedRunToTicket(admitted, env.principalAuthority);
20471
+ await markRunTerminal(admitted.runDirectory);
20472
+ return await runPublicCountersignResume(
20473
+ {
20474
+ runId,
20475
+ ...materials === void 0 ? {} : { summons: materials }
20476
+ },
20477
+ {
20478
+ ...env,
20479
+ ...typedCourtTicketNumbers === void 0 ? {} : { pendingCourtTicketNumbers: typedCourtTicketNumbers }
20480
+ },
20481
+ io
20482
+ );
20483
+ }
20484
+ });
20485
+ if (resumed !== void 0) {
20486
+ return resumed;
20487
+ }
20488
+ }
20489
+ }
20490
+ if (identityDiaristRan && typedTicket !== void 0) {
20491
+ try {
20492
+ await bindAdmittedTicketNumber(admitted, typedTicket);
20493
+ await relocateAdmittedRunToTicket(admitted, env.principalAuthority);
20494
+ await bindCourtTicketNumbersOnAdmitted(
20495
+ admitted,
20496
+ typedCourtTicketNumbers ?? [typedTicket]
20497
+ );
20498
+ } catch (error) {
20499
+ return await presentControlledFailure2(
20500
+ admitted,
20501
+ {
20502
+ timedOut: false,
20503
+ code: null,
20504
+ stderr: "",
20505
+ thrown: error
20506
+ },
20507
+ countersignAdapters(),
20508
+ env.principalAuthority,
20509
+ io
20510
+ );
20511
+ }
20512
+ }
19906
20513
  const turnProjection = {
19907
20514
  packageRoot: env.packageRoot,
19908
20515
  home: env.home,
@@ -19913,7 +20520,7 @@ async function runPublicDiarist(argv, env, io, parseDiaristArgv2) {
19913
20520
  ...env.correlationId === void 0 || env.correlationId.trim() === "" ? {} : { correlationId: env.correlationId },
19914
20521
  continuation: {
19915
20522
  kind: "initial",
19916
- prompt: buildInstructionTransportPrompt(
20523
+ prompt: buildCountersignTransportPrompt(
19917
20524
  admitted,
19918
20525
  engineSessionMaterialFromOptions({
19919
20526
  ...pickEngineAxis(env),
@@ -19922,28 +20529,59 @@ async function runPublicDiarist(argv, env, io, parseDiaristArgv2) {
19922
20529
  )
19923
20530
  }
19924
20531
  };
19925
- const turnRequest = buildDiaristTurnRequest(admitted, turnProjection);
19926
- return await runPostAdmissionOneShot({
20532
+ const turnRequest = buildCountersignTurnRequest(admitted, turnProjection);
20533
+ const result = await runPostAdmissionOneShot({
19927
20534
  admitted,
19928
20535
  env,
19929
20536
  io,
19930
20537
  request: turnRequest,
19931
- adapters: diaristAdapters(env),
20538
+ adapters: countersignAdapters({
20539
+ beforeDispatch: async (admittedSeat, lease) => {
20540
+ if (!identityDiaristRan) {
20541
+ await runCountersignCourtDiaristStation(admittedSeat, env, io);
20542
+ } else if (typedTicket !== void 0) {
20543
+ await runCountersignCourtDiaristStation(admittedSeat, env, io);
20544
+ }
20545
+ await relocateAdmittedRunToTicket(
20546
+ admittedSeat,
20547
+ env.principalAuthority,
20548
+ lease
20549
+ );
20550
+ Object.assign(
20551
+ turnRequest,
20552
+ buildCountersignTurnRequest(admittedSeat, turnProjection)
20553
+ );
20554
+ }
20555
+ }),
19932
20556
  ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
19933
20557
  });
20558
+ await relocateAdmittedRunToTicket(admitted, env.principalAuthority);
20559
+ return result;
19934
20560
  }
19935
- async function runPublicDiaristResume(request, env, io) {
20561
+ function countersignAdapters(options) {
20562
+ return {
20563
+ trySettle: (admitted, authority, scope) => trySettleCountersignTerminalResult(admitted, authority, scope),
20564
+ // Accepted receipts and failure terminals both present via shared path.
20565
+ shouldPresentSettled: () => true,
20566
+ ...options?.beforeDispatch === void 0 ? {} : { beforeDispatch: options.beforeDispatch }
20567
+ };
20568
+ }
20569
+ async function runPublicCountersignResume(request, env, io) {
19936
20570
  return await runPostAdmissionSeatResume({
19937
20571
  request,
19938
20572
  env,
19939
20573
  io,
19940
- load: (effective) => loadResumableDiaristRun(env.home, effective.runId, env.principalAuthority),
20574
+ load: (effective) => loadResumableCountersignRun(
20575
+ env.home,
20576
+ effective.runId,
20577
+ env.principalAuthority
20578
+ ),
19941
20579
  buildTurnRequest: async (admitted, effective) => {
19942
20580
  const summonsPrepared = await prepareSummonsResumeMaterials(
19943
20581
  admitted.runDirectory,
19944
20582
  effective.summons
19945
20583
  );
19946
- return buildDiaristTurnRequest(
20584
+ return buildCountersignTurnRequest(
19947
20585
  admitted,
19948
20586
  resumeTurnRequestProjectionOptions(
19949
20587
  admitted,
@@ -19953,22 +20591,36 @@ async function runPublicDiaristResume(request, env, io) {
19953
20591
  )
19954
20592
  );
19955
20593
  },
19956
- adapters: diaristAdapters(env),
20594
+ adapters: countersignAdapters({
20595
+ beforeDispatch: async (admitted) => {
20596
+ if (admitted.courtTicketNumbersDamage !== void 0) {
20597
+ throw new StationChildExhaustedError(admitted.courtTicketNumbersDamage);
20598
+ }
20599
+ if (env.pendingCourtTicketNumbers !== void 0) {
20600
+ await bindCourtTicketNumbersOnAdmitted(
20601
+ admitted,
20602
+ env.pendingCourtTicketNumbers
20603
+ );
20604
+ }
20605
+ await runCountersignCourtDiaristStation(admitted, env, io);
20606
+ }
20607
+ }),
19957
20608
  ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
19958
20609
  });
19959
20610
  }
19960
- var init_diarist_run = __esm({
19961
- "src/public-cli/diarist-run.ts"() {
20611
+ var init_countersign_run = __esm({
20612
+ "src/public-cli/countersign-run.ts"() {
19962
20613
  "use strict";
19963
20614
  init_engine_material();
19964
20615
  init_cli_errors();
20616
+ init_diarist_contracts();
20617
+ init_run_ticket_number();
19965
20618
  init_invocation();
19966
20619
  init_post_admission();
19967
20620
  init_run_lifecycle();
19968
20621
  init_seat_ticket_binding();
19969
20622
  init_settlement();
19970
20623
  init_turn_request();
19971
- init_run_ticket_number();
19972
20624
  }
19973
20625
  });
19974
20626
 
@@ -20149,11 +20801,15 @@ async function summonPublicRole(options) {
20149
20801
  env: {
20150
20802
  ...built.env,
20151
20803
  stationChild: true,
20804
+ // Forward composition-root adapters so nested court stations (e.g.
20805
+ // countersign → diarist) select the same faux/production table (#924).
20806
+ ...options.hostAdapters === void 0 ? {} : { hostAdapters: options.hostAdapters },
20152
20807
  ...config.autoResumeLimit === void 0 ? {} : { autoResumeLimit: config.autoResumeLimit },
20153
20808
  ...options.signal === void 0 ? {} : { signal: options.signal },
20154
20809
  ...options.reviewReask === void 0 ? {} : { reviewReask: options.reviewReask },
20155
20810
  ...options.gateReviewInstruction === void 0 ? {} : { gateReviewInstruction: options.gateReviewInstruction },
20156
20811
  ...options.boundTicketNumber === void 0 ? {} : { boundTicketNumber: options.boundTicketNumber },
20812
+ ...options.correlationId === void 0 || options.correlationId.trim() === "" ? {} : { correlationId: options.correlationId },
20157
20813
  ...options.createRunId === void 0 ? {} : { createRunId: options.createRunId }
20158
20814
  }
20159
20815
  };
@@ -20256,245 +20912,82 @@ async function summonPublicRole(options) {
20256
20912
  result = stepped.ok;
20257
20913
  break;
20258
20914
  }
20915
+ case "countersign": {
20916
+ const [{ runPublicCountersign: runPublicCountersign2 }, { parseCountersignArgv: parseCountersignArgv2 }] = await Promise.all([
20917
+ Promise.resolve().then(() => (init_countersign_run(), countersign_run_exports)),
20918
+ Promise.resolve().then(() => (init_invocation(), invocation_exports))
20919
+ ]);
20920
+ const stepped = await runPrepared(parseCountersignArgv2, (env, once) => runPublicCountersign2(options.argv, env, io, once));
20921
+ if ("fail" in stepped) return stepped.fail;
20922
+ result = stepped.ok;
20923
+ break;
20924
+ }
20259
20925
  }
20260
- const stderr = captured?.stderrText();
20261
- const runDirectory = result.admitted?.runDirectory;
20262
- return {
20263
- exitCode: result.exitCode,
20264
- ...result.terminal === void 0 ? {} : { terminal: result.terminal },
20265
- ...result.admitted === void 0 ? {} : { admitted: result.admitted },
20266
- ...typeof runDirectory === "string" && runDirectory.trim() !== "" ? { runDirectory } : {},
20267
- ...stderr === void 0 || stderr === "" ? {} : { stderr }
20268
- };
20269
- }
20270
- async function summonGateOfficer(options) {
20271
- let home = options.home;
20272
- if (home === void 0) {
20273
- const { homeFromRunDirectory: homeFromRunDirectory2 } = await Promise.resolve().then(() => (init_activation_ledger_topology(), activation_ledger_topology_exports));
20274
- home = homeFromRunDirectory2(options.sourceRunDirectory);
20275
- }
20276
- let gateReviewInstruction;
20277
- if (options.reask === void 0 && options.submission !== void 0) {
20278
- const { readableGateItem: readableGateItem2 } = await Promise.resolve().then(() => (init_readable_gate_item(), readable_gate_item_exports));
20279
- gateReviewInstruction = readableGateItem2(options.submission);
20280
- }
20281
- const common = {
20282
- cwd: options.cwd,
20283
- ...home === void 0 ? {} : { home },
20284
- ...options.packageRoot === void 0 ? {} : { packageRoot: options.packageRoot },
20285
- ...options.io === void 0 ? {} : { io: options.io },
20286
- ...options.signal === void 0 ? {} : { signal: options.signal },
20287
- ...options.reask === void 0 ? {} : { reviewReask: options.reask },
20288
- ...gateReviewInstruction === void 0 ? {} : { gateReviewInstruction },
20289
- ...options.roleTurnHost === void 0 ? {} : { roleTurnHost: options.roleTurnHost },
20290
- ...options.hostAdapters === void 0 ? {} : { hostAdapters: options.hostAdapters },
20291
- ...options.createRunId === void 0 ? {} : { createRunId: options.createRunId }
20292
- };
20293
- if (options.officer === "notary") {
20294
- return summonPublicRole({
20295
- role: "notary",
20296
- argv: ["--source-run", options.sourceRunDirectory, "--project", options.cwd],
20297
- ...common
20298
- });
20299
- }
20300
- if (options.officer === "auditor") {
20301
- return summonPublicRole({
20302
- role: "auditor",
20303
- argv: [
20304
- "--subject",
20305
- "judge",
20306
- "--source-run",
20307
- options.sourceRunDirectory,
20308
- `\u5377\u5B97\u6307\u9488\uFF1A${options.sourceRunDirectory}`
20309
- ],
20310
- ...common
20311
- });
20312
- }
20313
- return summonPublicRole({
20314
- role: "inspector",
20315
- argv: [`\u5377\u5B97\u6307\u9488\uFF1A${options.sourceRunDirectory}`],
20316
- ...common
20317
- });
20318
- }
20319
- var AK_ROLE_PACKAGE_ROOT_ENV;
20320
- var init_public_role_summons = __esm({
20321
- "src/public-role-summons.ts"() {
20322
- "use strict";
20323
- init_engine_material();
20324
- AK_ROLE_PACKAGE_ROOT_ENV = "AK_ROLE_PACKAGE_ROOT";
20325
- }
20326
- });
20327
-
20328
- // src/gatekeeper-role.ts
20329
- function gateSeatLabel(stage) {
20330
- if (stage === "inspector") return "\u53F0\u9662";
20331
- if (stage === "auditor") return "\u5BA1\u5211\u9662";
20332
- return "\u7B26\u5B9D\u90CE";
20333
- }
20334
- function gateOfficerForSubject(subject) {
20335
- if (subject.kind === "worker_completion") return "inspector";
20336
- if (subject.kind === "judge_compliance") return "auditor";
20337
- return "notary";
20338
- }
20339
- function failureReason(error) {
20340
- if (error instanceof AggregateError) return error.errors.map(failureReason).join("; ");
20341
- return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
20342
- }
20343
- function retainedReceipt(decision) {
20344
- return decision;
20345
- }
20346
- function readRecord(value) {
20347
- if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
20348
- return value;
20349
- }
20350
- function projectOfficerDecision(officer, decision, fallbackStatus) {
20351
- const receipt = retainedReceipt(decision);
20352
- const record4 = readRecord(decision);
20353
- const status = (record4 !== void 0 && typeof record4.status === "string" ? record4.status : void 0) ?? fallbackStatus;
20354
- if (status === "pass") {
20355
- return { status: "pass", officer, receipt };
20356
- }
20357
- if (status === "bounce" || status === "escalate") {
20358
- return { status, officer, receipt };
20359
- }
20360
- return { status: "needs_reask", officer, receipt };
20361
- }
20362
- function thisCourtOfficerPayloads(terminal) {
20363
- const outcome = terminal?.roleOutcome;
20364
- if (outcome !== void 0 && (outcome.kind === "accepted" || outcome.kind === "audit_escalation")) {
20365
- if (outcome.payloads !== void 0 && outcome.payloads.length > 0) return outcome.payloads;
20366
- }
20367
- if (outcome?.kind === "failure" && outcome.payloads !== void 0 && outcome.payloads.length > 0) {
20368
- return outcome.payloads;
20369
- }
20370
- return [];
20371
- }
20372
- function officerFailurePayloads(terminal) {
20373
- const outcome = terminal?.roleOutcome;
20374
- if (outcome?.kind === "failure") return outcome.payloads ?? terminal?.submissions ?? [];
20375
- return terminal?.submissions ?? [];
20376
- }
20377
- function projectOfficerPayloads(officer, payloads, fallbackStatus) {
20378
- if (payloads.length === 0) {
20379
- return projectOfficerDecision(officer, void 0, fallbackStatus);
20380
- }
20381
- return projectOfficerDecision(officer, payloads[payloads.length - 1], fallbackStatus);
20926
+ const stderr = captured?.stderrText();
20927
+ const runDirectory = result.admitted?.runDirectory;
20928
+ return {
20929
+ exitCode: result.exitCode,
20930
+ ...result.terminal === void 0 ? {} : { terminal: result.terminal },
20931
+ ...result.admitted === void 0 ? {} : { admitted: result.admitted },
20932
+ ...typeof runDirectory === "string" && runDirectory.trim() !== "" ? { runDirectory } : {},
20933
+ ...stderr === void 0 || stderr === "" ? {} : { stderr }
20934
+ };
20382
20935
  }
20383
- function projectOfficerTerminal(officer, summoned) {
20384
- const terminal = summoned.terminal;
20385
- const outcome = terminal?.roleOutcome;
20386
- const thisCourt = thisCourtOfficerPayloads(terminal);
20387
- if (outcome === void 0) {
20388
- const detail = summoned.stderr ?? "";
20389
- const failurePayloads = officerFailurePayloads(terminal);
20390
- return {
20391
- status: "transport_failure",
20392
- stage: officer,
20393
- reason: detail.length > 0 ? `${gateSeatLabel(officer)} public summon exit ${summoned.exitCode}: ${detail}` : `${gateSeatLabel(officer)} public summon produced no terminal (exit ${summoned.exitCode})`,
20394
- submission: failurePayloads.length > 0 ? failurePayloads : summoned
20395
- };
20396
- }
20397
- if (outcome.kind === "no_receipt") {
20398
- return {
20399
- status: "no_receipt",
20400
- stage: officer,
20401
- reason: typeof outcome.status === "string" && outcome.status.length > 0 ? outcome.status : "no_receipt",
20402
- facts: outcome
20403
- };
20404
- }
20405
- if (outcome.kind === "failure") {
20406
- const failurePayloads = officerFailurePayloads(terminal);
20407
- return {
20408
- status: "transport_failure",
20409
- stage: officer,
20410
- reason: outcome.diagnostic,
20411
- submission: failurePayloads.length > 0 ? failurePayloads : outcome.decisiveFacts
20412
- };
20413
- }
20414
- if (outcome.kind === "audit_escalation") {
20415
- return {
20416
- status: "escalate",
20417
- officer,
20418
- // This-court receipt only (#879) — historical rows remain on terminal.submissions.
20419
- receipt: thisCourt.length > 0 ? thisCourt[thisCourt.length - 1] : retainedReceipt(outcome)
20420
- };
20936
+ async function summonGateOfficer(options) {
20937
+ let home = options.home;
20938
+ if (home === void 0) {
20939
+ const { homeFromRunDirectory: homeFromRunDirectory2 } = await Promise.resolve().then(() => (init_activation_ledger_topology(), activation_ledger_topology_exports));
20940
+ home = homeFromRunDirectory2(options.sourceRunDirectory);
20421
20941
  }
20422
- if (outcome.kind === "accepted") {
20423
- return projectOfficerPayloads(officer, thisCourt, outcome.status);
20942
+ let gateReviewInstruction;
20943
+ if (options.reask === void 0 && options.submission !== void 0) {
20944
+ const { readableGateItem: readableGateItem2 } = await Promise.resolve().then(() => (init_readable_gate_item(), readable_gate_item_exports));
20945
+ gateReviewInstruction = readableGateItem2(options.submission);
20424
20946
  }
20425
- return {
20426
- status: "needs_reask",
20427
- officer,
20428
- // This-court receipt only (#879).
20429
- receipt: thisCourt.length > 0 ? thisCourt[thisCourt.length - 1] : retainedReceipt(outcome)
20947
+ const common = {
20948
+ cwd: options.cwd,
20949
+ ...home === void 0 ? {} : { home },
20950
+ ...options.packageRoot === void 0 ? {} : { packageRoot: options.packageRoot },
20951
+ ...options.io === void 0 ? {} : { io: options.io },
20952
+ ...options.signal === void 0 ? {} : { signal: options.signal },
20953
+ ...options.reask === void 0 ? {} : { reviewReask: options.reask },
20954
+ ...gateReviewInstruction === void 0 ? {} : { gateReviewInstruction },
20955
+ ...options.roleTurnHost === void 0 ? {} : { roleTurnHost: options.roleTurnHost },
20956
+ ...options.hostAdapters === void 0 ? {} : { hostAdapters: options.hostAdapters },
20957
+ ...options.createRunId === void 0 ? {} : { createRunId: options.createRunId }
20430
20958
  };
20431
- }
20432
- async function projectGatekeeperRun(options) {
20433
- const officer = gateOfficerForSubject(options.subject);
20434
- const runDirectory = options.runDirectory ?? auditorRunDirectory(options.context);
20435
- if (runDirectory === void 0) {
20436
- return {
20437
- officer,
20438
- result: {
20439
- status: "transport_failure",
20440
- stage: officer,
20441
- reason: `${gateSeatLabel(officer)} requires a parent run directory pointer`
20442
- }
20443
- };
20959
+ if (options.officer === "notary") {
20960
+ return summonPublicRole({
20961
+ role: "notary",
20962
+ argv: ["--source-run", options.sourceRunDirectory, "--project", options.cwd],
20963
+ ...common
20964
+ });
20444
20965
  }
20445
- let summoned;
20446
- try {
20447
- const summon = options.summonOfficer ?? (async (nextOfficer, sourceRunDirectory, officerSignal, reask, nextSubmission) => {
20448
- const { summonGateOfficer: summonGateOfficer2 } = await Promise.resolve().then(() => (init_public_role_summons(), public_role_summons_exports));
20449
- return summonGateOfficer2({
20450
- officer: nextOfficer,
20451
- sourceRunDirectory,
20452
- cwd: options.context.cwd ?? process.cwd(),
20453
- ...officerSignal === void 0 ? {} : { signal: officerSignal },
20454
- ...reask === void 0 ? {} : { reask },
20455
- ...nextSubmission === void 0 ? {} : { submission: nextSubmission },
20456
- ...options.home === void 0 ? {} : { home: options.home },
20457
- ...options.packageRoot === void 0 ? {} : { packageRoot: options.packageRoot },
20458
- ...options.roleTurnHost === void 0 ? {} : { roleTurnHost: options.roleTurnHost },
20459
- ...options.createRunId === void 0 ? {} : { createRunId: options.createRunId }
20460
- });
20966
+ if (options.officer === "auditor") {
20967
+ return summonPublicRole({
20968
+ role: "auditor",
20969
+ argv: [
20970
+ "--subject",
20971
+ "judge",
20972
+ "--source-run",
20973
+ options.sourceRunDirectory,
20974
+ `\u5377\u5B97\u6307\u9488\uFF1A${options.sourceRunDirectory}`
20975
+ ],
20976
+ ...common
20461
20977
  });
20462
- summoned = await summon(
20463
- officer,
20464
- runDirectory,
20465
- options.signal,
20466
- options.reask,
20467
- options.submission
20468
- );
20469
- } catch (error) {
20470
- return {
20471
- officer,
20472
- result: { status: "transport_failure", stage: officer, reason: failureReason(error) }
20473
- };
20474
20978
  }
20475
- return {
20476
- officer,
20477
- result: projectOfficerTerminal(officer, summoned),
20478
- summoned
20479
- };
20979
+ return summonPublicRole({
20980
+ role: "inspector",
20981
+ argv: [`\u5377\u5B97\u6307\u9488\uFF1A${options.sourceRunDirectory}`],
20982
+ ...common
20983
+ });
20480
20984
  }
20481
- var GATEKEEPER_TOOL_SPEC, OFFICER_CONCLUSION_REASK;
20482
- var init_gatekeeper_role = __esm({
20483
- "src/gatekeeper-role.ts"() {
20985
+ var AK_ROLE_PACKAGE_ROOT_ENV;
20986
+ var init_public_role_summons = __esm({
20987
+ "src/public-role-summons.ts"() {
20484
20988
  "use strict";
20485
- init_auditor_dossier_tool();
20486
- init_submission_errors();
20487
- init_inspector_contracts();
20488
- init_gatekeeper_output();
20489
- init_submission_errors();
20490
- GATEKEEPER_TOOL_SPEC = {
20491
- name: GATEKEEPER_OUTPUT_TOOL_NAME,
20492
- label: "\u95E8\u4E0B\u7701\u51B3\u8BAE",
20493
- description: "\u95E8\u4E0B\u7701\u7EC8\u5C40\u51B3\u8BAE\uFF0C\u72B6\u6001\u4E3A dispatch \u6216 pass\u3002",
20494
- promptSnippet: "\u95E8\u4E0B\u7701\u51B3\u8BAE",
20495
- parameters: gatekeeperOutputSchema
20496
- };
20497
- OFFICER_CONCLUSION_REASK = "\u4E0A\u6B21\u4EA4\u5377\u7684\u7ED3\u8BBA\u4E0D\u662F pass\u3001bounce\u3001escalate \u4E09\u6001\u4E4B\u4E00\u3002\u8BF7\u91CD\u65B0\u8F93\u51FA\uFF0C\u7ED3\u8BBA\u5B57\u6BB5\u5199\u660E\u5176\u4E00\uFF1B\u6253\u56DE\u6216\u4E0A\u5448\u7684\u8BDD\u5C31\u662F\u7ED9\u5BF9\u65B9\u770B\u7684\u539F\u6587\u3002";
20989
+ init_engine_material();
20990
+ AK_ROLE_PACKAGE_ROOT_ENV = "AK_ROLE_PACKAGE_ROOT";
20498
20991
  }
20499
20992
  });
20500
20993
 
@@ -20506,13 +20999,30 @@ init_engine_detour();
20506
20999
  import { randomUUID as randomUUID8 } from "node:crypto";
20507
21000
  import { mkdir as mkdir5, readFile as readFile21, writeFile as writeFile12 } from "node:fs/promises";
20508
21001
  import { createServer } from "node:net";
20509
- import { basename as basename10, dirname as dirname21, join as join41 } from "node:path";
21002
+ import { basename as basename9, dirname as dirname21, join as join41 } from "node:path";
20510
21003
  import { fileURLToPath as fileURLToPath2 } from "node:url";
20511
21004
 
20512
21005
  // src/gatekeeper-pass-envelope.ts
20513
21006
  init_archivist_record_entry();
20514
21007
  init_gatekeeper_role();
20515
21008
  init_session_assistant_usage();
21009
+ function createDefaultGateOfficerSummon(options) {
21010
+ return async (officer, sourceRunDirectory, signal, reask, submission) => {
21011
+ const { summonGateOfficer: summonGateOfficer2 } = await Promise.resolve().then(() => (init_public_role_summons(), public_role_summons_exports));
21012
+ return summonGateOfficer2({
21013
+ officer,
21014
+ sourceRunDirectory,
21015
+ cwd: options.cwd,
21016
+ ...signal === void 0 ? {} : { signal },
21017
+ ...reask === void 0 ? {} : { reask },
21018
+ ...submission === void 0 ? {} : { submission },
21019
+ ...options.home === void 0 ? {} : { home: options.home },
21020
+ ...options.packageRoot === void 0 ? {} : { packageRoot: options.packageRoot },
21021
+ ...options.roleTurnHost === void 0 ? {} : { roleTurnHost: options.roleTurnHost },
21022
+ ...options.createRunId === void 0 ? {} : { createRunId: options.createRunId }
21023
+ });
21024
+ };
21025
+ }
20516
21026
  function bookDirectOfficerPointer(context, officer, result, summoned) {
20517
21027
  if (result.status !== "pass" && result.status !== "bounce" && result.status !== "escalate" && result.status !== "needs_reask" && result.status !== "transport_failure") {
20518
21028
  return;
@@ -20532,12 +21042,15 @@ function bookDirectOfficerPointer(context, officer, result, summoned) {
20532
21042
  }
20533
21043
  async function requireGatekeeperPass(options) {
20534
21044
  let reask;
21045
+ const summonOfficer = options.summonOfficer ?? createDefaultGateOfficerSummon({
21046
+ cwd: options.context.cwd ?? process.cwd()
21047
+ });
20535
21048
  for (; ; ) {
20536
21049
  const projected = await projectGatekeeperRun({
20537
21050
  context: options.context,
20538
21051
  subject: options.subject,
21052
+ summonOfficer,
20539
21053
  ...options.signal === void 0 ? {} : { signal: options.signal },
20540
- ...options.summonOfficer === void 0 ? {} : { summonOfficer: options.summonOfficer },
20541
21054
  ...options.submission === void 0 ? {} : { submission: options.submission },
20542
21055
  ...reask === void 0 ? {} : { reask }
20543
21056
  });
@@ -20995,14 +21508,8 @@ init_engine_material();
20995
21508
  // src/engine-detour-tool.ts
20996
21509
  init_engine_detour();
20997
21510
  init_engine_detour_usage();
20998
- import { basename as basename9 } from "node:path";
21511
+ init_run_terminal_artifacts();
20999
21512
  import { Type as Type14 } from "typebox";
21000
- function basenameRunId(runDirectory) {
21001
- const leaf = basename9(runDirectory);
21002
- const at = leaf.indexOf("@");
21003
- if (at <= 0) return void 0;
21004
- return leaf.slice(0, at);
21005
- }
21006
21513
  var engineDetourArgsSchema = Type14.Object(
21007
21514
  {
21008
21515
  argv: Type14.Array(Type14.String({ minLength: 1 }), {
@@ -21045,7 +21552,7 @@ function createEngineDetourToolDefinition(input) {
21045
21552
  const sessionParent = ctx.sessionManager?.getSessionFile?.();
21046
21553
  const startedAt = Date.now();
21047
21554
  const runDirectory = typeof ctx.runDirectory === "string" && ctx.runDirectory.length > 0 ? ctx.runDirectory : void 0;
21048
- const runId = runDirectory === void 0 ? void 0 : basenameRunId(runDirectory);
21555
+ const runId = runDirectory === void 0 ? void 0 : runIdFromRunDirectory(runDirectory);
21049
21556
  const invocationScopeId = typeof ctx.invocationScopeId === "string" && ctx.invocationScopeId.trim() !== "" ? ctx.invocationScopeId.trim() : void 0;
21050
21557
  const host = typeof ctx.host === "string" && ctx.host.trim() !== "" ? ctx.host.trim() : void 0;
21051
21558
  const recordCall = (observed2) => {
@@ -21136,6 +21643,7 @@ function registerEngineDetourTool(roleHost, hostActions) {
21136
21643
  }
21137
21644
 
21138
21645
  // src/role-runtime.ts
21646
+ init_run_terminal_artifacts();
21139
21647
  init_receipt_delivery_policy();
21140
21648
 
21141
21649
  // src/collector-role.ts
@@ -22315,7 +22823,121 @@ var DIARIST_TOOL_SPEC = {
22315
22823
  parameters: diaristOutputSchema
22316
22824
  };
22317
22825
 
22826
+ // src/secretariat-role.ts
22827
+ init_terminating_infrastructure();
22828
+ init_secretariat_contracts();
22829
+ init_run_terminal_artifacts();
22830
+ init_secretariat_contracts();
22831
+ import { Type as Type20 } from "typebox";
22832
+ var secretariatVerdictSchema = withTerminatingOutputDeclarations(
22833
+ Type20.Object(
22834
+ {
22835
+ secretariatStatus: Type20.Unknown({
22836
+ description: "converged | escalate\uFF08\u7EC8\u5C40\u5F62\u72B6\u6307\u5F15\uFF0C\u975E\u95F8\uFF09"
22837
+ }),
22838
+ ticketNumber: Type20.Optional(
22839
+ Type20.Number({ description: "\u672C\u7968\u53F7\uFF1B\u7F72\u65F6\u6307\u5411\u6700\u7EC8\u6B63\u6587\u6240\u5728\u7968" })
22840
+ ),
22841
+ note: Type20.Optional(Type20.String({ description: "\u9644\u6CE8" })),
22842
+ evidence: Type20.Optional(Type20.Unknown({ description: "\u7559\u5B58\u8BC1\u636E" })),
22843
+ decisionGate: Type20.Optional(
22844
+ Type20.Object(
22845
+ {
22846
+ question: Type20.Optional(Type20.String()),
22847
+ options: Type20.Optional(Type20.Array(Type20.String()))
22848
+ },
22849
+ { additionalProperties: true, description: "\u9700\u965B\u4E0B\u5904\u7F6E\u7684\u95EE\u9898\u4E0E\u9009\u9879" }
22850
+ )
22851
+ )
22852
+ },
22853
+ { additionalProperties: true }
22854
+ )
22855
+ );
22856
+ secretariatVerdictSchema.required = [];
22857
+ var secretariatSummonCountersignSchema = Type20.Object(
22858
+ {
22859
+ instruction: Type20.Optional(
22860
+ Type20.String({
22861
+ description: "\u4F20\u53EC\u6563\u6587\uFF1B\u7968\u53F7\u5199\u5728\u5176\u4E2D\u3002\u7A7A\u5219\u6CBF\u7528\u672C\u5C40\u6307\u4EE4\u3002"
22862
+ })
22863
+ )
22864
+ },
22865
+ { additionalProperties: true }
22866
+ );
22867
+ secretariatSummonCountersignSchema.required = [];
22868
+ var SECRETARIAT_OUTPUT_TOOL_SPEC = {
22869
+ name: SECRETARIAT_OUTPUT_TOOL_NAME,
22870
+ label: "\u4E2D\u4E66\u7701\u8F93\u51FA",
22871
+ description: "\u4E2D\u4E66\u7701\u7EC8\u5C40\u56DE\u6267\uFF08\u7F72\u6216\u4E0A\u5448\uFF09\uFF1B\u7ED9\u4E8B\u4E2D\u5C01\u9A73\u987B\u6539\u7968\u91CD\u9001\uFF0C\u4E0D\u5728\u6B64\u7EC8\u5C40\u3002",
22872
+ promptSnippet: "\u4E2D\u4E66\u7701\u7EC8\u5C40\u56DE\u6267",
22873
+ parameters: secretariatVerdictSchema
22874
+ };
22875
+ var SECRETARIAT_SUMMON_COUNTERSIGN_TOOL_SPEC = {
22876
+ name: SECRETARIAT_SUMMON_COUNTERSIGN_TOOL_NAME,
22877
+ label: "\u4F20\u53EC\u7ED9\u4E8B\u4E2D",
22878
+ description: "\u7ECF\u5171\u4EAB\u6267\u884C\u63A5\u7F1D\u4F20\u53EC\u7ED9\u4E8B\u4E2D\u5BA1\u7968\uFF1B\u5C01\u9A73\u540E\u7EED\u540C\u4E00 run \u518D\u9001\u3002",
22879
+ promptSnippet: "\u4F20\u53EC\u7ED9\u4E8B\u4E2D",
22880
+ parameters: secretariatSummonCountersignSchema
22881
+ };
22882
+ function latestObjectPayload(payloads) {
22883
+ if (payloads === void 0 || payloads.length === 0) return void 0;
22884
+ const latest = payloads[payloads.length - 1];
22885
+ if (latest === null || typeof latest !== "object" || Array.isArray(latest)) {
22886
+ return void 0;
22887
+ }
22888
+ return latest;
22889
+ }
22890
+ function projectSecretariatSummonResult(summoned) {
22891
+ const terminal = summoned.terminal;
22892
+ const roleOutcome = terminal?.roleOutcome;
22893
+ const runDirectory = summoned.runDirectory;
22894
+ const runId = typeof runDirectory === "string" && runDirectory.trim() !== "" ? runIdFromRunDirectory(runDirectory) : void 0;
22895
+ const base = {
22896
+ exitCode: summoned.exitCode,
22897
+ ...runId === void 0 ? {} : { runId },
22898
+ ...runDirectory === void 0 ? {} : { runDirectory },
22899
+ ...summoned.stderr === void 0 || summoned.stderr === "" ? {} : { stderr: summoned.stderr }
22900
+ };
22901
+ if (roleOutcome === void 0) {
22902
+ return { ...base, outcomeKind: "no_terminal" };
22903
+ }
22904
+ if (roleOutcome.kind === "accepted" || roleOutcome.kind === "audit_escalation") {
22905
+ const payloads = Array.isArray(roleOutcome.payloads) ? roleOutcome.payloads : void 0;
22906
+ const latest = latestObjectPayload(payloads);
22907
+ const countersignStatus = latest !== void 0 && typeof latest.countersignStatus === "string" ? latest.countersignStatus : void 0;
22908
+ return {
22909
+ ...base,
22910
+ outcomeKind: roleOutcome.kind,
22911
+ // audit_escalation carries typed status; accepted may carry fixture/compat status.
22912
+ ..."status" in roleOutcome && typeof roleOutcome.status === "string" && roleOutcome.status.length > 0 ? { status: roleOutcome.status } : {},
22913
+ ...countersignStatus === void 0 ? {} : { countersignStatus },
22914
+ ...latest === void 0 ? {} : { receipt: latest },
22915
+ ...payloads === void 0 ? {} : { payloads },
22916
+ ...roleOutcome.decisiveFacts === void 0 ? {} : { decisiveFacts: roleOutcome.decisiveFacts }
22917
+ };
22918
+ }
22919
+ if (roleOutcome.kind === "failure") {
22920
+ const payloads = Array.isArray(roleOutcome.payloads) ? roleOutcome.payloads : void 0;
22921
+ return {
22922
+ ...base,
22923
+ outcomeKind: "failure",
22924
+ diagnostic: roleOutcome.diagnostic,
22925
+ ...roleOutcome.cause === void 0 ? {} : { cause: roleOutcome.cause },
22926
+ ...roleOutcome.decisiveFacts === void 0 ? {} : { decisiveFacts: roleOutcome.decisiveFacts },
22927
+ ...payloads === void 0 ? {} : { payloads },
22928
+ ...latestObjectPayload(payloads) === void 0 ? {} : { receipt: latestObjectPayload(payloads) }
22929
+ };
22930
+ }
22931
+ return {
22932
+ ...base,
22933
+ outcomeKind: roleOutcome.kind,
22934
+ ..."status" in roleOutcome && typeof roleOutcome.status === "string" && roleOutcome.status.length > 0 ? { status: roleOutcome.status } : {},
22935
+ ..."decisiveFacts" in roleOutcome && roleOutcome.decisiveFacts !== void 0 ? { decisiveFacts: roleOutcome.decisiveFacts } : {}
22936
+ };
22937
+ }
22938
+
22318
22939
  // src/role-runtime.ts
22940
+ init_secretariat_contracts();
22319
22941
  init_diarist_contracts();
22320
22942
 
22321
22943
  // src/diarist.ts
@@ -22373,13 +22995,13 @@ init_packaged_role_registry();
22373
22995
  init_activation_ledger_topology();
22374
22996
  import { resolve as resolve16 } from "node:path";
22375
22997
  import "@earendil-works/pi-coding-agent";
22376
- import { Type as Type21 } from "typebox";
22998
+ import { Type as Type22 } from "typebox";
22377
22999
 
22378
23000
  // src/navigator-public-session.ts
22379
23001
  init_sitian_facade();
22380
23002
 
22381
23003
  // src/navigator-session-contracts.ts
22382
- import { Type as Type20 } from "typebox";
23004
+ import { Type as Type21 } from "typebox";
22383
23005
  import { Value as Value3 } from "typebox/value";
22384
23006
  var NAVIGATOR_PREPARE_TOOL_NAME = "ak_navigator_prepare";
22385
23007
  var NAVIGATOR_UNAVAILABLE_KEYS = /* @__PURE__ */ new Set([
@@ -22487,26 +23109,26 @@ function navigatorProviderFailureFromPublicTerminal(outcome) {
22487
23109
  if (typed !== void 0) return { source: typed, cause: typed };
22488
23110
  return { source: "unknown", cause: "unknown" };
22489
23111
  }
22490
- var navigatorProviderFailureSchema = Type20.Object({
22491
- source: Type20.Union([
22492
- Type20.Literal("context"),
22493
- Type20.Literal("session"),
22494
- Type20.Literal("model"),
22495
- Type20.Literal("thinking"),
22496
- Type20.Literal("auth"),
22497
- Type20.Literal("quota"),
22498
- Type20.Literal("transport"),
22499
- Type20.Literal("unknown")
23112
+ var navigatorProviderFailureSchema = Type21.Object({
23113
+ source: Type21.Union([
23114
+ Type21.Literal("context"),
23115
+ Type21.Literal("session"),
23116
+ Type21.Literal("model"),
23117
+ Type21.Literal("thinking"),
23118
+ Type21.Literal("auth"),
23119
+ Type21.Literal("quota"),
23120
+ Type21.Literal("transport"),
23121
+ Type21.Literal("unknown")
22500
23122
  ]),
22501
- cause: Type20.Union([
22502
- Type20.Literal("context"),
22503
- Type20.Literal("session"),
22504
- Type20.Literal("model"),
22505
- Type20.Literal("thinking"),
22506
- Type20.Literal("auth"),
22507
- Type20.Literal("quota"),
22508
- Type20.Literal("transport"),
22509
- Type20.Literal("unknown")
23123
+ cause: Type21.Union([
23124
+ Type21.Literal("context"),
23125
+ Type21.Literal("session"),
23126
+ Type21.Literal("model"),
23127
+ Type21.Literal("thinking"),
23128
+ Type21.Literal("auth"),
23129
+ Type21.Literal("quota"),
23130
+ Type21.Literal("transport"),
23131
+ Type21.Literal("unknown")
22510
23132
  ])
22511
23133
  }, { additionalProperties: false });
22512
23134
  function parseNavigatorModelSetting(value) {
@@ -22712,8 +23334,8 @@ function resolveNavigatorAuthorityMaterial(roleInput, fileAuthority) {
22712
23334
  return void 0;
22713
23335
  }
22714
23336
  var NAVIGATOR_TARGETS = PACKAGED_ROLE_REGISTRY.map(({ role, phases }) => ({ role, phases }));
22715
- var prepareSchema = Type21.Object({
22716
- candidates: Type21.Optional(Type21.Unknown({
23337
+ var prepareSchema = Type22.Object({
23338
+ candidates: Type22.Optional(Type22.Unknown({
22717
23339
  description: "\u65B9\u5411\u5019\u9009\uFF1Bcandidates[].next.role \u5FC5\u586B\uFF0Cphase \u53EF\u9009\uFF0Croute/matches/reason/command \u53EF\u9009\u4E0A\u4E0B\u6587\uFF0C\u975E\u53D7\u7406\u95F8"
22718
23340
  }))
22719
23341
  }, { additionalProperties: true });
@@ -23343,32 +23965,32 @@ init_audit_escalation();
23343
23965
  init_terminating_infrastructure();
23344
23966
  init_submission_errors();
23345
23967
  init_judge_output();
23346
- import { Type as Type22 } from "typebox";
23968
+ import { Type as Type23 } from "typebox";
23347
23969
  var JUDGE_QUEUE_STATUSES = /* @__PURE__ */ new Set(["converged", "continue", "escalate"]);
23348
23970
  var JUDGE_STATUS_REASK = "judgeStatus \u4E0D\u662F converged\u3001continue\u3001escalate \u4E09\u6001\u4E4B\u4E00\u3002\u8BF7\u91CD\u65B0\u4EA4\u5377\uFF0Cstatus \u5199\u660E\u5176\u4E00\u3002";
23349
23971
  var judgeVerdictSchema = withTerminatingOutputDeclarations(
23350
- Type22.Object(
23972
+ Type23.Object(
23351
23973
  {
23352
- judgeStatus: Type22.Unknown({ description: "converged | continue | escalate \u2014 \u5F62\u72B6\u6307\u5F15\uFF0C\u975E schema \u95F8" }),
23353
- fix: Type22.Optional(
23354
- Type22.Object(
23355
- { summary: Type22.Optional(Type22.String({ description: "continue \u65F6\u7684\u8865\u6551\u6458\u8981" })) },
23974
+ judgeStatus: Type23.Unknown({ description: "converged | continue | escalate \u2014 \u5F62\u72B6\u6307\u5F15\uFF0C\u975E schema \u95F8" }),
23975
+ fix: Type23.Optional(
23976
+ Type23.Object(
23977
+ { summary: Type23.Optional(Type23.String({ description: "continue \u65F6\u7684\u8865\u6551\u6458\u8981" })) },
23356
23978
  { additionalProperties: true, description: "continue \u65F6\u7684\u8865\u6551\u8BF4\u660E" }
23357
23979
  )
23358
23980
  ),
23359
- classes: Type22.Optional(Type22.Array(Type22.Object({
23360
- name: Type22.Optional(Type22.String()),
23361
- owner: Type22.Optional(Type22.String()),
23362
- boundary: Type22.Optional(Type22.String()),
23363
- disposition: Type22.Optional(Type22.String())
23981
+ classes: Type23.Optional(Type23.Array(Type23.Object({
23982
+ name: Type23.Optional(Type23.String()),
23983
+ owner: Type23.Optional(Type23.String()),
23984
+ boundary: Type23.Optional(Type23.String()),
23985
+ disposition: Type23.Optional(Type23.String())
23364
23986
  }, { additionalProperties: true }), { description: "\u5DF2\u88C1\u51B3 finding \u7C7B\u53CA\u5176 owner \u4E0E\u4FEE\u7406\u8FB9\u754C" })),
23365
- note: Type22.Optional(Type22.String({ description: "\u53EF\u9009\u88C1\u51B3\u9644\u6CE8" })),
23366
- evidence: Type22.Optional(Type22.Unknown({ description: "\u7559\u5B58\u7684\u88C1\u51B3\u8BC1\u636E" })),
23367
- decisionGate: Type22.Optional(
23368
- Type22.Object(
23987
+ note: Type23.Optional(Type23.String({ description: "\u53EF\u9009\u88C1\u51B3\u9644\u6CE8" })),
23988
+ evidence: Type23.Optional(Type23.Unknown({ description: "\u7559\u5B58\u7684\u88C1\u51B3\u8BC1\u636E" })),
23989
+ decisionGate: Type23.Optional(
23990
+ Type23.Object(
23369
23991
  {
23370
- question: Type22.Optional(Type22.String()),
23371
- options: Type22.Optional(Type22.Array(Type22.String()))
23992
+ question: Type23.Optional(Type23.String()),
23993
+ options: Type23.Optional(Type23.Array(Type23.String()))
23372
23994
  },
23373
23995
  { additionalProperties: true, description: "\u9700\u4EBA\u6743\u5A01\u5904\u7F6E\u7684\u95EE\u9898\u4E0E\u9009\u9879" }
23374
23996
  )
@@ -23456,21 +24078,21 @@ init_open_tool_schema();
23456
24078
  init_terminating_infrastructure();
23457
24079
  init_reviewer_pinned_git();
23458
24080
  init_reviewer_output();
23459
- import { Type as Type23 } from "typebox";
23460
- var reviewerAmendmentsSchema = Type23.Object({
23461
- standards: Type23.Optional(Type23.String({ description: "\u6807\u51C6\u8F74\u5F39\u7AE0\u6B63\u6587" })),
23462
- spec: Type23.Optional(Type23.String({ description: "\u89C4\u683C\u8F74\u5F39\u7AE0\u6B63\u6587" }))
24081
+ import { Type as Type24 } from "typebox";
24082
+ var reviewerAmendmentsSchema = Type24.Object({
24083
+ standards: Type24.Optional(Type24.String({ description: "\u6807\u51C6\u8F74\u5F39\u7AE0\u6B63\u6587" })),
24084
+ spec: Type24.Optional(Type24.String({ description: "\u89C4\u683C\u8F74\u5F39\u7AE0\u6B63\u6587" }))
23463
24085
  }, { additionalProperties: true, description: "\u9010\u8F74\u5F39\u7AE0\u6B63\u6587\uFF1B\u65E0\u5F39\u7AE0\u7684\u8F74\u53EF\u7701\u7565\u3002" });
23464
24086
  var REVIEWER_STATUS_DESCRIPTION = "completed | refused \u2014 \u5F62\u72B6\u6307\u5F15\uFF0C\u975E schema \u95F8";
23465
- var reviewerOutputVariants = Type23.Union([
23466
- Type23.Object({
23467
- status: Type23.Unknown({ description: REVIEWER_STATUS_DESCRIPTION }),
23468
- amendments: Type23.Optional(reviewerAmendmentsSchema)
24087
+ var reviewerOutputVariants = Type24.Union([
24088
+ Type24.Object({
24089
+ status: Type24.Unknown({ description: REVIEWER_STATUS_DESCRIPTION }),
24090
+ amendments: Type24.Optional(reviewerAmendmentsSchema)
23469
24091
  }, { additionalProperties: false }),
23470
- Type23.Object({
23471
- status: Type23.Unknown({ description: REVIEWER_STATUS_DESCRIPTION }),
23472
- diagnostic: Type23.String({ description: "\u62D2\u7EDD\u8BCA\u65AD\u8BF4\u660E" }),
23473
- amendments: Type23.Optional(reviewerAmendmentsSchema)
24092
+ Type24.Object({
24093
+ status: Type24.Unknown({ description: REVIEWER_STATUS_DESCRIPTION }),
24094
+ diagnostic: Type24.String({ description: "\u62D2\u7EDD\u8BCA\u65AD\u8BF4\u660E" }),
24095
+ amendments: Type24.Optional(reviewerAmendmentsSchema)
23474
24096
  }, { additionalProperties: false })
23475
24097
  ]);
23476
24098
  var reviewerOutputSchema = withTerminatingOutputDeclarations(
@@ -23526,7 +24148,7 @@ init_submission_correctable_error();
23526
24148
  init_worker_output();
23527
24149
  init_fixer_output();
23528
24150
  init_fixer_packet();
23529
- import { Type as Type24 } from "typebox";
24151
+ import { Type as Type25 } from "typebox";
23530
24152
 
23531
24153
  // src/worker-submission-gates.ts
23532
24154
  init_archivist_record_entry();
@@ -23791,20 +24413,20 @@ function fixerBashSeatbeltDenyReason(matched) {
23791
24413
 
23792
24414
  // src/worker-role.ts
23793
24415
  var CODER_STATUS_DESCRIPTION = "planned | completed | refused | unfinished \u2014 \u5F62\u72B6\u6307\u5F15\uFF0C\u975E schema \u95F8\uFF1Bcompleted \u56DE\u6267\u542B TDD\u3001\u540C\u6A21\u5F0F\u3001\u5F15\u5165\u56DE\u5F52\u3001\u884C\u4E3A\u4E8B\u5B9E\u56DB\u9879\u8BC1\u636E\uFF1Bunfinished \u7F3A\u524D\u7F6E\u6216\u8FDD\u5BAA\u7EA6\u675F\u81F4\u672C\u5C40\u672A\u5B8C\u6210\u65F6\u53EF\u7528\uFF0C\u7F3A\u5F85\u51B3 owner \u51B3\u5B9A\u6216\u7B54\u590D\u5C5E\u7F3A\u524D\u7F6E\u3002";
23794
- var coderOutputVariants = Type24.Union([
23795
- Type24.Object({
23796
- status: Type24.Unknown({ description: CODER_STATUS_DESCRIPTION }),
23797
- report: Type24.String({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" })
24416
+ var coderOutputVariants = Type25.Union([
24417
+ Type25.Object({
24418
+ status: Type25.Unknown({ description: CODER_STATUS_DESCRIPTION }),
24419
+ report: Type25.String({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" })
23798
24420
  }, { additionalProperties: false }),
23799
- Type24.Object({
23800
- status: Type24.Unknown({ description: CODER_STATUS_DESCRIPTION }),
23801
- report: Type24.String({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" })
24421
+ Type25.Object({
24422
+ status: Type25.Unknown({ description: CODER_STATUS_DESCRIPTION }),
24423
+ report: Type25.String({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" })
23802
24424
  }, { additionalProperties: false }),
23803
- Type24.Object({
23804
- status: Type24.Unknown({ description: CODER_STATUS_DESCRIPTION }),
23805
- report: Type24.String({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" }),
23806
- remainingScope: Type24.String({ description: "\u672C\u5C40\u540E\u5269\u4F59\u5DE5\u4F5C" }),
23807
- reason: Type24.Optional(Type24.String({
24425
+ Type25.Object({
24426
+ status: Type25.Unknown({ description: CODER_STATUS_DESCRIPTION }),
24427
+ report: Type25.String({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" }),
24428
+ remainingScope: Type25.String({ description: "\u672C\u5C40\u540E\u5269\u4F59\u5DE5\u4F5C" }),
24429
+ reason: Type25.Optional(Type25.String({
23808
24430
  minLength: 1,
23809
24431
  description: "\u963B\u65AD\u539F\u56E0\uFF1A\u7F3A\u524D\u7F6E\u6216\u8FDD\u5BAA\u7EA6\u675F\u3002\u7F3A\u5F85\u51B3 owner \u51B3\u5B9A\u6216\u7B54\u590D\u5C5E\u7F3A\u524D\u7F6E\u3002"
23810
24432
  }))
@@ -24356,6 +24978,8 @@ function activationStage(role, runtime) {
24356
24978
  return { id: "load-and-install", run: async () => runtime.auditor.activate() };
24357
24979
  case "diarist":
24358
24980
  return { id: "load-and-install", run: async () => runtime.diarist.activate() };
24981
+ case "secretariat":
24982
+ return { id: "load-and-install", run: async () => runtime.secretariat.activate() };
24359
24983
  case "merger":
24360
24984
  return { id: "prepare-git-and-install", run: async () => runtime.merger() };
24361
24985
  }
@@ -24459,7 +25083,7 @@ function publicNavigatorSettlement(role, phase, event) {
24459
25083
  if (isAuditEscalationProjection(event.details)) {
24460
25084
  return { kind: "human_decision", role, phase, status: "audit_escalation" };
24461
25085
  }
24462
- const status = typeof details.status === "string" ? details.status : typeof details.judgeStatus === "string" ? details.judgeStatus : typeof details.countersignStatus === "string" ? details.countersignStatus : void 0;
25086
+ const status = typeof details.status === "string" ? details.status : typeof details.judgeStatus === "string" ? details.judgeStatus : typeof details.countersignStatus === "string" ? details.countersignStatus : typeof details.secretariatStatus === "string" ? details.secretariatStatus : void 0;
24463
25087
  if (status !== void 0 && status === "escalate") {
24464
25088
  return { kind: "human_decision", role, phase, status };
24465
25089
  }
@@ -24613,21 +25237,28 @@ function readDiaristTicketAssertion(submitted) {
24613
25237
  }
24614
25238
  return { kind: "invalid" };
24615
25239
  }
24616
- function readDiaristRunCoordinates(ctx) {
25240
+ function readRoleRunCoordinates(ctx, label) {
24617
25241
  const runDirectory = runDirectoryFromHostContext(ctx);
24618
- if (runDirectory === void 0) {
24619
- throw new Error("diarist accept requires AK_ROLE_RUN_DIR");
24620
- }
25242
+ if (runDirectory === void 0) throw new Error(`${label} requires AK_ROLE_RUN_DIR`);
24621
25243
  const admittedPath = join40(runDirectory, "admitted-request.json");
24622
25244
  const admitted = JSON.parse(readFileSync6(admittedPath, "utf8"));
24623
25245
  if (typeof admitted.projectRoot !== "string" || admitted.projectRoot.trim() === "") {
24624
- throw new Error(`diarist admitted-request missing projectRoot (${admittedPath})`);
25246
+ throw new Error(`${label} admitted-request missing projectRoot (${admittedPath})`);
24625
25247
  }
24626
- const bound = typeof admitted.ticketNumber === "number" && Number.isSafeInteger(admitted.ticketNumber) && admitted.ticketNumber >= 1 ? admitted.ticketNumber : void 0;
24627
25248
  return {
24628
25249
  runDirectory,
24629
25250
  projectRoot: admitted.projectRoot,
24630
25251
  home: homeFromRunDirectory(runDirectory),
25252
+ admitted
25253
+ };
25254
+ }
25255
+ function readDiaristRunCoordinates(ctx) {
25256
+ const coordinates = readRoleRunCoordinates(ctx, "diarist accept");
25257
+ const bound = typeof coordinates.admitted.ticketNumber === "number" && Number.isSafeInteger(coordinates.admitted.ticketNumber) && coordinates.admitted.ticketNumber >= 1 ? coordinates.admitted.ticketNumber : void 0;
25258
+ return {
25259
+ runDirectory: coordinates.runDirectory,
25260
+ projectRoot: coordinates.projectRoot,
25261
+ home: coordinates.home,
24631
25262
  ...bound === void 0 ? {} : { boundTicketNumber: bound }
24632
25263
  };
24633
25264
  }
@@ -24696,6 +25327,100 @@ ${error.message}`
24696
25327
  }
24697
25328
  var COUNTERSIGN_QUEUE_STATUSES = /* @__PURE__ */ new Set(["converged", "continue", "escalate"]);
24698
25329
  var COUNTERSIGN_STATUS_REASK = "countersignStatus \u4E0D\u662F converged\u3001continue\u3001escalate \u4E09\u6001\u4E4B\u4E00\u3002\u8BF7\u91CD\u65B0\u4EA4\u5377\uFF0Cstatus \u5199\u660E\u5176\u4E00\u3002";
25330
+ function createSecretariatRoleRuntime(roleHost, dependencies) {
25331
+ let parentInstruction = "";
25332
+ const base = createFiledOfficerRuntime(
25333
+ roleHost,
25334
+ {
25335
+ role: "secretariat",
25336
+ tool: SECRETARIAT_OUTPUT_TOOL_SPEC,
25337
+ acceptedText: SECRETARIAT_ACCEPTED_TEXT,
25338
+ soulTag: "secretariat"
25339
+ },
25340
+ dependencies
25341
+ );
25342
+ let summonRegistered = false;
25343
+ return {
25344
+ async activate() {
25345
+ await base.activate();
25346
+ if (!summonRegistered) {
25347
+ summonRegistered = true;
25348
+ roleHost.on("before_agent_start", (event) => {
25349
+ if (typeof event.prompt === "string" && event.prompt.trim() !== "") {
25350
+ parentInstruction = event.prompt;
25351
+ }
25352
+ });
25353
+ roleHost.registerTool({
25354
+ name: SECRETARIAT_SUMMON_COUNTERSIGN_TOOL_NAME,
25355
+ label: SECRETARIAT_SUMMON_COUNTERSIGN_TOOL_SPEC.label,
25356
+ description: SECRETARIAT_SUMMON_COUNTERSIGN_TOOL_SPEC.description,
25357
+ promptSnippet: SECRETARIAT_SUMMON_COUNTERSIGN_TOOL_SPEC.promptSnippet,
25358
+ parameters: SECRETARIAT_SUMMON_COUNTERSIGN_TOOL_SPEC.parameters,
25359
+ async execute(_toolCallId, parameters, signal, _onUpdate, ctx) {
25360
+ const fromArgs = typeof parameters?.instruction === "string" ? parameters.instruction.trim() : "";
25361
+ const instruction = fromArgs !== "" ? fromArgs : parentInstruction.trim();
25362
+ const correlationId = (() => {
25363
+ const runDirectory = runDirectoryFromHostContext(ctx);
25364
+ if (runDirectory === void 0) return void 0;
25365
+ return runIdFromRunDirectory(runDirectory);
25366
+ })();
25367
+ const summon = dependencies.summonCountersign;
25368
+ const summoned = summon === void 0 ? await (async () => {
25369
+ const coordinates = readRoleRunCoordinates(ctx, "secretariat summons");
25370
+ const { summonPublicRole: summonPublicRole2 } = await Promise.resolve().then(() => (init_public_role_summons(), public_role_summons_exports));
25371
+ return summonPublicRole2({
25372
+ role: "countersign",
25373
+ argv: ["--project", coordinates.projectRoot, "--", instruction],
25374
+ cwd: coordinates.projectRoot,
25375
+ home: coordinates.home,
25376
+ ...signal === void 0 ? {} : { signal },
25377
+ ...correlationId === void 0 ? {} : { correlationId },
25378
+ ...dependencies.packageRoot === void 0 ? {} : { packageRoot: dependencies.packageRoot },
25379
+ ...dependencies.hostAdapters === void 0 ? {} : { hostAdapters: dependencies.hostAdapters }
25380
+ });
25381
+ })() : await summon({
25382
+ instruction,
25383
+ cwd: ctx.cwd,
25384
+ ...signal === void 0 ? {} : { signal },
25385
+ ...correlationId === void 0 ? {} : { correlationId },
25386
+ ...dependencies.home === void 0 ? {} : { home: dependencies.home },
25387
+ ...dependencies.packageRoot === void 0 ? {} : { packageRoot: dependencies.packageRoot }
25388
+ });
25389
+ const details = projectSecretariatSummonResult(summoned);
25390
+ const outcomeKind = typeof details.outcomeKind === "string" ? details.outcomeKind : "unknown";
25391
+ const contentText = outcomeKind === "accepted" || outcomeKind === "audit_escalation" ? "\u7ED9\u4E8B\u4E2D\u56DE\u6267\u5DF2\u9001\u8FBE\u4E2D\u4E66\u7701" : outcomeKind === "failure" ? "\u7ED9\u4E8B\u4E2D\u4F20\u53EC\u5931\u8D25" : outcomeKind === "no_receipt" ? "\u7ED9\u4E8B\u4E2D\u65E0\u56DE\u6267" : "\u7ED9\u4E8B\u4E2D\u4F20\u53EC\u672A\u5F97\u7EC8\u5C40";
25392
+ return {
25393
+ content: [{ type: "text", text: contentText }],
25394
+ details
25395
+ };
25396
+ }
25397
+ });
25398
+ }
25399
+ const packageRequired = [
25400
+ SECRETARIAT_OUTPUT_TOOL_NAME,
25401
+ SECRETARIAT_SUMMON_COUNTERSIGN_TOOL_NAME
25402
+ ];
25403
+ const all = roleHost.getAllTools().map((tool) => tool.name);
25404
+ for (const name of packageRequired) {
25405
+ if (all.filter((item) => item === name).length !== 1) {
25406
+ throw new Error(`secretariat required tool collision or missing: ${name}`);
25407
+ }
25408
+ }
25409
+ const priorActive = roleHost.getActiveTools();
25410
+ const hostSurface = priorActive.length > 0 ? priorActive : all;
25411
+ const nextActive = [
25412
+ .../* @__PURE__ */ new Set([...hostSurface, ...packageRequired])
25413
+ ];
25414
+ roleHost.setActiveTools(nextActive);
25415
+ const active = roleHost.getActiveTools();
25416
+ for (const name of packageRequired) {
25417
+ if (!active.includes(name)) {
25418
+ throw new Error(`secretariat failed to activate required tool ${name}`);
25419
+ }
25420
+ }
25421
+ }
25422
+ };
25423
+ }
24699
25424
  function createCountersignRoleRuntime(roleHost, dependencies, hostActions) {
24700
25425
  const beforeAccept = hostActions !== void 0 && roleHost.requireGatekeeperPass !== void 0 ? async ({ toolCallId, parameters, signal, ctx }) => {
24701
25426
  const record4 = parameters !== null && typeof parameters === "object" && !Array.isArray(parameters) ? parameters : void 0;
@@ -25240,6 +25965,13 @@ function createRoleRuntimeExtension(dependencies) {
25240
25965
  }
25241
25966
  }
25242
25967
  );
25968
+ const secretariat = createSecretariatRoleRuntime(roleHost, {
25969
+ async loadSoul() {
25970
+ if (!dependencies.loadSecretariatSoul) throw new Error("Secretariat runtime dependencies are not configured");
25971
+ return dependencies.loadSecretariatSoul();
25972
+ },
25973
+ ...dependencies.packageRoot === void 0 ? {} : { packageRoot: dependencies.packageRoot }
25974
+ });
25243
25975
  const merger = createMergerRoleRuntime(roleHost, {
25244
25976
  async loadSoul() {
25245
25977
  if (!dependencies.loadMergerSoul) throw new Error("Merger runtime dependencies are not configured");
@@ -25473,6 +26205,7 @@ function createRoleRuntimeExtension(dependencies) {
25473
26205
  navigator,
25474
26206
  auditor,
25475
26207
  diarist,
26208
+ secretariat,
25476
26209
  merger: async () => {
25477
26210
  await merger.activate();
25478
26211
  }
@@ -25559,6 +26292,11 @@ function createRoleRuntimeExtension(dependencies) {
25559
26292
  if (!engineDetourRegistered) {
25560
26293
  engineDetourRegistered = registerEngineDetourTool(roleHost, hostActions);
25561
26294
  }
26295
+ if (entry.role === "secretariat" && engineDetourRegistered) {
26296
+ roleHost.setActiveTools([
26297
+ .../* @__PURE__ */ new Set([...roleHost.getActiveTools(), ENGINE_DETOUR_TOOL_NAME])
26298
+ ]);
26299
+ }
25562
26300
  if (entry.role === "coder" || entry.role === "fixer") {
25563
26301
  if (entry.role === "coder") coder.armSubmissionGate(ctx.cwd, ctx.sessionManager);
25564
26302
  else fixer.armSubmissionGate(ctx.cwd, ctx.sessionManager);
@@ -25641,7 +26379,7 @@ async function prepareRoleEnvelope(options) {
25641
26379
  await mkdir5(request.runDirectory, { recursive: true });
25642
26380
  for (const method of request.methods) {
25643
26381
  if (method.kind !== "skill") continue;
25644
- const name = basename10(dirname21(method.path));
26382
+ const name = basename9(dirname21(method.path));
25645
26383
  const raw = await readFile21(method.path, "utf8");
25646
26384
  methodSkills.set(name, { path: method.path, body: stripSkillFrontmatter(raw).trim() });
25647
26385
  }
@@ -26344,6 +27082,7 @@ function createRoleRuntimeDependencies(packageRoot) {
26344
27082
  loadCountersignSoul: () => loadMainRoleSessionMaterials("countersign"),
26345
27083
  loadGleanerLeftSoul: () => loadMainRoleSessionMaterials("gleaner-left"),
26346
27084
  loadDiaristSoul: () => loadMainRoleSessionMaterials("diarist"),
27085
+ loadSecretariatSoul: () => loadMainRoleSessionMaterials("secretariat"),
26347
27086
  loadNotarySourceRun: loadNotarySourceRunLocator,
26348
27087
  loadMergerSoul: () => loadMainRoleSessionMaterials("merger"),
26349
27088
  loadMergerInput: async (path) => JSON.parse(await readFile24(path, "utf8")),