@akagilnc/pi-workflow-roles 0.1.4321 → 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 (71) hide show
  1. package/README.md +4 -1
  2. package/README.zh-CN.md +5 -1
  3. package/dist/acp-host/production-host.js +1308 -587
  4. package/dist/doctor-contracts.js +2 -2
  5. package/dist/engine-detour-tool.js +2 -8
  6. package/dist/gatekeeper-role.js +4 -19
  7. package/dist/headless-host/production-host.js +2613 -1892
  8. package/dist/merger-contracts.js +2 -2
  9. package/dist/migrate-book-topology.js +34 -9
  10. package/dist/notary-contracts.js +2 -2
  11. package/dist/package-contracts/auditor-output.js +2 -2
  12. package/dist/package-contracts/fixer-output.js +2 -2
  13. package/dist/package-contracts/gatekeeper-output.js +2 -2
  14. package/dist/package-contracts/navigator-output.js +2 -2
  15. package/dist/package-contracts/terminating-infrastructure.js +7 -2
  16. package/dist/package-contracts/terminating-tools.js +6 -0
  17. package/dist/packaged-role-registry.js +20 -1
  18. package/dist/public-cli/case-dossier-delivery.js +45 -28
  19. package/dist/public-cli/countersign-run.js +439 -0
  20. package/dist/public-cli/invocation.js +10 -0
  21. package/dist/public-cli/main.js +388 -101
  22. package/dist/public-cli/option-definitions.js +14 -0
  23. package/dist/public-cli/post-admission.js +44 -49
  24. package/dist/public-cli/run-lifecycle.js +13 -1
  25. package/dist/public-cli/settlement.js +14 -53
  26. package/dist/public-role-summons.js +14 -0
  27. package/dist/secretariat-contracts.js +8 -0
  28. package/dist/sitian-appender.js +21 -4
  29. package/extensions/role-runtime.ts +1 -0
  30. package/package.json +1 -1
  31. package/scripts/build-package.mjs +1 -0
  32. package/souls/secretariat.md +26 -0
  33. package/souls/ticket-law.md +9 -0
  34. package/src/collector-tool-schemas.ts +2 -2
  35. package/src/countersign-role.ts +2 -2
  36. package/src/diarist-role.ts +2 -2
  37. package/src/doctor-contracts.ts +2 -2
  38. package/src/engine-detour-tool.ts +3 -9
  39. package/src/gatekeeper-pass-envelope.ts +35 -2
  40. package/src/gatekeeper-role.ts +8 -31
  41. package/src/gleaner-left-role.ts +2 -2
  42. package/src/host-contracts.ts +2 -1
  43. package/src/inspector-role.ts +2 -2
  44. package/src/judge-role.ts +2 -2
  45. package/src/merger-contracts.ts +2 -2
  46. package/src/notary-contracts.ts +2 -2
  47. package/src/package-contracts/auditor-output.ts +2 -2
  48. package/src/package-contracts/fixer-output.ts +2 -2
  49. package/src/package-contracts/gatekeeper-output.ts +2 -2
  50. package/src/package-contracts/navigator-output.ts +2 -2
  51. package/src/package-contracts/terminating-infrastructure.ts +13 -3
  52. package/src/package-contracts/terminating-tools.ts +9 -1
  53. package/src/packaged-role-registry.ts +20 -1
  54. package/src/public-cli/case-dossier-delivery.ts +48 -29
  55. package/src/public-cli/cli.ts +10 -0
  56. package/src/public-cli/countersign-run.ts +29 -5
  57. package/src/public-cli/invocation.ts +28 -2
  58. package/src/public-cli/option-definitions.ts +17 -0
  59. package/src/public-cli/post-admission.ts +45 -58
  60. package/src/public-cli/run-lifecycle.ts +29 -2
  61. package/src/public-cli/secretariat-run.ts +266 -0
  62. package/src/public-cli/settlement.ts +31 -55
  63. package/src/public-cli/terminal.ts +2 -1
  64. package/src/public-role-summons.ts +23 -1
  65. package/src/reviewer-role.ts +2 -2
  66. package/src/role-runtime-dependencies.ts +1 -0
  67. package/src/role-runtime.ts +203 -18
  68. package/src/secretariat-contracts.ts +27 -0
  69. package/src/secretariat-role.ts +210 -0
  70. package/src/sitian-appender.ts +36 -3
  71. package/src/worker-role.ts +2 -2
@@ -1246,10 +1246,15 @@ var init_open_tool_schema = __esm({
1246
1246
 
1247
1247
  // src/package-contracts/terminating-infrastructure.ts
1248
1248
  import { Type as Type3 } from "typebox";
1249
- function withInfrastructureFailureDeclaration(schema) {
1249
+ function withTerminatingOutputDeclarations(schema) {
1250
1250
  const baseProperties = schema.properties;
1251
1251
  const properties = {
1252
1252
  ...baseProperties ?? {},
1253
+ ...baseProperties?.ticketNumber === void 0 ? {
1254
+ ticketNumber: Type3.Unknown({
1255
+ description: "\u53EF\u9009\u672C\u7968\u53F7\uFF1A\u5C1A\u672A\u7ED1\u5B9A\u65F6\u7531\u89D2\u8272\u5728\u65E2\u6709\u56DE\u6267\u4E2D\u7533\u62A5\uFF1B\u673A\u68B0\u5C42\u53EA\u8BB0\u5F55\u5408\u6CD5\u6B63\u6574\u6570\uFF0C\u4E0D\u4ECE\u6563\u6587\u63A8\u5BFC\u3001\u4E0D\u9A8C\u771F\u3002\u7F3A\u5931\u6216\u9519\u5F62\u4E0D\u62D2\u6536\u3002"
1256
+ })
1257
+ } : {},
1253
1258
  [INFRASTRUCTURE_FAILURE_DECLARATION_KEY]: infrastructureFailureDeclarationSchema.properties[INFRASTRUCTURE_FAILURE_DECLARATION_KEY]
1254
1259
  };
1255
1260
  const object = Type3.Object(properties, { additionalProperties: true });
@@ -1343,15 +1348,274 @@ var init_gatekeeper_output = __esm({
1343
1348
  })
1344
1349
  })
1345
1350
  );
1346
- gatekeeperOutputSchema = withInfrastructureFailureDeclaration(
1351
+ gatekeeperOutputSchema = withTerminatingOutputDeclarations(
1347
1352
  gatekeeperDecisionSchema
1348
1353
  );
1349
1354
  }
1350
1355
  });
1351
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
+
1352
1616
  // src/package-resources/engine-material.ts
1353
1617
  import { existsSync as existsSync2, readdirSync as readdirSync2 } from "node:fs";
1354
- import { join as join8 } from "node:path";
1618
+ import { join as join9 } from "node:path";
1355
1619
  function pickEngineAxis(source) {
1356
1620
  return {
1357
1621
  ...source.engine === void 0 ? {} : { engine: source.engine },
@@ -1372,11 +1636,11 @@ function isEngineNameSyntax(name) {
1372
1636
  return true;
1373
1637
  }
1374
1638
  function resolveEngineMaterialDirectory(packageRoot) {
1375
- return join8(packageRoot, ENGINE_MATERIAL_RELATIVE_ROOT);
1639
+ return join9(packageRoot, ENGINE_MATERIAL_RELATIVE_ROOT);
1376
1640
  }
1377
1641
  function resolveEngineMaterialPath(packageRoot, name) {
1378
1642
  const legal = assertLegalEngineName(name);
1379
- return join8(resolveEngineMaterialDirectory(packageRoot), `${legal}.md`);
1643
+ return join9(resolveEngineMaterialDirectory(packageRoot), `${legal}.md`);
1380
1644
  }
1381
1645
  function assertLegalEngineName(name) {
1382
1646
  if (!isEngineNameSyntax(name)) {
@@ -1434,7 +1698,7 @@ __export(durable_principal_exports, {
1434
1698
  piDurablePrincipalAuthority: () => piDurablePrincipalAuthority
1435
1699
  });
1436
1700
  import { lstat } from "node:fs/promises";
1437
- import { join as join9 } from "node:path";
1701
+ import { join as join10 } from "node:path";
1438
1702
  function encode(coordinates) {
1439
1703
  return coordinates;
1440
1704
  }
@@ -1484,7 +1748,7 @@ var init_durable_principal = __esm({
1484
1748
  }
1485
1749
  return {
1486
1750
  sessionDirectory: record4.sessionDirectory,
1487
- 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")
1488
1752
  };
1489
1753
  },
1490
1754
  async isAvailable(principal) {
@@ -1552,7 +1816,7 @@ var init_navigator_output = __esm({
1552
1816
  init_terminating_infrastructure();
1553
1817
  NAVIGATOR_OUTPUT_TOOL_NAME = "ak_navigator_output";
1554
1818
  NAVIGATOR_ACCEPTED_TEXT = "\u6E38\u5955\u4F7F\u5EFA\u8BAE\u5DF2\u53D7\u7406";
1555
- navigatorOutputSchema = withInfrastructureFailureDeclaration(
1819
+ navigatorOutputSchema = withTerminatingOutputDeclarations(
1556
1820
  openToolObject(
1557
1821
  Type5.Object({
1558
1822
  status: Type5.Unknown({
@@ -1650,7 +1914,7 @@ var init_fixer_output = __esm({
1650
1914
  Type6.Object({ status: Type6.Unknown({ description: FIXER_STATUS_DESCRIPTION }), report: Type6.String({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" }), classResults: Type6.Array(classResultSchema, { description: "\u5404\u7C7B\u62D2\u7EDD\u7ED3\u7B97" }) }),
1651
1915
  Type6.Object({ status: Type6.Unknown({ description: FIXER_STATUS_DESCRIPTION }), report: Type6.String({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" }), classResults: Type6.Array(classResultSchema, { description: "\u5404\u7C7B\u5B8C\u6210\u6216\u62D2\u7EDD\u7ED3\u7B97" }), testEvidence: Type6.Optional(testEvidenceSchema) })
1652
1916
  ]);
1653
- fixerOutputSchema = withInfrastructureFailureDeclaration(
1917
+ fixerOutputSchema = withTerminatingOutputDeclarations(
1654
1918
  openToolObjectFromUnion(fixerOutputVariants)
1655
1919
  );
1656
1920
  }
@@ -1816,7 +2080,7 @@ var init_doctor_contracts = __esm({
1816
2080
  missingEvidence: Type8.Array(Type8.Object({ need: nonblank, targetKeys: evidenceIds }, { additionalProperties: true }), { description: "\u5982\u5B9E\u8BC1\u8BCD\u6240\u9700\u800C\u5C1A\u7F3A\u7684\u8BC1\u636E" })
1817
2081
  }, { additionalProperties: false, description: "\u8BC1\u636E\u4E0D\u8DB3\u4EE5\u652F\u6491\u5982\u5B9E\u6848\u8BC1\u8BCD" })
1818
2082
  ]);
1819
- doctorSubmissionSchema = withInfrastructureFailureDeclaration(
2083
+ doctorSubmissionSchema = withTerminatingOutputDeclarations(
1820
2084
  openToolObjectFromUnion(doctorSubmissionVariants)
1821
2085
  );
1822
2086
  doctorEvidenceReadSchema = Type8.Object({ evidenceId: Type8.String({ minLength: 1, description: "\u5F85\u8BFB\u7559\u5B58\u8BC1\u636E\u6807\u8BC6" }), offset: Type8.Optional(Type8.Integer({ minimum: 0, description: "\u8D77\u59CB\u5B57\u8282\u504F\u79FB\uFF08\u4ECE 0 \u8BA1\uFF09" })), limit: Type8.Optional(Type8.Integer({ minimum: 1, description: "\u8FD4\u56DE\u5B57\u8282\u6570\uFF08\u65E0\u4E0A\u9650\uFF09" })) }, { additionalProperties: true });
@@ -1934,7 +2198,7 @@ var init_merger_contracts = __esm({
1934
2198
  Type9.Object({ status: Type9.Unknown({ description: MERGER_STATUS_DESCRIPTION }), attemptId: Type9.String({ description: "\u5DF2\u53D7\u7406\u5408\u5E76 attempt \u8EAB\u4EFD" }), report: Type9.String({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" }), mergeCommitId: Type9.String({ description: "\u5B8C\u6210\u5408\u5E76 commit object ID" }) }, { additionalProperties: false }),
1935
2199
  Type9.Object({ status: Type9.Unknown({ description: MERGER_STATUS_DESCRIPTION }), attemptId: Type9.String({ description: "\u5DF2\u53D7\u7406\u5408\u5E76 attempt \u8EAB\u4EFD" }), diagnosis: Type9.String({ description: "\u5408\u5E76\u65E0\u6CD5\u6216\u4E0D\u5E94\u7531\u672C\u5E2D\u5B8C\u6210\u7684\u539F\u56E0\uFF08\u542B\u65E0\u8FDB\u884C\u4E2D\u5408\u5E76\u3001\u65E0\u6D3B\u53EF\u5E72\u3001\u9700\u65B0\u7684\u4EA7\u54C1/\u6743\u529B\u51B3\u5B9A\uFF09" }), report: Type9.String({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" }) }, { additionalProperties: false })
1936
2200
  ]);
1937
- mergerOutputSchema = withInfrastructureFailureDeclaration(openToolObjectFromUnion(mergerOutputVariants));
2201
+ mergerOutputSchema = withTerminatingOutputDeclarations(openToolObjectFromUnion(mergerOutputVariants));
1938
2202
  MERGER_OUTPUT_TOOL_NAME = "ak_merger_output";
1939
2203
  MERGER_ACCEPTED_TEXT = "\u5408\u5E76\u56DE\u6267\u5DF2\u63A5\u53D7";
1940
2204
  record = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
@@ -1975,7 +2239,7 @@ var init_notary_contracts = __esm({
1975
2239
  }
1976
2240
  };
1977
2241
  NOTARY_FIXED_KICKOFF = "\u7B26\u5B9D\u90CE\u6848\u5377\u5DF2\u53D7\u7406\uFF1B\u6765\u6E90 run \u5B9A\u4F4D\u89C1\u4F1A\u8BDD\u6750\u6599\u3002";
1978
- notaryOutputSchema = withInfrastructureFailureDeclaration(
2242
+ notaryOutputSchema = withTerminatingOutputDeclarations(
1979
2243
  openToolObject(
1980
2244
  Type10.Object({
1981
2245
  status: Type10.Unknown({
@@ -2030,7 +2294,7 @@ var init_auditor_output = __esm({
2030
2294
  init_terminating_infrastructure();
2031
2295
  AUDITOR_OUTPUT_TOOL_NAME = "ak_auditor_output";
2032
2296
  AUDITOR_ACCEPTED_TEXT = "\u5BA1\u5211\u9662\u56DE\u6267\u5DF2\u63A5\u53D7";
2033
- auditorOutputSchema = withInfrastructureFailureDeclaration(
2297
+ auditorOutputSchema = withTerminatingOutputDeclarations(
2034
2298
  openToolObject(
2035
2299
  Type11.Object({
2036
2300
  status: Type11.Unknown({
@@ -2254,6 +2518,17 @@ var init_diarist_contracts = __esm({
2254
2518
  }
2255
2519
  });
2256
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
+
2257
2532
  // src/packaged-role-registry.ts
2258
2533
  function packagedRoleMetadata(role) {
2259
2534
  return PACKAGED_ROLE_REGISTRY.find((entry) => entry.role === role);
@@ -2285,10 +2560,12 @@ var init_packaged_role_registry = __esm({
2285
2560
  init_inspector_contracts();
2286
2561
  init_auditor_output();
2287
2562
  init_diarist_contracts();
2563
+ init_secretariat_contracts();
2288
2564
  NOTARY_SESSION_MATERIALS = [
2289
2565
  "CLAUDE.md",
2290
2566
  "souls/notary.md",
2291
2567
  "souls/audit-law.md",
2568
+ "souls/ticket-law.md",
2292
2569
  "souls/gate-output-guide.md"
2293
2570
  ];
2294
2571
  INSPECTOR_SESSION_MATERIALS = [
@@ -2411,7 +2688,24 @@ var init_packaged_role_registry = __esm({
2411
2688
  inputFlag: void 0,
2412
2689
  phaseFlag: void 0,
2413
2690
  activationStage: "load-and-install",
2414
- 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
+ ]
2415
2709
  },
2416
2710
  {
2417
2711
  role: "gleaner-left",
@@ -2577,7 +2871,7 @@ import {
2577
2871
  unlinkSync,
2578
2872
  writeFileSync as writeFileSync2
2579
2873
  } from "node:fs";
2580
- import { dirname as dirname5, join as join10 } from "node:path";
2874
+ import { dirname as dirname5, join as join11 } from "node:path";
2581
2875
  function isRecord2(value) {
2582
2876
  return typeof value === "object" && value !== null && !Array.isArray(value);
2583
2877
  }
@@ -2704,25 +2998,40 @@ function resolveSitianVolumeCategory(kind) {
2704
2998
  }
2705
2999
  return kind;
2706
3000
  }
3001
+ function ticketProvenanceUnderBookPaths(ledgerHome, bookKey, ticketId) {
3002
+ const sessionDir = join11(activationBookDirectory(ledgerHome, bookKey), ticketId);
3003
+ return { sessionDir, recordFile: join11(sessionDir, SITIAN_RECORDS_LEAF) };
3004
+ }
2707
3005
  function resolveSitianRecordPathInLedger(input, ledgerHome) {
2708
3006
  const category = resolveSitianVolumeCategory(input.kind);
2709
3007
  const ticketNumber = category === "ticket-provenance" ? typeof input.subject === "string" && /^[1-9][0-9]*$/.test(input.subject) ? input.subject : typeof input.subject === "object" && typeof input.subject.ticketNumber === "number" && Number.isSafeInteger(input.subject.ticketNumber) && input.subject.ticketNumber > 0 ? String(input.subject.ticketNumber) : void 0 : void 0;
2710
3008
  let sessionDir;
3009
+ let recordFile;
2711
3010
  if (ticketNumber !== void 0) {
2712
- const bookDir = activationBookDirectory(
3011
+ const paths = ticketProvenanceUnderBookPaths(
2713
3012
  ledgerHome,
2714
- resolveBookKeyFromGit(input.cwd ?? process.cwd())
3013
+ resolveBookKeyFromGit(input.cwd ?? process.cwd()),
3014
+ ticketNumber
2715
3015
  );
2716
- sessionDir = join10(bookDir, ticketNumber);
3016
+ sessionDir = paths.sessionDir;
3017
+ recordFile = paths.recordFile;
2717
3018
  } else {
2718
3019
  if (input.sessionParent === void 0 || input.sessionParent.length === 0 || !physicallyContainedIn(ledgerHome, input.sessionParent)) {
2719
3020
  throw new Error("Sitian record ownership requires a parent session inside the ledger home");
2720
3021
  }
2721
- sessionDir = join10(dirname5(input.sessionParent), category);
3022
+ sessionDir = join11(dirname5(input.sessionParent), category);
3023
+ recordFile = join11(sessionDir, SITIAN_RECORDS_LEAF);
2722
3024
  }
2723
- const recordFile = join10(sessionDir, "records.jsonl");
2724
3025
  return { sessionDir, recordFile, ledgerHome };
2725
3026
  }
3027
+ function projectTicketRecordsPathShape() {
3028
+ const { recordFile } = ticketProvenanceUnderBookPaths(
3029
+ join11("~", ".ak-roles"),
3030
+ "<\u7C3F>",
3031
+ "<\u7968\u53F7>"
3032
+ );
3033
+ return recordFile.replace(/\\/g, "/");
3034
+ }
2726
3035
  function resolveSitianRecordPath(input) {
2727
3036
  const ledgerHome = input.home !== void 0 && input.home.length > 0 ? resolveActivationLedgerHome(input.home) : resolveActivationLedgerHomeForPath(input.sessionParent);
2728
3037
  return resolveSitianRecordPathInLedger(input, ledgerHome);
@@ -2759,7 +3068,7 @@ function appendSitianRecord(input) {
2759
3068
  );
2760
3069
  }
2761
3070
  }
2762
- var S4_SUBMISSION_LEDGER_KINDS;
3071
+ var S4_SUBMISSION_LEDGER_KINDS, SITIAN_RECORDS_LEAF;
2763
3072
  var init_sitian_appender = __esm({
2764
3073
  "src/sitian-appender.ts"() {
2765
3074
  "use strict";
@@ -2773,6 +3082,7 @@ var init_sitian_appender = __esm({
2773
3082
  "sealed",
2774
3083
  "post-seal-anomaly"
2775
3084
  ]);
3085
+ SITIAN_RECORDS_LEAF = "records.jsonl";
2776
3086
  }
2777
3087
  });
2778
3088
 
@@ -2852,12 +3162,12 @@ __export(role_turn_host_exports, {
2852
3162
  import { execFile, spawn as spawn2 } from "node:child_process";
2853
3163
  import { constants } from "node:fs";
2854
3164
  import { access, appendFile, readFile as readFile3, realpath } from "node:fs/promises";
2855
- 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";
2856
3166
  import { platform } from "node:process";
2857
3167
  import { promisify } from "node:util";
2858
3168
  import { randomUUID as randomUUID2 } from "node:crypto";
2859
3169
  function resolveInternalRoleEntrypoint(packageRoot) {
2860
- return join11(packageRoot, INTERNAL_ROLE_ENTRYPOINT_RELATIVE);
3170
+ return join12(packageRoot, INTERNAL_ROLE_ENTRYPOINT_RELATIVE);
2861
3171
  }
2862
3172
  function buildExplicitInternalActivationArgs(selectedRoleEntry, extraArgs = []) {
2863
3173
  return ["--no-extensions", "-e", selectedRoleEntry, ...extraArgs];
@@ -3277,126 +3587,25 @@ var init_host_descriptions = __esm({
3277
3587
  "--strict-mcp-config"
3278
3588
  ]),
3279
3589
  promptFlag: "-p",
3280
- modelFlag: "--model",
3281
- effortFlag: "--effort",
3282
- // File path keeps large role envelopes off ARG_MAX.
3283
- systemPromptFlag: "--system-prompt-file",
3284
- jsonSchemaFlag: "--json-schema",
3285
- mcpConfigFlag: "--mcp-config",
3286
- sessionIdFlag: "--session-id",
3287
- resumeFlag: "--resume"
3288
- }),
3289
- /**
3290
- * Codex headless (#646). Binary under operator home; auth stays in CODEX_HOME.
3291
- * Argv/parse/schema-close are codex-exec helpers — not Claude flag mapping.
3292
- */
3293
- "codex": Object.freeze({
3294
- protocol: "codex-exec",
3295
- binaryFromHome: Object.freeze([".local", "bin", "codex"]),
3296
- sessionBindingFile: "codex-headless-session.json"
3297
- })
3298
- });
3299
- }
3300
- });
3301
-
3302
- // src/session-assistant-usage.ts
3303
- var session_assistant_usage_exports = {};
3304
- __export(session_assistant_usage_exports, {
3305
- readAssistantUsageFromSessionFile: () => readAssistantUsageFromSessionFile,
3306
- sessionFileFromPublicSummon: () => sessionFileFromPublicSummon,
3307
- usageFromPublicSummon: () => usageFromPublicSummon
3308
- });
3309
- import { join as join12 } from "node:path";
3310
- async function readAssistantUsageFromSessionFile(sessionFile) {
3311
- const { readFile: readFile25 } = await import("node:fs/promises");
3312
- let text;
3313
- try {
3314
- text = await readFile25(sessionFile, "utf8");
3315
- } catch (error) {
3316
- if (error?.code === "ENOENT") return void 0;
3317
- throw error;
3318
- }
3319
- let rows;
3320
- try {
3321
- rows = text.trim().split("\n").filter(Boolean).map((line2) => JSON.parse(line2));
3322
- } catch (error) {
3323
- throw new Error(
3324
- `session usage parse failed (${sessionFile}): ${error instanceof Error ? error.message : String(error)}`,
3325
- { cause: error }
3326
- );
3327
- }
3328
- let total = 0;
3329
- let input = 0;
3330
- let output = 0;
3331
- let cacheRead = 0;
3332
- let cacheWrite = 0;
3333
- let costInput = 0;
3334
- let costOutput = 0;
3335
- let costCacheRead = 0;
3336
- let costCacheWrite = 0;
3337
- let costTotal = 0;
3338
- let sawCost = false;
3339
- for (const row of rows) {
3340
- if (row.type !== "message" || row.message?.role !== "assistant") continue;
3341
- const usage = row.message.usage;
3342
- if (usage === void 0) continue;
3343
- total += usage.totalTokens ?? 0;
3344
- input += usage.input ?? 0;
3345
- output += usage.output ?? 0;
3346
- cacheRead += usage.cacheRead ?? 0;
3347
- cacheWrite += usage.cacheWrite ?? 0;
3348
- if (usage.cost !== void 0) {
3349
- sawCost = true;
3350
- costInput += usage.cost.input ?? 0;
3351
- costOutput += usage.cost.output ?? 0;
3352
- costCacheRead += usage.cost.cacheRead ?? 0;
3353
- costCacheWrite += usage.cost.cacheWrite ?? 0;
3354
- costTotal += usage.cost.total ?? 0;
3355
- }
3356
- }
3357
- if (total <= 0 && input <= 0 && output <= 0) return void 0;
3358
- const base = {
3359
- input,
3360
- output,
3361
- cacheRead,
3362
- cacheWrite,
3363
- totalTokens: total > 0 ? total : input + output + cacheRead + cacheWrite
3364
- };
3365
- if (!sawCost) return base;
3366
- return {
3367
- ...base,
3368
- cost: {
3369
- input: costInput,
3370
- output: costOutput,
3371
- cacheRead: costCacheRead,
3372
- cacheWrite: costCacheWrite,
3373
- total: costTotal
3374
- }
3375
- };
3376
- }
3377
- function sessionFileFromPublicSummon(summoned) {
3378
- if (typeof summoned.runDirectory === "string" && summoned.runDirectory.trim() !== "") {
3379
- return join12(summoned.runDirectory, "session", "session.jsonl");
3380
- }
3381
- const fromArtifacts = summoned.terminal?.artifacts?.map((a) => a.path).find((p) => typeof p === "string" && p.endsWith("session.jsonl"));
3382
- if (fromArtifacts !== void 0) return fromArtifacts;
3383
- const outcome = summoned.terminal?.roleOutcome;
3384
- if (outcome === void 0) return void 0;
3385
- const facts = outcome.decisiveFacts;
3386
- const pointer = facts?.runPointer;
3387
- if (typeof pointer === "string" && pointer.trim() !== "") {
3388
- return join12(pointer, "session", "session.jsonl");
3389
- }
3390
- return void 0;
3391
- }
3392
- async function usageFromPublicSummon(summoned) {
3393
- const sessionFile = sessionFileFromPublicSummon(summoned);
3394
- if (sessionFile === void 0) return void 0;
3395
- return readAssistantUsageFromSessionFile(sessionFile);
3396
- }
3397
- var init_session_assistant_usage = __esm({
3398
- "src/session-assistant-usage.ts"() {
3399
- "use strict";
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
+ });
3400
3609
  }
3401
3610
  });
3402
3611
 
@@ -3492,8 +3701,8 @@ async function runComplianceAudit(options) {
3492
3701
  const subject = options.subject;
3493
3702
  const summon = options.summonAuditor ?? (async (auditSubject, sourceRunDirectory, auditSignal, reask2) => {
3494
3703
  const { summonPublicRole: summonPublicRole2 } = await Promise.resolve().then(() => (init_public_role_summons(), public_role_summons_exports));
3495
- const { homeFromRunDirectory: homeFromRunDirectory3 } = await Promise.resolve().then(() => (init_activation_ledger_topology(), activation_ledger_topology_exports));
3496
- const home = homeFromRunDirectory3(sourceRunDirectory);
3704
+ const { homeFromRunDirectory: homeFromRunDirectory2 } = await Promise.resolve().then(() => (init_activation_ledger_topology(), activation_ledger_topology_exports));
3705
+ const home = homeFromRunDirectory2(sourceRunDirectory);
3497
3706
  return await summonPublicRole2({
3498
3707
  role: "auditor",
3499
3708
  argv: [
@@ -3964,6 +4173,8 @@ function acceptedFacts(toolName, details) {
3964
4173
  return typeof record4.judgeStatus === "string" ? { status: record4.judgeStatus } : {};
3965
4174
  case COUNTERSIGN_OUTPUT_TOOL_NAME:
3966
4175
  return typeof record4.countersignStatus === "string" ? { status: record4.countersignStatus } : {};
4176
+ case SECRETARIAT_OUTPUT_TOOL_NAME:
4177
+ return typeof record4.secretariatStatus === "string" ? { status: record4.secretariatStatus } : {};
3967
4178
  case MERGER_OUTPUT_TOOL_NAME: {
3968
4179
  const status = typeof record4.status === "string" ? record4.status : void 0;
3969
4180
  return {
@@ -3995,6 +4206,7 @@ var init_terminating_tools = __esm({
3995
4206
  init_gleaner_left_contracts();
3996
4207
  init_inspector_contracts();
3997
4208
  init_diarist_contracts();
4209
+ init_secretariat_contracts();
3998
4210
  init_worker_output();
3999
4211
  TERMINATING_TOOL_NAMES = [
4000
4212
  CODER_OUTPUT_TOOL_NAME,
@@ -4011,7 +4223,8 @@ var init_terminating_tools = __esm({
4011
4223
  GATEKEEPER_OUTPUT_TOOL_NAME,
4012
4224
  NAVIGATOR_OUTPUT_TOOL_NAME,
4013
4225
  AUDITOR_OUTPUT_TOOL_NAME,
4014
- DIARIST_OUTPUT_TOOL_NAME
4226
+ DIARIST_OUTPUT_TOOL_NAME,
4227
+ SECRETARIAT_OUTPUT_TOOL_NAME
4015
4228
  ];
4016
4229
  AcceptedDetailsContractError = class extends CorrectableSubmissionError {
4017
4230
  code = "accepted_details_contract";
@@ -5331,7 +5544,7 @@ async function readRoleRunStateDisk(runDirectory) {
5331
5544
  if (typeof record4.runId !== "string" || record4.runId.trim() === "") {
5332
5545
  return void 0;
5333
5546
  }
5334
- 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") {
5335
5548
  return void 0;
5336
5549
  }
5337
5550
  if (record4.state !== "admitted" && record4.state !== "running" && record4.state !== "resumable" && record4.state !== "terminal") {
@@ -6144,6 +6357,24 @@ async function loadResumableJudgeRun(home, runId, authority) {
6144
6357
  };
6145
6358
  return seatLoadedResult(loaded, admitted);
6146
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
+ }
6147
6378
  async function loadResumableInstructionSeatRun(home, runId, authority) {
6148
6379
  const loaded = await loadResumableRunRecord(home, runId, authority);
6149
6380
  if (loaded.run.role !== "gatekeeper" && loaded.run.role !== "navigator" && loaded.run.role !== "auditor") {
@@ -6589,7 +6820,7 @@ function createTypedOptionConsumer(definitions) {
6589
6820
  }
6590
6821
  };
6591
6822
  }
6592
- 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;
6593
6824
  var init_option_definitions = __esm({
6594
6825
  "src/public-cli/option-definitions.ts"() {
6595
6826
  "use strict";
@@ -6802,6 +7033,10 @@ var init_option_definitions = __esm({
6802
7033
  bindOwner("diarist", SHARED_PROJECT_SEMANTICS),
6803
7034
  bindOwner("diarist", SHARED_ATTACH_SEMANTICS)
6804
7035
  ];
7036
+ SECRETARIAT_OPTIONS = [
7037
+ bindOwner("secretariat", SHARED_PROJECT_SEMANTICS),
7038
+ bindOwner("secretariat", SHARED_ATTACH_SEMANTICS)
7039
+ ];
6805
7040
  CODER_OPTIONS = [
6806
7041
  {
6807
7042
  id: "phase",
@@ -7164,6 +7399,7 @@ var init_option_definitions = __esm({
7164
7399
  navigator: NAVIGATOR_OPTIONS,
7165
7400
  auditor: AUDITOR_OPTIONS,
7166
7401
  diarist: DIARIST_OPTIONS,
7402
+ secretariat: SECRETARIAT_OPTIONS,
7167
7403
  analyst: ANALYST_OPTIONS
7168
7404
  };
7169
7405
  TOP_LEVEL_HELP = {
@@ -7300,6 +7536,14 @@ var init_option_definitions = __esm({
7300
7536
  'ak-role diarist --attach ./design.md "\u8865\u5F55\u672C\u8F6E\u8BBE\u8BA1\u4FEE\u8BA2\u3002"'
7301
7537
  ]
7302
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
+ },
7303
7547
  notary: {
7304
7548
  command: "notary",
7305
7549
  summary: "Direct Notary document check (quote fidelity + ticket alignment); zero prompt/attachment.",
@@ -7410,6 +7654,7 @@ __export(invocation_exports, {
7410
7654
  admitNavigatorInvocation: () => admitNavigatorInvocation,
7411
7655
  admitNotaryInvocation: () => admitNotaryInvocation,
7412
7656
  admitReviewerInvocation: () => admitReviewerInvocation,
7657
+ admitSecretariatInvocation: () => admitSecretariatInvocation,
7413
7658
  bindAdmittedTicketNumber: () => bindAdmittedTicketNumber,
7414
7659
  bindCourtTicketNumbersOnAdmitted: () => bindCourtTicketNumbersOnAdmitted,
7415
7660
  bindTicketNumberOnRunDirectory: () => bindTicketNumberOnRunDirectory,
@@ -7425,6 +7670,7 @@ __export(invocation_exports, {
7425
7670
  buildMergerTransportPrompt: () => buildMergerTransportPrompt,
7426
7671
  buildNotaryTransportPrompt: () => buildNotaryTransportPrompt,
7427
7672
  buildReviewerTransportPrompt: () => buildReviewerTransportPrompt,
7673
+ buildSecretariatTransportPrompt: () => buildSecretariatTransportPrompt,
7428
7674
  deriveMergerEnvelopeFromActiveMerge: () => deriveMergerEnvelopeFromActiveMerge,
7429
7675
  ensureRunArtifactsDir: () => ensureRunArtifactsDir,
7430
7676
  freezeAttachmentsIntoRun: () => freezeAttachmentsIntoRun,
@@ -7452,6 +7698,7 @@ __export(invocation_exports, {
7452
7698
  parseNotaryArgv: () => parseNotaryArgv,
7453
7699
  parsePositiveTicketNumber: () => parsePositiveTicketNumber,
7454
7700
  parseReviewerArgv: () => parseReviewerArgv,
7701
+ parseSecretariatArgv: () => parseSecretariatArgv,
7455
7702
  persistAdmittedSourceRunPath: () => persistAdmittedSourceRunPath,
7456
7703
  recordEffectiveInvocationModel: () => recordEffectiveInvocationModel,
7457
7704
  recordLaunchedPiIdentity: () => recordLaunchedPiIdentity,
@@ -7881,6 +8128,9 @@ function parseAuditorArgv(args) {
7881
8128
  function parseDiaristArgv(args) {
7882
8129
  return parseInstructionArgv(args, "diarist");
7883
8130
  }
8131
+ function parseSecretariatArgv(args) {
8132
+ return parseInstructionArgv(args, "secretariat");
8133
+ }
7884
8134
  function parseCoderArgv(args) {
7885
8135
  const attachmentPaths = [];
7886
8136
  let project;
@@ -8114,6 +8364,9 @@ async function admitAuditorInvocation(options) {
8114
8364
  async function admitDiaristInvocation(options) {
8115
8365
  return admitStandardMaterialInvocation("diarist", options);
8116
8366
  }
8367
+ async function admitSecretariatInvocation(options) {
8368
+ return admitStandardMaterialInvocation("secretariat", options);
8369
+ }
8117
8370
  function buildInstructionTransportPrompt(admitted, engineMaterial) {
8118
8371
  const lines = [admitted.instructionEmpty ? "" : admitted.instruction];
8119
8372
  if (admitted.attachments.length > 0) {
@@ -8128,6 +8381,9 @@ function buildInstructionTransportPrompt(admitted, engineMaterial) {
8128
8381
  function buildJudgeTransportPrompt(admitted, engineMaterial) {
8129
8382
  return buildInstructionTransportPrompt(admitted, engineMaterial);
8130
8383
  }
8384
+ function buildSecretariatTransportPrompt(admitted, engineMaterial) {
8385
+ return buildInstructionTransportPrompt(admitted, engineMaterial);
8386
+ }
8131
8387
  function buildInspectorTransportPrompt(admitted, engineMaterial) {
8132
8388
  return buildInstructionTransportPrompt(admitted, engineMaterial);
8133
8389
  }
@@ -14269,7 +14525,6 @@ __export(settlement_exports, {
14269
14525
  publishMergerArtifacts: () => publishMergerArtifacts,
14270
14526
  publishReviewerArtifacts: () => publishReviewerArtifacts,
14271
14527
  raceNavigatorGrace: () => raceNavigatorGrace,
14272
- readBoundAuditorKnownFailure: () => readBoundAuditorKnownFailure,
14273
14528
  readBoundEvidenceChildKnownFailure: () => readBoundEvidenceChildKnownFailure,
14274
14529
  readCollectorInfrastructureFailure: () => readCollectorInfrastructureFailure,
14275
14530
  readEngineDetourInfrastructureFailure: () => readEngineDetourInfrastructureFailure,
@@ -14307,6 +14562,7 @@ __export(settlement_exports, {
14307
14562
  trySettleNavigatorTerminalResult: () => trySettleNavigatorTerminalResult,
14308
14563
  trySettleNotaryTerminalResult: () => trySettleNotaryTerminalResult,
14309
14564
  trySettleReviewerTerminalResult: () => trySettleReviewerTerminalResult,
14565
+ trySettleSecretariatTerminalResult: () => trySettleSecretariatTerminalResult,
14310
14566
  withSubmissions: () => withSubmissions
14311
14567
  });
14312
14568
  import { randomUUID as randomUUID4 } from "node:crypto";
@@ -14813,32 +15069,6 @@ async function loadBoundAuditorVolumes(sessionFile) {
14813
15069
  }
14814
15070
  const parentId = parentEntries.find((entry) => entry.type === "session")?.id;
14815
15071
  if (parentId === void 0) return void 0;
14816
- const isResumeEnvelopeBytes = (value) => {
14817
- if (typeof value !== "string") return false;
14818
- if (value.length === 0) return true;
14819
- const nl = value.indexOf("\n");
14820
- const firstLine = nl === -1 ? value : value.slice(0, nl);
14821
- const body = firstLine === "" && nl !== -1 ? value.slice(nl + 1) : value;
14822
- return body.startsWith("\u672C\u6B21\u914D\u7F6E\u7684\u52B3\u52A1\u5F15\u64CE\u53CA\u5176\u624B\u518C\uFF1A") || body.startsWith("- engine:");
14823
- };
14824
- const isResumeEnvelope = (msg) => {
14825
- if (!isRecord11(msg) || msg.role !== "user") return false;
14826
- const text = typeof msg.text === "string" ? msg.text : typeof msg.content === "string" ? msg.content : void 0;
14827
- if (isResumeEnvelopeBytes(text)) return true;
14828
- const content = msg.content;
14829
- if (Array.isArray(content)) {
14830
- return content.some((p) => isRecord11(p) && (isResumeEnvelopeBytes(p.text) || isResumeEnvelopeBytes(p.content)));
14831
- }
14832
- return false;
14833
- };
14834
- let latestParentUserIndex = -1;
14835
- for (let i = parentEntries.length - 1; i >= 0; i -= 1) {
14836
- const entry = parentEntries[i];
14837
- if (entry?.type !== "message" || entry.message?.role !== "user") continue;
14838
- if (isResumeEnvelope(entry.message)) continue;
14839
- latestParentUserIndex = i;
14840
- break;
14841
- }
14842
15072
  const childDirectories = [join29(dirname14(sessionFile), "auditor-roles")];
14843
15073
  const valid = [];
14844
15074
  let sawAnyDirectory = false;
@@ -14875,12 +15105,9 @@ async function loadBoundAuditorVolumes(sessionFile) {
14875
15105
  for (const { entry: bindingEntry, start, end } of bindingPasses) {
14876
15106
  const bindingParent = bindingEntry !== void 0 && isRecord11(bindingEntry.data) && isRecord11(bindingEntry.data.parent) ? bindingEntry.data.parent : void 0;
14877
15107
  const attemptEntryId = typeof bindingParent?.attemptEntryId === "string" ? bindingParent.attemptEntryId : void 0;
14878
- const attemptEntryIndex = attemptEntryId === void 0 ? -1 : parentEntries.findIndex((entry) => entry.id === attemptEntryId);
14879
15108
  const boundSessionFile = typeof bindingParent?.sessionFile === "string" ? bindingParent.sessionFile : typeof header.parentSession === "string" ? header.parentSession : void 0;
14880
15109
  if (boundSessionFile !== sessionFile) continue;
14881
- if (bindingParent !== void 0 && (bindingParent.sessionId !== parentId || attemptEntryIndex < latestParentUserIndex)) {
14882
- continue;
14883
- }
15110
+ if (bindingParent !== void 0 && bindingParent.sessionId !== parentId) continue;
14884
15111
  if (bindingParent === void 0 && header.parentSession !== sessionFile) continue;
14885
15112
  valid.push({
14886
15113
  entries: entries.slice(start, end),
@@ -14935,11 +15162,6 @@ function providerStopFallbackFromAuditorVolumes(volumes) {
14935
15162
  }
14936
15163
  return void 0;
14937
15164
  }
14938
- async function readBoundAuditorKnownFailure(sessionFile) {
14939
- const volumes = await loadBoundAuditorVolumes(sessionFile);
14940
- if (volumes === void 0) return void 0;
14941
- return complianceFailureFromAuditorVolumes(volumes) ?? providerStopFallbackFromAuditorVolumes(volumes);
14942
- }
14943
15165
  async function readBoundAuditorComplianceFailure(sessionFile) {
14944
15166
  const volumes = await loadBoundAuditorVolumes(sessionFile);
14945
15167
  if (volumes === void 0) return void 0;
@@ -16179,6 +16401,15 @@ async function settleLawfulDiaristTerminalResult(admitted, authority, scope) {
16179
16401
  async function trySettleDiaristTerminalResult(admitted, authority, scope) {
16180
16402
  return settleLawfulDiaristTerminalResult(admitted, authority, scope);
16181
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
+ }
16182
16413
  async function settleLawfulInspectorTerminalResult(admitted, authority, scope) {
16183
16414
  return settleLawfulSeatAcceptedTerminalResult(admitted, authority, {
16184
16415
  role: "inspector",
@@ -16805,6 +17036,7 @@ var init_settlement = __esm({
16805
17036
  init_countersign_contracts();
16806
17037
  init_gleaner_left_contracts();
16807
17038
  init_diarist_contracts();
17039
+ init_secretariat_contracts();
16808
17040
  init_inspector_contracts();
16809
17041
  init_gatekeeper_output();
16810
17042
  init_navigator_output();
@@ -17509,11 +17741,14 @@ __export(case_dossier_delivery_exports, {
17509
17741
  import { mkdtemp as mkdtemp2, readFile as readFile19, rm as rm2, writeFile as writeFile9 } from "node:fs/promises";
17510
17742
  import { tmpdir as tmpdir2 } from "node:os";
17511
17743
  import { join as join32 } from "node:path";
17512
- function describeDossierFile(path) {
17513
- return path;
17514
- }
17515
17744
  async function projectCaseDossierPointerSection(input) {
17516
- if (input.ticketNumber === void 0) return void 0;
17745
+ if (input.ticketNumber === void 0) {
17746
+ return [
17747
+ UNBOUND_DOSSIER_PATH_HEADING,
17748
+ "",
17749
+ `\u8BB0\u5F55\u5377\u5B97\uFF1A${projectTicketRecordsPathShape()}`
17750
+ ].join("\n");
17751
+ }
17517
17752
  const volume = resolveTicketProvenanceVolume(
17518
17753
  input.ticketNumber,
17519
17754
  input.projectRoot,
@@ -17523,7 +17758,7 @@ async function projectCaseDossierPointerSection(input) {
17523
17758
  CASE_DOSSIER_SECTION_HEADING,
17524
17759
  "",
17525
17760
  `\u7968\u53F7\uFF1A#${input.ticketNumber}`,
17526
- `\u8BB0\u5F55\u5377\u5B97\uFF1A${describeDossierFile(volume.recordFile)}`
17761
+ `\u8BB0\u5F55\u5377\u5B97\uFF1A${volume.recordFile}`
17527
17762
  ].join("\n");
17528
17763
  }
17529
17764
  async function deliverCaseDossierAsAttachment(input) {
@@ -17532,7 +17767,6 @@ async function deliverCaseDossierAsAttachment(input) {
17532
17767
  projectRoot: input.projectRoot,
17533
17768
  home: input.home
17534
17769
  });
17535
- if (section === void 0) return void 0;
17536
17770
  const stagingDir = await mkdtemp2(join32(tmpdir2(), "ak-case-dossier-"));
17537
17771
  try {
17538
17772
  const stagingPath = join32(stagingDir, CASE_DOSSIER_ATTACH_FILE);
@@ -17564,13 +17798,15 @@ async function loadCaseDossierReadingMaterial(runDirectory) {
17564
17798
  if (section.trim() === "") return void 0;
17565
17799
  return { kind: "case-dossier-pointer", frozenPath, section };
17566
17800
  }
17567
- var CASE_DOSSIER_SECTION_HEADING, CASE_DOSSIER_ATTACH_KEY, CASE_DOSSIER_ATTACH_FILE;
17801
+ var CASE_DOSSIER_SECTION_HEADING, UNBOUND_DOSSIER_PATH_HEADING, CASE_DOSSIER_ATTACH_KEY, CASE_DOSSIER_ATTACH_FILE;
17568
17802
  var init_case_dossier_delivery = __esm({
17569
17803
  "src/public-cli/case-dossier-delivery.ts"() {
17570
17804
  "use strict";
17805
+ init_sitian_facade();
17571
17806
  init_ticket_provenance();
17572
17807
  init_invocation();
17573
17808
  CASE_DOSSIER_SECTION_HEADING = "## \u672C\u7968\u8D77\u5C45\u5F55\uFF08\u7CFB\u7EDF\u968F\u6848\u63D0\u4F9B\uFF09";
17809
+ UNBOUND_DOSSIER_PATH_HEADING = "## \u8D77\u5C45\u5F55\u8DEF\u5F84\uFF08\u7CFB\u7EDF\u968F\u6848\u63D0\u4F9B\uFF09";
17574
17810
  CASE_DOSSIER_ATTACH_KEY = "case-dossier";
17575
17811
  CASE_DOSSIER_ATTACH_FILE = "case-dossier-pointer.md";
17576
17812
  }
@@ -18069,12 +18305,6 @@ function describeCaughtError(error) {
18069
18305
  }
18070
18306
  return { message: String(error) };
18071
18307
  }
18072
- function appendContinuationSection(continuation, section) {
18073
- const prompt = `${continuation.prompt}
18074
-
18075
- ${section}`;
18076
- return continuation.kind === "initial" ? { kind: "initial", prompt } : { kind: "resume", prompt };
18077
- }
18078
18308
  function isStationChildOfficerDialogue(role, env) {
18079
18309
  return env.stationChild === true && isOfficerReviewSeat(role);
18080
18310
  }
@@ -18212,10 +18442,24 @@ async function dispatchPostAdmissionTurn(input) {
18212
18442
  const shouldPresent = adapters.shouldPresentSettled ?? ((terminal) => isLawfulTypedTerminalOutcome(terminal.roleOutcome));
18213
18443
  let afterDispatchApplied = false;
18214
18444
  const finishAfterTurn = async (result) => {
18215
- if (adapters.afterDispatch === void 0 || afterDispatchApplied) return result;
18445
+ if (afterDispatchApplied) return result;
18216
18446
  afterDispatchApplied = true;
18217
18447
  try {
18218
- await adapters.afterDispatch(admitted, lease);
18448
+ if (admitted.ticketNumber === void 0) {
18449
+ const rows = await readRecordedSubmissionRows(
18450
+ admitted.projectRoot,
18451
+ admitted.runId,
18452
+ { home: homeFromRunDirectory(admitted.runDirectory), sessionParent: join35(admitted.runDirectory, "session", "session.jsonl") }
18453
+ );
18454
+ const asserted = rows.filter((row) => row.kind === "accepted" && row.role === admitted.role).map((row) => row.accepted).find((payload) => {
18455
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) return false;
18456
+ const value = payload.ticketNumber;
18457
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
18458
+ });
18459
+ const ticketNumber = asserted === void 0 ? void 0 : asserted.ticketNumber;
18460
+ if (ticketNumber !== void 0) await bindAdmittedTicketNumber(admitted, ticketNumber);
18461
+ }
18462
+ if (adapters.afterDispatch !== void 0) await adapters.afterDispatch(admitted, lease);
18219
18463
  return result;
18220
18464
  } catch (error) {
18221
18465
  const primaryFailure = result.terminal !== void 0 && !isLawfulTypedTerminalOutcome(result.terminal.roleOutcome);
@@ -18330,29 +18574,12 @@ async function dispatchPostAdmissionTurn(input) {
18330
18574
  if (typeof liveHost === "string" && liveHost.trim() !== "") {
18331
18575
  turnRequest = { ...turnRequest, host: liveHost.trim() };
18332
18576
  }
18333
- if (isStationChildOfficerDialogue(admitted.role, env)) {
18334
- await deliverCaseDossierAsAttachment({
18335
- ticketNumber: admitted.ticketNumber,
18336
- projectRoot: admitted.projectRoot,
18337
- home: env.home,
18338
- runDirectory: admitted.runDirectory
18339
- });
18340
- } else {
18341
- const dossierSection = await projectCaseDossierPointerSection({
18342
- ticketNumber: admitted.ticketNumber,
18343
- projectRoot: admitted.projectRoot,
18344
- home: env.home
18345
- });
18346
- if (dossierSection !== void 0) {
18347
- turnRequest = {
18348
- ...turnRequest,
18349
- continuation: appendContinuationSection(
18350
- turnRequest.continuation,
18351
- dossierSection
18352
- )
18353
- };
18354
- }
18355
- }
18577
+ await deliverCaseDossierAsAttachment({
18578
+ ticketNumber: admitted.ticketNumber,
18579
+ projectRoot: admitted.projectRoot,
18580
+ home: env.home,
18581
+ runDirectory: admitted.runDirectory
18582
+ });
18356
18583
  await markRunRunning(
18357
18584
  admitted.runDirectory,
18358
18585
  env.model,
@@ -18609,7 +18836,7 @@ function resumeTurnRequestProjectionOptions(admitted, request, env, summonsPrepa
18609
18836
  ...env.model === void 0 ? {} : { model: env.model },
18610
18837
  ...pickEngineAxis(env),
18611
18838
  ...env.timeoutMs === void 0 ? {} : { timeoutMs: env.timeoutMs },
18612
- ...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 },
18613
18840
  continuation: {
18614
18841
  kind: "resume",
18615
18842
  prompt
@@ -18766,10 +18993,7 @@ async function runPostAdmissionSeatResume(input) {
18766
18993
  dispatch: async (turnRequest) => {
18767
18994
  const result = await dispatchPostAdmissionTurn({
18768
18995
  admitted: loaded.admitted,
18769
- env: {
18770
- ...input.env,
18771
- ...loaded.admitted.correlationId === void 0 ? {} : { correlationId: loaded.admitted.correlationId }
18772
- },
18996
+ env: input.env,
18773
18997
  io: attemptIo,
18774
18998
  request: turnRequest,
18775
18999
  lease,
@@ -18940,6 +19164,7 @@ var init_post_admission = __esm({
18940
19164
  init_run_lifecycle();
18941
19165
  init_cli_errors();
18942
19166
  init_invocation();
19167
+ init_submission_ledger();
18943
19168
  init_activation_ledger_topology();
18944
19169
  init_engine_material();
18945
19170
  init_session_identity();
@@ -19863,12 +20088,294 @@ function diaristAdapters(env) {
19863
20088
  afterDispatch: async (admitted, lease) => {
19864
20089
  await bindAndRelocateDiaristIfBoardBound(admitted, env.principalAuthority, lease);
19865
20090
  }
19866
- };
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
+ }
19867
20374
  }
19868
- async function runPublicDiarist(argv, env, io, parseDiaristArgv2) {
20375
+ async function runPublicCountersign(argv, env, io, parseCountersignArgv2) {
19869
20376
  let parsed;
19870
20377
  try {
19871
- parsed = parseDiaristArgv2(argv);
20378
+ parsed = parseCountersignArgv2(argv);
19872
20379
  } catch (error) {
19873
20380
  if (error instanceof CliUsageError) {
19874
20381
  presentStructuralRejection(error, io);
@@ -19876,32 +20383,9 @@ async function runPublicDiarist(argv, env, io, parseDiaristArgv2) {
19876
20383
  }
19877
20384
  throw error;
19878
20385
  }
19879
- const projectRoot = parsed.project ?? env.cwd;
19880
- const handoffTicket = env.boundTicketNumber;
19881
- if (typeof handoffTicket === "number" && Number.isSafeInteger(handoffTicket) && handoffTicket >= 1) {
19882
- const summons = {
19883
- instruction: parsed.instruction,
19884
- instructionEmpty: parsed.instruction.trim() === "",
19885
- attachmentPaths: parsed.attachmentPaths
19886
- };
19887
- const resumed = await tryResumeSameTicketSeatRun({
19888
- home: env.home,
19889
- projectRoot,
19890
- role: "diarist",
19891
- ticketNumber: handoffTicket,
19892
- freshSummons: env.freshSummons,
19893
- summons,
19894
- resume: (runId, materials) => runPublicDiaristResume(
19895
- { runId, ...materials === void 0 ? {} : { summons: materials } },
19896
- env,
19897
- io
19898
- )
19899
- });
19900
- if (resumed !== void 0) return resumed;
19901
- }
19902
20386
  let admitted;
19903
20387
  try {
19904
- admitted = await admitDiaristInvocation({
20388
+ admitted = await admitCountersignInvocation({
19905
20389
  home: env.home,
19906
20390
  principalAuthority: env.principalAuthority,
19907
20391
  cwd: env.cwd,
@@ -19910,8 +20394,7 @@ async function runPublicDiarist(argv, env, io, parseDiaristArgv2) {
19910
20394
  ...parsed.project === void 0 ? {} : { project: parsed.project },
19911
20395
  ...env.createRunId === void 0 ? {} : { createRunId: env.createRunId },
19912
20396
  ...env.model === void 0 ? {} : { model: env.model },
19913
- ...env.correlationId === void 0 ? {} : { correlationId: env.correlationId },
19914
- ...handoffTicket === void 0 ? {} : { assertedTicketNumber: handoffTicket }
20397
+ ...env.correlationId === void 0 ? {} : { correlationId: env.correlationId }
19915
20398
  });
19916
20399
  } catch (error) {
19917
20400
  if (error instanceof CliUsageError) {
@@ -19921,6 +20404,112 @@ async function runPublicDiarist(argv, env, io, parseDiaristArgv2) {
19921
20404
  throw error;
19922
20405
  }
19923
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
+ }
19924
20513
  const turnProjection = {
19925
20514
  packageRoot: env.packageRoot,
19926
20515
  home: env.home,
@@ -19931,7 +20520,7 @@ async function runPublicDiarist(argv, env, io, parseDiaristArgv2) {
19931
20520
  ...env.correlationId === void 0 || env.correlationId.trim() === "" ? {} : { correlationId: env.correlationId },
19932
20521
  continuation: {
19933
20522
  kind: "initial",
19934
- prompt: buildInstructionTransportPrompt(
20523
+ prompt: buildCountersignTransportPrompt(
19935
20524
  admitted,
19936
20525
  engineSessionMaterialFromOptions({
19937
20526
  ...pickEngineAxis(env),
@@ -19940,28 +20529,59 @@ async function runPublicDiarist(argv, env, io, parseDiaristArgv2) {
19940
20529
  )
19941
20530
  }
19942
20531
  };
19943
- const turnRequest = buildDiaristTurnRequest(admitted, turnProjection);
19944
- return await runPostAdmissionOneShot({
20532
+ const turnRequest = buildCountersignTurnRequest(admitted, turnProjection);
20533
+ const result = await runPostAdmissionOneShot({
19945
20534
  admitted,
19946
20535
  env,
19947
20536
  io,
19948
20537
  request: turnRequest,
19949
- 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
+ }),
19950
20556
  ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
19951
20557
  });
20558
+ await relocateAdmittedRunToTicket(admitted, env.principalAuthority);
20559
+ return result;
19952
20560
  }
19953
- 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) {
19954
20570
  return await runPostAdmissionSeatResume({
19955
20571
  request,
19956
20572
  env,
19957
20573
  io,
19958
- load: (effective) => loadResumableDiaristRun(env.home, effective.runId, env.principalAuthority),
20574
+ load: (effective) => loadResumableCountersignRun(
20575
+ env.home,
20576
+ effective.runId,
20577
+ env.principalAuthority
20578
+ ),
19959
20579
  buildTurnRequest: async (admitted, effective) => {
19960
20580
  const summonsPrepared = await prepareSummonsResumeMaterials(
19961
20581
  admitted.runDirectory,
19962
20582
  effective.summons
19963
20583
  );
19964
- return buildDiaristTurnRequest(
20584
+ return buildCountersignTurnRequest(
19965
20585
  admitted,
19966
20586
  resumeTurnRequestProjectionOptions(
19967
20587
  admitted,
@@ -19971,22 +20591,36 @@ async function runPublicDiaristResume(request, env, io) {
19971
20591
  )
19972
20592
  );
19973
20593
  },
19974
- 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
+ }),
19975
20608
  ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
19976
20609
  });
19977
20610
  }
19978
- var init_diarist_run = __esm({
19979
- "src/public-cli/diarist-run.ts"() {
20611
+ var init_countersign_run = __esm({
20612
+ "src/public-cli/countersign-run.ts"() {
19980
20613
  "use strict";
19981
20614
  init_engine_material();
19982
20615
  init_cli_errors();
20616
+ init_diarist_contracts();
20617
+ init_run_ticket_number();
19983
20618
  init_invocation();
19984
20619
  init_post_admission();
19985
20620
  init_run_lifecycle();
19986
20621
  init_seat_ticket_binding();
19987
20622
  init_settlement();
19988
20623
  init_turn_request();
19989
- init_run_ticket_number();
19990
20624
  }
19991
20625
  });
19992
20626
 
@@ -20167,11 +20801,15 @@ async function summonPublicRole(options) {
20167
20801
  env: {
20168
20802
  ...built.env,
20169
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 },
20170
20807
  ...config.autoResumeLimit === void 0 ? {} : { autoResumeLimit: config.autoResumeLimit },
20171
20808
  ...options.signal === void 0 ? {} : { signal: options.signal },
20172
20809
  ...options.reviewReask === void 0 ? {} : { reviewReask: options.reviewReask },
20173
20810
  ...options.gateReviewInstruction === void 0 ? {} : { gateReviewInstruction: options.gateReviewInstruction },
20174
20811
  ...options.boundTicketNumber === void 0 ? {} : { boundTicketNumber: options.boundTicketNumber },
20812
+ ...options.correlationId === void 0 || options.correlationId.trim() === "" ? {} : { correlationId: options.correlationId },
20175
20813
  ...options.createRunId === void 0 ? {} : { createRunId: options.createRunId }
20176
20814
  }
20177
20815
  };
@@ -20274,245 +20912,82 @@ async function summonPublicRole(options) {
20274
20912
  result = stepped.ok;
20275
20913
  break;
20276
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
+ }
20277
20925
  }
20278
- const stderr = captured?.stderrText();
20279
- const runDirectory = result.admitted?.runDirectory;
20280
- return {
20281
- exitCode: result.exitCode,
20282
- ...result.terminal === void 0 ? {} : { terminal: result.terminal },
20283
- ...result.admitted === void 0 ? {} : { admitted: result.admitted },
20284
- ...typeof runDirectory === "string" && runDirectory.trim() !== "" ? { runDirectory } : {},
20285
- ...stderr === void 0 || stderr === "" ? {} : { stderr }
20286
- };
20287
- }
20288
- async function summonGateOfficer(options) {
20289
- let home = options.home;
20290
- if (home === void 0) {
20291
- const { homeFromRunDirectory: homeFromRunDirectory3 } = await Promise.resolve().then(() => (init_activation_ledger_topology(), activation_ledger_topology_exports));
20292
- home = homeFromRunDirectory3(options.sourceRunDirectory);
20293
- }
20294
- let gateReviewInstruction;
20295
- if (options.reask === void 0 && options.submission !== void 0) {
20296
- const { readableGateItem: readableGateItem2 } = await Promise.resolve().then(() => (init_readable_gate_item(), readable_gate_item_exports));
20297
- gateReviewInstruction = readableGateItem2(options.submission);
20298
- }
20299
- const common = {
20300
- cwd: options.cwd,
20301
- ...home === void 0 ? {} : { home },
20302
- ...options.packageRoot === void 0 ? {} : { packageRoot: options.packageRoot },
20303
- ...options.io === void 0 ? {} : { io: options.io },
20304
- ...options.signal === void 0 ? {} : { signal: options.signal },
20305
- ...options.reask === void 0 ? {} : { reviewReask: options.reask },
20306
- ...gateReviewInstruction === void 0 ? {} : { gateReviewInstruction },
20307
- ...options.roleTurnHost === void 0 ? {} : { roleTurnHost: options.roleTurnHost },
20308
- ...options.hostAdapters === void 0 ? {} : { hostAdapters: options.hostAdapters },
20309
- ...options.createRunId === void 0 ? {} : { createRunId: options.createRunId }
20310
- };
20311
- if (options.officer === "notary") {
20312
- return summonPublicRole({
20313
- role: "notary",
20314
- argv: ["--source-run", options.sourceRunDirectory, "--project", options.cwd],
20315
- ...common
20316
- });
20317
- }
20318
- if (options.officer === "auditor") {
20319
- return summonPublicRole({
20320
- role: "auditor",
20321
- argv: [
20322
- "--subject",
20323
- "judge",
20324
- "--source-run",
20325
- options.sourceRunDirectory,
20326
- `\u5377\u5B97\u6307\u9488\uFF1A${options.sourceRunDirectory}`
20327
- ],
20328
- ...common
20329
- });
20330
- }
20331
- return summonPublicRole({
20332
- role: "inspector",
20333
- argv: [`\u5377\u5B97\u6307\u9488\uFF1A${options.sourceRunDirectory}`],
20334
- ...common
20335
- });
20336
- }
20337
- var AK_ROLE_PACKAGE_ROOT_ENV;
20338
- var init_public_role_summons = __esm({
20339
- "src/public-role-summons.ts"() {
20340
- "use strict";
20341
- init_engine_material();
20342
- AK_ROLE_PACKAGE_ROOT_ENV = "AK_ROLE_PACKAGE_ROOT";
20343
- }
20344
- });
20345
-
20346
- // src/gatekeeper-role.ts
20347
- function gateSeatLabel(stage) {
20348
- if (stage === "inspector") return "\u53F0\u9662";
20349
- if (stage === "auditor") return "\u5BA1\u5211\u9662";
20350
- return "\u7B26\u5B9D\u90CE";
20351
- }
20352
- function gateOfficerForSubject(subject) {
20353
- if (subject.kind === "worker_completion") return "inspector";
20354
- if (subject.kind === "judge_compliance") return "auditor";
20355
- return "notary";
20356
- }
20357
- function failureReason(error) {
20358
- if (error instanceof AggregateError) return error.errors.map(failureReason).join("; ");
20359
- return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
20360
- }
20361
- function retainedReceipt(decision) {
20362
- return decision;
20363
- }
20364
- function readRecord(value) {
20365
- if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
20366
- return value;
20367
- }
20368
- function projectOfficerDecision(officer, decision, fallbackStatus) {
20369
- const receipt = retainedReceipt(decision);
20370
- const record4 = readRecord(decision);
20371
- const status = (record4 !== void 0 && typeof record4.status === "string" ? record4.status : void 0) ?? fallbackStatus;
20372
- if (status === "pass") {
20373
- return { status: "pass", officer, receipt };
20374
- }
20375
- if (status === "bounce" || status === "escalate") {
20376
- return { status, officer, receipt };
20377
- }
20378
- return { status: "needs_reask", officer, receipt };
20379
- }
20380
- function thisCourtOfficerPayloads(terminal) {
20381
- const outcome = terminal?.roleOutcome;
20382
- if (outcome !== void 0 && (outcome.kind === "accepted" || outcome.kind === "audit_escalation")) {
20383
- if (outcome.payloads !== void 0 && outcome.payloads.length > 0) return outcome.payloads;
20384
- }
20385
- if (outcome?.kind === "failure" && outcome.payloads !== void 0 && outcome.payloads.length > 0) {
20386
- return outcome.payloads;
20387
- }
20388
- return [];
20389
- }
20390
- function officerFailurePayloads(terminal) {
20391
- const outcome = terminal?.roleOutcome;
20392
- if (outcome?.kind === "failure") return outcome.payloads ?? terminal?.submissions ?? [];
20393
- return terminal?.submissions ?? [];
20394
- }
20395
- function projectOfficerPayloads(officer, payloads, fallbackStatus) {
20396
- if (payloads.length === 0) {
20397
- return projectOfficerDecision(officer, void 0, fallbackStatus);
20398
- }
20399
- 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
+ };
20400
20935
  }
20401
- function projectOfficerTerminal(officer, summoned) {
20402
- const terminal = summoned.terminal;
20403
- const outcome = terminal?.roleOutcome;
20404
- const thisCourt = thisCourtOfficerPayloads(terminal);
20405
- if (outcome === void 0) {
20406
- const detail = summoned.stderr ?? "";
20407
- const failurePayloads = officerFailurePayloads(terminal);
20408
- return {
20409
- status: "transport_failure",
20410
- stage: officer,
20411
- reason: detail.length > 0 ? `${gateSeatLabel(officer)} public summon exit ${summoned.exitCode}: ${detail}` : `${gateSeatLabel(officer)} public summon produced no terminal (exit ${summoned.exitCode})`,
20412
- submission: failurePayloads.length > 0 ? failurePayloads : summoned
20413
- };
20414
- }
20415
- if (outcome.kind === "no_receipt") {
20416
- return {
20417
- status: "no_receipt",
20418
- stage: officer,
20419
- reason: typeof outcome.status === "string" && outcome.status.length > 0 ? outcome.status : "no_receipt",
20420
- facts: outcome
20421
- };
20422
- }
20423
- if (outcome.kind === "failure") {
20424
- const failurePayloads = officerFailurePayloads(terminal);
20425
- return {
20426
- status: "transport_failure",
20427
- stage: officer,
20428
- reason: outcome.diagnostic,
20429
- submission: failurePayloads.length > 0 ? failurePayloads : outcome.decisiveFacts
20430
- };
20431
- }
20432
- if (outcome.kind === "audit_escalation") {
20433
- return {
20434
- status: "escalate",
20435
- officer,
20436
- // This-court receipt only (#879) — historical rows remain on terminal.submissions.
20437
- receipt: thisCourt.length > 0 ? thisCourt[thisCourt.length - 1] : retainedReceipt(outcome)
20438
- };
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);
20439
20941
  }
20440
- if (outcome.kind === "accepted") {
20441
- 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);
20442
20946
  }
20443
- return {
20444
- status: "needs_reask",
20445
- officer,
20446
- // This-court receipt only (#879).
20447
- 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 }
20448
20958
  };
20449
- }
20450
- async function projectGatekeeperRun(options) {
20451
- const officer = gateOfficerForSubject(options.subject);
20452
- const runDirectory = options.runDirectory ?? auditorRunDirectory(options.context);
20453
- if (runDirectory === void 0) {
20454
- return {
20455
- officer,
20456
- result: {
20457
- status: "transport_failure",
20458
- stage: officer,
20459
- reason: `${gateSeatLabel(officer)} requires a parent run directory pointer`
20460
- }
20461
- };
20959
+ if (options.officer === "notary") {
20960
+ return summonPublicRole({
20961
+ role: "notary",
20962
+ argv: ["--source-run", options.sourceRunDirectory, "--project", options.cwd],
20963
+ ...common
20964
+ });
20462
20965
  }
20463
- let summoned;
20464
- try {
20465
- const summon = options.summonOfficer ?? (async (nextOfficer, sourceRunDirectory, officerSignal, reask, nextSubmission) => {
20466
- const { summonGateOfficer: summonGateOfficer2 } = await Promise.resolve().then(() => (init_public_role_summons(), public_role_summons_exports));
20467
- return summonGateOfficer2({
20468
- officer: nextOfficer,
20469
- sourceRunDirectory,
20470
- cwd: options.context.cwd ?? process.cwd(),
20471
- ...officerSignal === void 0 ? {} : { signal: officerSignal },
20472
- ...reask === void 0 ? {} : { reask },
20473
- ...nextSubmission === void 0 ? {} : { submission: nextSubmission },
20474
- ...options.home === void 0 ? {} : { home: options.home },
20475
- ...options.packageRoot === void 0 ? {} : { packageRoot: options.packageRoot },
20476
- ...options.roleTurnHost === void 0 ? {} : { roleTurnHost: options.roleTurnHost },
20477
- ...options.createRunId === void 0 ? {} : { createRunId: options.createRunId }
20478
- });
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
20479
20977
  });
20480
- summoned = await summon(
20481
- officer,
20482
- runDirectory,
20483
- options.signal,
20484
- options.reask,
20485
- options.submission
20486
- );
20487
- } catch (error) {
20488
- return {
20489
- officer,
20490
- result: { status: "transport_failure", stage: officer, reason: failureReason(error) }
20491
- };
20492
20978
  }
20493
- return {
20494
- officer,
20495
- result: projectOfficerTerminal(officer, summoned),
20496
- summoned
20497
- };
20979
+ return summonPublicRole({
20980
+ role: "inspector",
20981
+ argv: [`\u5377\u5B97\u6307\u9488\uFF1A${options.sourceRunDirectory}`],
20982
+ ...common
20983
+ });
20498
20984
  }
20499
- var GATEKEEPER_TOOL_SPEC, OFFICER_CONCLUSION_REASK;
20500
- var init_gatekeeper_role = __esm({
20501
- "src/gatekeeper-role.ts"() {
20985
+ var AK_ROLE_PACKAGE_ROOT_ENV;
20986
+ var init_public_role_summons = __esm({
20987
+ "src/public-role-summons.ts"() {
20502
20988
  "use strict";
20503
- init_auditor_dossier_tool();
20504
- init_submission_errors();
20505
- init_inspector_contracts();
20506
- init_gatekeeper_output();
20507
- init_submission_errors();
20508
- GATEKEEPER_TOOL_SPEC = {
20509
- name: GATEKEEPER_OUTPUT_TOOL_NAME,
20510
- label: "\u95E8\u4E0B\u7701\u51B3\u8BAE",
20511
- description: "\u95E8\u4E0B\u7701\u7EC8\u5C40\u51B3\u8BAE\uFF0C\u72B6\u6001\u4E3A dispatch \u6216 pass\u3002",
20512
- promptSnippet: "\u95E8\u4E0B\u7701\u51B3\u8BAE",
20513
- parameters: gatekeeperOutputSchema
20514
- };
20515
- 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";
20516
20991
  }
20517
20992
  });
20518
20993
 
@@ -20524,13 +20999,30 @@ init_engine_detour();
20524
20999
  import { randomUUID as randomUUID8 } from "node:crypto";
20525
21000
  import { mkdir as mkdir5, readFile as readFile21, writeFile as writeFile12 } from "node:fs/promises";
20526
21001
  import { createServer } from "node:net";
20527
- 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";
20528
21003
  import { fileURLToPath as fileURLToPath2 } from "node:url";
20529
21004
 
20530
21005
  // src/gatekeeper-pass-envelope.ts
20531
21006
  init_archivist_record_entry();
20532
21007
  init_gatekeeper_role();
20533
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
+ }
20534
21026
  function bookDirectOfficerPointer(context, officer, result, summoned) {
20535
21027
  if (result.status !== "pass" && result.status !== "bounce" && result.status !== "escalate" && result.status !== "needs_reask" && result.status !== "transport_failure") {
20536
21028
  return;
@@ -20550,12 +21042,15 @@ function bookDirectOfficerPointer(context, officer, result, summoned) {
20550
21042
  }
20551
21043
  async function requireGatekeeperPass(options) {
20552
21044
  let reask;
21045
+ const summonOfficer = options.summonOfficer ?? createDefaultGateOfficerSummon({
21046
+ cwd: options.context.cwd ?? process.cwd()
21047
+ });
20553
21048
  for (; ; ) {
20554
21049
  const projected = await projectGatekeeperRun({
20555
21050
  context: options.context,
20556
21051
  subject: options.subject,
21052
+ summonOfficer,
20557
21053
  ...options.signal === void 0 ? {} : { signal: options.signal },
20558
- ...options.summonOfficer === void 0 ? {} : { summonOfficer: options.summonOfficer },
20559
21054
  ...options.submission === void 0 ? {} : { submission: options.submission },
20560
21055
  ...reask === void 0 ? {} : { reask }
20561
21056
  });
@@ -21013,14 +21508,8 @@ init_engine_material();
21013
21508
  // src/engine-detour-tool.ts
21014
21509
  init_engine_detour();
21015
21510
  init_engine_detour_usage();
21016
- import { basename as basename9 } from "node:path";
21511
+ init_run_terminal_artifacts();
21017
21512
  import { Type as Type14 } from "typebox";
21018
- function basenameRunId(runDirectory) {
21019
- const leaf = basename9(runDirectory);
21020
- const at = leaf.indexOf("@");
21021
- if (at <= 0) return void 0;
21022
- return leaf.slice(0, at);
21023
- }
21024
21513
  var engineDetourArgsSchema = Type14.Object(
21025
21514
  {
21026
21515
  argv: Type14.Array(Type14.String({ minLength: 1 }), {
@@ -21063,7 +21552,7 @@ function createEngineDetourToolDefinition(input) {
21063
21552
  const sessionParent = ctx.sessionManager?.getSessionFile?.();
21064
21553
  const startedAt = Date.now();
21065
21554
  const runDirectory = typeof ctx.runDirectory === "string" && ctx.runDirectory.length > 0 ? ctx.runDirectory : void 0;
21066
- const runId = runDirectory === void 0 ? void 0 : basenameRunId(runDirectory);
21555
+ const runId = runDirectory === void 0 ? void 0 : runIdFromRunDirectory(runDirectory);
21067
21556
  const invocationScopeId = typeof ctx.invocationScopeId === "string" && ctx.invocationScopeId.trim() !== "" ? ctx.invocationScopeId.trim() : void 0;
21068
21557
  const host = typeof ctx.host === "string" && ctx.host.trim() !== "" ? ctx.host.trim() : void 0;
21069
21558
  const recordCall = (observed2) => {
@@ -21154,6 +21643,7 @@ function registerEngineDetourTool(roleHost, hostActions) {
21154
21643
  }
21155
21644
 
21156
21645
  // src/role-runtime.ts
21646
+ init_run_terminal_artifacts();
21157
21647
  init_receipt_delivery_policy();
21158
21648
 
21159
21649
  // src/collector-role.ts
@@ -21268,7 +21758,7 @@ var collectorOutputBaseSchema = openToolObject(
21268
21758
  })
21269
21759
  })
21270
21760
  );
21271
- var collectorOutputArgsSchema = withInfrastructureFailureDeclaration(
21761
+ var collectorOutputArgsSchema = withTerminatingOutputDeclarations(
21272
21762
  collectorOutputBaseSchema
21273
21763
  );
21274
21764
 
@@ -22115,7 +22605,7 @@ init_terminating_infrastructure();
22115
22605
  init_countersign_contracts();
22116
22606
  init_countersign_contracts();
22117
22607
  import { Type as Type16 } from "typebox";
22118
- var countersignVerdictSchema = withInfrastructureFailureDeclaration(
22608
+ var countersignVerdictSchema = withTerminatingOutputDeclarations(
22119
22609
  Type16.Object(
22120
22610
  {
22121
22611
  countersignStatus: Type16.Unknown({ description: "converged | continue | escalate\u3002\u975E\u4E09\u6001\u65F6\u8BF7\u91CD\u8BFB\u540E\u91CD\u4EA4\uFF0C\u52FF\u6539\u6807\u3002" }),
@@ -22158,7 +22648,7 @@ init_terminating_infrastructure();
22158
22648
  init_gleaner_left_contracts();
22159
22649
  init_gleaner_left_contracts();
22160
22650
  import { Type as Type17 } from "typebox";
22161
- var gleanerLeftOutputSchema = withInfrastructureFailureDeclaration(
22651
+ var gleanerLeftOutputSchema = withTerminatingOutputDeclarations(
22162
22652
  openToolObject(
22163
22653
  Type17.Object({
22164
22654
  status: Type17.Unknown({
@@ -22193,7 +22683,7 @@ init_open_tool_schema();
22193
22683
  init_terminating_infrastructure();
22194
22684
  init_inspector_contracts();
22195
22685
  import { Type as Type18 } from "typebox";
22196
- var inspectorOutputSchema = withInfrastructureFailureDeclaration(
22686
+ var inspectorOutputSchema = withTerminatingOutputDeclarations(
22197
22687
  openToolObject(
22198
22688
  Type18.Object({
22199
22689
  status: Type18.Unknown({
@@ -22225,7 +22715,7 @@ init_terminating_infrastructure();
22225
22715
  init_diarist_contracts();
22226
22716
  init_diarist_contracts();
22227
22717
  import { Type as Type19 } from "typebox";
22228
- var diaristOutputSchema = withInfrastructureFailureDeclaration(
22718
+ var diaristOutputSchema = withTerminatingOutputDeclarations(
22229
22719
  openToolObject(
22230
22720
  Type19.Object({
22231
22721
  status: Type19.Unknown({
@@ -22333,7 +22823,121 @@ var DIARIST_TOOL_SPEC = {
22333
22823
  parameters: diaristOutputSchema
22334
22824
  };
22335
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
+
22336
22939
  // src/role-runtime.ts
22940
+ init_secretariat_contracts();
22337
22941
  init_diarist_contracts();
22338
22942
 
22339
22943
  // src/diarist.ts
@@ -22391,13 +22995,13 @@ init_packaged_role_registry();
22391
22995
  init_activation_ledger_topology();
22392
22996
  import { resolve as resolve16 } from "node:path";
22393
22997
  import "@earendil-works/pi-coding-agent";
22394
- import { Type as Type21 } from "typebox";
22998
+ import { Type as Type22 } from "typebox";
22395
22999
 
22396
23000
  // src/navigator-public-session.ts
22397
23001
  init_sitian_facade();
22398
23002
 
22399
23003
  // src/navigator-session-contracts.ts
22400
- import { Type as Type20 } from "typebox";
23004
+ import { Type as Type21 } from "typebox";
22401
23005
  import { Value as Value3 } from "typebox/value";
22402
23006
  var NAVIGATOR_PREPARE_TOOL_NAME = "ak_navigator_prepare";
22403
23007
  var NAVIGATOR_UNAVAILABLE_KEYS = /* @__PURE__ */ new Set([
@@ -22505,26 +23109,26 @@ function navigatorProviderFailureFromPublicTerminal(outcome) {
22505
23109
  if (typed !== void 0) return { source: typed, cause: typed };
22506
23110
  return { source: "unknown", cause: "unknown" };
22507
23111
  }
22508
- var navigatorProviderFailureSchema = Type20.Object({
22509
- source: Type20.Union([
22510
- Type20.Literal("context"),
22511
- Type20.Literal("session"),
22512
- Type20.Literal("model"),
22513
- Type20.Literal("thinking"),
22514
- Type20.Literal("auth"),
22515
- Type20.Literal("quota"),
22516
- Type20.Literal("transport"),
22517
- 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")
22518
23122
  ]),
22519
- cause: Type20.Union([
22520
- Type20.Literal("context"),
22521
- Type20.Literal("session"),
22522
- Type20.Literal("model"),
22523
- Type20.Literal("thinking"),
22524
- Type20.Literal("auth"),
22525
- Type20.Literal("quota"),
22526
- Type20.Literal("transport"),
22527
- 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")
22528
23132
  ])
22529
23133
  }, { additionalProperties: false });
22530
23134
  function parseNavigatorModelSetting(value) {
@@ -22730,8 +23334,8 @@ function resolveNavigatorAuthorityMaterial(roleInput, fileAuthority) {
22730
23334
  return void 0;
22731
23335
  }
22732
23336
  var NAVIGATOR_TARGETS = PACKAGED_ROLE_REGISTRY.map(({ role, phases }) => ({ role, phases }));
22733
- var prepareSchema = Type21.Object({
22734
- candidates: Type21.Optional(Type21.Unknown({
23337
+ var prepareSchema = Type22.Object({
23338
+ candidates: Type22.Optional(Type22.Unknown({
22735
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"
22736
23340
  }))
22737
23341
  }, { additionalProperties: true });
@@ -23361,32 +23965,32 @@ init_audit_escalation();
23361
23965
  init_terminating_infrastructure();
23362
23966
  init_submission_errors();
23363
23967
  init_judge_output();
23364
- import { Type as Type22 } from "typebox";
23968
+ import { Type as Type23 } from "typebox";
23365
23969
  var JUDGE_QUEUE_STATUSES = /* @__PURE__ */ new Set(["converged", "continue", "escalate"]);
23366
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";
23367
- var judgeVerdictSchema = withInfrastructureFailureDeclaration(
23368
- Type22.Object(
23971
+ var judgeVerdictSchema = withTerminatingOutputDeclarations(
23972
+ Type23.Object(
23369
23973
  {
23370
- judgeStatus: Type22.Unknown({ description: "converged | continue | escalate \u2014 \u5F62\u72B6\u6307\u5F15\uFF0C\u975E schema \u95F8" }),
23371
- fix: Type22.Optional(
23372
- Type22.Object(
23373
- { 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" })) },
23374
23978
  { additionalProperties: true, description: "continue \u65F6\u7684\u8865\u6551\u8BF4\u660E" }
23375
23979
  )
23376
23980
  ),
23377
- classes: Type22.Optional(Type22.Array(Type22.Object({
23378
- name: Type22.Optional(Type22.String()),
23379
- owner: Type22.Optional(Type22.String()),
23380
- boundary: Type22.Optional(Type22.String()),
23381
- 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())
23382
23986
  }, { additionalProperties: true }), { description: "\u5DF2\u88C1\u51B3 finding \u7C7B\u53CA\u5176 owner \u4E0E\u4FEE\u7406\u8FB9\u754C" })),
23383
- note: Type22.Optional(Type22.String({ description: "\u53EF\u9009\u88C1\u51B3\u9644\u6CE8" })),
23384
- evidence: Type22.Optional(Type22.Unknown({ description: "\u7559\u5B58\u7684\u88C1\u51B3\u8BC1\u636E" })),
23385
- decisionGate: Type22.Optional(
23386
- 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(
23387
23991
  {
23388
- question: Type22.Optional(Type22.String()),
23389
- options: Type22.Optional(Type22.Array(Type22.String()))
23992
+ question: Type23.Optional(Type23.String()),
23993
+ options: Type23.Optional(Type23.Array(Type23.String()))
23390
23994
  },
23391
23995
  { additionalProperties: true, description: "\u9700\u4EBA\u6743\u5A01\u5904\u7F6E\u7684\u95EE\u9898\u4E0E\u9009\u9879" }
23392
23996
  )
@@ -23474,24 +24078,24 @@ init_open_tool_schema();
23474
24078
  init_terminating_infrastructure();
23475
24079
  init_reviewer_pinned_git();
23476
24080
  init_reviewer_output();
23477
- import { Type as Type23 } from "typebox";
23478
- var reviewerAmendmentsSchema = Type23.Object({
23479
- standards: Type23.Optional(Type23.String({ description: "\u6807\u51C6\u8F74\u5F39\u7AE0\u6B63\u6587" })),
23480
- 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" }))
23481
24085
  }, { additionalProperties: true, description: "\u9010\u8F74\u5F39\u7AE0\u6B63\u6587\uFF1B\u65E0\u5F39\u7AE0\u7684\u8F74\u53EF\u7701\u7565\u3002" });
23482
24086
  var REVIEWER_STATUS_DESCRIPTION = "completed | refused \u2014 \u5F62\u72B6\u6307\u5F15\uFF0C\u975E schema \u95F8";
23483
- var reviewerOutputVariants = Type23.Union([
23484
- Type23.Object({
23485
- status: Type23.Unknown({ description: REVIEWER_STATUS_DESCRIPTION }),
23486
- 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)
23487
24091
  }, { additionalProperties: false }),
23488
- Type23.Object({
23489
- status: Type23.Unknown({ description: REVIEWER_STATUS_DESCRIPTION }),
23490
- diagnostic: Type23.String({ description: "\u62D2\u7EDD\u8BCA\u65AD\u8BF4\u660E" }),
23491
- 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)
23492
24096
  }, { additionalProperties: false })
23493
24097
  ]);
23494
- var reviewerOutputSchema = withInfrastructureFailureDeclaration(
24098
+ var reviewerOutputSchema = withTerminatingOutputDeclarations(
23495
24099
  openToolObjectFromUnion(reviewerOutputVariants)
23496
24100
  );
23497
24101
  function createReviewerRoleRuntime(pi, dependencies, _hostActions) {
@@ -23544,7 +24148,7 @@ init_submission_correctable_error();
23544
24148
  init_worker_output();
23545
24149
  init_fixer_output();
23546
24150
  init_fixer_packet();
23547
- import { Type as Type24 } from "typebox";
24151
+ import { Type as Type25 } from "typebox";
23548
24152
 
23549
24153
  // src/worker-submission-gates.ts
23550
24154
  init_archivist_record_entry();
@@ -23809,26 +24413,26 @@ function fixerBashSeatbeltDenyReason(matched) {
23809
24413
 
23810
24414
  // src/worker-role.ts
23811
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";
23812
- var coderOutputVariants = Type24.Union([
23813
- Type24.Object({
23814
- status: Type24.Unknown({ description: CODER_STATUS_DESCRIPTION }),
23815
- 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" })
23816
24420
  }, { additionalProperties: false }),
23817
- Type24.Object({
23818
- status: Type24.Unknown({ description: CODER_STATUS_DESCRIPTION }),
23819
- 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" })
23820
24424
  }, { additionalProperties: false }),
23821
- Type24.Object({
23822
- status: Type24.Unknown({ description: CODER_STATUS_DESCRIPTION }),
23823
- report: Type24.String({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" }),
23824
- remainingScope: Type24.String({ description: "\u672C\u5C40\u540E\u5269\u4F59\u5DE5\u4F5C" }),
23825
- 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({
23826
24430
  minLength: 1,
23827
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"
23828
24432
  }))
23829
24433
  }, { additionalProperties: false })
23830
24434
  ]);
23831
- var coderOutputSchema = withInfrastructureFailureDeclaration(
24435
+ var coderOutputSchema = withTerminatingOutputDeclarations(
23832
24436
  openToolObjectFromUnion(coderOutputVariants)
23833
24437
  );
23834
24438
  var FIXER_FLAG_DEFINITIONS = {
@@ -24374,6 +24978,8 @@ function activationStage(role, runtime) {
24374
24978
  return { id: "load-and-install", run: async () => runtime.auditor.activate() };
24375
24979
  case "diarist":
24376
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() };
24377
24983
  case "merger":
24378
24984
  return { id: "prepare-git-and-install", run: async () => runtime.merger() };
24379
24985
  }
@@ -24477,7 +25083,7 @@ function publicNavigatorSettlement(role, phase, event) {
24477
25083
  if (isAuditEscalationProjection(event.details)) {
24478
25084
  return { kind: "human_decision", role, phase, status: "audit_escalation" };
24479
25085
  }
24480
- 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;
24481
25087
  if (status !== void 0 && status === "escalate") {
24482
25088
  return { kind: "human_decision", role, phase, status };
24483
25089
  }
@@ -24631,21 +25237,28 @@ function readDiaristTicketAssertion(submitted) {
24631
25237
  }
24632
25238
  return { kind: "invalid" };
24633
25239
  }
24634
- function readDiaristRunCoordinates(ctx) {
25240
+ function readRoleRunCoordinates(ctx, label) {
24635
25241
  const runDirectory = runDirectoryFromHostContext(ctx);
24636
- if (runDirectory === void 0) {
24637
- throw new Error("diarist accept requires AK_ROLE_RUN_DIR");
24638
- }
25242
+ if (runDirectory === void 0) throw new Error(`${label} requires AK_ROLE_RUN_DIR`);
24639
25243
  const admittedPath = join40(runDirectory, "admitted-request.json");
24640
25244
  const admitted = JSON.parse(readFileSync6(admittedPath, "utf8"));
24641
25245
  if (typeof admitted.projectRoot !== "string" || admitted.projectRoot.trim() === "") {
24642
- throw new Error(`diarist admitted-request missing projectRoot (${admittedPath})`);
25246
+ throw new Error(`${label} admitted-request missing projectRoot (${admittedPath})`);
24643
25247
  }
24644
- const bound = typeof admitted.ticketNumber === "number" && Number.isSafeInteger(admitted.ticketNumber) && admitted.ticketNumber >= 1 ? admitted.ticketNumber : void 0;
24645
25248
  return {
24646
25249
  runDirectory,
24647
25250
  projectRoot: admitted.projectRoot,
24648
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,
24649
25262
  ...bound === void 0 ? {} : { boundTicketNumber: bound }
24650
25263
  };
24651
25264
  }
@@ -24714,6 +25327,100 @@ ${error.message}`
24714
25327
  }
24715
25328
  var COUNTERSIGN_QUEUE_STATUSES = /* @__PURE__ */ new Set(["converged", "continue", "escalate"]);
24716
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
+ }
24717
25424
  function createCountersignRoleRuntime(roleHost, dependencies, hostActions) {
24718
25425
  const beforeAccept = hostActions !== void 0 && roleHost.requireGatekeeperPass !== void 0 ? async ({ toolCallId, parameters, signal, ctx }) => {
24719
25426
  const record4 = parameters !== null && typeof parameters === "object" && !Array.isArray(parameters) ? parameters : void 0;
@@ -25258,6 +25965,13 @@ function createRoleRuntimeExtension(dependencies) {
25258
25965
  }
25259
25966
  }
25260
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
+ });
25261
25975
  const merger = createMergerRoleRuntime(roleHost, {
25262
25976
  async loadSoul() {
25263
25977
  if (!dependencies.loadMergerSoul) throw new Error("Merger runtime dependencies are not configured");
@@ -25491,6 +26205,7 @@ function createRoleRuntimeExtension(dependencies) {
25491
26205
  navigator,
25492
26206
  auditor,
25493
26207
  diarist,
26208
+ secretariat,
25494
26209
  merger: async () => {
25495
26210
  await merger.activate();
25496
26211
  }
@@ -25577,6 +26292,11 @@ function createRoleRuntimeExtension(dependencies) {
25577
26292
  if (!engineDetourRegistered) {
25578
26293
  engineDetourRegistered = registerEngineDetourTool(roleHost, hostActions);
25579
26294
  }
26295
+ if (entry.role === "secretariat" && engineDetourRegistered) {
26296
+ roleHost.setActiveTools([
26297
+ .../* @__PURE__ */ new Set([...roleHost.getActiveTools(), ENGINE_DETOUR_TOOL_NAME])
26298
+ ]);
26299
+ }
25580
26300
  if (entry.role === "coder" || entry.role === "fixer") {
25581
26301
  if (entry.role === "coder") coder.armSubmissionGate(ctx.cwd, ctx.sessionManager);
25582
26302
  else fixer.armSubmissionGate(ctx.cwd, ctx.sessionManager);
@@ -25659,7 +26379,7 @@ async function prepareRoleEnvelope(options) {
25659
26379
  await mkdir5(request.runDirectory, { recursive: true });
25660
26380
  for (const method of request.methods) {
25661
26381
  if (method.kind !== "skill") continue;
25662
- const name = basename10(dirname21(method.path));
26382
+ const name = basename9(dirname21(method.path));
25663
26383
  const raw = await readFile21(method.path, "utf8");
25664
26384
  methodSkills.set(name, { path: method.path, body: stripSkillFrontmatter(raw).trim() });
25665
26385
  }
@@ -26362,6 +27082,7 @@ function createRoleRuntimeDependencies(packageRoot) {
26362
27082
  loadCountersignSoul: () => loadMainRoleSessionMaterials("countersign"),
26363
27083
  loadGleanerLeftSoul: () => loadMainRoleSessionMaterials("gleaner-left"),
26364
27084
  loadDiaristSoul: () => loadMainRoleSessionMaterials("diarist"),
27085
+ loadSecretariatSoul: () => loadMainRoleSessionMaterials("secretariat"),
26365
27086
  loadNotarySourceRun: loadNotarySourceRunLocator,
26366
27087
  loadMergerSoul: () => loadMainRoleSessionMaterials("merger"),
26367
27088
  loadMergerInput: async (path) => JSON.parse(await readFile24(path, "utf8")),