@akagilnc/pi-workflow-roles 0.1.5375 → 0.1.5406

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 (79) hide show
  1. package/README.md +2 -0
  2. package/README.zh-CN.md +2 -0
  3. package/dist/acp-host/production-host.js +6381 -5684
  4. package/dist/archivist-record-pointer.js +38 -0
  5. package/dist/collector-tool-schemas.js +18 -0
  6. package/dist/compliance-transport.js +5 -0
  7. package/dist/diarist-contracts.js +26 -0
  8. package/dist/doctor-auditor.js +1 -0
  9. package/dist/engine-detour-usage.js +6 -6
  10. package/dist/filed-submission.js +28 -0
  11. package/dist/gatekeeper-role.js +6 -10
  12. package/dist/gleaner-left-contracts.js +16 -0
  13. package/dist/headless-host/production-host.js +1644 -947
  14. package/dist/judge-role.js +21 -16
  15. package/dist/migrate-book-topology.js +452 -81
  16. package/dist/navigator-attendance.js +10 -9
  17. package/dist/navigator-invocation-identity.js +18 -0
  18. package/dist/package-contracts/reviewer-output.js +16 -0
  19. package/dist/package-contracts/worker-output.js +18 -2
  20. package/dist/pi/role-turn-host.js +9 -0
  21. package/dist/public-cli/cli.js +1 -0
  22. package/dist/public-cli/instruction-seat-run.js +258 -55
  23. package/dist/public-cli/main.js +1209 -346
  24. package/dist/public-cli/post-admission.js +427 -244
  25. package/dist/public-cli/settlement.js +111 -48
  26. package/dist/public-cli/terminal.js +12 -1
  27. package/dist/public-cli/turn-request.js +3 -0
  28. package/dist/receipt-delivery-policy.js +152 -17
  29. package/dist/role-submission-declarations.js +131 -0
  30. package/dist/secretariat-contracts.js +23 -1
  31. package/dist/submission-errors.js +11 -1
  32. package/dist/submission-gate.js +32 -12
  33. package/package.json +1 -1
  34. package/src/archivist-record-pointer.ts +48 -0
  35. package/src/auditor-role.ts +2 -8
  36. package/src/collector-role.ts +5 -28
  37. package/src/compliance-transport.ts +10 -2
  38. package/src/countersign-role.ts +2 -7
  39. package/src/diarist-contracts.ts +37 -0
  40. package/src/diarist-role.ts +4 -44
  41. package/src/doctor-auditor.ts +3 -0
  42. package/src/doctor-role.ts +16 -11
  43. package/src/engine-detour-usage.ts +7 -6
  44. package/src/external-host-turn-loop.ts +24 -12
  45. package/src/filed-submission.ts +44 -0
  46. package/src/gatekeeper-role.ts +8 -16
  47. package/src/gleaner-left-contracts.ts +26 -1
  48. package/src/gleaner-left-role.ts +4 -32
  49. package/src/host-contracts.ts +7 -0
  50. package/src/inspector-role.ts +2 -7
  51. package/src/judge-role.ts +31 -24
  52. package/src/merger-role.ts +5 -8
  53. package/src/navigator-attendance.ts +17 -12
  54. package/src/navigator-invocation-identity.ts +31 -0
  55. package/src/navigator-role.ts +2 -8
  56. package/src/notary-role.ts +5 -20
  57. package/src/package-contracts/reviewer-output.ts +25 -0
  58. package/src/package-contracts/worker-output.ts +43 -5
  59. package/src/pi/adapter.ts +33 -8
  60. package/src/pi/role-turn-host.ts +7 -0
  61. package/src/public-cli/cli.ts +1 -0
  62. package/src/public-cli/instruction-seat-run.ts +292 -61
  63. package/src/public-cli/post-admission.ts +556 -324
  64. package/src/public-cli/settlement.ts +112 -50
  65. package/src/public-cli/terminal.ts +16 -4
  66. package/src/public-cli/turn-request.ts +10 -1
  67. package/src/receipt-delivery-policy.ts +209 -17
  68. package/src/reviewer-role.ts +7 -35
  69. package/src/role-envelope.ts +5 -1
  70. package/src/role-runtime-dependencies.ts +1 -0
  71. package/src/role-runtime.ts +72 -56
  72. package/src/role-submission-declarations.ts +143 -0
  73. package/src/secretariat-contracts.ts +35 -0
  74. package/src/secretariat-role.ts +4 -40
  75. package/src/submission-correctable-error.ts +5 -2
  76. package/src/submission-errors.ts +12 -1
  77. package/src/submission-gate.ts +41 -12
  78. package/src/worker-role.ts +81 -86
  79. package/src/worker-submission-gates.ts +32 -7
@@ -285,15 +285,6 @@ var init_judge_output = __esm({
285
285
  }
286
286
  });
287
287
 
288
- // src/package-contracts/reviewer-output.ts
289
- var REVIEWER_OUTPUT_TOOL_NAME;
290
- var init_reviewer_output = __esm({
291
- "src/package-contracts/reviewer-output.ts"() {
292
- "use strict";
293
- REVIEWER_OUTPUT_TOOL_NAME = "ak_reviewer_output";
294
- }
295
- });
296
-
297
288
  // src/open-tool-schema.ts
298
289
  import { Type as Type3 } from "typebox";
299
290
  function described(name, schema) {
@@ -317,8 +308,32 @@ var init_open_tool_schema = __esm({
317
308
  }
318
309
  });
319
310
 
320
- // src/package-contracts/gatekeeper-output.ts
311
+ // src/package-contracts/reviewer-output.ts
321
312
  import { Type as Type4 } from "typebox";
313
+ var REVIEWER_OUTPUT_TOOL_NAME, REVIEWER_AMENDMENTS_DESCRIPTION, REVIEWER_STATUS_DESCRIPTION, reviewerOutputObject, reviewerOutputSchema;
314
+ var init_reviewer_output = __esm({
315
+ "src/package-contracts/reviewer-output.ts"() {
316
+ "use strict";
317
+ init_open_tool_schema();
318
+ init_terminating_infrastructure();
319
+ REVIEWER_OUTPUT_TOOL_NAME = "ak_reviewer_output";
320
+ REVIEWER_AMENDMENTS_DESCRIPTION = "\u5DF2\u8FD0\u884C lens \u7684 amendments \u627F\u8F7D candidates\u3001\u9010\u6761\u5904\u7F6E\u4E0E verdict \u7684\u5B8C\u6574\u62A5\u544A\uFF08\u975E\u4EC5 verdict \u884C\uFF09\uFF1B\u663E\u5F0F\u5355\u8F74\u65F6\u53E6\u4E00\u8F74\u53EF\u7701\u7565\uFF08completeness / correctness\uFF09\u3002hard-stop\uFF0Fusage error \u4E3A refused \u65F6\uFF0C\u5DF2\u4EA7\u51FA\u62A5\u544A\u4ECD\u7167\u5F55\u5BF9\u5E94 lens \u5B57\u6BB5\u3002";
321
+ REVIEWER_STATUS_DESCRIPTION = "completed | refused\u3002\u4E24\u79CD\u6B63\u5E38 lens verdict\uFF08completeness / correctness\uFF09\u5747 completed\uFF1Bhard-stop \u4E0E usage error \u4E3A refused\uFF08\u5DF2\u4EA7\u51FA\u62A5\u544A\u4ECD\u7167\u5F55\u8FDB\u6240\u9009 lens amendments\uFF09\u3002";
322
+ reviewerOutputObject = Type4.Object({
323
+ status: Type4.Unknown({ description: REVIEWER_STATUS_DESCRIPTION }),
324
+ amendments: Type4.Unknown({ description: REVIEWER_AMENDMENTS_DESCRIPTION }),
325
+ diagnostic: Type4.Unknown({
326
+ description: "\u62D2\u7EDD\u8BCA\u65AD\u8BF4\u660E\uFF1Bhard-stop\uFF0Fusage error \u539F\u56E0\u8FDB\u6B64\u5B57\u6BB5\uFF0C\u5DF2\u4EA7\u51FA\u62A5\u544A\u53E6\u7167\u5F55 amendments"
327
+ })
328
+ });
329
+ reviewerOutputSchema = withTerminatingOutputDeclarations(
330
+ openToolObject(reviewerOutputObject)
331
+ );
332
+ }
333
+ });
334
+
335
+ // src/package-contracts/gatekeeper-output.ts
336
+ import { Type as Type5 } from "typebox";
322
337
  var GATEKEEPER_OUTPUT_TOOL_NAME, gatekeeperDecisionSchema, gatekeeperOutputSchema;
323
338
  var init_gatekeeper_output = __esm({
324
339
  "src/package-contracts/gatekeeper-output.ts"() {
@@ -328,14 +343,14 @@ var init_gatekeeper_output = __esm({
328
343
  init_unknown_value();
329
344
  GATEKEEPER_OUTPUT_TOOL_NAME = "ak_gatekeeper_output";
330
345
  gatekeeperDecisionSchema = openToolObject(
331
- Type4.Object({
332
- status: Type4.Unknown({
346
+ Type5.Object({
347
+ status: Type5.Unknown({
333
348
  description: "dispatch | pass"
334
349
  }),
335
- officer: Type4.Unknown({
350
+ officer: Type5.Unknown({
336
351
  description: "status \u4E3A dispatch \u65F6\u4E3A inspector | notary"
337
352
  }),
338
- findings: Type4.Unknown({
353
+ findings: Type5.Unknown({
339
354
  description: "status \u4E3A pass \u65F6\u53EF\u9009 string[] findings"
340
355
  })
341
356
  })
@@ -355,7 +370,7 @@ __export(navigator_output_exports, {
355
370
  projectLawfulNavigatorOutput: () => projectLawfulNavigatorOutput,
356
371
  validateRecordedNavigatorOutput: () => validateRecordedNavigatorOutput
357
372
  });
358
- import { Type as Type5 } from "typebox";
373
+ import { Type as Type6 } from "typebox";
359
374
  function projectLawfulNavigatorOutput(value) {
360
375
  if (value === void 0 || value === null) return void 0;
361
376
  if (typeof value === "string") return { prose: value };
@@ -397,8 +412,8 @@ var init_navigator_output = __esm({
397
412
  NAVIGATOR_OUTPUT_TOOL_NAME = "ak_navigator_output";
398
413
  navigatorOutputSchema = withTerminatingOutputDeclarations(
399
414
  openToolObject(
400
- Type5.Object({
401
- prose: Type5.Unknown({
415
+ Type6.Object({
416
+ prose: Type6.Unknown({
402
417
  description: "\u6E38\u5955\u4F7F\u6563\u6587\u5EFA\u8BAE\uFF0C\u539F\u6837\u5448\u73B0\u3002\u4E0D\u8981\u6C42 candidates/next \u7B49\u7ED3\u6784\u5316\u5B57\u6BB5\u3002"
403
418
  })
404
419
  })
@@ -408,7 +423,7 @@ var init_navigator_output = __esm({
408
423
  });
409
424
 
410
425
  // src/package-contracts/fixer-output.ts
411
- import { Type as Type6 } from "typebox";
426
+ import { Type as Type7 } from "typebox";
412
427
  function validateFixerOutput(value, _phase) {
413
428
  return value;
414
429
  }
@@ -421,22 +436,22 @@ var init_fixer_output = __esm({
421
436
  FIXER_OUTPUT_TOOL_NAME = "ak_fixer_output";
422
437
  PARTIALLY_COMPLETED_DEFINITION = "partially_completed \u53EA\u80FD\u5728\u6709\u5408\u6CD5\u62D2\u7EDD\u9879\uFF08\u5B8C\u6210\u9879\u4E0E\u5408\u6CD5\u62D2\u7EDD\u9879\u5E76\u5B58\uFF09\u65F6\u7528\uFF0C\u522B\u7684\u60C5\u51B5\u4E0D\u51C6\u7528\u3002";
423
438
  FIXER_STATUS_DESCRIPTION = `planned | completed | refused | unfinished | partially_completed\u3002unfinished \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${PARTIALLY_COMPLETED_DEFINITION}`;
424
- fixerOutputObject = Type6.Object({
425
- status: Type6.Unknown({ description: FIXER_STATUS_DESCRIPTION }),
426
- report: Type6.Unknown({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" }),
427
- remainingScope: Type6.Unknown({
439
+ fixerOutputObject = Type7.Object({
440
+ status: Type7.Unknown({ description: FIXER_STATUS_DESCRIPTION }),
441
+ report: Type7.Unknown({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" }),
442
+ remainingScope: Type7.Unknown({
428
443
  description: "\u672C\u5C40\u540E\u5269\u4F59\u5DE5\u4F5C\uFF1B\u4F9D\u6CD5\u4E0D\u80FD\u5B8C\u6210\u7684\u8303\u56F4\u4E5F\u5199\u6B64\u5904\u3002"
429
444
  }),
430
- blocker: Type6.Unknown({
445
+ blocker: Type7.Unknown({
431
446
  description: "\u5408\u6CD5\u963B\u65AD\u5B8C\u6210\u7684 blocker\uFF0C\u539F\u6837\u7559\u5B58\u3002\u53EF\u5199 cause\uFF08authority_violation \u6216 prerequisite_unmet\uFF09\u3001evidence\uFF1Bprerequisite_unmet \u8FD8\u53EF\u5199 prerequisiteId\u3002"
432
447
  }),
433
- reason: Type6.Unknown({
448
+ reason: Type7.Unknown({
434
449
  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"
435
450
  }),
436
- classResults: Type6.Unknown({
451
+ classResults: Type7.Unknown({
437
452
  description: "\u5404\u7C7B class \u7ED3\u7B97\uFF0C\u539F\u6837\u7559\u5B58\u3002\u5B8C\u6210\u9879\u7684 disposition \u4E3A completed\uFF0C\u53EF\u5199 name\u3001searchScope\u3001exceptions\uFF08where\u3001reason\uFF09\u3001commitSha\u3002\u62D2\u7EDD\u9879\u7684 disposition \u4E3A refused\uFF0C\u53EF\u5199 name\u3001remainingScope\u3001blocker\u3002"
438
453
  }),
439
- testEvidence: Type6.Unknown({
454
+ testEvidence: Type7.Unknown({
440
455
  description: "\u6D4B\u8BD5\u8BC1\u636E\u6761\uFF1Bdiff \u542B\u6D4B\u8BD5\u6539\u52A8\u65F6\u63D0\u4EA4\uFF1B\u673A\u5668\u4E0D\u6838\u9A8C\u3002\u53EF\u5199 contract\uFF08\u6D4B\u8BD5\u6539\u52A8\u6240\u8BC1\u660E\u7684\u5951\u7EA6\uFF09\u3001minimumNecessaryCost\uFF08\u6D4B\u8BD5\u6539\u52A8\u7684\u4E00\u884C\u6700\u5C0F\u5FC5\u8981\u6210\u672C\uFF09\u3001measuredDuration\uFF08\u805A\u7126\u9A8C\u8BC1\u5B9E\u6D4B\u65F6\u957F\uFF09\u3002"
441
456
  })
442
457
  });
@@ -447,7 +462,7 @@ var init_fixer_output = __esm({
447
462
  });
448
463
 
449
464
  // src/package-contracts/fixer-packet.ts
450
- import { Type as Type7 } from "typebox";
465
+ import { Type as Type8 } from "typebox";
451
466
  import { Value } from "typebox/value";
452
467
  function causeMessage(cause) {
453
468
  if (cause instanceof Error) return cause.message;
@@ -504,11 +519,11 @@ var init_fixer_packet = __esm({
504
519
  "use strict";
505
520
  init_unknown_value();
506
521
  FIXER_PREREQUISITE_ID_PATTERN = "^[A-Za-z0-9][A-Za-z0-9._-]*$";
507
- fixerPrerequisiteSchema = Type7.Object({
508
- id: Type7.String({ pattern: FIXER_PREREQUISITE_ID_PATTERN }),
509
- requirement: Type7.String({ pattern: "\\S" })
522
+ fixerPrerequisiteSchema = Type8.Object({
523
+ id: Type8.String({ pattern: FIXER_PREREQUISITE_ID_PATTERN }),
524
+ requirement: Type8.String({ pattern: "\\S" })
510
525
  });
511
- fixerPrerequisitesSchema = Type7.Array(fixerPrerequisiteSchema);
526
+ fixerPrerequisitesSchema = Type8.Array(fixerPrerequisiteSchema);
512
527
  FixerPacketValidationError = class extends Error {
513
528
  code = "AK_INVALID_FIX_PACKET";
514
529
  constructor(cause) {
@@ -524,20 +539,34 @@ var init_fixer_packet = __esm({
524
539
  });
525
540
 
526
541
  // src/package-contracts/worker-output.ts
542
+ import { Type as Type9 } from "typebox";
527
543
  function validateAcceptedCoderDetails(output) {
528
544
  return output;
529
545
  }
530
546
  function validateAcceptedWorkerDetails(output, roleLabel = "Coder") {
531
547
  return roleLabel === "Fixer" ? validateFixerOutput(output) : validateAcceptedCoderDetails(output);
532
548
  }
533
- var CODER_OUTPUT_TOOL_NAME;
549
+ var CODER_OUTPUT_TOOL_NAME, CODER_STATUS_DESCRIPTION, coderOutputObject, coderOutputSchema;
534
550
  var init_worker_output = __esm({
535
551
  "src/package-contracts/worker-output.ts"() {
536
552
  "use strict";
553
+ init_open_tool_schema();
537
554
  init_fixer_output();
538
555
  init_fixer_packet();
539
- init_fixer_output();
556
+ init_terminating_infrastructure();
540
557
  CODER_OUTPUT_TOOL_NAME = "ak_coder_output";
558
+ CODER_STATUS_DESCRIPTION = `planned | completed | refused | partially_completed | unfinished\u3002unfinished\uFF1A\u7F3A\u524D\u7F6E\u6216\u8FDD\u5BAA\u7EA6\u675F\u81F4\u672C\u5C40\u672A\u5B8C\u6210\u3002${PARTIALLY_COMPLETED_DEFINITION}`;
559
+ coderOutputObject = Type9.Object({
560
+ status: Type9.Unknown({ description: CODER_STATUS_DESCRIPTION }),
561
+ report: Type9.Unknown({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" }),
562
+ remainingScope: Type9.Unknown({ description: "\u672C\u5C40\u540E\u5269\u4F59\u5DE5\u4F5C" }),
563
+ reason: Type9.Unknown({
564
+ 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"
565
+ })
566
+ });
567
+ coderOutputSchema = withTerminatingOutputDeclarations(
568
+ openToolObject(coderOutputObject)
569
+ );
541
570
  }
542
571
  });
543
572
 
@@ -549,7 +578,7 @@ var init_canonical_json = __esm({
549
578
  });
550
579
 
551
580
  // src/doctor-contracts.ts
552
- import { Type as Type8 } from "typebox";
581
+ import { Type as Type10 } from "typebox";
553
582
  function validateDoctorSubmissionShape(value) {
554
583
  return value;
555
584
  }
@@ -575,25 +604,25 @@ var init_doctor_contracts = __esm({
575
604
  biteNone = "noRealBite";
576
605
  DOCTOR_BITE_KINDS = [biteActual, biteNone];
577
606
  DOCTOR_STATUS_DESCRIPTION = "completed | refused\u3002completed \u5141\u8BB8\u7A7A findings\uFF1Brefused \u4EC5\u5F53\u8BC1\u636E\u4E0D\u8DB3\u4EE5\u652F\u6491\u5982\u5B9E\u6848\u8BC1\u8BCD";
578
- doctorSubmissionObject = Type8.Object({
579
- status: Type8.Unknown({ description: DOCTOR_STATUS_DESCRIPTION }),
580
- case: Type8.Unknown({
607
+ doctorSubmissionObject = Type10.Object({
608
+ status: Type10.Unknown({ description: DOCTOR_STATUS_DESCRIPTION }),
609
+ case: Type10.Unknown({
581
610
  description: "\u7559\u5B58\u592A\u533B\u7F72\u6848\u8EAB\u4EFD\uFF0C\u539F\u6837\u7559\u5B58\uFF08\u5982 issueNumber\u3001runsPath\uFF09\u3002\u673A\u68B0\u5C42\u53E6\u6309\u7ED1\u5B9A run \u6295\u5F71\u6848\u8EAB\u4EFD\uFF0C\u4E0D\u5728\u672C\u5B57\u6BB5\u91CD\u5224\u3002"
582
611
  }),
583
- findings: Type8.Unknown({
612
+ findings: Type10.Unknown({
584
613
  description: `\u9010\u6761\u8D44\u4EA7\u89C2\u5BDF\u4E0E\u5904\u65B9\uFF0C\u539F\u6837\u7559\u5B58\u3002\u4E00\u6761\u53EF\u542B targetKey\u3001targetKind\uFF08${DOCTOR_TARGET_KINDS.join(" | ")}\uFF09\u3001observation\u3001evidenceIds\u3001disposition\uFF08${DOCTOR_DISPOSITIONS.join(" | ")}\uFF09\u3001assetEvidence\uFF08targetKey\u3001targetKind\u3001evidenceId\uFF09\u3001guardrails\uFF08reproducibleFailure\u3001owningSeamOrInvariant\u3001deletionOrSimplificationSuffices\uFF0C\u5404\u9879\u53EF\u542B answer\u3001evidenceIds\u3001explanation\uFF09\u3001prescription\uFF08kind \u4E3A ${DOCTOR_PRESCRIPTION_KINDS.join(" | ")}\uFF0C\u53E6\u53EF\u5199 recommendation\u3001necessityExplanation\uFF09\u3001lastRealBite\uFF08kind \u4E3A ${DOCTOR_BITE_KINDS.join(" | ")}\uFF0C\u53E6\u53EF\u5199 targetKey\u3001evidenceId\u3001eligibleEvidenceIds\uFF09\u3002\u4E0D\u8981\u6C42\u4EFB\u4F55\u5904\u65B9\u6216\u53EF\u590D\u7528 finding\uFF1B\u7F3A\u53EF\u590D\u7528\u8D44\u4EA7\u6216 bounded-bite \u8BC1\u636E\u53EA\u6392\u9664\u5BF9\u5E94\u8D44\u4EA7\u5904\u65B9\u3002\u673A\u5668\u4E0D\u6838\u9A8C\u3002`
585
614
  }),
586
- reason: Type8.Unknown({
615
+ reason: Type10.Unknown({
587
616
  description: "\u8BC1\u636E\u4E0D\u8DB3\u4EE5\u652F\u6491\u5982\u5B9E\u8BC1\u8BCD\u7684\u539F\u56E0\uFF1B\u4EC5 refused \u65F6\u7528\u3002"
588
617
  }),
589
- missingEvidence: Type8.Unknown({
618
+ missingEvidence: Type10.Unknown({
590
619
  description: "\u5982\u5B9E\u8BC1\u8BCD\u6240\u9700\u800C\u5C1A\u7F3A\u7684\u8BC1\u636E\uFF0C\u539F\u6837\u7559\u5B58\uFF08\u5982\u6BCF\u9879 need\u3001targetKeys\uFF09\u3002"
591
620
  })
592
621
  });
593
622
  doctorSubmissionSchema = withTerminatingOutputDeclarations(
594
623
  openToolObject(doctorSubmissionObject)
595
624
  );
596
- 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 });
625
+ doctorEvidenceReadSchema = Type10.Object({ evidenceId: Type10.String({ minLength: 1, description: "\u5F85\u8BFB\u7559\u5B58\u8BC1\u636E\u6807\u8BC6" }), offset: Type10.Optional(Type10.Integer({ minimum: 0, description: "\u8D77\u59CB\u5B57\u8282\u504F\u79FB\uFF08\u4ECE 0 \u8BA1\uFF09" })), limit: Type10.Optional(Type10.Integer({ minimum: 1, description: "\u8FD4\u56DE\u5B57\u8282\u6570\uFF08\u65E0\u4E0A\u9650\uFF09" })) }, { additionalProperties: true });
597
626
  DoctorEvidenceStore = class {
598
627
  constructor(patient) {
599
628
  this.patient = patient;
@@ -662,7 +691,7 @@ var init_exact_utf8 = __esm({
662
691
  });
663
692
 
664
693
  // src/merger-contracts.ts
665
- import { Type as Type9 } from "typebox";
694
+ import { Type as Type11 } from "typebox";
666
695
  function fail2(message = "Merger input violates its exact contract") {
667
696
  throw new MergerInputContractError(message);
668
697
  }
@@ -693,24 +722,24 @@ var init_merger_contracts = __esm({
693
722
  init_open_tool_schema();
694
723
  init_terminating_infrastructure();
695
724
  init_unknown_value();
696
- materialSchema = Type9.Object({ bytesBase64: Type9.String(), sha256: Type9.String() });
697
- checkSchema = Type9.Object({ name: Type9.String({ minLength: 1 }), argv: Type9.Array(Type9.String({ minLength: 1 }), { minItems: 1 }) });
698
- mergerInputSchema = Type9.Object({
699
- attemptId: Type9.String({ minLength: 1, description: "\u5BF9\u8D26 attempt \u8EAB\u4EFD\uFF08transport\uFF09" }),
700
- targetObjectId: Type9.String({ description: "\u6750\u6599\uFF1Atarget parent OID\uFF1B\u53EF\u7A7A" }),
701
- sourceObjectId: Type9.String({ description: "\u6750\u6599\uFF1Asource parent OID\uFF1B\u53EF\u7A7A" }),
702
- materials: Type9.Object({ task: materialSchema, authority: materialSchema, targetIntent: materialSchema, sourceIntent: materialSchema }),
703
- expectedConflictPaths: Type9.Array(Type9.String(), { description: "\u6750\u6599\uFF1A\u5F53\u524D\u672A\u5408\u5E76\u8DEF\u5F84\uFF1B\u53EF\u7A7A" }),
704
- resolutionScope: Type9.Array(Type9.String(), { description: "\u6750\u6599\uFF1A\u89E3\u6790\u8303\u56F4\u63D0\u793A\uFF1B\u53EF\u7A7A" }),
705
- authorizedChecks: Type9.Array(checkSchema)
725
+ materialSchema = Type11.Object({ bytesBase64: Type11.String(), sha256: Type11.String() });
726
+ checkSchema = Type11.Object({ name: Type11.String({ minLength: 1 }), argv: Type11.Array(Type11.String({ minLength: 1 }), { minItems: 1 }) });
727
+ mergerInputSchema = Type11.Object({
728
+ attemptId: Type11.String({ minLength: 1, description: "\u5BF9\u8D26 attempt \u8EAB\u4EFD\uFF08transport\uFF09" }),
729
+ targetObjectId: Type11.String({ description: "\u6750\u6599\uFF1Atarget parent OID\uFF1B\u53EF\u7A7A" }),
730
+ sourceObjectId: Type11.String({ description: "\u6750\u6599\uFF1Asource parent OID\uFF1B\u53EF\u7A7A" }),
731
+ materials: Type11.Object({ task: materialSchema, authority: materialSchema, targetIntent: materialSchema, sourceIntent: materialSchema }),
732
+ expectedConflictPaths: Type11.Array(Type11.String(), { description: "\u6750\u6599\uFF1A\u5F53\u524D\u672A\u5408\u5E76\u8DEF\u5F84\uFF1B\u53EF\u7A7A" }),
733
+ resolutionScope: Type11.Array(Type11.String(), { description: "\u6750\u6599\uFF1A\u89E3\u6790\u8303\u56F4\u63D0\u793A\uFF1B\u53EF\u7A7A" }),
734
+ authorizedChecks: Type11.Array(checkSchema)
706
735
  });
707
736
  MERGER_STATUS_DESCRIPTION = "completed | escalate";
708
- mergerOutputObject = Type9.Object({
709
- status: Type9.Unknown({ description: MERGER_STATUS_DESCRIPTION }),
710
- attemptId: Type9.Unknown({ description: "\u5DF2\u53D7\u7406\u5408\u5E76 attempt \u8EAB\u4EFD" }),
711
- report: Type9.Unknown({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" }),
712
- mergeCommitId: Type9.Unknown({ description: "\u5B8C\u6210\u5408\u5E76 commit object ID" }),
713
- diagnosis: Type9.Unknown({
737
+ mergerOutputObject = Type11.Object({
738
+ status: Type11.Unknown({ description: MERGER_STATUS_DESCRIPTION }),
739
+ attemptId: Type11.Unknown({ description: "\u5DF2\u53D7\u7406\u5408\u5E76 attempt \u8EAB\u4EFD" }),
740
+ report: Type11.Unknown({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" }),
741
+ mergeCommitId: Type11.Unknown({ description: "\u5B8C\u6210\u5408\u5E76 commit object ID" }),
742
+ diagnosis: Type11.Unknown({
714
743
  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"
715
744
  })
716
745
  });
@@ -729,7 +758,7 @@ var init_merger_contracts = __esm({
729
758
  });
730
759
 
731
760
  // src/notary-contracts.ts
732
- var NOTARY_OUTPUT_TOOL_NAME, NOTARY_SOURCE_RUN_FLAG, NOTARY_TICKET_FLAG, notaryOutputSchema;
761
+ var NOTARY_OUTPUT_TOOL_NAME, NOTARY_SOURCE_RUN_FLAG, NOTARY_TICKET_FLAG;
733
762
  var init_notary_contracts = __esm({
734
763
  "src/notary-contracts.ts"() {
735
764
  "use strict";
@@ -750,7 +779,6 @@ var init_notary_contracts = __esm({
750
779
  type: "string"
751
780
  }
752
781
  };
753
- notaryOutputSchema = reviewSubmissionSchema;
754
782
  }
755
783
  });
756
784
 
@@ -766,12 +794,27 @@ var init_countersign_contracts = __esm({
766
794
  });
767
795
 
768
796
  // src/gleaner-left-contracts.ts
769
- var GLEANER_LEFT_OUTPUT_TOOL_NAME, GLEANER_LEFT_BASE_FLAG;
797
+ import { Type as Type12 } from "typebox";
798
+ var GLEANER_LEFT_OUTPUT_TOOL_NAME, gleanerLeftOutputSchema, GLEANER_LEFT_BASE_FLAG;
770
799
  var init_gleaner_left_contracts = __esm({
771
800
  "src/gleaner-left-contracts.ts"() {
772
801
  "use strict";
802
+ init_open_tool_schema();
803
+ init_terminating_infrastructure();
773
804
  init_unknown_value();
774
805
  GLEANER_LEFT_OUTPUT_TOOL_NAME = "ak_gleaner_left_output";
806
+ gleanerLeftOutputSchema = withTerminatingOutputDeclarations(
807
+ openToolObject(
808
+ Type12.Object({
809
+ status: Type12.Unknown({
810
+ description: "completed"
811
+ }),
812
+ findings: Type12.Unknown({
813
+ description: "\u5F39\u7AE0\u5217\u8868\uFF1B\u6BCF\u6761\u53EF\u542B pointer\uFF08\u6587\u4EF6/\u884C\u6307\u9488\uFF09\u4E0E statement\uFF08\u7591\u70B9\u9648\u8FF0\uFF09\uFF0C\u539F\u6837\u7559\u5B58\u3002\u7A7A\u5217\u8868\u5408\u6CD5\u5B8C\u5C40\uFF1B\u673A\u5668\u4E0D\u5224\u5F39\u7AE0\u662F\u5426\u6210\u7ACB\u3002"
814
+ })
815
+ })
816
+ )
817
+ );
775
818
  GLEANER_LEFT_BASE_FLAG = {
776
819
  name: "ak-gleaner-left-base",
777
820
  definition: {
@@ -801,14 +844,13 @@ var init_inspector_contracts = __esm({
801
844
  });
802
845
 
803
846
  // src/package-contracts/auditor-output.ts
804
- var AUDITOR_OUTPUT_TOOL_NAME, auditorOutputSchema;
847
+ var AUDITOR_OUTPUT_TOOL_NAME;
805
848
  var init_auditor_output = __esm({
806
849
  "src/package-contracts/auditor-output.ts"() {
807
850
  "use strict";
808
851
  init_review_submission();
809
852
  init_unknown_value();
810
853
  AUDITOR_OUTPUT_TOOL_NAME = REVIEW_SUBMISSION_OUTPUT_TOOL_NAME;
811
- auditorOutputSchema = reviewSubmissionSchema;
812
854
  }
813
855
  });
814
856
 
@@ -935,6 +977,7 @@ var init_run_ticket_number = __esm({
935
977
  });
936
978
 
937
979
  // src/diarist-contracts.ts
980
+ import { Type as Type13 } from "typebox";
938
981
  function projectDiaristSessions(value) {
939
982
  const raw = value?.sessions;
940
983
  if (raw === void 0) return [];
@@ -954,23 +997,68 @@ function projectDiaristTicketSessions(value) {
954
997
  }
955
998
  return Array.from(perTicket, ([ticketNumber, sessions]) => ({ ticketNumber, sessions }));
956
999
  }
957
- var DIARIST_OUTPUT_TOOL_NAME;
1000
+ var DIARIST_OUTPUT_TOOL_NAME, DIARIST_SESSIONS_DESCRIPTION, diaristOutputSchema;
958
1001
  var init_diarist_contracts = __esm({
959
1002
  "src/diarist-contracts.ts"() {
960
1003
  "use strict";
1004
+ init_open_tool_schema();
1005
+ init_terminating_infrastructure();
961
1006
  init_ticket_provenance_contracts();
962
1007
  init_run_ticket_number();
963
1008
  init_unknown_value();
964
1009
  DIARIST_OUTPUT_TOOL_NAME = "ak_diarist_output";
1010
+ DIARIST_SESSIONS_DESCRIPTION = "\u5BF9\u8BDD\u8FB9\u754C\u3002\u6BCF\u5377\u542B path\uFF08\u4F1A\u8BDD\u5377\u7EDD\u5BF9\u6216\u53EF\u8BFB\u8DEF\u5F84\uFF09\u4E0E ranges\uFF08\u672C\u5377\u672C\u8F6E\u5404\u533A\u95F4\uFF09\u3002\u6BCF\u6BB5\u533A\u95F4\u542B from / to\uFF1B\u8D77\u70B9\u4E0E\u7EC8\u70B9\u5404\u5199 id\uFF08\u539F\u751F id\uFF09\u6216 line\uFF08\u672C\u8F6E\u884C\u53F7\uFF09\uFF0C\u4E8C\u9009\u4E00\u3002\u7A7A\u5217\u8868\uFF1D\u672C\u8F6E\u65E0\u5BF9\u8BDD\u53EF\u5212\u3002\u7AEF\u70B9\u65E0\u6CD5\u6307\u540D\u65F6\u8D70 reask\uFF0C\u4E0D\u4E2D\u6B62\u3002";
1011
+ diaristOutputSchema = withTerminatingOutputDeclarations(
1012
+ openToolObject(
1013
+ Type13.Object({
1014
+ status: Type13.Unknown({
1015
+ description: "completed | escalate"
1016
+ }),
1017
+ ticketNumber: Type13.Optional(
1018
+ Type13.Unknown({
1019
+ description: "\u672C\u5EAD\u5BF9\u8C61\u7968\u53F7\uFF08\u6B63\u6574\u6570\uFF09\u6216 null/\u7701\u7565\uFF1D\u771F\u65E0\u7968\uFF1B\u4E0B\u6E38\u8D70 typed \u952E\uFF1B\u8BA4\u4E0D\u51FA\u7528 status=escalate\uFF0C\u4E0D\u6D17\u6210\u65E0\u5F55\u3002\u673A\u68B0\u5C42\u4E0D\u91CD\u5224\u3002"
1020
+ })
1021
+ ),
1022
+ reason: Type13.Unknown({
1023
+ description: "status \u4E3A escalate \u65F6\uFF1A\u8BA4\u4E0D\u51FA\u672C\u5EAD\u5BF9\u8C61\u7684\u539F\u56E0"
1024
+ }),
1025
+ sessions: Type13.Optional(Type13.Unknown({ description: DIARIST_SESSIONS_DESCRIPTION })),
1026
+ ticketSessions: Type13.Unknown({
1027
+ description: `\u591A\u7968\u5EAD\u9010\u7968\u5BF9\u8BDD\u8FB9\u754C\uFF1B\u6BCF\u7968\u542B ticketNumber\uFF08\u672C\u6761\u8FB9\u754C\u6240\u5F52\u7968\u53F7\uFF0C\u6B63\u6574\u6570\uFF09\u4E0E sessions\uFF08${DIARIST_SESSIONS_DESCRIPTION}\uFF09\u3002\u4E00\u6B21\u4EA4\u5377\u5404\u7968\u5404\u81EA\u5206\u5F55\u3002\u4E0E\u5355\u7968 sessions \u4E8C\u9009\u4E00\u3002`
1028
+ })
1029
+ })
1030
+ )
1031
+ );
965
1032
  }
966
1033
  });
967
1034
 
968
1035
  // src/secretariat-contracts.ts
969
- var SECRETARIAT_OUTPUT_TOOL_NAME, SECRETARIAT_GATE_OFFICER_ENTRY_TYPE, SECRETARIAT_COUNTERSIGN_TERMINAL_FACT_KEY;
1036
+ import { Type as Type14 } from "typebox";
1037
+ var SECRETARIAT_OUTPUT_TOOL_NAME, secretariatVerdictSchema, SECRETARIAT_GATE_OFFICER_ENTRY_TYPE, SECRETARIAT_COUNTERSIGN_TERMINAL_FACT_KEY;
970
1038
  var init_secretariat_contracts = __esm({
971
1039
  "src/secretariat-contracts.ts"() {
972
1040
  "use strict";
1041
+ init_terminating_infrastructure();
973
1042
  SECRETARIAT_OUTPUT_TOOL_NAME = "ak_secretariat_output";
1043
+ secretariatVerdictSchema = withTerminatingOutputDeclarations(
1044
+ Type14.Object(
1045
+ {
1046
+ secretariatStatus: Type14.Unknown({
1047
+ description: "converged | escalate"
1048
+ }),
1049
+ ticketNumber: Type14.Optional(
1050
+ Type14.Unknown({ description: "\u672C\u7968\u53F7\uFF1B\u7F72\u65F6\u6307\u5411\u6700\u7EC8\u6B63\u6587\u6240\u5728\u7968" })
1051
+ ),
1052
+ note: Type14.Unknown({ description: "\u9644\u6CE8" }),
1053
+ evidence: Type14.Optional(Type14.Unknown({ description: "\u7559\u5B58\u8BC1\u636E" })),
1054
+ decisionGate: Type14.Unknown({
1055
+ description: "\u9700\u965B\u4E0B\u5904\u7F6E\u7684\u95EE\u9898\u4E0E\u9009\u9879\uFF1B\u53EF\u5199 question \u4E0E options\uFF0C\u539F\u6837\u7559\u5B58\u3002"
1056
+ })
1057
+ },
1058
+ { additionalProperties: true }
1059
+ )
1060
+ );
1061
+ secretariatVerdictSchema.required = [];
974
1062
  SECRETARIAT_GATE_OFFICER_ENTRY_TYPE = "ak-secretariat-gate-officer";
975
1063
  SECRETARIAT_COUNTERSIGN_TERMINAL_FACT_KEY = "countersignTerminal";
976
1064
  }
@@ -1740,6 +1828,9 @@ ${serializeReceipt(result.submission)}`;
1740
1828
  }
1741
1829
  return `\u95E8\u4E0B\u7701 ${result.status}\uFF08${result.stage}\uFF09\uFF1A${result.reason}`;
1742
1830
  }
1831
+ function isOneShotWorkerReminderCode(code) {
1832
+ return code === "worker_commit_reminder" || code === "worker_prefix_reminder";
1833
+ }
1743
1834
  function unreadableDiscriminatorNotice(field, received) {
1744
1835
  if (received === void 0) return `\u8BFB\u4E0D\u51FA ${field}`;
1745
1836
  return `\u8BFB\u4E0D\u51FA ${field}\uFF1A${readableGateItem(received)}`;
@@ -1780,7 +1871,7 @@ var init_submission_errors = __esm({
1780
1871
  WorkerUnfinishedReasonReminderError = class extends Error {
1781
1872
  code = "worker_unfinished_reason_reminder";
1782
1873
  constructor() {
1783
- super("\u672C\u6B21 unfinished \u56DE\u6267\u672A\u542B reason\uFF1B\u672C\u63A5\u7F1D\u7F3A\u7531\u81F3\u591A\u6253\u56DE\u4E24\u6B21\u3002");
1874
+ super("\u672C\u6B21 unfinished \u56DE\u6267\u672A\u542B reason\uFF1B\u8BF7\u8865\u4E0A reason \u540E\u518D\u4EA4\u3002");
1784
1875
  this.name = "WorkerUnfinishedReasonReminderError";
1785
1876
  }
1786
1877
  };
@@ -2438,6 +2529,23 @@ function markerMatchesExpectedIdentity(marker, expected) {
2438
2529
  }
2439
2530
  return true;
2440
2531
  }
2532
+ function packagedRoleOutputRejectionReason(message) {
2533
+ if (typeof message.toolName !== "string") return void 0;
2534
+ if (!PACKAGED_ROLE_OUTPUT_TOOLS.has(message.toolName) && message.toolName !== "ak_submission_output") {
2535
+ return void 0;
2536
+ }
2537
+ if (message.isError !== true) return void 0;
2538
+ if (classifyPackagedRoleTerminalResult(message).kind !== "nonterminal") return void 0;
2539
+ const content = message.content;
2540
+ if (typeof content === "string") return content.trim();
2541
+ if (!Array.isArray(content)) return "";
2542
+ return content.map((part) => {
2543
+ if (isRecord(part) && part.type === "text" && typeof part.text === "string") {
2544
+ return part.text;
2545
+ }
2546
+ return "";
2547
+ }).join("").trim();
2548
+ }
2441
2549
  function classifyPackagedRoleTerminalResult(message) {
2442
2550
  if (typeof message.toolName !== "string") return { kind: "nonterminal" };
2443
2551
  if (!PACKAGED_ROLE_OUTPUT_TOOLS.has(message.toolName) && message.toolName !== "ak_submission_output") return { kind: "nonterminal" };
@@ -3879,7 +3987,7 @@ __export(auditor_dossier_tool_exports, {
3879
3987
  createAuditorDossierTool: () => createAuditorDossierTool
3880
3988
  });
3881
3989
  import { dirname as dirname8, join as join12, resolve as resolve6 } from "node:path";
3882
- import { Type as Type11 } from "typebox";
3990
+ import { Type as Type16 } from "typebox";
3883
3991
  function auditorRunDirectory(context) {
3884
3992
  const sessionFile = context.sessionManager?.getSessionFile?.();
3885
3993
  if (sessionFile === void 0) return void 0;
@@ -3891,7 +3999,7 @@ function createAuditorDossierTool(runDirectory) {
3891
3999
  description: "\u5B9A\u4F4D\u672C\u5BA1\u8BA1\u5E2D\u7ED1\u5B9A\u7684 run \u5377\u5B97\u53CA\u5176\u8BC1\u636E\u5165\u53E3\u3002",
3892
4000
  // #836 r16 class 3: execute() ignores `_params` entirely — a closed root
3893
4001
  // only rejects the role for saying more.
3894
- parameters: Type11.Object({}, { additionalProperties: true }),
4002
+ parameters: Type16.Object({}, { additionalProperties: true }),
3895
4003
  async execute(_id, _params) {
3896
4004
  if (runDirectory === void 0) {
3897
4005
  return {
@@ -3922,6 +4030,161 @@ var init_auditor_dossier_tool = __esm({
3922
4030
  }
3923
4031
  });
3924
4032
 
4033
+ // src/collector-tool-schemas.ts
4034
+ import { Type as Type17 } from "typebox";
4035
+ var collectorOutputBaseSchema, collectorOutputArgsSchema;
4036
+ var init_collector_tool_schemas = __esm({
4037
+ "src/collector-tool-schemas.ts"() {
4038
+ "use strict";
4039
+ init_open_tool_schema();
4040
+ init_terminating_infrastructure();
4041
+ collectorOutputBaseSchema = openToolObject(
4042
+ Type17.Object({
4043
+ groups: Type17.Unsafe({
4044
+ description: "\u6309\u673A\u5668\u8EAB\u4EFD\u5F52\u7EC4\u7684\u51FA\u5E2D\u3001\u6750\u6599\u4E0E\u9010\u6761 findings\uFF08LLM \u81EA\u884C\u4ECE\u5BBF\u4E3B CLI \u53D6\u8BC1\u6574\u7406\uFF1B\u4EE3\u7801\u4E0D\u4EE3\u6536\u4E0D\u5F52\u5E76\uFF09\u3002"
4045
+ }),
4046
+ unfinishedReasons: Type17.Unknown({
4047
+ description: "\u672A\u5B8C\u6210\u539F\u56E0\uFF1B\u53D6\u8BC1\u53D7\u9650\u65F6\u5982\u5B9E\u62A5\u544A\u3002"
4048
+ })
4049
+ })
4050
+ );
4051
+ collectorOutputArgsSchema = withTerminatingOutputDeclarations(
4052
+ collectorOutputBaseSchema
4053
+ );
4054
+ }
4055
+ });
4056
+
4057
+ // src/role-submission-declarations.ts
4058
+ function roleSubmissionDeclaration(role) {
4059
+ const name = packagedRoleOutputTool(role);
4060
+ if (name === void 0) throw new Error(`${role} output tool is not declared`);
4061
+ const face = SUBMISSION_FACE[role];
4062
+ return {
4063
+ role,
4064
+ name,
4065
+ label: face.label,
4066
+ description: face.description,
4067
+ ..."promptSnippet" in face ? { promptSnippet: face.promptSnippet } : {},
4068
+ parameters: face.parameters
4069
+ };
4070
+ }
4071
+ var SUBMISSION_FACE;
4072
+ var init_role_submission_declarations = __esm({
4073
+ "src/role-submission-declarations.ts"() {
4074
+ "use strict";
4075
+ init_packaged_role_registry();
4076
+ init_review_submission();
4077
+ init_collector_tool_schemas();
4078
+ init_diarist_contracts();
4079
+ init_doctor_contracts();
4080
+ init_fixer_output();
4081
+ init_gatekeeper_output();
4082
+ init_gleaner_left_contracts();
4083
+ init_merger_contracts();
4084
+ init_navigator_output();
4085
+ init_reviewer_output();
4086
+ init_secretariat_contracts();
4087
+ init_worker_output();
4088
+ SUBMISSION_FACE = {
4089
+ judge: {
4090
+ label: "\u5927\u7406\u5BFA\u8F93\u51FA",
4091
+ description: "\u63D0\u4EA4\u5927\u7406\u5BFA\u7EC8\u5C40\u5224\u8BCD\uFF1B\u4EA4\u5377\u8C03\u7528\u7ED3\u675F\u540E\uFF0C\u7531\u516C\u5F00\u8C03\u7528\u63A5\u7F1D\u6309\u5224\u8BCD\u72B6\u6001\u6267\u884C\u9002\u7528\u5BA1\u6838\u3002",
4092
+ promptSnippet: "\u63D0\u4EA4\u5927\u7406\u5BFA\u7EC8\u5C40\u5224\u8BCD",
4093
+ parameters: reviewSubmissionSchema
4094
+ },
4095
+ fixer: {
4096
+ label: "\u4FEE\u5185\u53F8\u8F93\u51FA",
4097
+ description: "\u63D0\u4EA4\u4FEE\u5185\u53F8\u7EC8\u5C40\u56DE\u6267\u3002",
4098
+ promptSnippet: "\u63D0\u4EA4\u4FEE\u5185\u53F8\u7EC8\u5C40\u56DE\u6267",
4099
+ parameters: fixerOutputSchema
4100
+ },
4101
+ coder: {
4102
+ label: "\u5C06\u4F5C\u76D1\u8F93\u51FA",
4103
+ description: "\u63D0\u4EA4\u5C06\u4F5C\u76D1\u7EC8\u5C40\u56DE\u6267\u3002",
4104
+ promptSnippet: "\u63D0\u4EA4\u5C06\u4F5C\u76D1\u7EC8\u5C40\u56DE\u6267",
4105
+ parameters: coderOutputSchema
4106
+ },
4107
+ reviewer: {
4108
+ label: "\u5FA1\u53F2\u53F0\u8F93\u51FA",
4109
+ description: "\u63D0\u4EA4\u5FA1\u53F2\u53F0\u7EC8\u5C40\u56DE\u6267\u3002",
4110
+ promptSnippet: "\u63D0\u4EA4\u5FA1\u53F2\u53F0\u7EC8\u5C40\u56DE\u6267",
4111
+ parameters: reviewerOutputSchema
4112
+ },
4113
+ collector: {
4114
+ label: "\u901A\u8FDB\u53F8\u8F93\u51FA",
4115
+ description: "\u63D0\u4EA4\u901A\u8FDB\u53F8\u56DE\u6267\u3002",
4116
+ promptSnippet: "\u63D0\u4EA4\u901A\u8FDB\u53F8\u56DE\u6267",
4117
+ parameters: collectorOutputArgsSchema
4118
+ },
4119
+ doctor: {
4120
+ label: "\u592A\u533B\u7F72\u8F93\u51FA",
4121
+ description: DOCTOR_OUTPUT_TOOL_DESCRIPTION,
4122
+ parameters: doctorSubmissionSchema
4123
+ },
4124
+ merger: {
4125
+ label: "\u5408\u5E76\u8F93\u51FA",
4126
+ description: "\u63D0\u4EA4\u5408\u5E76\u7ED3\u679C\uFF1B\u8F93\u51FA\u5206\u652F\u4E3A completed \u4E0E escalate\u3002",
4127
+ promptSnippet: "\u63D0\u4EA4\u5408\u5E76\u7ED3\u679C",
4128
+ parameters: mergerOutputSchema
4129
+ },
4130
+ notary: {
4131
+ label: "\u7B26\u5B9D\u90CE\u8F93\u51FA",
4132
+ description: "\u63D0\u4EA4\u5F15\u6587\u4FDD\u771F\u4E0E\u7968\u9762\u5BF9\u9F50\u7684 converged/continue/escalate \u51B3\u8BAE\u3002",
4133
+ promptSnippet: "\u63D0\u4EA4\u7B26\u5B9D\u90CE\u51B3\u8BAE",
4134
+ parameters: reviewSubmissionSchema
4135
+ },
4136
+ countersign: {
4137
+ label: "\u7ED9\u4E8B\u4E2D\u8F93\u51FA",
4138
+ description: "\u7ED9\u4E8B\u4E2D\u51B3\u8BAE\u3002",
4139
+ promptSnippet: "\u7ED9\u4E8B\u4E2D\u51B3\u8BAE",
4140
+ parameters: reviewSubmissionSchema
4141
+ },
4142
+ secretariat: {
4143
+ label: "\u4E2D\u4E66\u7701\u8F93\u51FA",
4144
+ description: "\u4E2D\u4E66\u7701\u7EC8\u5C40\u56DE\u6267\u3002",
4145
+ promptSnippet: "\u4E2D\u4E66\u7701\u7EC8\u5C40\u56DE\u6267",
4146
+ parameters: secretariatVerdictSchema
4147
+ },
4148
+ "gleaner-left": {
4149
+ label: "\u5DE6\u62FE\u9057\u8F93\u51FA",
4150
+ description: "\u5DE6\u62FE\u9057\u5F39\u7AE0\u3002",
4151
+ promptSnippet: "\u5DE6\u62FE\u9057\u5F39\u7AE0",
4152
+ parameters: gleanerLeftOutputSchema
4153
+ },
4154
+ inspector: {
4155
+ label: "\u53F0\u9662\u8F93\u51FA",
4156
+ description: "\u53F0\u9662\u7EC8\u5C40\u56DE\u6267\uFF0C\u72B6\u6001\u4E3A converged\u3001continue \u6216 escalate\u3002",
4157
+ promptSnippet: "\u53F0\u9662\u7EC8\u5C40\u56DE\u6267",
4158
+ parameters: reviewSubmissionSchema
4159
+ },
4160
+ gatekeeper: {
4161
+ label: "\u95E8\u4E0B\u7701\u51B3\u8BAE",
4162
+ description: "\u95E8\u4E0B\u7701\u7EC8\u5C40\u51B3\u8BAE\u3002status \u4E3A dispatch \u6216 pass\u3002",
4163
+ promptSnippet: "\u95E8\u4E0B\u7701\u51B3\u8BAE",
4164
+ parameters: gatekeeperOutputSchema
4165
+ },
4166
+ navigator: {
4167
+ label: "\u6E38\u5955\u4F7F\u5EFA\u8BAE",
4168
+ description: "\u6E38\u5955\u4F7F\u7EC8\u5C40\u56DE\u6267\uFF1A\u6563\u6587\u5EFA\u8BAE\uFF0C\u539F\u6837\u5448\u73B0\u3002",
4169
+ promptSnippet: "\u6E38\u5955\u4F7F\u5EFA\u8BAE",
4170
+ parameters: navigatorOutputSchema
4171
+ },
4172
+ auditor: {
4173
+ label: "\u5BA1\u5211\u9662\u8F93\u51FA",
4174
+ description: "\u5BA1\u5211\u9662\u7EC8\u5C40\u56DE\u6267\uFF0Cstatus \u4E3A converged\u3001continue \u6216 escalate\u3002",
4175
+ promptSnippet: "\u5BA1\u5211\u9662\u7EC8\u5C40\u56DE\u6267",
4176
+ parameters: reviewSubmissionSchema
4177
+ },
4178
+ diarist: {
4179
+ label: "\u8D77\u5C45\u90CE\u8F93\u51FA",
4180
+ description: "\u8D77\u5C45\u90CE\u4EA4\u5355\u7968 sessions \u6216\u591A\u7968\u9010\u7968 ticketSessions \u8FB9\u754C\uFF1B\u8BA4\u4E0D\u51FA\u672C\u5EAD\u5BF9\u8C61\u5219 escalate\u3002",
4181
+ promptSnippet: "\u8D77\u5C45\u90CE\u4EA4\u8FB9\u754C",
4182
+ parameters: diaristOutputSchema
4183
+ }
4184
+ };
4185
+ }
4186
+ });
4187
+
3925
4188
  // src/run-terminal-artifacts.ts
3926
4189
  var run_terminal_artifacts_exports = {};
3927
4190
  __export(run_terminal_artifacts_exports, {
@@ -4108,7 +4371,7 @@ function reviewQueueStatus(status) {
4108
4371
  function projectOfficerDecision(officer, decision, fallbackStatus) {
4109
4372
  const receipt = retainedReceipt(decision);
4110
4373
  const record = isRecord(decision) ? decision : void 0;
4111
- const status = (record !== void 0 && typeof record.status === "string" ? record.status : void 0) ?? fallbackStatus;
4374
+ const status = record !== void 0 && Object.hasOwn(record, "status") ? receivedDiscriminator(record, "status") : fallbackStatus;
4112
4375
  const queueStatus = typeof status === "string" ? reviewQueueStatus(status) : void 0;
4113
4376
  if (queueStatus === "converged") {
4114
4377
  return { status: "converged", officer, receipt };
@@ -4261,6 +4524,7 @@ var init_gatekeeper_role = __esm({
4261
4524
  init_inspector_contracts();
4262
4525
  init_review_submission();
4263
4526
  init_gatekeeper_output();
4527
+ init_role_submission_declarations();
4264
4528
  init_run_terminal_artifacts();
4265
4529
  init_unknown_value();
4266
4530
  init_submission_errors();
@@ -4271,13 +4535,7 @@ var init_gatekeeper_role = __esm({
4271
4535
  countersign_verdict: "notary",
4272
4536
  secretariat_verdict: "countersign"
4273
4537
  };
4274
- GATEKEEPER_TOOL_SPEC = {
4275
- name: GATEKEEPER_OUTPUT_TOOL_NAME,
4276
- label: "\u95E8\u4E0B\u7701\u51B3\u8BAE",
4277
- description: "\u95E8\u4E0B\u7701\u7EC8\u5C40\u51B3\u8BAE\u3002status \u4E3A dispatch \u6216 pass\u3002",
4278
- promptSnippet: "\u95E8\u4E0B\u7701\u51B3\u8BAE",
4279
- parameters: gatekeeperOutputSchema
4280
- };
4538
+ GATEKEEPER_TOOL_SPEC = roleSubmissionDeclaration("gatekeeper");
4281
4539
  }
4282
4540
  });
4283
4541
 
@@ -4315,6 +4573,13 @@ function formatTerminalResult(result) {
4315
4573
  `diagnostic ${encodeTerminalField(result.roleOutcome.diagnostic)}`
4316
4574
  );
4317
4575
  }
4576
+ if (result.roleOutcome.kind === "accepted" && result.roleOutcome.decisiveFacts?.directionUnsettled === true) {
4577
+ lines.push("fact directionUnsettled true");
4578
+ const subsequent = result.roleOutcome.decisiveFacts.subsequentAudit;
4579
+ if (typeof subsequent === "string") {
4580
+ lines.push(`fact subsequentAudit ${encodeTerminalField(subsequent)}`);
4581
+ }
4582
+ }
4318
4583
  if (result.roleOutcome.kind === "failure" || result.roleOutcome.kind === "no_receipt" || result.roleOutcome.kind === "audit_escalation" || result.roleOutcome.decisiveFacts?.failedAttempts !== void 0) {
4319
4584
  const facts = result.roleOutcome.kind === "accepted" ? { failedAttempts: result.roleOutcome.decisiveFacts?.failedAttempts } : result.roleOutcome.decisiveFacts ?? {};
4320
4585
  for (const [key, value] of Object.entries(facts)) {
@@ -4373,7 +4638,7 @@ function formatTerminalResult(result) {
4373
4638
  lines.push(`recorded-submission ${encodeTerminalField(rendered)}`);
4374
4639
  }
4375
4640
  } else {
4376
- const payloads = result.roleOutcome.kind === "accepted" || result.roleOutcome.kind === "audit_escalation" ? coalesceSubmissionRows(result.roleOutcome.payloads, result.submissions) : result.submissions ?? [];
4641
+ const payloads = result.roleOutcome.kind === "accepted" || result.roleOutcome.kind === "audit_escalation" ? coalesceSubmissionRows(result.submissions, result.roleOutcome.payloads) : result.submissions ?? [];
4377
4642
  for (let i = payloads.length - 1; i >= 0; i -= 1) {
4378
4643
  const payload = payloads[i];
4379
4644
  const rendered = typeof payload === "string" ? payload : JSON.stringify(payload);
@@ -4389,87 +4654,311 @@ var init_terminal = __esm({
4389
4654
  }
4390
4655
  });
4391
4656
 
4392
- // src/session-assistant-usage.ts
4393
- var session_assistant_usage_exports = {};
4394
- __export(session_assistant_usage_exports, {
4395
- readAssistantUsageFromSessionFile: () => readAssistantUsageFromSessionFile,
4396
- sessionFileFromPublicSummon: () => sessionFileFromPublicSummon,
4397
- usageFromPublicSummon: () => usageFromPublicSummon
4398
- });
4399
- import { join as join14 } from "node:path";
4400
- async function readAssistantUsageFromSessionFile(sessionFile) {
4401
- const { readFile: readFile25 } = await import("node:fs/promises");
4402
- let text;
4403
- try {
4404
- text = await readFile25(sessionFile, "utf8");
4405
- } catch (error) {
4406
- if (error?.code === "ENOENT") return void 0;
4407
- throw error;
4408
- }
4409
- let rows;
4410
- try {
4411
- rows = text.trim().split("\n").filter(Boolean).map((line2) => JSON.parse(line2));
4412
- } catch (error) {
4413
- throw new Error(
4414
- `session usage parse failed (${sessionFile}): ${errorText(error)}`,
4415
- { cause: error }
4416
- );
4657
+ // src/receipt-delivery-policy.ts
4658
+ function receiptAttemptPointer(runPointer, invocationScopeId) {
4659
+ const scope = invocationScopeId?.trim() ?? "";
4660
+ if (scope.length > 0) return `invocation:${scope}`;
4661
+ return `current:${runPointer}`;
4662
+ }
4663
+ function deliveryLimitFromConfig(value) {
4664
+ return parseAutoResumeLimit(value ?? AUTO_RESUME_LIMIT);
4665
+ }
4666
+ function deliveryLimitFromEnv(env) {
4667
+ const raw = env[RECEIPT_DELIVERY_LIMIT_ENV];
4668
+ if (raw === void 0 || raw.trim() === "") return deliveryLimitFromConfig(void 0);
4669
+ const parsed = Number(raw);
4670
+ if (!Number.isInteger(parsed)) return deliveryLimitFromConfig(void 0);
4671
+ return deliveryLimitFromConfig(parsed);
4672
+ }
4673
+ function deliveryTurnsFact(value) {
4674
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
4675
+ throw new TypeError("deliveryTurns must be a non-negative integer");
4417
4676
  }
4418
- let total = 0;
4419
- let input = 0;
4420
- let output = 0;
4421
- let cacheRead = 0;
4422
- let cacheWrite = 0;
4423
- let costInput = 0;
4424
- let costOutput = 0;
4425
- let costCacheRead = 0;
4426
- let costCacheWrite = 0;
4427
- let costTotal = 0;
4428
- let sawCost = false;
4429
- for (const row of rows) {
4430
- if (row.type !== "message" || row.message?.role !== "assistant") continue;
4431
- const usage = row.message.usage;
4432
- if (usage === void 0) continue;
4433
- total += usage.totalTokens ?? 0;
4434
- input += usage.input ?? 0;
4435
- output += usage.output ?? 0;
4436
- cacheRead += usage.cacheRead ?? 0;
4437
- cacheWrite += usage.cacheWrite ?? 0;
4438
- if (usage.cost !== void 0) {
4439
- sawCost = true;
4440
- costInput += usage.cost.input ?? 0;
4441
- costOutput += usage.cost.output ?? 0;
4442
- costCacheRead += usage.cost.cacheRead ?? 0;
4443
- costCacheWrite += usage.cost.cacheWrite ?? 0;
4444
- costTotal += usage.cost.total ?? 0;
4445
- }
4677
+ return value;
4678
+ }
4679
+ function parseNoReceiptLifecycleFacts(input) {
4680
+ if (!isRecord(input) || typeof input.terminalToolCalled !== "boolean" || input.sessionCompletion !== "settled-without-accepted-receipt" || input.acceptedReceipt !== false || typeof input.runPointer !== "string" || input.runPointer.trim() === "" || typeof input.attemptPointer !== "string" || input.attemptPointer.trim() === "" || !Array.isArray(input.rejectedReceipts) || !input.rejectedReceipts.every((item) => isRecord(item) && typeof item.reason === "string")) {
4681
+ throw new TypeError("malformed no-receipt lifecycle facts");
4446
4682
  }
4447
- if (total <= 0 && input <= 0 && output <= 0) return void 0;
4448
- const base = {
4449
- input,
4450
- output,
4451
- cacheRead,
4452
- cacheWrite,
4453
- totalTokens: total > 0 ? total : input + output + cacheRead + cacheWrite
4683
+ return {
4684
+ terminalToolCalled: input.terminalToolCalled,
4685
+ rejectedReceipts: input.rejectedReceipts.map((item) => ({
4686
+ reason: item.reason,
4687
+ diagnosticAvailable: item.reason.trim() !== ""
4688
+ })),
4689
+ deliveryTurns: deliveryTurnsFact(input.deliveryTurns),
4690
+ sessionCompletion: "settled-without-accepted-receipt",
4691
+ runPointer: input.runPointer,
4692
+ attemptPointer: input.attemptPointer,
4693
+ acceptedReceipt: false
4454
4694
  };
4455
- if (!sawCost) return base;
4695
+ }
4696
+ function noReceiptLifecycleFacts(input) {
4456
4697
  return {
4457
- ...base,
4458
- cost: {
4459
- input: costInput,
4460
- output: costOutput,
4461
- cacheRead: costCacheRead,
4462
- cacheWrite: costCacheWrite,
4463
- total: costTotal
4464
- }
4698
+ terminalToolCalled: input.terminalToolCalled,
4699
+ rejectedReceipts: input.rejectedReceipts.map(({ reason }) => ({
4700
+ reason,
4701
+ diagnosticAvailable: reason.trim() !== ""
4702
+ })),
4703
+ deliveryTurns: deliveryTurnsFact(input.deliveryTurns),
4704
+ sessionCompletion: "settled-without-accepted-receipt",
4705
+ runPointer: input.runPointer,
4706
+ attemptPointer: input.attemptPointer,
4707
+ acceptedReceipt: false
4465
4708
  };
4466
4709
  }
4467
- function sessionFileFromPublicSummon(summoned) {
4468
- if (typeof summoned.runDirectory === "string" && summoned.runDirectory.trim() !== "") {
4469
- return join14(summoned.runDirectory, "session", "session.jsonl");
4470
- }
4471
- const fromArtifacts = summoned.terminal?.artifacts?.map((a) => a.path).find((p) => typeof p === "string" && p.endsWith("session.jsonl"));
4472
- if (fromArtifacts !== void 0) return fromArtifacts;
4710
+ function createReceiptDeliveryPolicy(limit) {
4711
+ const deliveryLimit = deliveryLimitFromConfig(limit);
4712
+ let accepted = false;
4713
+ let closed = false;
4714
+ let terminalToolCalled = false;
4715
+ let deliveryTurns = 0;
4716
+ let budgetSpent = 0;
4717
+ const rejectedReceipts = [];
4718
+ const spend = () => {
4719
+ if (budgetSpent < deliveryLimit) budgetSpent += 1;
4720
+ };
4721
+ return {
4722
+ /** The effective ceiling this budget spends (#1132 — never re-read). */
4723
+ limit: deliveryLimit,
4724
+ recordAccepted() {
4725
+ accepted = true;
4726
+ terminalToolCalled = true;
4727
+ },
4728
+ /** Infrastructure owns terminality and must never trigger receipt催交. */
4729
+ stopForInfrastructure() {
4730
+ accepted = true;
4731
+ },
4732
+ /**
4733
+ * Record the rejection this turn already produced.
4734
+ * The fact does not spend a budget. The seam that sends the next prompt
4735
+ * owns that count.
4736
+ */
4737
+ recordRejected(reason) {
4738
+ terminalToolCalled = true;
4739
+ rejectedReceipts.push({ reason, diagnosticAvailable: reason.trim() !== "" });
4740
+ },
4741
+ recordDeliveryRequest() {
4742
+ deliveryTurns += 1;
4743
+ spend();
4744
+ },
4745
+ /**
4746
+ * Stop asking. The issued count stays whatever was actually sent (#1132 —
4747
+ * do not fill the remainder up to the ceiling).
4748
+ */
4749
+ closeBudget() {
4750
+ closed = true;
4751
+ },
4752
+ /**
4753
+ * A nested session settled without an accepted receipt. Close so this layer
4754
+ * does not open another prompt on that session. The issued count stays the
4755
+ * larger of the two seams: a nested zero must not wipe prompts this layer
4756
+ * already sent, and adding the two counts would bill one send twice.
4757
+ */
4758
+ recordNestedNoReceipt(facts) {
4759
+ terminalToolCalled = terminalToolCalled || facts.terminalToolCalled;
4760
+ rejectedReceipts.push(...facts.rejectedReceipts);
4761
+ deliveryTurns = Math.max(deliveryTurns, facts.deliveryTurns);
4762
+ closed = true;
4763
+ },
4764
+ nextAction() {
4765
+ if (accepted) return "accepted";
4766
+ if (closed) return "no-receipt";
4767
+ return budgetSpent < deliveryLimit ? "request-delivery" : "no-receipt";
4768
+ },
4769
+ /** Delivery requests actually issued so far (#1132). */
4770
+ issuedDeliveryRequests() {
4771
+ return deliveryTurns;
4772
+ },
4773
+ /** Current typed delivery facts. No prose. */
4774
+ deliveryState() {
4775
+ return {
4776
+ terminalToolCalled,
4777
+ rejectedReceipts: rejectedReceipts.map((item) => ({ ...item })),
4778
+ deliveryTurns,
4779
+ acceptedReceipt: false
4780
+ };
4781
+ },
4782
+ facts(binding) {
4783
+ return noReceiptLifecycleFacts({ terminalToolCalled, rejectedReceipts: [...rejectedReceipts], deliveryTurns, ...binding });
4784
+ },
4785
+ /**
4786
+ * Continue a public call after the in-memory policy was rebuilt.
4787
+ * Sends already issued spend the same budget; copied rejections keep
4788
+ * the fact and do not spend again.
4789
+ */
4790
+ continueIssued(prior) {
4791
+ for (const receipt of prior.rejectedReceipts) {
4792
+ this.recordRejected(receipt.reason);
4793
+ }
4794
+ if (prior.terminalToolCalled === true) terminalToolCalled = true;
4795
+ for (let index = 0; index < prior.deliveryTurns; index += 1) {
4796
+ this.recordDeliveryRequest();
4797
+ }
4798
+ }
4799
+ };
4800
+ }
4801
+ function entryRecord(entry) {
4802
+ return isRecord(entry) ? entry : void 0;
4803
+ }
4804
+ function customTypeOf(record, message) {
4805
+ return record.customType ?? message?.customType;
4806
+ }
4807
+ function dataOf(record, message) {
4808
+ return record.data ?? message?.details;
4809
+ }
4810
+ function scopeTag(record) {
4811
+ const message = isRecord(record.message) ? record.message : void 0;
4812
+ const customType = customTypeOf(record, message);
4813
+ const data = dataOf(record, message);
4814
+ if ((customType === RECEIPT_DELIVERY_REQUEST_ENTRY || customType === RECEIPT_REJECTION_ENTRY) && isRecord(data) && typeof data.invocationScopeId === "string" && data.invocationScopeId.trim() !== "") {
4815
+ return data.invocationScopeId;
4816
+ }
4817
+ if (customType !== NO_RECEIPT_LIFECYCLE_ENTRY_TYPE) return void 0;
4818
+ try {
4819
+ const facts = parseNoReceiptLifecycleFacts(data);
4820
+ const prefix = "invocation:";
4821
+ if (!facts.attemptPointer.startsWith(prefix)) return void 0;
4822
+ const scope = facts.attemptPointer.slice(prefix.length);
4823
+ return scope.trim() === "" ? void 0 : scope;
4824
+ } catch {
4825
+ return void 0;
4826
+ }
4827
+ }
4828
+ function priorReceiptContinuation(entries, invocationScopeId) {
4829
+ const pointer = receiptAttemptPointer("", invocationScopeId);
4830
+ let entryTurns = 0;
4831
+ let factTurns = 0;
4832
+ let rejectedReceipts = [];
4833
+ let snapshotTerminal = false;
4834
+ for (const entry of entries) {
4835
+ const record = entryRecord(entry);
4836
+ if (record === void 0) continue;
4837
+ const tagged = scopeTag(record);
4838
+ if (tagged !== void 0) {
4839
+ const message = isRecord(record.message) ? record.message : void 0;
4840
+ const customType = customTypeOf(record, message);
4841
+ if (tagged !== invocationScopeId) continue;
4842
+ if (customType === RECEIPT_DELIVERY_REQUEST_ENTRY) entryTurns += 1;
4843
+ if (customType === RECEIPT_REJECTION_ENTRY) {
4844
+ const data = dataOf(record, message);
4845
+ if (isRecord(data) && typeof data.reason === "string") rejectedReceipts.push({ reason: data.reason });
4846
+ }
4847
+ if (customType !== NO_RECEIPT_LIFECYCLE_ENTRY_TYPE) continue;
4848
+ try {
4849
+ const facts = parseNoReceiptLifecycleFacts(dataOf(record, message));
4850
+ if (facts.attemptPointer !== pointer) continue;
4851
+ factTurns = Math.max(factTurns, facts.deliveryTurns);
4852
+ if (facts.rejectedReceipts.length >= rejectedReceipts.length) {
4853
+ rejectedReceipts = facts.rejectedReceipts.map(({ reason }) => ({ reason }));
4854
+ }
4855
+ snapshotTerminal ||= facts.terminalToolCalled;
4856
+ } catch {
4857
+ }
4858
+ continue;
4859
+ }
4860
+ }
4861
+ return {
4862
+ deliveryTurns: Math.max(entryTurns, factTurns),
4863
+ rejectedReceipts,
4864
+ terminalToolCalled: snapshotTerminal || rejectedReceipts.length > 0
4865
+ };
4866
+ }
4867
+ var NO_RECEIPT_LIFECYCLE_ENTRY_TYPE, RECEIPT_DELIVERY_REQUEST_ENTRY, RECEIPT_REJECTION_ENTRY, RECEIPT_DELIVERY_LIMIT_ENV;
4868
+ var init_receipt_delivery_policy = __esm({
4869
+ "src/receipt-delivery-policy.ts"() {
4870
+ "use strict";
4871
+ init_run_lifecycle();
4872
+ init_config();
4873
+ init_unknown_value();
4874
+ NO_RECEIPT_LIFECYCLE_ENTRY_TYPE = "ak-no-receipt-lifecycle";
4875
+ RECEIPT_DELIVERY_REQUEST_ENTRY = "ak-receipt-delivery-request";
4876
+ RECEIPT_REJECTION_ENTRY = "ak-receipt-rejection";
4877
+ RECEIPT_DELIVERY_LIMIT_ENV = "AK_ROLE_RECEIPT_DELIVERY_LIMIT";
4878
+ }
4879
+ });
4880
+
4881
+ // src/session-assistant-usage.ts
4882
+ var session_assistant_usage_exports = {};
4883
+ __export(session_assistant_usage_exports, {
4884
+ readAssistantUsageFromSessionFile: () => readAssistantUsageFromSessionFile,
4885
+ sessionFileFromPublicSummon: () => sessionFileFromPublicSummon,
4886
+ usageFromPublicSummon: () => usageFromPublicSummon
4887
+ });
4888
+ import { join as join14 } from "node:path";
4889
+ async function readAssistantUsageFromSessionFile(sessionFile) {
4890
+ const { readFile: readFile26 } = await import("node:fs/promises");
4891
+ let text;
4892
+ try {
4893
+ text = await readFile26(sessionFile, "utf8");
4894
+ } catch (error) {
4895
+ if (error?.code === "ENOENT") return void 0;
4896
+ throw error;
4897
+ }
4898
+ let rows;
4899
+ try {
4900
+ rows = text.trim().split("\n").filter(Boolean).map((line2) => JSON.parse(line2));
4901
+ } catch (error) {
4902
+ throw new Error(
4903
+ `session usage parse failed (${sessionFile}): ${errorText(error)}`,
4904
+ { cause: error }
4905
+ );
4906
+ }
4907
+ let total = 0;
4908
+ let input = 0;
4909
+ let output = 0;
4910
+ let cacheRead = 0;
4911
+ let cacheWrite = 0;
4912
+ let costInput = 0;
4913
+ let costOutput = 0;
4914
+ let costCacheRead = 0;
4915
+ let costCacheWrite = 0;
4916
+ let costTotal = 0;
4917
+ let sawCost = false;
4918
+ for (const row of rows) {
4919
+ if (row.type !== "message" || row.message?.role !== "assistant") continue;
4920
+ const usage = row.message.usage;
4921
+ if (usage === void 0) continue;
4922
+ total += usage.totalTokens ?? 0;
4923
+ input += usage.input ?? 0;
4924
+ output += usage.output ?? 0;
4925
+ cacheRead += usage.cacheRead ?? 0;
4926
+ cacheWrite += usage.cacheWrite ?? 0;
4927
+ if (usage.cost !== void 0) {
4928
+ sawCost = true;
4929
+ costInput += usage.cost.input ?? 0;
4930
+ costOutput += usage.cost.output ?? 0;
4931
+ costCacheRead += usage.cost.cacheRead ?? 0;
4932
+ costCacheWrite += usage.cost.cacheWrite ?? 0;
4933
+ costTotal += usage.cost.total ?? 0;
4934
+ }
4935
+ }
4936
+ if (total <= 0 && input <= 0 && output <= 0) return void 0;
4937
+ const base = {
4938
+ input,
4939
+ output,
4940
+ cacheRead,
4941
+ cacheWrite,
4942
+ totalTokens: total > 0 ? total : input + output + cacheRead + cacheWrite
4943
+ };
4944
+ if (!sawCost) return base;
4945
+ return {
4946
+ ...base,
4947
+ cost: {
4948
+ input: costInput,
4949
+ output: costOutput,
4950
+ cacheRead: costCacheRead,
4951
+ cacheWrite: costCacheWrite,
4952
+ total: costTotal
4953
+ }
4954
+ };
4955
+ }
4956
+ function sessionFileFromPublicSummon(summoned) {
4957
+ if (typeof summoned.runDirectory === "string" && summoned.runDirectory.trim() !== "") {
4958
+ return join14(summoned.runDirectory, "session", "session.jsonl");
4959
+ }
4960
+ const fromArtifacts = summoned.terminal?.artifacts?.map((a) => a.path).find((p) => typeof p === "string" && p.endsWith("session.jsonl"));
4961
+ if (fromArtifacts !== void 0) return fromArtifacts;
4473
4962
  const outcome = summoned.terminal?.roleOutcome;
4474
4963
  if (outcome === void 0) return void 0;
4475
4964
  const facts = outcome.decisiveFacts;
@@ -4906,6 +5395,8 @@ function createPiRoleTurnHost(config) {
4906
5395
  else env.AK_ROLE_INVOCATION_SCOPE = request.invocationScopeId;
4907
5396
  if (request.host === void 0 || request.host.trim() === "") delete env.AK_ROLE_HOST;
4908
5397
  else env.AK_ROLE_HOST = request.host.trim();
5398
+ if (request.deliveryRequestLimit === void 0) delete env[RECEIPT_DELIVERY_LIMIT_ENV];
5399
+ else env[RECEIPT_DELIVERY_LIMIT_ENV] = String(request.deliveryRequestLimit);
4909
5400
  applyEngineChildEnv(env, request.engine);
4910
5401
  if (typeof process.env.AK_ROLE_AUDITOR_SOURCE_RUN === "string" && process.env.AK_ROLE_AUDITOR_SOURCE_RUN.trim() !== "") {
4911
5402
  env.AK_ROLE_AUDITOR_SOURCE_RUN = process.env.AK_ROLE_AUDITOR_SOURCE_RUN;
@@ -4965,6 +5456,7 @@ var init_role_turn_host = __esm({
4965
5456
  init_engine_detour();
4966
5457
  init_role_activation_flags();
4967
5458
  init_user_dialogue_stdin();
5459
+ init_receipt_delivery_policy();
4968
5460
  init_sitian_facade();
4969
5461
  INTERNAL_ROLE_ENTRYPOINT_RELATIVE2 = "extensions/role-runtime.ts";
4970
5462
  EXPLICIT_INTERNAL_LOAD_PROBE_ARGS = [
@@ -9046,10 +9538,10 @@ function pairGateRounds(volumes) {
9046
9538
  return rounds.sort((a, b) => a.officerStartedAt.localeCompare(b.officerStartedAt)).map((round, index) => ({ ...round, roundIndex: index + 1 }));
9047
9539
  }
9048
9540
  async function resolveOfficerSessionFromPointerFile(pointerPath) {
9049
- const { readFile: readFile25 } = await import("node:fs/promises");
9541
+ const { readFile: readFile26 } = await import("node:fs/promises");
9050
9542
  let raw;
9051
9543
  try {
9052
- raw = JSON.parse(await readFile25(pointerPath, "utf8"));
9544
+ raw = JSON.parse(await readFile26(pointerPath, "utf8"));
9053
9545
  } catch (error) {
9054
9546
  throw new Error(
9055
9547
  `direct officer run pointer unreadable in ${pointerPath}: ${errorText(error)}`,
@@ -9929,9 +10421,7 @@ function runDirectoryFromSessionDirectory(sessionDirectory) {
9929
10421
  function sessionFileFromSessionDirectory(sessionDirectory) {
9930
10422
  return join26(sessionDirectory, "session.jsonl");
9931
10423
  }
9932
- function mintEngineDetourInvocationScope(input) {
9933
- const engine = input.effectiveEngine?.trim();
9934
- if (engine === void 0 || engine.length === 0) return void 0;
10424
+ function mintEngineDetourInvocationScope(_input) {
9935
10425
  return randomUUID4();
9936
10426
  }
9937
10427
  function withEngineDetourInvocationScope(request, invocationScopeId) {
@@ -10021,101 +10511,6 @@ var init_dossier_resolution = __esm({
10021
10511
  }
10022
10512
  });
10023
10513
 
10024
- // src/receipt-delivery-policy.ts
10025
- function parseNoReceiptLifecycleFacts(input) {
10026
- if (!isRecord(input) || typeof input.terminalToolCalled !== "boolean" || input.deliveryTurns !== RECEIPT_DELIVERY_TURN_LIMIT || input.sessionCompletion !== "settled-without-accepted-receipt" || input.acceptedReceipt !== false || typeof input.runPointer !== "string" || input.runPointer.trim() === "" || typeof input.attemptPointer !== "string" || input.attemptPointer.trim() === "" || !Array.isArray(input.rejectedReceipts) || !input.rejectedReceipts.every((item) => isRecord(item) && typeof item.reason === "string")) {
10027
- throw new TypeError("malformed no-receipt lifecycle facts");
10028
- }
10029
- return {
10030
- terminalToolCalled: input.terminalToolCalled,
10031
- rejectedReceipts: input.rejectedReceipts.map((item) => ({
10032
- reason: item.reason,
10033
- diagnosticAvailable: item.reason.trim() !== ""
10034
- })),
10035
- deliveryTurns: RECEIPT_DELIVERY_TURN_LIMIT,
10036
- sessionCompletion: "settled-without-accepted-receipt",
10037
- runPointer: input.runPointer,
10038
- attemptPointer: input.attemptPointer,
10039
- acceptedReceipt: false
10040
- };
10041
- }
10042
- function noReceiptLifecycleFacts(input) {
10043
- if (input.deliveryTurns !== RECEIPT_DELIVERY_TURN_LIMIT) {
10044
- throw new TypeError("no-receipt lifecycle requires an exhausted delivery budget");
10045
- }
10046
- return {
10047
- terminalToolCalled: input.terminalToolCalled,
10048
- rejectedReceipts: input.rejectedReceipts.map(({ reason }) => ({
10049
- reason,
10050
- diagnosticAvailable: reason.trim() !== ""
10051
- })),
10052
- deliveryTurns: RECEIPT_DELIVERY_TURN_LIMIT,
10053
- sessionCompletion: "settled-without-accepted-receipt",
10054
- runPointer: input.runPointer,
10055
- attemptPointer: input.attemptPointer,
10056
- acceptedReceipt: false
10057
- };
10058
- }
10059
- function createReceiptDeliveryPolicy() {
10060
- let accepted = false;
10061
- let terminalToolCalled = false;
10062
- let deliveryTurns = 0;
10063
- const rejectedReceipts = [];
10064
- return {
10065
- recordAccepted() {
10066
- accepted = true;
10067
- terminalToolCalled = true;
10068
- },
10069
- /** Infrastructure owns terminality and must never trigger receipt催交. */
10070
- stopForInfrastructure() {
10071
- accepted = true;
10072
- },
10073
- recordRejected(reason) {
10074
- terminalToolCalled = true;
10075
- rejectedReceipts.push({ reason, diagnosticAvailable: reason.trim() !== "" });
10076
- deliveryTurns = Math.min(RECEIPT_DELIVERY_TURN_LIMIT, deliveryTurns + 1);
10077
- },
10078
- recordDeliveryRequest() {
10079
- deliveryTurns = Math.min(RECEIPT_DELIVERY_TURN_LIMIT, deliveryTurns + 1);
10080
- },
10081
- /**
10082
- * A nested session settled without an accepted receipt after spending its own
10083
- * delivery budget. Adopt its facts and close this budget: another prompt would
10084
- * open an independent session, not a delivery request on the settled one.
10085
- */
10086
- recordNestedNoReceipt(facts) {
10087
- terminalToolCalled = terminalToolCalled || facts.terminalToolCalled;
10088
- rejectedReceipts.push(...facts.rejectedReceipts);
10089
- deliveryTurns = RECEIPT_DELIVERY_TURN_LIMIT;
10090
- },
10091
- nextAction() {
10092
- if (accepted) return "accepted";
10093
- return deliveryTurns < RECEIPT_DELIVERY_TURN_LIMIT ? "request-delivery" : "no-receipt";
10094
- },
10095
- /** Current typed delivery facts. No prose. */
10096
- deliveryState() {
10097
- return {
10098
- terminalToolCalled,
10099
- rejectedReceipts: rejectedReceipts.map((item) => ({ ...item })),
10100
- deliveryTurns,
10101
- acceptedReceipt: false
10102
- };
10103
- },
10104
- facts(binding) {
10105
- return noReceiptLifecycleFacts({ terminalToolCalled, rejectedReceipts: [...rejectedReceipts], deliveryTurns, ...binding });
10106
- }
10107
- };
10108
- }
10109
- var RECEIPT_DELIVERY_TURN_LIMIT, NO_RECEIPT_LIFECYCLE_ENTRY_TYPE;
10110
- var init_receipt_delivery_policy = __esm({
10111
- "src/receipt-delivery-policy.ts"() {
10112
- "use strict";
10113
- init_unknown_value();
10114
- RECEIPT_DELIVERY_TURN_LIMIT = 2;
10115
- NO_RECEIPT_LIFECYCLE_ENTRY_TYPE = "ak-no-receipt-lifecycle";
10116
- }
10117
- });
10118
-
10119
10514
  // src/public-cli/settlement.ts
10120
10515
  var settlement_exports = {};
10121
10516
  __export(settlement_exports, {
@@ -10258,13 +10653,76 @@ async function attachRecordedSubmissions(admitted, terminal, scope) {
10258
10653
  if (errorPath !== void 0) privateFailureErrorPaths.set(result, errorPath);
10259
10654
  return result;
10260
10655
  }
10261
- async function settleHostEndedNoReceipt(admitted, authority, scope) {
10656
+ function lifecycleFactsFromEntry(entry) {
10657
+ const customType = entry.customType ?? entry.message?.customType;
10658
+ if (customType !== NO_RECEIPT_LIFECYCLE_ENTRY_TYPE) return void 0;
10659
+ return entry.data ?? entry.message?.details;
10660
+ }
10661
+ async function readCurrentAttemptNoReceiptFacts(admitted, authority, scope) {
10662
+ const { sessionFile } = coordinatesFromAdmitted(authority, admitted);
10663
+ const entries = await readBoundSessionEntries(sessionFile).catch(() => void 0);
10664
+ if (entries === void 0) return void 0;
10665
+ const scopeId = scope?.invocationScopeId?.trim() ?? "";
10666
+ if (scopeId.length > 0) {
10667
+ const pointer = receiptAttemptPointer(admitted.runDirectory, scopeId);
10668
+ let selected;
10669
+ for (const entry of entries) {
10670
+ const raw2 = lifecycleFactsFromEntry(entry);
10671
+ if (raw2 === void 0) continue;
10672
+ try {
10673
+ const facts2 = parseNoReceiptLifecycleFacts(raw2);
10674
+ if (facts2.runPointer !== admitted.runDirectory) continue;
10675
+ if (facts2.attemptPointer !== pointer) continue;
10676
+ if (selected === void 0 || facts2.deliveryTurns >= selected.deliveryTurns) {
10677
+ selected = facts2;
10678
+ }
10679
+ } catch {
10680
+ }
10681
+ }
10682
+ return selected;
10683
+ }
10684
+ let attemptStart = 0;
10685
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
10686
+ if (entries[index]?.type === "message" && entries[index]?.message?.role === "user") {
10687
+ attemptStart = index;
10688
+ break;
10689
+ }
10690
+ }
10691
+ const lifecycleEntry = entries.slice(attemptStart).reverse().find((entry) => lifecycleFactsFromEntry(entry) !== void 0);
10692
+ const raw = lifecycleEntry === void 0 ? void 0 : lifecycleFactsFromEntry(lifecycleEntry);
10693
+ if (raw === void 0) return void 0;
10694
+ let facts;
10695
+ try {
10696
+ facts = parseNoReceiptLifecycleFacts(raw);
10697
+ } catch {
10698
+ return void 0;
10699
+ }
10700
+ if (facts.runPointer !== admitted.runDirectory) return void 0;
10701
+ if (facts.attemptPointer !== receiptAttemptPointer(admitted.runDirectory)) return void 0;
10702
+ return facts;
10703
+ }
10704
+ async function settleHostEndedNoReceipt(admitted, authority, scope, issuedDeliveryRequests = 0) {
10705
+ const scopeId = scope?.invocationScopeId?.trim() ?? "";
10706
+ const persisted = scopeId.length > 0 ? void 0 : await readCurrentAttemptNoReceiptFacts(admitted, authority, scope);
10707
+ let terminalToolCalled = persisted?.terminalToolCalled ?? false;
10708
+ let rejectedReceipts = persisted?.rejectedReceipts ?? [];
10709
+ let recordedTurns = persisted?.deliveryTurns ?? 0;
10710
+ if (scopeId.length > 0) {
10711
+ const { sessionFile } = coordinatesFromAdmitted(authority, admitted);
10712
+ const entries = await readBoundSessionEntries(sessionFile).catch(() => void 0);
10713
+ if (entries !== void 0) {
10714
+ const prior = priorReceiptContinuation(entries, scopeId);
10715
+ terminalToolCalled = prior.terminalToolCalled;
10716
+ rejectedReceipts = prior.rejectedReceipts;
10717
+ recordedTurns = prior.deliveryTurns;
10718
+ }
10719
+ }
10262
10720
  const facts = noReceiptLifecycleFacts({
10263
- terminalToolCalled: false,
10264
- rejectedReceipts: [],
10265
- deliveryTurns: RECEIPT_DELIVERY_TURN_LIMIT,
10721
+ terminalToolCalled,
10722
+ rejectedReceipts,
10723
+ deliveryTurns: Math.max(issuedDeliveryRequests, recordedTurns),
10266
10724
  runPointer: admitted.runDirectory,
10267
- attemptPointer: `current:${admitted.runDirectory}`
10725
+ attemptPointer: receiptAttemptPointer(admitted.runDirectory, scope?.invocationScopeId)
10268
10726
  });
10269
10727
  const coordinates = coordinatesFromAdmitted(authority, admitted);
10270
10728
  await clearOppositeTerminalArtifactFace(admitted.runDirectory);
@@ -11837,44 +12295,26 @@ async function settleFailureTerminalResult(admitted, failure, authority, options
11837
12295
  const coordinates = coordinatesFromAdmitted(authority, admitted);
11838
12296
  const { sessionDirectory, sessionFile } = coordinates;
11839
12297
  if (failure.cause === "output") {
11840
- const entries = await readBoundSessionEntries(sessionFile).catch(() => void 0);
11841
- if (entries !== void 0) {
11842
- let attemptStart = 0;
11843
- for (let index = entries.length - 1; index >= 0; index -= 1) {
11844
- if (entries[index]?.type === "message" && entries[index]?.message?.role === "user") {
11845
- attemptStart = index;
11846
- break;
11847
- }
11848
- }
11849
- const lifecycleEntry = entries.slice(attemptStart).reverse().find((entry) => entry.customType === NO_RECEIPT_LIFECYCLE_ENTRY_TYPE || entry.message?.customType === NO_RECEIPT_LIFECYCLE_ENTRY_TYPE);
11850
- const raw = lifecycleEntry?.data ?? lifecycleEntry?.message?.details;
11851
- if (raw !== void 0) {
11852
- let facts;
11853
- try {
11854
- facts = parseNoReceiptLifecycleFacts(raw);
11855
- } catch {
11856
- }
11857
- if (facts !== void 0 && facts.runPointer === admitted.runDirectory && facts.attemptPointer === `current:${admitted.runDirectory}`) {
11858
- let decisiveFacts2 = facts;
11859
- await clearOppositeTerminalArtifactFace(admitted.runDirectory);
11860
- return withOptionalGateProjection(
11861
- {
11862
- roleOutcome: {
11863
- kind: "no_receipt",
11864
- role: admitted.role,
11865
- status: "no-accepted-receipt",
11866
- ...facts,
11867
- decisiveFacts: decisiveFacts2
11868
- },
11869
- navigator: await extractNavigatorFactFromAdmittedSession(sessionFile),
11870
- artifacts: [],
11871
- runId: admitted.runId
11872
- },
11873
- sessionDirectory,
11874
- detourGateContext(admitted, options)
11875
- );
11876
- }
11877
- }
12298
+ const facts = await readCurrentAttemptNoReceiptFacts(admitted, authority, options);
12299
+ if (facts !== void 0) {
12300
+ const decisiveFacts2 = facts;
12301
+ await clearOppositeTerminalArtifactFace(admitted.runDirectory);
12302
+ return withOptionalGateProjection(
12303
+ {
12304
+ roleOutcome: {
12305
+ kind: "no_receipt",
12306
+ role: admitted.role,
12307
+ status: "no-accepted-receipt",
12308
+ ...facts,
12309
+ decisiveFacts: decisiveFacts2
12310
+ },
12311
+ navigator: await extractNavigatorFactFromAdmittedSession(sessionFile),
12312
+ artifacts: [],
12313
+ runId: admitted.runId
12314
+ },
12315
+ sessionDirectory,
12316
+ detourGateContext(admitted, options)
12317
+ );
11878
12318
  }
11879
12319
  }
11880
12320
  const navigator = await extractNavigatorFactFromAdmittedSession(sessionFile);
@@ -12044,16 +12484,19 @@ var init_settlement = __esm({
12044
12484
 
12045
12485
  // src/archivist-record-pointer.ts
12046
12486
  import { mkdirSync as mkdirSync2, writeFileSync } from "node:fs";
12487
+ import { readFile as readFile17 } from "node:fs/promises";
12047
12488
  import { dirname as dirname17, join as join28 } from "node:path";
12048
12489
  function bookDirectOfficerRunPointer(options) {
12049
12490
  const nest = join28(dirname17(options.parentSessionFile), "auditor-roles");
12050
12491
  mkdirSync2(nest, { recursive: true });
12492
+ const submissionToolCallId = options.submissionToolCallId?.trim() ?? "";
12051
12493
  const pointer = {
12052
12494
  version: 1,
12053
12495
  kind: DIRECT_OFFICER_RUN_POINTER_KIND,
12054
12496
  officer: options.officer,
12055
12497
  sessionFile: options.sessionFile,
12056
- ...options.runDirectory !== void 0 && options.runDirectory.trim() !== "" ? { runDirectory: options.runDirectory } : {}
12498
+ ...options.runDirectory !== void 0 && options.runDirectory.trim() !== "" ? { runDirectory: options.runDirectory } : {},
12499
+ ...submissionToolCallId === "" ? {} : { submissionToolCallId }
12057
12500
  };
12058
12501
  writeFileSync(
12059
12502
  join28(nest, `${options.officer}.pointer.json`),
@@ -12063,10 +12506,36 @@ function bookDirectOfficerRunPointer(options) {
12063
12506
  );
12064
12507
  return pointer;
12065
12508
  }
12509
+ async function readDirectOfficerRunPointer(parentSessionFile, officer) {
12510
+ try {
12511
+ const raw = JSON.parse(await readFile17(
12512
+ join28(dirname17(parentSessionFile), "auditor-roles", `${officer}.pointer.json`),
12513
+ "utf8"
12514
+ ));
12515
+ if (!isRecord(raw) || raw.kind !== DIRECT_OFFICER_RUN_POINTER_KIND || raw.version !== 1) {
12516
+ return void 0;
12517
+ }
12518
+ if (raw.officer !== officer) return void 0;
12519
+ if (typeof raw.sessionFile !== "string" || raw.sessionFile.trim() === "") return void 0;
12520
+ const runDirectory = typeof raw.runDirectory === "string" && raw.runDirectory.trim() !== "" ? raw.runDirectory : void 0;
12521
+ const submissionToolCallId = typeof raw.submissionToolCallId === "string" && raw.submissionToolCallId.trim() !== "" ? raw.submissionToolCallId : void 0;
12522
+ return {
12523
+ version: 1,
12524
+ kind: DIRECT_OFFICER_RUN_POINTER_KIND,
12525
+ officer,
12526
+ sessionFile: raw.sessionFile,
12527
+ ...runDirectory === void 0 ? {} : { runDirectory },
12528
+ ...submissionToolCallId === void 0 ? {} : { submissionToolCallId }
12529
+ };
12530
+ } catch {
12531
+ return void 0;
12532
+ }
12533
+ }
12066
12534
  var DIRECT_OFFICER_RUN_POINTER_KIND;
12067
12535
  var init_archivist_record_pointer = __esm({
12068
12536
  "src/archivist-record-pointer.ts"() {
12069
12537
  "use strict";
12538
+ init_unknown_value();
12070
12539
  DIRECT_OFFICER_RUN_POINTER_KIND = "direct-officer-run-pointer";
12071
12540
  }
12072
12541
  });
@@ -12084,6 +12553,7 @@ function createPiDoctorAuditor() {
12084
12553
  submission: options.submission,
12085
12554
  ...auditorRunDirectory(options.context) === void 0 ? {} : { runDirectory: auditorRunDirectory(options.context) },
12086
12555
  ...options.signal === void 0 ? {} : { signal: options.signal },
12556
+ ...options.autoResumeLimit === void 0 ? {} : { autoResumeLimit: options.autoResumeLimit },
12087
12557
  ...options.summonAuditor === void 0 ? {} : { summonAuditor: options.summonAuditor }
12088
12558
  });
12089
12559
  };
@@ -12098,16 +12568,56 @@ var init_doctor_auditor = __esm({
12098
12568
  }
12099
12569
  });
12100
12570
 
12571
+ // src/filed-submission.ts
12572
+ function registerFiledSubmissionTool(roleHost, tool, options) {
12573
+ roleHost.registerTool({
12574
+ name: tool.name,
12575
+ label: tool.label,
12576
+ description: tool.description,
12577
+ ...tool.promptSnippet === void 0 ? {} : { promptSnippet: tool.promptSnippet },
12578
+ parameters: tool.parameters,
12579
+ async execute(toolCallId, parameters, signal, _onUpdate, ctx) {
12580
+ const blocked = options.readyError();
12581
+ if (blocked !== void 0) throw new Error(blocked);
12582
+ const projected = options.beforeAccept === void 0 ? void 0 : await options.beforeAccept({ toolCallId, parameters, signal, ctx });
12583
+ return {
12584
+ content: [],
12585
+ details: projected === void 0 ? parameters : projected,
12586
+ terminate: true
12587
+ };
12588
+ }
12589
+ });
12590
+ }
12591
+ var init_filed_submission = __esm({
12592
+ "src/filed-submission.ts"() {
12593
+ "use strict";
12594
+ }
12595
+ });
12596
+
12101
12597
  // src/judge-role.ts
12102
12598
  async function runJudgeGates(input) {
12103
12599
  const passes = [];
12104
12600
  for (const subject of JUDGE_GATES) {
12105
12601
  if (await input.gateAlreadyConverged(subject)) continue;
12106
12602
  const pass = await input.runGate(subject);
12107
- const status = pass?.status;
12108
- if (pass === void 0 || status !== "converged" && status !== "continue" && status !== "escalate") {
12603
+ const received = pass?.status;
12604
+ if (pass === void 0 || (typeof received !== "string" || !REVIEW_QUEUE_STATUSES.has(received) && received !== "needs_reask")) {
12109
12605
  throw new Error("judge gate returned no conclusion");
12110
12606
  }
12607
+ const status = received;
12608
+ if (status === "needs_reask") {
12609
+ return {
12610
+ status,
12611
+ passes: [{
12612
+ subject,
12613
+ status,
12614
+ receipt: pass.receipt,
12615
+ ...pass.runId === void 0 ? {} : { runId: pass.runId },
12616
+ ...pass.runDirectory === void 0 ? {} : { runDirectory: pass.runDirectory },
12617
+ ...pass.terminal === void 0 ? {} : { terminal: pass.terminal }
12618
+ }]
12619
+ };
12620
+ }
12111
12621
  passes.push({
12112
12622
  subject,
12113
12623
  status,
@@ -12128,16 +12638,8 @@ function createJudgeRoleRuntime(pi, dependencies) {
12128
12638
  if (soul.length === 0) throw new Error("Judge soul is empty");
12129
12639
  if (!lifecycleRegistered) {
12130
12640
  lifecycleRegistered = true;
12131
- pi.registerTool({
12132
- name: JUDGE_OUTPUT_TOOL_NAME,
12133
- label: "\u5927\u7406\u5BFA\u8F93\u51FA",
12134
- description: "\u63D0\u4EA4\u5927\u7406\u5BFA\u7EC8\u5C40\u5224\u8BCD\uFF1B\u4EA4\u5377\u8C03\u7528\u7ED3\u675F\u540E\uFF0C\u7531\u516C\u5F00\u8C03\u7528\u63A5\u7F1D\u6309\u5224\u8BCD\u72B6\u6001\u6267\u884C\u9002\u7528\u5BA1\u6838\u3002",
12135
- promptSnippet: "\u63D0\u4EA4\u5927\u7406\u5BFA\u7EC8\u5C40\u5224\u8BCD",
12136
- parameters: judgeVerdictSchema,
12137
- async execute(toolCallId, parameters, signal, _onUpdate, ctx) {
12138
- if (soul === void 0) throw new Error("\u5927\u7406\u5BFA\u804C\u5206\u672A\u88C5\u8F7D");
12139
- return { content: [], details: parameters, terminate: true };
12140
- }
12641
+ registerFiledSubmissionTool(pi, roleSubmissionDeclaration("judge"), {
12642
+ readyError: () => soul === void 0 ? "\u5927\u7406\u5BFA\u804C\u5206\u672A\u88C5\u8F7D" : void 0
12141
12643
  });
12142
12644
  pi.on("before_agent_start", (event) => {
12143
12645
  if (soul === void 0) throw new Error("\u5927\u7406\u5BFA\u804C\u5206\u672A\u88C5\u8F7D");
@@ -12153,19 +12655,20 @@ ${soul}
12153
12655
  }
12154
12656
  };
12155
12657
  }
12156
- var JUDGE_GATES, judgeVerdictSchema;
12658
+ var JUDGE_GATES;
12157
12659
  var init_judge_role = __esm({
12158
12660
  "src/judge-role.ts"() {
12159
12661
  "use strict";
12160
12662
  init_host_contracts();
12161
12663
  init_review_submission();
12664
+ init_filed_submission();
12665
+ init_role_submission_declarations();
12162
12666
  init_gatekeeper_role();
12163
12667
  init_judge_output();
12164
12668
  JUDGE_GATES = [
12165
12669
  { kind: "judge_draft" },
12166
12670
  { kind: "judge_compliance" }
12167
12671
  ];
12168
- judgeVerdictSchema = reviewSubmissionSchema;
12169
12672
  }
12170
12673
  });
12171
12674
 
@@ -12188,11 +12691,10 @@ function latestQueueStatus(terminal) {
12188
12691
  if (outcome.kind === "audit_escalation") return "escalate";
12189
12692
  if (outcome.kind !== "accepted") return void 0;
12190
12693
  const latest = outcome.payloads?.[outcome.payloads.length - 1];
12191
- if (isRecord(latest)) {
12192
- const status = latest.status;
12193
- if (typeof status === "string" && status.trim() !== "") return status;
12694
+ if (isRecord(latest) && Object.hasOwn(latest, "status")) {
12695
+ return receivedDiscriminator(latest, "status");
12194
12696
  }
12195
- return typeof outcome.status === "string" && outcome.status.trim() !== "" ? outcome.status : void 0;
12697
+ return outcome.status;
12196
12698
  }
12197
12699
  function latestQueuePayload(terminal) {
12198
12700
  const outcome = terminal?.roleOutcome;
@@ -12220,7 +12722,7 @@ function createDefaultGateOfficerSummon(options) {
12220
12722
  });
12221
12723
  };
12222
12724
  }
12223
- function bookDirectOfficerPointer(context, officer, result, summoned) {
12725
+ function bookDirectOfficerPointer(context, officer, result, summoned, toolCallId) {
12224
12726
  if (result.status !== "converged" && result.status !== "continue" && result.status !== "escalate" && result.status !== "needs_reask" && result.status !== "transport_failure") {
12225
12727
  return;
12226
12728
  }
@@ -12234,11 +12736,14 @@ function bookDirectOfficerPointer(context, officer, result, summoned) {
12234
12736
  parentSessionFile: parentFile,
12235
12737
  officer,
12236
12738
  sessionFile,
12237
- ...typeof summoned.runDirectory === "string" && summoned.runDirectory.trim() !== "" ? { runDirectory: summoned.runDirectory } : {}
12739
+ ...typeof summoned.runDirectory === "string" && summoned.runDirectory.trim() !== "" ? { runDirectory: summoned.runDirectory } : {},
12740
+ ...toolCallId.trim() === "" ? {} : { submissionToolCallId: toolCallId }
12238
12741
  });
12239
12742
  }
12240
12743
  async function requireSubmissionGate(options) {
12241
12744
  let reask;
12745
+ let reasksSpent = 0;
12746
+ const reaskLimit = deliveryLimitFromConfig(options.autoResumeLimit);
12242
12747
  const summonOfficer = options.summonOfficer ?? createDefaultGateOfficerSummon({
12243
12748
  cwd: options.context.cwd ?? process.cwd()
12244
12749
  });
@@ -12258,7 +12763,8 @@ async function requireSubmissionGate(options) {
12258
12763
  options.context,
12259
12764
  projected.officer,
12260
12765
  gatekeeper,
12261
- projected.summoned
12766
+ projected.summoned,
12767
+ options.toolCallId
12262
12768
  );
12263
12769
  } catch (error) {
12264
12770
  options.hostActions.failInfrastructure(error, options.context, options.toolCallId);
@@ -12281,6 +12787,17 @@ async function requireSubmissionGate(options) {
12281
12787
  };
12282
12788
  }
12283
12789
  if (gatekeeper.status === "needs_reask") {
12790
+ if (reasksSpent >= reaskLimit) {
12791
+ return {
12792
+ status: "needs_reask",
12793
+ officer: projected.officer,
12794
+ receipt: gatekeeper.receipt,
12795
+ ...typeof gatekeeper.runId === "string" && gatekeeper.runId.trim() !== "" ? { runId: gatekeeper.runId } : {},
12796
+ ...typeof projected.summoned?.runDirectory === "string" && projected.summoned.runDirectory.trim() !== "" ? { runDirectory: projected.summoned.runDirectory } : {},
12797
+ ...projected.summoned?.terminal === void 0 ? {} : { terminal: projected.summoned.terminal }
12798
+ };
12799
+ }
12800
+ reasksSpent += 1;
12284
12801
  reask = officerConclusionReask(gatekeeper.receivedStatus);
12285
12802
  continue;
12286
12803
  }
@@ -12309,6 +12826,8 @@ var init_submission_gate = __esm({
12309
12826
  "use strict";
12310
12827
  init_archivist_record_pointer();
12311
12828
  init_gatekeeper_role();
12829
+ init_submission_errors();
12830
+ init_receipt_delivery_policy();
12312
12831
  init_session_assistant_usage();
12313
12832
  init_unknown_value();
12314
12833
  }
@@ -12488,7 +13007,8 @@ function projectRoleTurnRequest(admitted, roleDetails, options) {
12488
13007
  ...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs },
12489
13008
  ...options.courtAttemptId === void 0 || options.courtAttemptId.length === 0 ? {} : { courtAttemptId: options.courtAttemptId },
12490
13009
  ...options.invocationScopeId === void 0 || options.invocationScopeId.length === 0 ? {} : { invocationScopeId: options.invocationScopeId },
12491
- ...options.stationChild === void 0 ? {} : { stationChild: options.stationChild }
13010
+ ...options.stationChild === void 0 ? {} : { stationChild: options.stationChild },
13011
+ ...options.deliveryRequestLimit === void 0 ? {} : { deliveryRequestLimit: options.deliveryRequestLimit }
12492
13012
  };
12493
13013
  }
12494
13014
  function packagedSettleSkill(admitted) {
@@ -12566,7 +13086,7 @@ var init_turn_request = __esm({
12566
13086
  });
12567
13087
 
12568
13088
  // src/session-identity.ts
12569
- import { mkdir as mkdir3, readFile as readFile17, rename as rename3, writeFile as writeFile6 } from "node:fs/promises";
13089
+ import { mkdir as mkdir3, readFile as readFile18, rename as rename3, writeFile as writeFile6 } from "node:fs/promises";
12570
13090
  import { dirname as dirname18, join as join30 } from "node:path";
12571
13091
  function createSessionIdentityAuthority(authority, sessionBindingFile) {
12572
13092
  const bindingPath = (principal) => join30(authority.decode(principal).sessionDirectory, sessionBindingFile);
@@ -12576,7 +13096,7 @@ function createSessionIdentityAuthority(authority, sessionBindingFile) {
12576
13096
  },
12577
13097
  async load(principal) {
12578
13098
  try {
12579
- const value = JSON.parse(await readFile17(bindingPath(principal), "utf8"));
13099
+ const value = JSON.parse(await readFile18(bindingPath(principal), "utf8"));
12580
13100
  if (typeof value !== "object" || value === null || typeof value.sessionId !== "string") {
12581
13101
  throw new Error("durable session binding is invalid");
12582
13102
  }
@@ -13412,8 +13932,203 @@ async function settleDeferredPersist(admitted, authority, adapters, io, result)
13412
13932
  io,
13413
13933
  true
13414
13934
  );
13415
- return { ...failed, turnDispatched: true, skipAutoResume: true };
13935
+ return {
13936
+ ...failed,
13937
+ turnDispatched: true,
13938
+ skipAutoResume: true
13939
+ };
13940
+ }
13941
+ }
13942
+ function settlementScopeForTurn(request) {
13943
+ const hasCourt = request.courtAttemptId !== void 0 && request.courtAttemptId.length > 0;
13944
+ const hasScope = request.invocationScopeId !== void 0 && request.invocationScopeId.length > 0;
13945
+ if (!hasCourt && !hasScope) return void 0;
13946
+ return {
13947
+ ...hasCourt ? { courtAttemptId: request.courtAttemptId } : {},
13948
+ ...hasScope ? { invocationScopeId: request.invocationScopeId } : {}
13949
+ };
13950
+ }
13951
+ async function buildReceiptDeliveryRequest(input) {
13952
+ const { admitted, env, request, receiptDelivery } = input;
13953
+ const hostSessionId = await readStoredHostSessionId(
13954
+ env.host,
13955
+ env.principalAuthority,
13956
+ admitted.principal
13957
+ );
13958
+ return {
13959
+ ...request,
13960
+ continuation: {
13961
+ kind: "resume",
13962
+ prompt: JSON.stringify({
13963
+ ...receiptDelivery.deliveryState(),
13964
+ deliveryTurns: receiptDelivery.issuedDeliveryRequests() + 1
13965
+ }),
13966
+ ...hostSessionId === void 0 ? {} : { hostSessionId }
13967
+ },
13968
+ deliveryRequestLimit: receiptDelivery.limit
13969
+ };
13970
+ }
13971
+ async function settleCompletedHostTurn(input) {
13972
+ const { admitted, env, io, adapters, shouldPresent, request, result, persistRunState, deferredPersist } = input;
13973
+ const finishAfterTurn = input.finishAfterTurn;
13974
+ let stderrLogWriteFailure;
13975
+ try {
13976
+ await writeFile7(
13977
+ join33(admitted.runDirectory, "stderr.log"),
13978
+ result.stderr,
13979
+ "utf8"
13980
+ );
13981
+ } catch (error) {
13982
+ stderrLogWriteFailure = error;
13983
+ await recordBestEffortPostDispatchDiagnostic(
13984
+ admitted,
13985
+ env,
13986
+ `stderr.log write failed (best-effort continue): ${describeErrorIdentity(error)}`,
13987
+ io
13988
+ );
13989
+ }
13990
+ const courtScope = settlementScopeForTurn(request);
13991
+ let settled;
13992
+ let settledOutcome;
13993
+ let hostSignalFailed = false;
13994
+ let resolution;
13995
+ try {
13996
+ const sessionFile = admitted.principal !== void 0 ? env.principalAuthority.decode(admitted.principal).sessionFile : "";
13997
+ const runnerKnownFailure = adapters.resolveRunnerKnownFailure !== void 0 && sessionFile !== "" ? await adapters.resolveRunnerKnownFailure({ result, sessionFile }) : result.knownFailure;
13998
+ resolution = await resolveAuditedRunnerFailureResolution({
13999
+ runner: runnerKnownFailure,
14000
+ sessionFile,
14001
+ credential: void 0,
14002
+ runDirectory: admitted.runDirectory
14003
+ });
14004
+ const processCancelName = processCancelSignalName(env.signal);
14005
+ const directHostFailureSignal = result.timedOut || result.knownFailure !== void 0 || runnerKnownFailure !== void 0 || processCancelName !== void 0;
14006
+ hostSignalFailed = directHostFailureSignal || result.code !== null && result.code !== 0 || resolution.knownFailure !== void 0;
14007
+ settled = await adapters.trySettle(admitted, env.principalAuthority, courtScope);
14008
+ if (settled !== void 0) {
14009
+ settled = await attachRecordedSubmissions(admitted, settled, courtScope);
14010
+ }
14011
+ const settledIsFreshThisAttempt = settled === void 0 || settled.roleOutcome.kind !== "accepted" && settled.roleOutcome.kind !== "audit_escalation" ? true : await attemptProducedFreshSubmission(admitted, courtScope);
14012
+ const staleAcceptanceOutranksRealFailure = !settledIsFreshThisAttempt && hostSignalFailed;
14013
+ const cancelAfterSettle = processCancelSignalName(env.signal);
14014
+ if (settled !== void 0 && shouldPresent(settled) && !directHostFailureSignal && !staleAcceptanceOutranksRealFailure && stderrLogWriteFailure === void 0 && cancelAfterSettle === void 0) {
14015
+ if (settled.roleOutcome.kind === "accepted" && request.courtAttemptId !== void 0 && request.courtAttemptId.length > 0) {
14016
+ try {
14017
+ await clearCurrentCourt(admitted.runDirectory, request.courtAttemptId);
14018
+ } catch (error) {
14019
+ await recordBestEffortPostDispatchDiagnostic(
14020
+ admitted,
14021
+ env,
14022
+ `current-court cleanup failed after accepted settlement (best-effort continue): ${describeErrorIdentity(error)}`,
14023
+ io
14024
+ );
14025
+ }
14026
+ }
14027
+ settledOutcome = {
14028
+ exitCode: exitCodeForTerminalOutcome(settled.roleOutcome),
14029
+ admitted,
14030
+ terminal: settled,
14031
+ turnDispatched: true
14032
+ };
14033
+ }
14034
+ } catch (error) {
14035
+ const settledFailure = await settleAfterTurnStarted(
14036
+ admitted,
14037
+ withEngineDetourInvocationScope({
14038
+ timedOut: false,
14039
+ code: result.code,
14040
+ stderr: result.stderr,
14041
+ thrown: error
14042
+ }, request.invocationScopeId),
14043
+ adapters,
14044
+ env.principalAuthority,
14045
+ io,
14046
+ persistRunState
14047
+ );
14048
+ return { kind: "settled", outcome: await finishAfterTurn({ ...settledFailure, turnDispatched: true, ...deferredPersist }) };
14049
+ }
14050
+ if (settledOutcome !== void 0) {
14051
+ const lateCancel = processCancelSignalName(env.signal);
14052
+ if (lateCancel !== void 0) {
14053
+ return { kind: "settled", outcome: await finishAfterTurn(
14054
+ await settleProcessCancelAfterTurn({
14055
+ admitted,
14056
+ cancelName: lateCancel,
14057
+ result,
14058
+ adapters,
14059
+ env,
14060
+ io,
14061
+ persistRunState,
14062
+ deferredPersist,
14063
+ invocationScopeId: request.invocationScopeId
14064
+ })
14065
+ ) };
14066
+ }
14067
+ if (persistRunState) {
14068
+ try {
14069
+ await persistReturnedRunState(admitted, { lawful: true });
14070
+ } catch (error) {
14071
+ await recordBestEffortPostDispatchDiagnostic(
14072
+ admitted,
14073
+ env,
14074
+ `run-state persistence failed beside host terminal (best-effort continue): ${describeErrorIdentity(error)}`,
14075
+ io
14076
+ );
14077
+ }
14078
+ }
14079
+ return { kind: "settled", outcome: await finishAfterTurn({ ...settledOutcome, ...deferredPersist }) };
14080
+ }
14081
+ if (hostSignalFailed) {
14082
+ const resolutionInput = controlledFailureInputFromResolution(resolution);
14083
+ const processCancelName = processCancelSignalName(env.signal);
14084
+ const stderrLogWriteDetails = stderrLogWriteFailure === void 0 ? void 0 : { stderrLogWriteFailure: describeCaughtError(stderrLogWriteFailure) };
14085
+ const failed = await settleAfterTurnStarted(
14086
+ admitted,
14087
+ withEngineDetourInvocationScope({
14088
+ timedOut: result.timedOut,
14089
+ code: result.code,
14090
+ stderr: result.stderr,
14091
+ ...resolutionInput,
14092
+ ...processCancelName === void 0 ? {} : { knownDiagnostic: processCancelDiagnostic(processCancelName) },
14093
+ // Secondary fact only — never the cause. Rides on whichever channel
14094
+ // classification actually reads (knownFailure.details owns it when
14095
+ // a knownFailure exists; the top-level knownDetails otherwise).
14096
+ ...stderrLogWriteDetails === void 0 ? {} : resolutionInput.knownFailure !== void 0 ? {
14097
+ knownFailure: {
14098
+ ...resolutionInput.knownFailure,
14099
+ details: { ...resolutionInput.knownFailure.details ?? {}, ...stderrLogWriteDetails }
14100
+ }
14101
+ } : { knownDetails: stderrLogWriteDetails }
14102
+ }, request.invocationScopeId),
14103
+ adapters,
14104
+ env.principalAuthority,
14105
+ io,
14106
+ persistRunState
14107
+ );
14108
+ return { kind: "settled", outcome: await finishAfterTurn(
14109
+ withProcessCancelSkipAutoResume(
14110
+ { ...failed, turnDispatched: true, ...deferredPersist },
14111
+ env.signal
14112
+ )
14113
+ ) };
13416
14114
  }
14115
+ if (stderrLogWriteFailure !== void 0) {
14116
+ const failed = await settleAfterTurnStarted(
14117
+ admitted,
14118
+ withEngineDetourInvocationScope({
14119
+ timedOut: false,
14120
+ code: result.code,
14121
+ stderr: result.stderr,
14122
+ thrown: stderrLogWriteFailure
14123
+ }, request.invocationScopeId),
14124
+ adapters,
14125
+ env.principalAuthority,
14126
+ io,
14127
+ persistRunState
14128
+ );
14129
+ return { kind: "settled", outcome: await finishAfterTurn({ ...failed, turnDispatched: true, ...deferredPersist }) };
14130
+ }
14131
+ return { kind: "still-missing" };
13417
14132
  }
13418
14133
  async function dispatchPostAdmissionTurn(input) {
13419
14134
  const { admitted, env, io, request, lease, adapters, effectiveEngine } = input;
@@ -13421,6 +14136,9 @@ async function dispatchPostAdmissionTurn(input) {
13421
14136
  const deferredPersist = persistRunState ? {} : { needsPersist: true };
13422
14137
  const shouldPresent = adapters.shouldPresentSettled ?? ((terminal) => isLawfulTypedTerminalOutcome(terminal.roleOutcome));
13423
14138
  let afterDispatchApplied = false;
14139
+ const receiptDelivery = input.receiptDelivery ?? createReceiptDeliveryPolicy(env.autoResumeLimit);
14140
+ let turnDispatched = false;
14141
+ const akSeamDeliversReceipt = env.host !== void 0 && env.host !== "" && env.host !== DEFAULT_ROLE_TURN_HOST;
13424
14142
  const finishAfterTurn = async (result) => {
13425
14143
  if (afterDispatchApplied) return result;
13426
14144
  afterDispatchApplied = true;
@@ -13518,7 +14236,7 @@ async function dispatchPostAdmissionTurn(input) {
13518
14236
  return { exitCode: 0, admitted, terminal: paused, skipAutoResume: true };
13519
14237
  }
13520
14238
  } catch (error) {
13521
- const settled2 = await presentControlledFailure2(
14239
+ const settled = await presentControlledFailure2(
13522
14240
  admitted,
13523
14241
  withEngineDetourInvocationScope({
13524
14242
  timedOut: false,
@@ -13531,7 +14249,7 @@ async function dispatchPostAdmissionTurn(input) {
13531
14249
  io,
13532
14250
  persistRunState
13533
14251
  );
13534
- return { ...settled2, ...deferredPersist };
14252
+ return { ...settled, ...deferredPersist };
13535
14253
  }
13536
14254
  }
13537
14255
  let turnRequest = {
@@ -13555,10 +14273,11 @@ async function dispatchPostAdmissionTurn(input) {
13555
14273
  let result;
13556
14274
  try {
13557
14275
  recordRunStart(admitted.runDirectory);
14276
+ turnDispatched = true;
13558
14277
  result = await env.roleTurnHost.executeTurn(turnRequest);
13559
14278
  } catch (error) {
13560
14279
  const processCancelName = processCancelSignalName(env.signal);
13561
- const settled2 = await settleAfterTurnStarted(
14280
+ const settled = await settleAfterTurnStarted(
13562
14281
  admitted,
13563
14282
  withEngineDetourInvocationScope({
13564
14283
  timedOut: false,
@@ -13573,175 +14292,111 @@ async function dispatchPostAdmissionTurn(input) {
13573
14292
  );
13574
14293
  return await finishAfterTurn(
13575
14294
  withProcessCancelSkipAutoResume(
13576
- { ...settled2, turnDispatched: true, ...deferredPersist },
14295
+ { ...settled, turnDispatched: true, ...deferredPersist },
13577
14296
  env.signal
13578
14297
  )
13579
14298
  );
13580
14299
  }
13581
- let stderrLogWriteFailure;
13582
- try {
13583
- await writeFile7(
13584
- join33(admitted.runDirectory, "stderr.log"),
13585
- result.stderr,
13586
- "utf8"
13587
- );
13588
- } catch (error) {
13589
- stderrLogWriteFailure = error;
13590
- await recordBestEffortPostDispatchDiagnostic(
13591
- admitted,
13592
- env,
13593
- `stderr.log write failed (best-effort continue): ${describeErrorIdentity(error)}`,
13594
- io
13595
- );
13596
- }
13597
- const courtScope = (request.courtAttemptId === void 0 || request.courtAttemptId.length === 0) && (request.invocationScopeId === void 0 || request.invocationScopeId.length === 0) ? void 0 : {
13598
- ...request.courtAttemptId === void 0 || request.courtAttemptId.length === 0 ? {} : { courtAttemptId: request.courtAttemptId },
13599
- ...request.invocationScopeId === void 0 || request.invocationScopeId.length === 0 ? {} : { invocationScopeId: request.invocationScopeId }
13600
- };
13601
- let settled;
13602
- let settledOutcome;
13603
- let hostSignalFailed = false;
13604
- let resolution;
13605
- try {
13606
- const sessionFile = admitted.principal !== void 0 ? env.principalAuthority.decode(admitted.principal).sessionFile : "";
13607
- const runnerKnownFailure = adapters.resolveRunnerKnownFailure !== void 0 && sessionFile !== "" ? await adapters.resolveRunnerKnownFailure({ result, sessionFile }) : result.knownFailure;
13608
- resolution = await resolveAuditedRunnerFailureResolution({
13609
- runner: runnerKnownFailure,
13610
- sessionFile,
13611
- credential: void 0,
13612
- runDirectory: admitted.runDirectory
13613
- });
13614
- const processCancelName = processCancelSignalName(env.signal);
13615
- const directHostFailureSignal = result.timedOut || result.knownFailure !== void 0 || runnerKnownFailure !== void 0 || processCancelName !== void 0;
13616
- hostSignalFailed = directHostFailureSignal || result.code !== null && result.code !== 0 || resolution.knownFailure !== void 0;
13617
- settled = await adapters.trySettle(admitted, env.principalAuthority, courtScope);
13618
- if (settled !== void 0) {
13619
- settled = await attachRecordedSubmissions(admitted, settled, courtScope);
13620
- }
13621
- const settledIsFreshThisAttempt = settled === void 0 || settled.roleOutcome.kind !== "accepted" && settled.roleOutcome.kind !== "audit_escalation" ? true : await attemptProducedFreshSubmission(admitted, courtScope);
13622
- const staleAcceptanceOutranksRealFailure = !settledIsFreshThisAttempt && hostSignalFailed;
13623
- const cancelAfterSettle = processCancelSignalName(env.signal);
13624
- if (settled !== void 0 && shouldPresent(settled) && !directHostFailureSignal && !staleAcceptanceOutranksRealFailure && stderrLogWriteFailure === void 0 && cancelAfterSettle === void 0) {
13625
- if (settled.roleOutcome.kind === "accepted" && request.courtAttemptId !== void 0 && request.courtAttemptId.length > 0) {
13626
- try {
13627
- await clearCurrentCourt(admitted.runDirectory, request.courtAttemptId);
13628
- } catch (error) {
13629
- await recordBestEffortPostDispatchDiagnostic(
13630
- admitted,
13631
- env,
13632
- `current-court cleanup failed after accepted settlement (best-effort continue): ${describeErrorIdentity(error)}`,
13633
- io
13634
- );
13635
- }
13636
- }
13637
- settledOutcome = {
13638
- exitCode: exitCodeForTerminalOutcome(settled.roleOutcome),
14300
+ const settledTurn = await settleCompletedHostTurn({
14301
+ admitted,
14302
+ env,
14303
+ io,
14304
+ adapters,
14305
+ shouldPresent,
14306
+ request,
14307
+ result,
14308
+ persistRunState,
14309
+ deferredPersist,
14310
+ finishAfterTurn
14311
+ });
14312
+ if (settledTurn.kind === "settled") return settledTurn.outcome;
14313
+ while (akSeamDeliversReceipt && receiptDelivery.nextAction() === "request-delivery") {
14314
+ let deliveryResult;
14315
+ let deliveryTurnRequest;
14316
+ try {
14317
+ const deliveryRequest = await buildReceiptDeliveryRequest({
13639
14318
  admitted,
13640
- terminal: settled,
13641
- turnDispatched: true
14319
+ env,
14320
+ // Host and the other axes already selected on this turn ride the
14321
+ // shared projection. The pre-projection request does not have them.
14322
+ request: turnRequest,
14323
+ receiptDelivery
14324
+ });
14325
+ deliveryTurnRequest = {
14326
+ ...deliveryRequest,
14327
+ principal: admitted.principal,
14328
+ runDirectory: admitted.runDirectory,
14329
+ ...env.signal === void 0 ? {} : { signal: env.signal }
13642
14330
  };
13643
- }
13644
- } catch (error) {
13645
- const settledFailure = await settleAfterTurnStarted(
13646
- admitted,
13647
- withEngineDetourInvocationScope({
13648
- timedOut: false,
13649
- code: result.code,
13650
- stderr: result.stderr,
13651
- thrown: error
13652
- }, request.invocationScopeId),
13653
- adapters,
13654
- env.principalAuthority,
13655
- io,
13656
- persistRunState
13657
- );
13658
- return await finishAfterTurn({ ...settledFailure, turnDispatched: true, ...deferredPersist });
13659
- }
13660
- if (settledOutcome !== void 0) {
13661
- const lateCancel = processCancelSignalName(env.signal);
13662
- if (lateCancel !== void 0) {
13663
- return await finishAfterTurn(
13664
- await settleProcessCancelAfterTurn({
13665
- admitted,
13666
- cancelName: lateCancel,
13667
- result,
13668
- adapters,
13669
- env,
13670
- io,
13671
- persistRunState,
13672
- deferredPersist,
13673
- invocationScopeId: request.invocationScopeId
13674
- })
13675
- );
13676
- }
13677
- if (persistRunState) {
13678
- try {
13679
- await persistReturnedRunState(admitted, { lawful: true });
13680
- } catch (error) {
13681
- await recordBestEffortPostDispatchDiagnostic(
13682
- admitted,
13683
- env,
13684
- `run-state persistence failed beside host terminal (best-effort continue): ${describeErrorIdentity(error)}`,
13685
- io
13686
- );
13687
- }
13688
- }
13689
- return await finishAfterTurn({ ...settledOutcome, ...deferredPersist });
13690
- }
13691
- if (hostSignalFailed) {
13692
- const resolutionInput = controlledFailureInputFromResolution(resolution);
13693
- const processCancelName = processCancelSignalName(env.signal);
13694
- const stderrLogWriteDetails = stderrLogWriteFailure === void 0 ? void 0 : { stderrLogWriteFailure: describeCaughtError(stderrLogWriteFailure) };
13695
- const failed = await settleAfterTurnStarted(
13696
- admitted,
13697
- withEngineDetourInvocationScope({
13698
- timedOut: result.timedOut,
13699
- code: result.code,
13700
- stderr: result.stderr,
13701
- ...resolutionInput,
13702
- ...processCancelName === void 0 ? {} : { knownDiagnostic: processCancelDiagnostic(processCancelName) },
13703
- // Secondary fact only — never the cause. Rides on whichever channel
13704
- // classification actually reads (knownFailure.details owns it when
13705
- // a knownFailure exists; the top-level knownDetails otherwise).
13706
- ...stderrLogWriteDetails === void 0 ? {} : resolutionInput.knownFailure !== void 0 ? {
13707
- knownFailure: {
13708
- ...resolutionInput.knownFailure,
13709
- details: { ...resolutionInput.knownFailure.details ?? {}, ...stderrLogWriteDetails }
13710
- }
13711
- } : { knownDetails: stderrLogWriteDetails }
13712
- }, request.invocationScopeId),
13713
- adapters,
13714
- env.principalAuthority,
13715
- io,
13716
- persistRunState
13717
- );
13718
- return await finishAfterTurn(
13719
- withProcessCancelSkipAutoResume(
13720
- { ...failed, turnDispatched: true, ...deferredPersist },
13721
- env.signal
13722
- )
13723
- );
13724
- }
13725
- if (stderrLogWriteFailure !== void 0) {
13726
- const failed = await settleAfterTurnStarted(
14331
+ receiptDelivery.recordDeliveryRequest();
14332
+ deliveryResult = await env.roleTurnHost.executeTurn(deliveryTurnRequest);
14333
+ } catch (error) {
14334
+ const settled = await settleAfterTurnStarted(
14335
+ admitted,
14336
+ withEngineDetourInvocationScope(
14337
+ { timedOut: false, code: null, stderr: "", thrown: error },
14338
+ request.invocationScopeId
14339
+ ),
14340
+ adapters,
14341
+ env.principalAuthority,
14342
+ io,
14343
+ persistRunState
14344
+ );
14345
+ return await finishAfterTurn(
14346
+ withProcessCancelSkipAutoResume(
14347
+ {
14348
+ ...settled,
14349
+ turnDispatched: true,
14350
+ ...deferredPersist
14351
+ },
14352
+ env.signal
14353
+ )
14354
+ );
14355
+ }
14356
+ const deliveryTurn = await settleCompletedHostTurn({
13727
14357
  admitted,
13728
- withEngineDetourInvocationScope({
13729
- timedOut: false,
13730
- code: result.code,
13731
- stderr: result.stderr,
13732
- thrown: stderrLogWriteFailure
13733
- }, request.invocationScopeId),
14358
+ env,
14359
+ // Only the final Terminal presents; intermediate delivery attempts stay quiet.
14360
+ io: { ...io, stdout: () => {
14361
+ } },
13734
14362
  adapters,
13735
- env.principalAuthority,
13736
- io,
13737
- persistRunState
13738
- );
13739
- return await finishAfterTurn({ ...failed, turnDispatched: true, ...deferredPersist });
14363
+ shouldPresent,
14364
+ request: deliveryTurnRequest,
14365
+ result: deliveryResult,
14366
+ // Run-state terminal write belongs to the OUTERMOST turn only, so a
14367
+ // still-silent delivery attempt never makes the run look lawfully terminal.
14368
+ persistRunState: false,
14369
+ deferredPersist,
14370
+ finishAfterTurn
14371
+ });
14372
+ if (deliveryTurn.kind === "settled") {
14373
+ if (persistRunState && deliveryTurn.outcome.terminal !== void 0) {
14374
+ try {
14375
+ await persistReturnedRunState(admitted, {
14376
+ lawful: isLawfulTypedTerminalOutcome(deliveryTurn.outcome.terminal.roleOutcome)
14377
+ });
14378
+ } catch (error) {
14379
+ await recordBestEffortPostDispatchDiagnostic(
14380
+ admitted,
14381
+ env,
14382
+ `run-state persistence failed beside\u50AC\u4EA4 terminal (best-effort continue): ${describeErrorIdentity(error)}`,
14383
+ io
14384
+ );
14385
+ }
14386
+ }
14387
+ return await finishAfterTurn(deliveryTurn.outcome);
14388
+ }
13740
14389
  }
14390
+ const noReceiptScope = settlementScopeForTurn(request);
13741
14391
  const noReceipt = await attachRecordedSubmissions(
13742
14392
  admitted,
13743
- await settleHostEndedNoReceipt(admitted, env.principalAuthority, courtScope),
13744
- courtScope
14393
+ await settleHostEndedNoReceipt(
14394
+ admitted,
14395
+ env.principalAuthority,
14396
+ noReceiptScope,
14397
+ receiptDelivery.issuedDeliveryRequests()
14398
+ ),
14399
+ noReceiptScope
13745
14400
  );
13746
14401
  const noReceiptCancel = processCancelSignalName(env.signal);
13747
14402
  if (noReceiptCancel !== void 0) {
@@ -13778,6 +14433,11 @@ async function dispatchPostAdmissionTurn(input) {
13778
14433
  turnDispatched: true,
13779
14434
  ...deferredPersist
13780
14435
  });
14436
+ } catch (error) {
14437
+ if (turnDispatched && !(error instanceof TurnDispatchedFailure)) {
14438
+ throw new TurnDispatchedFailure(error);
14439
+ }
14440
+ throw error;
13781
14441
  } finally {
13782
14442
  if (lease !== void 0) {
13783
14443
  try {
@@ -13823,7 +14483,9 @@ function resumeTurnRequestProjectionOptions(admitted, request, env, summonsPrepa
13823
14483
  prompt
13824
14484
  },
13825
14485
  ...request.message === void 0 ? {} : { courtAttemptId: randomUUID7() },
13826
- ...env.stationChild === void 0 ? {} : { stationChild: env.stationChild }
14486
+ ...env.stationChild === void 0 ? {} : { stationChild: env.stationChild },
14487
+ // #1132: one configured ceiling, already resolved by the caller (#422).
14488
+ deliveryRequestLimit: deliveryLimitFromConfig(env.autoResumeLimit)
13827
14489
  };
13828
14490
  }
13829
14491
  function roleTurnOptions(env, admitted, continuation) {
@@ -13833,7 +14495,9 @@ function roleTurnOptions(env, admitted, continuation) {
13833
14495
  ...env.host === void 0 ? {} : { host: env.host },
13834
14496
  ...correlationId === void 0 || correlationId.trim() === "" ? {} : { correlationId },
13835
14497
  continuation,
13836
- ...env.stationChild === void 0 ? {} : { stationChild: env.stationChild }
14498
+ ...env.stationChild === void 0 ? {} : { stationChild: env.stationChild },
14499
+ // #1132: one configured ceiling, already resolved by the caller (#422).
14500
+ deliveryRequestLimit: deliveryLimitFromConfig(env.autoResumeLimit)
13837
14501
  };
13838
14502
  }
13839
14503
  async function dispatchAfterWriterLease(input) {
@@ -13851,6 +14515,7 @@ async function dispatchAfterWriterLease(input) {
13851
14515
  async function runSettledAutoResumeLoop(input) {
13852
14516
  const adapters = withOnceSuccessfulBeforeDispatch(input.adapters);
13853
14517
  const dispatchEnv = input.dispatchEnv ?? input.env;
14518
+ const receiptDelivery = createReceiptDeliveryPolicy(input.env.autoResumeLimit);
13854
14519
  return runWithAutoResumeLoop({
13855
14520
  admitted: input.admitted,
13856
14521
  principalAuthority: input.env.principalAuthority,
@@ -13872,6 +14537,7 @@ async function runSettledAutoResumeLoop(input) {
13872
14537
  ...lease === void 0 ? {} : { lease },
13873
14538
  adapters,
13874
14539
  persistRunState: false,
14540
+ receiptDelivery,
13875
14541
  ...input.effectiveEngine === void 0 ? {} : { effectiveEngine: input.effectiveEngine }
13876
14542
  });
13877
14543
  return settleDeferredPersist(
@@ -14234,12 +14900,14 @@ var init_post_admission = __esm({
14234
14900
  init_activation_ledger_topology();
14235
14901
  init_engine_material();
14236
14902
  init_session_identity();
14903
+ init_receipt_delivery_policy();
14237
14904
  init_role_run_relocation();
14238
14905
  init_packaged_role_registry();
14239
14906
  init_engine_detour_usage();
14240
14907
  init_run_lifecycle();
14241
14908
  init_process_cancel();
14242
14909
  init_activation_ledger_topology();
14910
+ init_host_descriptions();
14243
14911
  init_host_session_record();
14244
14912
  init_settlement();
14245
14913
  init_terminal();
@@ -14385,15 +15053,70 @@ function unreadablePostSubmissionStatus(admitted, terminal) {
14385
15053
  const route = POST_SUBMISSION_ROUTING[admitted.role];
14386
15054
  if (route === void 0) return void 0;
14387
15055
  const payload = terminal.roleOutcome.payloads?.at(-1);
14388
- const status = isRecord(payload) ? payload.status : void 0;
14389
- return typeof status === "string" && route.statuses.has(status) ? void 0 : route.reask;
15056
+ const status = receivedDiscriminator(payload, "status");
15057
+ return typeof status === "string" && route.statuses.has(status) ? void 0 : route.reask ?? officerConclusionReask(status);
15058
+ }
15059
+ function withUnreadableReask(env) {
15060
+ const spent = env.unreadableReasksSpent ?? 0;
15061
+ if (spent >= deliveryLimitFromConfig(env.autoResumeLimit)) return void 0;
15062
+ return { ...env, unreadableReasksSpent: spent + 1 };
15063
+ }
15064
+ function isUnreadableReaskExhausted(value) {
15065
+ return value === UNREADABLE_REASK_EXHAUSTED;
15066
+ }
15067
+ function presentOriginalVolume(held, terminal, io) {
15068
+ if (terminal?.roleOutcome.decisiveFacts?.directionUnsettled === true) {
15069
+ io.stdout(formatTerminalResult(terminal));
15070
+ return;
15071
+ }
15072
+ if (held.length > 0) {
15073
+ for (const value of held) io.stdout(value);
15074
+ return;
15075
+ }
15076
+ if (terminal !== void 0) io.stdout(formatTerminalResult(terminal));
15077
+ }
15078
+ function withUnsettledDirection(parent, officer) {
15079
+ const outcome = parent.roleOutcome;
15080
+ if (outcome.kind !== "accepted" && outcome.kind !== "audit_escalation") return parent;
15081
+ const officerOutcome = officer?.roleOutcome;
15082
+ const officerPayloads = coalesceSubmissionRows(
15083
+ officer?.submissions,
15084
+ officerOutcome !== void 0 && officerOutcome.kind !== "no_receipt" ? officerOutcome.payloads : void 0
15085
+ );
15086
+ return {
15087
+ ...parent,
15088
+ roleOutcome: {
15089
+ ...outcome,
15090
+ decisiveFacts: {
15091
+ ...outcome.decisiveFacts ?? {},
15092
+ directionUnsettled: true,
15093
+ subsequentAudit: "incomplete",
15094
+ ...officerOutcome === void 0 ? {} : { officerRole: officerOutcome.role },
15095
+ ...officer?.runId === void 0 ? {} : { officerRunId: officer.runId },
15096
+ ...officerPayloads.length === 0 ? {} : { officerPayloads }
15097
+ }
15098
+ }
15099
+ };
14390
15100
  }
14391
- async function reaskUnreadablePostSubmissionStatus(admitted, terminal, env, io) {
14392
- const message = unreadablePostSubmissionStatus(admitted, terminal);
15101
+ function heldUnreadableTerminal(terminal) {
15102
+ if (terminal?.roleOutcome.kind !== "accepted") return false;
15103
+ if (latestPayloadEscalated(terminal.roleOutcome)) return false;
15104
+ const status = latestQueueStatus(terminal);
15105
+ return typeof status !== "string" || !REVIEW_QUEUE_STATUSES.has(status);
15106
+ }
15107
+ function presentUnsettledAudit(parent, officer, io) {
15108
+ const terminal = withUnsettledDirection(parent, officer);
15109
+ io.stdout(formatTerminalResult(terminal));
15110
+ if (officer !== void 0) io.stdout(formatTerminalResult(officer));
15111
+ return terminal;
15112
+ }
15113
+ async function reaskUnreadablePostSubmissionStatus(admitted, terminal, env, io, message = unreadablePostSubmissionStatus(admitted, terminal)) {
14393
15114
  if (message === void 0) return void 0;
15115
+ const next = withUnreadableReask(env);
15116
+ if (next === void 0) return UNREADABLE_REASK_EXHAUSTED;
14394
15117
  return runPublicInstructionSeatResume(
14395
15118
  { runId: admitted.runId, message },
14396
- { ...env, autoResumeLimit: 0 },
15119
+ next,
14397
15120
  io
14398
15121
  );
14399
15122
  }
@@ -14547,6 +15270,11 @@ async function dispatchAdmitted(admitted, env, io) {
14547
15270
  env,
14548
15271
  io
14549
15272
  );
15273
+ if (isUnreadableReaskExhausted(unreadableReask)) {
15274
+ const terminal = result.terminal === void 0 ? void 0 : withUnsettledDirection(result.terminal);
15275
+ presentOriginalVolume(held, terminal, io);
15276
+ return terminal === void 0 ? result : { ...result, terminal };
15277
+ }
14550
15278
  if (unreadableReask !== void 0) return unreadableReask;
14551
15279
  if (AUDITED_ROLES.has(admitted.role) && result.terminal?.roleOutcome.kind === "accepted") {
14552
15280
  return auditSubmittedRole(result, env, io);
@@ -14678,20 +15406,16 @@ async function runCountersignBody(parsed, env, io) {
14678
15406
  await persistAdmittedSourceRunPath(admitted, gateParentRunPath);
14679
15407
  admitted = { ...admitted, sourceRunPath: gateParentRunPath };
14680
15408
  }
14681
- const turnProjection = {
14682
- ...projectPublicTurnAxes(env),
14683
- ...env.correlationId === void 0 || env.correlationId.trim() === "" ? {} : { correlationId: env.correlationId },
14684
- continuation: {
14685
- kind: "initial",
14686
- prompt: env.reviewReask ?? env.gateReviewInstruction ?? buildInstructionTransportPrompt(
14687
- admitted,
14688
- engineSessionMaterialFromOptions({
14689
- ...pickEngineAxis(env),
14690
- packageRoot: env.packageRoot
14691
- })
14692
- )
14693
- }
14694
- };
15409
+ const turnProjection = roleTurnOptions(env, admitted, {
15410
+ kind: "initial",
15411
+ prompt: env.reviewReask ?? env.gateReviewInstruction ?? buildInstructionTransportPrompt(
15412
+ admitted,
15413
+ engineSessionMaterialFromOptions({
15414
+ ...pickEngineAxis(env),
15415
+ packageRoot: env.packageRoot
15416
+ })
15417
+ )
15418
+ });
14695
15419
  const turnRequest = buildInstructionSeatTurnRequest(admitted, turnProjection);
14696
15420
  const result = await runPostAdmissionOneShot({
14697
15421
  admitted,
@@ -14960,7 +15684,23 @@ async function runPublicInstructionSeatResume(request, env, io) {
14960
15684
  },
14961
15685
  afterAdmittedLoad: async (admitted) => {
14962
15686
  await warnMissingMethodSkills(env.home, env.host, admitted.role, requiredMethodSkills(admitted), io.stdout);
14963
- return { kind: "continue", adapters: seatAdapters(admitted, env) };
15687
+ const adapters = seatAdapters(admitted, env);
15688
+ if ((env.unreadableReasksSpent ?? 0) === 0 && env.reviewReask === void 0) {
15689
+ return { kind: "continue", adapters };
15690
+ }
15691
+ const original = await adapters.trySettle(
15692
+ admitted,
15693
+ env.principalAuthority,
15694
+ await readCurrentCourt(admitted.runDirectory)
15695
+ );
15696
+ const unsettled = POST_SUBMISSION_ROUTING[admitted.role] === void 0 ? heldUnreadableTerminal(original) : unreadablePostSubmissionStatus(admitted, original) !== void 0;
15697
+ return {
15698
+ kind: "continue",
15699
+ adapters: original === void 0 || !unsettled ? adapters : {
15700
+ ...adapters,
15701
+ trySettle: async (seat, authority, scope) => await adapters.trySettle(seat, authority, scope) ?? original
15702
+ }
15703
+ };
14964
15704
  },
14965
15705
  ...env.engine === void 0 ? {} : { effectiveEngine: env.engine }
14966
15706
  });
@@ -14970,6 +15710,11 @@ async function runPublicInstructionSeatResume(request, env, io) {
14970
15710
  env,
14971
15711
  io
14972
15712
  );
15713
+ if (isUnreadableReaskExhausted(unreadableReask)) {
15714
+ const terminal = result.terminal === void 0 ? void 0 : withUnsettledDirection(result.terminal);
15715
+ presentOriginalVolume(held, terminal, io);
15716
+ return terminal === void 0 ? result : { ...result, terminal };
15717
+ }
14973
15718
  if (unreadableReask !== void 0) return unreadableReask;
14974
15719
  if (result.admitted !== void 0 && AUDITED_ROLES.has(result.admitted.role) && result.terminal?.roleOutcome.kind === "accepted") {
14975
15720
  return auditSubmittedRole(result, env, io);
@@ -14995,26 +15740,46 @@ async function runPublicInstructionSeatResume(request, env, io) {
14995
15740
  }
14996
15741
  async function queueConclusionFromChild(child, env, io) {
14997
15742
  if (!GATE_CHILD_ROLES.has(child.role)) return void 0;
15743
+ if (child.role === "countersign") {
15744
+ const terminal = await trySettlePublicSeat(
15745
+ child,
15746
+ env.principalAuthority,
15747
+ await readCurrentCourt(child.runDirectory)
15748
+ );
15749
+ const status = latestQueueStatus(terminal);
15750
+ if (terminal !== void 0 && typeof status === "string" && REVIEW_QUEUE_STATUSES.has(status)) {
15751
+ return { admitted: child, terminal, status };
15752
+ }
15753
+ return { stop: { exitCode: 0, ...terminal === void 0 ? {} : { terminal } } };
15754
+ }
14998
15755
  let current = child;
15756
+ let budgetEnv = { ...env, unreadableReasksSpent: 0 };
14999
15757
  for (; ; ) {
15000
15758
  const terminal = await trySettlePublicSeat(
15001
15759
  current,
15002
15760
  env.principalAuthority,
15003
- void 0
15761
+ await readCurrentCourt(current.runDirectory)
15004
15762
  );
15005
15763
  const status = latestQueueStatus(terminal);
15006
- if (terminal !== void 0 && status !== void 0 && QUEUE_CONCLUSIONS.has(status)) {
15764
+ if (terminal !== void 0 && typeof status === "string" && REVIEW_QUEUE_STATUSES.has(status)) {
15007
15765
  return { admitted: current, terminal, status };
15008
15766
  }
15009
- const reasked = await runPublicInstructionSeatResume({
15010
- runId: current.runId,
15011
- message: officerConclusionReask(status)
15012
- }, env, io);
15013
- if (reasked.exitCode !== 0 || reasked.admitted === void 0 || reasked.terminal === void 0) {
15767
+ const reasked = await reaskUnreadablePostSubmissionStatus(
15768
+ current,
15769
+ terminal,
15770
+ budgetEnv,
15771
+ io,
15772
+ officerConclusionReask(status)
15773
+ );
15774
+ if (reasked === void 0 || isUnreadableReaskExhausted(reasked)) {
15775
+ return { stop: { exitCode: 0, ...terminal === void 0 ? {} : { terminal } } };
15776
+ }
15777
+ budgetEnv = withUnreadableReask(budgetEnv);
15778
+ if (reasked.exitCode !== 0 || reasked.admitted === void 0 || reasked.terminal === void 0 || reasked.terminal.roleOutcome.kind === "no_receipt" || reasked.terminal.roleOutcome.decisiveFacts?.directionUnsettled === true) {
15014
15779
  return { stop: reasked };
15015
15780
  }
15016
15781
  const reaskedStatus = latestQueueStatus(reasked.terminal);
15017
- if (reaskedStatus !== void 0 && QUEUE_CONCLUSIONS.has(reaskedStatus)) {
15782
+ if (typeof reaskedStatus === "string" && REVIEW_QUEUE_STATUSES.has(reaskedStatus)) {
15018
15783
  return { admitted: reasked.admitted, terminal: reasked.terminal, status: reaskedStatus };
15019
15784
  }
15020
15785
  if (latestPayloadEscalated(reasked.terminal.roleOutcome)) return { stop: reasked };
@@ -15028,7 +15793,17 @@ async function continueParentAfterChild(parentRunId, child, env, io) {
15028
15793
  }
15029
15794
  const admitted = loaded.admitted;
15030
15795
  const resolved = await queueConclusionFromChild(child, env, io);
15031
- if (resolved !== void 0 && "stop" in resolved) return resolved.stop;
15796
+ if (resolved !== void 0 && "stop" in resolved) {
15797
+ const stopped = resolved.stop;
15798
+ if (stopped.exitCode === 0 && heldUnreadableTerminal(stopped.terminal) && stopped.terminal !== void 0) {
15799
+ const parentTerminal = await trySettlePublicSeat(admitted, env.principalAuthority, void 0);
15800
+ if (parentTerminal?.roleOutcome.kind === "accepted" || parentTerminal?.roleOutcome.kind === "audit_escalation") {
15801
+ const terminal = presentUnsettledAudit(parentTerminal, stopped.terminal, io);
15802
+ return { exitCode: 0, admitted, terminal };
15803
+ }
15804
+ }
15805
+ return stopped;
15806
+ }
15032
15807
  if (resolved !== void 0 && resolved.status === "escalate") {
15033
15808
  return { exitCode: 0, admitted: resolved.admitted, terminal: resolved.terminal };
15034
15809
  }
@@ -15036,37 +15811,67 @@ async function continueParentAfterChild(parentRunId, child, env, io) {
15036
15811
  if (AUDITED_ROLES.has(admitted.role) && resolved.status === "converged") {
15037
15812
  const terminal = await trySettlePublicSeat(admitted, env.principalAuthority, void 0);
15038
15813
  if (terminal?.roleOutcome.kind !== "accepted") throw new Error("pending submission is not recorded");
15039
- return auditSubmittedRole({ exitCode: 0, admitted, terminal }, env, io, resolved.admitted.role, latestQueuePayload(resolved.terminal), resolved.admitted.runId);
15814
+ return auditSubmittedRole({ exitCode: 0, admitted, terminal }, env, io, resolved.admitted, latestQueuePayload(resolved.terminal));
15040
15815
  }
15041
15816
  return runPublicInstructionSeatResume({
15042
15817
  runId: parentRunId,
15043
15818
  message: readableGateItem(latestQueuePayload(resolved.terminal))
15044
- }, { ...env, autoResumeLimit: 0 }, io);
15819
+ }, { ...env, unreadableReasksSpent: 0 }, io);
15045
15820
  }
15046
15821
  const result = await dispatchAdmitted(admitted, env, { ...io, omitFailureStderrDiagnostic: true });
15047
15822
  showResumeErrorPointer(io, result.exitCode, result.terminal);
15048
15823
  return result;
15049
15824
  }
15050
- async function auditSubmittedRole(turn, env, io, passedOfficer, passedReceipt, passedRunId) {
15825
+ async function officerPassedCurrentSubmission(input) {
15826
+ const { env, officer } = input;
15827
+ const pointer = await readDirectOfficerRunPointer(input.parentSessionFile, officer);
15828
+ if (pointer?.runDirectory === void 0) return false;
15829
+ if (pointer.submissionToolCallId !== input.toolCallId) return false;
15830
+ const officerRunId = runIdFromRunDirectory(pointer.runDirectory);
15831
+ if (officerRunId === void 0) return false;
15832
+ let admitted;
15833
+ try {
15834
+ const loaded = await loadResumablePublicRole(
15835
+ env.home,
15836
+ officerRunId,
15837
+ env.principalAuthority
15838
+ );
15839
+ admitted = loaded.admitted;
15840
+ } catch {
15841
+ return false;
15842
+ }
15843
+ if (admitted.role !== officer) return false;
15844
+ const court = await readCurrentCourt(admitted.runDirectory);
15845
+ const terminal = await trySettlePublicSeat(admitted, env.principalAuthority, court);
15846
+ return latestQueueStatus(terminal) === "converged";
15847
+ }
15848
+ async function auditSubmittedRole(turn, env, io, resumedOfficer, passedReceipt) {
15051
15849
  const admitted = turn.admitted;
15052
15850
  if (admitted === void 0 || !AUDITED_ROLES.has(admitted.role) || turn.terminal?.roleOutcome.kind !== "accepted") return turn;
15053
15851
  const accepted = turn.terminal.roleOutcome.payloads?.at(-1);
15054
15852
  if (accepted === void 0) throw new Error("accepted submission has no payload");
15055
15853
  const record = isRecord(accepted) ? accepted : void 0;
15056
15854
  const status = admitted.role === "secretariat" ? record?.secretariatStatus : record?.status;
15855
+ const gateOwnsStatusReask = typeof env.parentRunPath === "string" && env.parentRunPath.trim() !== "";
15057
15856
  if (admitted.role === "secretariat" && status !== "converged" && status !== "escalate") {
15058
- return runPublicInstructionSeatResume(
15059
- { runId: admitted.runId, message: SECRETARIAT_STATUS_REASK },
15060
- { ...env, autoResumeLimit: 0 },
15061
- io
15062
- );
15857
+ if (gateOwnsStatusReask) return turn;
15858
+ const next = withUnreadableReask(env);
15859
+ if (next === void 0) {
15860
+ const terminal2 = withUnsettledDirection(turn.terminal);
15861
+ io.stdout(formatTerminalResult(terminal2));
15862
+ return { ...turn, terminal: terminal2 };
15863
+ }
15864
+ return runPublicInstructionSeatResume({ runId: admitted.runId, message: SECRETARIAT_STATUS_REASK }, next, io);
15063
15865
  }
15064
- if (admitted.role === "countersign" && (typeof status !== "string" || !QUEUE_CONCLUSIONS.has(status))) {
15065
- return runPublicInstructionSeatResume(
15066
- { runId: admitted.runId, message: COUNTERSIGN_STATUS_REASK },
15067
- { ...env, autoResumeLimit: 0 },
15068
- io
15069
- );
15866
+ if (admitted.role === "countersign" && (typeof status !== "string" || !REVIEW_QUEUE_STATUSES.has(status))) {
15867
+ if (gateOwnsStatusReask) return turn;
15868
+ const next = withUnreadableReask(env);
15869
+ if (next === void 0) {
15870
+ const terminal2 = withUnsettledDirection(turn.terminal);
15871
+ io.stdout(formatTerminalResult(terminal2));
15872
+ return { ...turn, terminal: terminal2 };
15873
+ }
15874
+ return runPublicInstructionSeatResume({ runId: admitted.runId, message: officerConclusionReask(status) }, next, io);
15070
15875
  }
15071
15876
  const selfEscalationSkipsAudit = status === "escalate" && (admitted.role === "judge" || admitted.role === "secretariat" || admitted.role === "countersign");
15072
15877
  const skipAudit = selfEscalationSkipsAudit || (admitted.role === "fixer" || admitted.role === "coder") && (typeof status !== "string" || !WORKER_DONE_STATUSES.has(status));
@@ -15096,12 +15901,19 @@ async function auditSubmittedRole(turn, env, io, passedOfficer, passedReceipt, p
15096
15901
  abort() {
15097
15902
  }
15098
15903
  };
15904
+ const passedThisSubmission = (officer) => officerPassedCurrentSubmission({
15905
+ env,
15906
+ parentSessionFile: sessionFile,
15907
+ officer,
15908
+ toolCallId
15909
+ });
15099
15910
  if (admitted.role === "doctor") {
15100
- if (passedOfficer !== "auditor") {
15911
+ if (!await passedThisSubmission("auditor")) {
15101
15912
  let lastSummon;
15102
15913
  const decision = await createPiDoctorAuditor()({
15103
15914
  context,
15104
15915
  submission: accepted,
15916
+ ...env.autoResumeLimit === void 0 ? {} : { autoResumeLimit: env.autoResumeLimit },
15105
15917
  ...env.signal === void 0 ? {} : { signal: env.signal },
15106
15918
  summonAuditor: async (subject, sourceRunDirectory, signal, reask, submission) => {
15107
15919
  const summoned = await summonPublicRole({
@@ -15130,6 +15942,7 @@ async function auditSubmittedRole(turn, env, io, passedOfficer, passedReceipt, p
15130
15942
  parentSessionFile: sessionFile,
15131
15943
  officer: "auditor",
15132
15944
  sessionFile: officerSession,
15945
+ submissionToolCallId: toolCallId,
15133
15946
  ...summoned.runDirectory === void 0 ? {} : { runDirectory: summoned.runDirectory }
15134
15947
  });
15135
15948
  }
@@ -15141,7 +15954,15 @@ async function auditSubmittedRole(turn, env, io, passedOfficer, passedReceipt, p
15141
15954
  return runPublicInstructionSeatResume({
15142
15955
  runId: admitted.runId,
15143
15956
  message: readableGateItem(decision.receipt ?? decision.violations)
15144
- }, { ...env, autoResumeLimit: 0 }, io);
15957
+ }, { ...env, unreadableReasksSpent: 0 }, io);
15958
+ }
15959
+ if (decision.status === "received") {
15960
+ if (lastSummon?.terminal === void 0) {
15961
+ throw new Error("doctor audit kept an unreadable reply with no terminal");
15962
+ }
15963
+ if (turn.terminal === void 0) throw new Error("doctor submission has no terminal");
15964
+ const terminal2 = presentUnsettledAudit(turn.terminal, lastSummon.terminal, io);
15965
+ return { exitCode: 0, admitted, terminal: terminal2 };
15145
15966
  }
15146
15967
  if (decision.status !== "converged") {
15147
15968
  if (lastSummon?.terminal !== void 0) {
@@ -15164,13 +15985,14 @@ async function auditSubmittedRole(turn, env, io, passedOfficer, passedReceipt, p
15164
15985
  ...env.hostAdapters === void 0 ? {} : { hostAdapters: env.hostAdapters }
15165
15986
  });
15166
15987
  let chain;
15167
- let officerRunId = passedRunId;
15988
+ let officerRunId = resumedOfficer?.runId;
15168
15989
  const runGate = (subject) => requireSubmissionGate({
15169
15990
  context,
15170
15991
  subject,
15171
15992
  toolCallId,
15172
15993
  submission: accepted,
15173
15994
  summonOfficer,
15995
+ ...env.autoResumeLimit === void 0 ? {} : { autoResumeLimit: env.autoResumeLimit },
15174
15996
  ...env.signal === void 0 ? {} : { signal: env.signal },
15175
15997
  hostActions: {
15176
15998
  failInfrastructure(error) {
@@ -15182,13 +16004,13 @@ async function auditSubmittedRole(turn, env, io, passedOfficer, passedReceipt, p
15182
16004
  });
15183
16005
  if (admitted.role === "judge") {
15184
16006
  chain = await runJudgeGates({
15185
- gateAlreadyConverged: async (subject) => passedOfficer === "auditor" || passedOfficer === "notary" && subject.kind === "judge_draft",
16007
+ gateAlreadyConverged: async (subject) => passedThisSubmission(gateOfficerForSubject(subject)),
15186
16008
  runGate
15187
16009
  });
15188
16010
  } else {
15189
16011
  const subject = admitted.role === "fixer" || admitted.role === "coder" ? { kind: "worker_completion" } : admitted.role === "secretariat" ? { kind: "secretariat_verdict" } : { kind: "countersign_verdict" };
15190
16012
  const officer = gateOfficerForSubject(subject);
15191
- if (passedOfficer === officer) {
16013
+ if (await passedThisSubmission(officer)) {
15192
16014
  chain = { status: "converged", passes: [] };
15193
16015
  } else {
15194
16016
  const pass = await runGate(subject);
@@ -15201,17 +16023,29 @@ async function auditSubmittedRole(turn, env, io, passedOfficer, passedReceipt, p
15201
16023
  status: pass.status,
15202
16024
  receipt: pass.receipt,
15203
16025
  ...pass.runId === void 0 ? {} : { runId: pass.runId },
15204
- ...pass.runDirectory === void 0 ? {} : { runDirectory: pass.runDirectory }
16026
+ ...pass.runDirectory === void 0 ? {} : { runDirectory: pass.runDirectory },
16027
+ ...pass.terminal === void 0 ? {} : { terminal: pass.terminal }
15205
16028
  }]
15206
16029
  };
15207
16030
  }
15208
16031
  }
16032
+ if (chain.status === "needs_reask") {
16033
+ const officerTerminal = chain.passes.at(-1)?.terminal;
16034
+ if (officerTerminal === void 0) throw new Error("unreadable audit has no terminal result");
16035
+ if (turn.terminal === void 0) throw new Error("audited submission has no terminal");
16036
+ const terminal2 = presentUnsettledAudit(turn.terminal, officerTerminal, io);
16037
+ return { exitCode: 0, admitted, terminal: terminal2 };
16038
+ }
15209
16039
  if (chain.status === "escalate") {
15210
16040
  const escalation = chain.passes.at(-1);
15211
16041
  const escalatedRunId = escalation?.runId ?? (escalation?.runDirectory === void 0 ? void 0 : runIdFromRunDirectory(escalation.runDirectory));
15212
16042
  if (escalatedRunId === void 0) throw new Error("escalated audit has no resumable run identity");
15213
16043
  const officer = await loadResumablePublicRole(env.home, escalatedRunId, env.principalAuthority);
15214
- const terminal2 = await trySettlePublicSeat(officer.admitted, env.principalAuthority, void 0);
16044
+ const terminal2 = await trySettlePublicSeat(
16045
+ officer.admitted,
16046
+ env.principalAuthority,
16047
+ await readCurrentCourt(officer.admitted.runDirectory)
16048
+ );
15215
16049
  if (terminal2 === void 0) throw new Error("escalated audit has no terminal result");
15216
16050
  io.stdout(formatTerminalResult(terminal2));
15217
16051
  return { exitCode: 0, admitted: officer.admitted, terminal: terminal2 };
@@ -15220,7 +16054,7 @@ async function auditSubmittedRole(turn, env, io, passedOfficer, passedReceipt, p
15220
16054
  return runPublicInstructionSeatResume({
15221
16055
  runId: admitted.runId,
15222
16056
  message: readableGateItem(chain.passes.at(-1)?.receipt)
15223
- }, { ...env, autoResumeLimit: 0 }, io);
16057
+ }, { ...env, unreadableReasksSpent: 0 }, io);
15224
16058
  }
15225
16059
  if (admitted.role === "secretariat") {
15226
16060
  const pass = chain.passes.at(-1);
@@ -15240,7 +16074,7 @@ async function auditSubmittedRole(turn, env, io, passedOfficer, passedReceipt, p
15240
16074
  io.stdout(formatTerminalResult(terminal));
15241
16075
  return turn;
15242
16076
  }
15243
- var AUDITED_ROLES, SECRETARIAT_STATUS_REASK, COUNTERSIGN_STATUS_REASK, WORKER_ROUTING_STATUSES, WORKER_STATUS_REASK, DOCTOR_ROUTING_STATUSES, DOCTOR_STATUS_REASK, POST_SUBMISSION_ROUTING, QUEUE_CONCLUSIONS, GATE_CHILD_ROLES;
16077
+ var AUDITED_ROLES, SECRETARIAT_STATUS_REASK, WORKER_ROUTING_STATUSES, WORKER_STATUS_REASK, DOCTOR_ROUTING_STATUSES, DOCTOR_STATUS_REASK, POST_SUBMISSION_ROUTING, UNREADABLE_REASK_EXHAUSTED, GATE_CHILD_ROLES;
15244
16078
  var init_instruction_seat_run = __esm({
15245
16079
  "src/public-cli/instruction-seat-run.ts"() {
15246
16080
  "use strict";
@@ -15249,10 +16083,13 @@ var init_instruction_seat_run = __esm({
15249
16083
  init_archivist_record_pointer();
15250
16084
  init_doctor_auditor();
15251
16085
  init_gatekeeper_role();
16086
+ init_submission_errors();
16087
+ init_review_submission();
15252
16088
  init_judge_role();
15253
16089
  init_worker_submission_contracts();
15254
16090
  init_secretariat_contracts();
15255
16091
  init_readable_gate_item();
16092
+ init_receipt_delivery_policy();
15256
16093
  init_run_terminal_artifacts();
15257
16094
  init_submission_gate();
15258
16095
  init_submission_ledger();
@@ -15277,7 +16114,6 @@ var init_instruction_seat_run = __esm({
15277
16114
  init_unknown_value();
15278
16115
  AUDITED_ROLES = /* @__PURE__ */ new Set(["judge", "fixer", "coder", "secretariat", "countersign", "doctor"]);
15279
16116
  SECRETARIAT_STATUS_REASK = "secretariatStatus \u4E0D\u662F converged\u3001escalate \u4E4B\u4E00\u3002\u8BF7\u91CD\u65B0\u4EA4\u5377\uFF0CsecretariatStatus \u5199\u660E\u5176\u4E00\u3002";
15280
- COUNTERSIGN_STATUS_REASK = "status \u4E0D\u662F converged\u3001continue\u3001escalate \u4E09\u6001\u4E4B\u4E00\u3002\u8BF7\u91CD\u65B0\u4EA4\u5377\uFF0Cstatus \u5199\u660E\u5176\u4E00\u3002";
15281
16117
  WORKER_ROUTING_STATUSES = /* @__PURE__ */ new Set([
15282
16118
  "planned",
15283
16119
  "completed",
@@ -15290,8 +16126,7 @@ var init_instruction_seat_run = __esm({
15290
16126
  DOCTOR_STATUS_REASK = "status \u4E0D\u662F completed\u3001refused \u4E4B\u4E00\u3002\u8BF7\u91CD\u65B0\u4EA4\u5377\uFF0Cstatus \u5199\u660E\u5176\u4E00\u3002";
15291
16127
  POST_SUBMISSION_ROUTING = {
15292
16128
  judge: {
15293
- statuses: /* @__PURE__ */ new Set(["converged", "continue", "escalate"]),
15294
- reask: "status \u4E0D\u662F converged\u3001continue\u3001escalate \u4E09\u6001\u4E4B\u4E00\u3002\u8BF7\u91CD\u65B0\u4EA4\u5377\uFF0Cstatus \u5199\u660E\u5176\u4E00\u3002"
16129
+ statuses: REVIEW_QUEUE_STATUSES
15295
16130
  },
15296
16131
  coder: {
15297
16132
  statuses: WORKER_ROUTING_STATUSES,
@@ -15312,7 +16147,7 @@ var init_instruction_seat_run = __esm({
15312
16147
  reask: DOCTOR_STATUS_REASK
15313
16148
  }
15314
16149
  };
15315
- QUEUE_CONCLUSIONS = /* @__PURE__ */ new Set(["converged", "continue", "escalate"]);
16150
+ UNREADABLE_REASK_EXHAUSTED = { unreadableReaskExhausted: true };
15316
16151
  GATE_CHILD_ROLES = /* @__PURE__ */ new Set(["notary", "auditor", "inspector", "countersign"]);
15317
16152
  }
15318
16153
  });
@@ -15352,7 +16187,7 @@ var init_analyst_book_key = __esm({
15352
16187
  });
15353
16188
 
15354
16189
  // src/analyst-index.ts
15355
- import { open as open2, readFile as readFile18, unlink as unlink4 } from "node:fs/promises";
16190
+ import { open as open2, readFile as readFile19, unlink as unlink4 } from "node:fs/promises";
15356
16191
  import { dirname as dirname21, join as join34 } from "node:path";
15357
16192
  import { setTimeout as sleep } from "node:timers/promises";
15358
16193
  async function withAnalystLibraryIndexLock(ledgerHome, fn) {
@@ -15476,7 +16311,7 @@ async function readAnalystLibraryIndexPage(ledgerHome) {
15476
16311
  const path = analystLibraryIndexPath(ledgerHome);
15477
16312
  let raw;
15478
16313
  try {
15479
- raw = await readFile18(path, "utf8");
16314
+ raw = await readFile19(path, "utf8");
15480
16315
  } catch (error) {
15481
16316
  if (isMissingPathError(error)) return void 0;
15482
16317
  throw error;
@@ -15679,7 +16514,7 @@ var init_analyst_cohort = __esm({
15679
16514
  });
15680
16515
 
15681
16516
  // src/analyst-ledger.ts
15682
- import { readdir as readdir6, readFile as readFile19 } from "node:fs/promises";
16517
+ import { readdir as readdir6, readFile as readFile20 } from "node:fs/promises";
15683
16518
  import { basename as basename9, join as join35 } from "node:path";
15684
16519
  async function readExistingRunLifecycleState(runDirectory) {
15685
16520
  return (await readRoleRunIdentity(runDirectory))?.state;
@@ -15729,7 +16564,7 @@ async function listLedgerBookNames(booksRoot) {
15729
16564
  async function readInvocationScopeFields(runDirectory) {
15730
16565
  let raw;
15731
16566
  try {
15732
- raw = await readFile19(join35(runDirectory, "invocation.json"), "utf8");
16567
+ raw = await readFile20(join35(runDirectory, "invocation.json"), "utf8");
15733
16568
  } catch (error) {
15734
16569
  if (isMissingPathError(error)) return void 0;
15735
16570
  throw error;
@@ -15762,7 +16597,7 @@ function decideIssueScope(input) {
15762
16597
  }
15763
16598
  async function resolveSessionFile(runDirectory) {
15764
16599
  try {
15765
- const raw = await readFile19(join35(runDirectory, "invocation.json"), "utf8");
16600
+ const raw = await readFile20(join35(runDirectory, "invocation.json"), "utf8");
15766
16601
  const parsed = JSON.parse(raw);
15767
16602
  if (isRecord(parsed) && typeof parsed.sessionFile === "string" && parsed.sessionFile.trim() !== "") {
15768
16603
  return parsed.sessionFile;
@@ -17022,8 +17857,8 @@ var init_analyst_model_groups = __esm({
17022
17857
  });
17023
17858
 
17024
17859
  // src/analyst-entry.ts
17025
- import { readFile as readFile20 } from "node:fs/promises";
17026
- import { Type as Type12 } from "typebox";
17860
+ import { readFile as readFile21 } from "node:fs/promises";
17861
+ import { Type as Type18 } from "typebox";
17027
17862
  function cachedPageMatchesRequestedScope(page, input) {
17028
17863
  if (page.bookKey !== input.bookKey) return false;
17029
17864
  const requestedTicket = input.ticketNumber ?? input.issueNumber;
@@ -17050,7 +17885,7 @@ async function readOrComputeAnalystIssuePage(input, options) {
17050
17885
  ...issueNumber === void 0 && input.bookKey === void 0 ? { scopeRootIdentity: projectRoot } : {}
17051
17886
  });
17052
17887
  try {
17053
- const raw = await readFile20(pagePath, "utf8");
17888
+ const raw = await readFile21(pagePath, "utf8");
17054
17889
  const page = JSON.parse(raw);
17055
17890
  if (cachedPageMatchesRequestedScope(page, { bookKey, ...input })) {
17056
17891
  const ghostScan = await scanAnalystIssueRuns({
@@ -17151,7 +17986,7 @@ async function runAnalystModelGroupsMode(input, home) {
17151
17986
  scopeRootIdentity: projectRoot
17152
17987
  });
17153
17988
  try {
17154
- const raw = await readFile20(pagePath, "utf8");
17989
+ const raw = await readFile21(pagePath, "utf8");
17155
17990
  JSON.parse(raw);
17156
17991
  } catch (error) {
17157
17992
  if (!isMissingPathError(error)) {
@@ -17228,16 +18063,16 @@ var init_analyst_entry = __esm({
17228
18063
  }
17229
18064
  }
17230
18065
  };
17231
- analystSweepModeInputSchema = Type12.Object(
18066
+ analystSweepModeInputSchema = Type18.Object(
17232
18067
  {
17233
- mode: Type12.Literal("sweep"),
17234
- mergedPullRequests: Type12.Array(
17235
- Type12.Object(
18068
+ mode: Type18.Literal("sweep"),
18069
+ mergedPullRequests: Type18.Array(
18070
+ Type18.Object(
17236
18071
  {
17237
- projectRoot: Type12.String(),
18072
+ projectRoot: Type18.String(),
17238
18073
  /** 排除后改动行数 — omit or 0 → typed 空缺; finite ≥ 0 only. */
17239
- changedLines: Type12.Optional(
17240
- Type12.Number({ minimum: 0, maximum: Number.MAX_VALUE })
18074
+ changedLines: Type18.Optional(
18075
+ Type18.Number({ minimum: 0, maximum: Number.MAX_VALUE })
17241
18076
  )
17242
18077
  }
17243
18078
  )
@@ -17248,7 +18083,7 @@ var init_analyst_entry = __esm({
17248
18083
  });
17249
18084
 
17250
18085
  // src/public-cli/analyst-run.ts
17251
- import { readFile as readFile21 } from "node:fs/promises";
18086
+ import { readFile as readFile22 } from "node:fs/promises";
17252
18087
  import { isAbsolute as isAbsolute9, resolve as resolve15 } from "node:path";
17253
18088
  import { Value as Value3 } from "typebox/value";
17254
18089
  function resolveAnalystIssueBookKeyFromCwd(cwd = process.cwd()) {
@@ -17302,7 +18137,7 @@ async function buildAnalystSweepModeInputFromAttachmentPaths(attachmentPaths) {
17302
18137
  const absolute = isAbsolute9(sourcePath) ? sourcePath : resolve15(sourcePath);
17303
18138
  let bytes;
17304
18139
  try {
17305
- bytes = await readFile21(absolute);
18140
+ bytes = await readFile22(absolute);
17306
18141
  } catch (error) {
17307
18142
  throw new CliUsageError(
17308
18143
  `analyst sweep attachment is not a readable regular file: ${sourcePath}`,
@@ -18190,7 +19025,7 @@ async function runAkRole(argv, env) {
18190
19025
  io
18191
19026
  );
18192
19027
  let current = result;
18193
- while (current.exitCode === 0 && current.admitted?.correlationId !== void 0 && current.terminal?.roleOutcome.kind === "accepted" && !latestPayloadEscalated(current.terminal.roleOutcome)) {
19028
+ while (current.exitCode === 0 && current.admitted?.correlationId !== void 0 && current.terminal?.roleOutcome.kind === "accepted" && current.terminal.roleOutcome.decisiveFacts?.directionUnsettled !== true && !latestPayloadEscalated(current.terminal.roleOutcome)) {
18194
19029
  const parentRunId = current.admitted.correlationId;
18195
19030
  resumeFailureContext = {
18196
19031
  home,
@@ -18936,10 +19771,14 @@ async function runComplianceAudit(options) {
18936
19771
  });
18937
19772
  });
18938
19773
  let reask;
19774
+ let reasksSpent = 0;
19775
+ const reaskLimit = deliveryLimitFromConfig(options.autoResumeLimit);
18939
19776
  for (; ; ) {
18940
19777
  const summoned = await summon(subject, runDirectory, options.signal, reask, submission);
18941
19778
  const decision = await projectAuditorTerminal(summoned);
18942
19779
  if (decision.status === "received") {
19780
+ if (reasksSpent >= reaskLimit) return decision;
19781
+ reasksSpent += 1;
18943
19782
  reask = officerConclusionReask(receivedDiscriminator(decision.reply, "status"));
18944
19783
  continue;
18945
19784
  }
@@ -18955,6 +19794,7 @@ var init_compliance_transport = __esm({
18955
19794
  init_submission_errors();
18956
19795
  init_terminal();
18957
19796
  init_readable_gate_item();
19797
+ init_receipt_delivery_policy();
18958
19798
  init_unknown_value();
18959
19799
  AUDITOR_DOSSIER_PROMPT = "\u5377\u5B97\u6307\u9488\uFF1A";
18960
19800
  AUDITOR_PARENT_ATTEMPT_BINDING_ENTRY_TYPE = "ak_auditor_parent_attempt_binding";
@@ -19094,7 +19934,7 @@ __export(run_lifecycle_exports, {
19094
19934
  renderResumeCommand: () => renderResumeCommand,
19095
19935
  writeRoleRunState: () => writeRoleRunState
19096
19936
  });
19097
- import { chmod, lstat as lstat6, open as open3, readdir as readdir7, readFile as readFile22, unlink as unlink5, writeFile as writeFile8 } from "node:fs/promises";
19937
+ import { chmod, lstat as lstat6, open as open3, readdir as readdir7, readFile as readFile23, unlink as unlink5, writeFile as writeFile8 } from "node:fs/promises";
19098
19938
  import { basename as basename10, join as join39 } from "node:path";
19099
19939
  function buildAutoResumeContinuationPrompt(options) {
19100
19940
  return appendEngineSessionMaterial(
@@ -19171,7 +20011,7 @@ function parseCurrentCourtState(raw) {
19171
20011
  async function readRoleRunStateRaw(runDirectory) {
19172
20012
  let raw;
19173
20013
  try {
19174
- raw = JSON.parse(await readFile22(join39(runDirectory, RUN_STATE_FILE), "utf8"));
20014
+ raw = JSON.parse(await readFile23(join39(runDirectory, RUN_STATE_FILE), "utf8"));
19175
20015
  } catch (error) {
19176
20016
  if (errorCodeOf(error) === "ENOENT") return void 0;
19177
20017
  throw error;
@@ -19429,7 +20269,7 @@ function isProcessAlive(pid) {
19429
20269
  async function autopsyWriterLock(lockPath) {
19430
20270
  let content;
19431
20271
  try {
19432
- content = await readFile22(lockPath, "utf8");
20272
+ content = await readFile23(lockPath, "utf8");
19433
20273
  } catch (error) {
19434
20274
  if (errorCodeOf(error) === "ENOENT") return { verdict: "absent" };
19435
20275
  return { verdict: "unknown", reason: "unreadable", readFailure: error };
@@ -19626,7 +20466,7 @@ async function readRunParentPath(runDirectory) {
19626
20466
  let raw;
19627
20467
  try {
19628
20468
  raw = JSON.parse(
19629
- await readFile22(join39(runDirectory, "admitted-request.json"), "utf8")
20469
+ await readFile23(join39(runDirectory, "admitted-request.json"), "utf8")
19630
20470
  );
19631
20471
  } catch (error) {
19632
20472
  if (errorCodeOf(error) === "ENOENT") return void 0;
@@ -19741,7 +20581,7 @@ async function loadResumableRunRecord(home, runId, authority) {
19741
20581
  let sourceRun;
19742
20582
  try {
19743
20583
  const raw = JSON.parse(
19744
- await readFile22(run.admittedRequestPath, "utf8")
20584
+ await readFile23(run.admittedRequestPath, "utf8")
19745
20585
  );
19746
20586
  if (isRecord(raw)) {
19747
20587
  const record = raw;
@@ -19863,7 +20703,7 @@ async function loadResumableRunRecord(home, runId, authority) {
19863
20703
  let model;
19864
20704
  try {
19865
20705
  const invocationRaw = JSON.parse(
19866
- await readFile22(join39(run.runDirectory, "invocation.json"), "utf8")
20706
+ await readFile23(join39(run.runDirectory, "invocation.json"), "utf8")
19867
20707
  );
19868
20708
  if (isRecord(invocationRaw)) {
19869
20709
  const rec = invocationRaw;
@@ -20614,7 +21454,7 @@ init_host_descriptions();
20614
21454
  import { randomUUID as randomUUID11 } from "node:crypto";
20615
21455
 
20616
21456
  // src/role-runtime-dependencies.ts
20617
- import { readFile as readFile24 } from "node:fs/promises";
21457
+ import { readFile as readFile25 } from "node:fs/promises";
20618
21458
  init_doctor_evidence();
20619
21459
 
20620
21460
  // src/navigator-attendance.ts
@@ -20623,7 +21463,7 @@ init_packaged_role_registry();
20623
21463
  init_activation_ledger_topology();
20624
21464
  import { resolve as resolve17 } from "node:path";
20625
21465
  import "@earendil-works/pi-coding-agent";
20626
- import { Type as Type13 } from "typebox";
21466
+ import { Type as Type19 } from "typebox";
20627
21467
 
20628
21468
  // src/navigator-public-session.ts
20629
21469
  init_sitian_facade();
@@ -20632,7 +21472,7 @@ import { basename as basename11 } from "node:path";
20632
21472
 
20633
21473
  // src/navigator-session-contracts.ts
20634
21474
  init_unknown_value();
20635
- import { Type as Type10 } from "typebox";
21475
+ import { Type as Type15 } from "typebox";
20636
21476
  import { Value as Value2 } from "typebox/value";
20637
21477
  var NAVIGATOR_PREPARE_TOOL_NAME = "ak_navigator_prepare";
20638
21478
  var NAVIGATOR_UNAVAILABLE_KEYS = /* @__PURE__ */ new Set([
@@ -20737,26 +21577,26 @@ function navigatorProviderFailureFromPublicTerminal(outcome) {
20737
21577
  if (typed !== void 0) return { source: typed, cause: typed };
20738
21578
  return { source: "unknown", cause: "unknown" };
20739
21579
  }
20740
- var navigatorProviderFailureSchema = Type10.Object({
20741
- source: Type10.Union([
20742
- Type10.Literal("context"),
20743
- Type10.Literal("session"),
20744
- Type10.Literal("model"),
20745
- Type10.Literal("thinking"),
20746
- Type10.Literal("auth"),
20747
- Type10.Literal("quota"),
20748
- Type10.Literal("transport"),
20749
- Type10.Literal("unknown")
21580
+ var navigatorProviderFailureSchema = Type15.Object({
21581
+ source: Type15.Union([
21582
+ Type15.Literal("context"),
21583
+ Type15.Literal("session"),
21584
+ Type15.Literal("model"),
21585
+ Type15.Literal("thinking"),
21586
+ Type15.Literal("auth"),
21587
+ Type15.Literal("quota"),
21588
+ Type15.Literal("transport"),
21589
+ Type15.Literal("unknown")
20750
21590
  ]),
20751
- cause: Type10.Union([
20752
- Type10.Literal("context"),
20753
- Type10.Literal("session"),
20754
- Type10.Literal("model"),
20755
- Type10.Literal("thinking"),
20756
- Type10.Literal("auth"),
20757
- Type10.Literal("quota"),
20758
- Type10.Literal("transport"),
20759
- Type10.Literal("unknown")
21591
+ cause: Type15.Union([
21592
+ Type15.Literal("context"),
21593
+ Type15.Literal("session"),
21594
+ Type15.Literal("model"),
21595
+ Type15.Literal("thinking"),
21596
+ Type15.Literal("auth"),
21597
+ Type15.Literal("quota"),
21598
+ Type15.Literal("transport"),
21599
+ Type15.Literal("unknown")
20760
21600
  ])
20761
21601
  }, { additionalProperties: false });
20762
21602
  function parseNavigatorModelSetting(value) {
@@ -21138,8 +21978,8 @@ function resolveNavigatorAuthorityMaterial(roleInput, fileAuthority) {
21138
21978
  return void 0;
21139
21979
  }
21140
21980
  var NAVIGATOR_TARGETS = PACKAGED_ROLE_REGISTRY.map(({ role, phases }) => ({ role, phases }));
21141
- var prepareSchema = Type13.Object({
21142
- prose: Type13.Optional(Type13.Unknown({
21981
+ var prepareSchema = Type19.Object({
21982
+ prose: Type19.Optional(Type19.Unknown({
21143
21983
  description: "\u6E38\u5955\u4F7F\u6563\u6587\u5EFA\u8BAE\uFF0C\u539F\u6837\u5448\u73B0\u3002\u4E0D\u8981\u6C42 candidates/next \u7ED3\u6784\u3002"
21144
21984
  }))
21145
21985
  }, { additionalProperties: true });
@@ -21341,8 +22181,8 @@ function createNavigatorAttendance(options) {
21341
22181
  try {
21342
22182
  try {
21343
22183
  if (disposed) throw navigatorUnavailableError("session", new Error("Navigator attendance was disposed"));
21344
- const delivery = createReceiptDeliveryPolicy();
21345
- const promptAllowingRejectedPrepare = async (text, deliveryRequest) => {
22184
+ const delivery = createReceiptDeliveryPolicy(options.deliveryRequestLimit);
22185
+ const promptAllowingRejectedPrepare = async (text) => {
21346
22186
  await persistNavigatorWorkBase(activeSession.recordPointer(), { subject, authority });
21347
22187
  const entryStart = activeSession.entries().length;
21348
22188
  prepareBatchRejected = false;
@@ -21369,17 +22209,15 @@ function createNavigatorAttendance(options) {
21369
22209
  delivery.recordNestedNoReceipt(sessionNoReceipt);
21370
22210
  return;
21371
22211
  }
21372
- if (deliveryRequest && output === void 0) delivery.recordDeliveryRequest();
21373
22212
  };
21374
- await promptAllowingRejectedPrepare(request, false);
22213
+ await promptAllowingRejectedPrepare(request);
21375
22214
  if (boundSettlement !== void 0) {
21376
22215
  while (output === void 0 && prepareBatchRejected && delivery.nextAction() === "request-delivery") {
21377
- await promptAllowingRejectedPrepare(JSON.stringify(delivery.deliveryState()), true);
22216
+ delivery.recordDeliveryRequest();
22217
+ await promptAllowingRejectedPrepare(JSON.stringify(delivery.deliveryState()));
21378
22218
  }
21379
22219
  if (output === void 0 && delivery.nextAction() === "request-delivery") {
21380
- while (delivery.nextAction() === "request-delivery") {
21381
- delivery.recordDeliveryRequest();
21382
- }
22220
+ delivery.closeBudget();
21383
22221
  }
21384
22222
  if (output === void 0 && delivery.nextAction() === "no-receipt" && activeSession.providerFailure?.() === void 0) {
21385
22223
  const facts = delivery.facts({ runPointer: activeSession.recordPointer(), attemptPointer: invocationId });
@@ -21577,7 +22415,7 @@ function createNavigatorAttendance(options) {
21577
22415
  init_doctor_evidence();
21578
22416
  init_unknown_value();
21579
22417
  init_host_contracts();
21580
- import { readFile as readFile23 } from "node:fs/promises";
22418
+ import { readFile as readFile24 } from "node:fs/promises";
21581
22419
  import { resolve as resolve18 } from "node:path";
21582
22420
  init_notary_source_run();
21583
22421
  init_packaged_role_registry();
@@ -21591,7 +22429,7 @@ function navigatorInputReference(getFlag, role) {
21591
22429
  async function loadNavigatorWorkContext(options) {
21592
22430
  const reference = navigatorInputReference(options.getFlag, options.role);
21593
22431
  const subjectMode = packagedNavigatorSubject(options.role);
21594
- const input = reference === void 0 || subjectMode === "case" || subjectMode === "source-run" ? void 0 : await readFile23(reference, "utf8");
22432
+ const input = reference === void 0 || subjectMode === "case" || subjectMode === "source-run" ? void 0 : await readFile24(reference, "utf8");
21595
22433
  const subjectRoot = subjectPath(reference ?? options.context.sessionManager.getSessionDir(), options.context.cwd);
21596
22434
  let subjectKey = reference === void 0 ? subjectRoot : navigatorSubjectKeyForInput(subjectRoot, reference, options.context.cwd);
21597
22435
  let subject = input ?? `work subject: ${subjectKey}`;
@@ -21648,7 +22486,7 @@ async function loadNavigatorWorkContext(options) {
21648
22486
  let authorityMaterial;
21649
22487
  for (const path of authorityFiles) {
21650
22488
  try {
21651
- const content = await readFile23(path, "utf8");
22489
+ const content = await readFile24(path, "utf8");
21652
22490
  if (content.trim() !== "") {
21653
22491
  authorityMaterial = content;
21654
22492
  break;
@@ -21676,24 +22514,25 @@ init_notary_source_run();
21676
22514
  init_host_contracts();
21677
22515
  init_sitian_facade();
21678
22516
  init_submission_ledger();
22517
+ init_filed_submission();
21679
22518
  import { randomUUID as randomUUID8 } from "node:crypto";
21680
22519
  import { readFileSync as readFileSync6, writeSync as writeSync2 } from "node:fs";
21681
22520
  import { join as join43 } from "node:path";
21682
22521
  import { Value as Value4 } from "typebox/value";
21683
22522
 
21684
22523
  // src/activation-trace.ts
21685
- import { Type as Type14 } from "typebox";
21686
- var causeSchema = Type14.Object({
21687
- identity: Type14.String({ minLength: 1 }),
21688
- name: Type14.String({ minLength: 1 }),
21689
- message: Type14.String(),
21690
- evidenceId: Type14.Optional(Type14.String({ minLength: 1 }))
22524
+ import { Type as Type20 } from "typebox";
22525
+ var causeSchema = Type20.Object({
22526
+ identity: Type20.String({ minLength: 1 }),
22527
+ name: Type20.String({ minLength: 1 }),
22528
+ message: Type20.String(),
22529
+ evidenceId: Type20.Optional(Type20.String({ minLength: 1 }))
21691
22530
  }, { additionalProperties: false });
21692
- var activationTraceRecordSchema = Type14.Object({
21693
- role: Type14.String({ minLength: 1 }),
21694
- stageId: Type14.String({ pattern: "^[a-z][a-z0-9-]*$" }),
21695
- status: Type14.Literal("failed"),
21696
- timestamp: Type14.String({ format: "date-time" }),
22531
+ var activationTraceRecordSchema = Type20.Object({
22532
+ role: Type20.String({ minLength: 1 }),
22533
+ stageId: Type20.String({ pattern: "^[a-z][a-z0-9-]*$" }),
22534
+ status: Type20.Literal("failed"),
22535
+ timestamp: Type20.String({ format: "date-time" }),
21697
22536
  cause: causeSchema
21698
22537
  }, { additionalProperties: false });
21699
22538
  var activationCauseEvidence = 0;
@@ -21857,10 +22696,10 @@ init_engine_material();
21857
22696
  init_engine_detour();
21858
22697
  init_engine_detour_usage();
21859
22698
  init_run_terminal_artifacts();
21860
- import { Type as Type15 } from "typebox";
21861
- var engineDetourArgsSchema = Type15.Object(
22699
+ import { Type as Type21 } from "typebox";
22700
+ var engineDetourArgsSchema = Type21.Object(
21862
22701
  {
21863
- argv: Type15.Array(Type15.String({ minLength: 1 }), {
22702
+ argv: Type21.Array(Type21.String({ minLength: 1 }), {
21864
22703
  minItems: 1,
21865
22704
  description: "\u9996\u9879\u4E3A PATH \u4E2D\u7684\u53EF\u6267\u884C\u6587\u4EF6\uFF0C\u5176\u4F59\u9879\u4E3A\u53C2\u6570\u3002"
21866
22705
  })
@@ -21994,28 +22833,10 @@ function registerEngineDetourTool(roleHost, hostActions) {
21994
22833
  init_receipt_delivery_policy();
21995
22834
 
21996
22835
  // src/collector-role.ts
22836
+ init_filed_submission();
22837
+ init_role_submission_declarations();
21997
22838
  init_collector_config();
21998
22839
  init_collector_output();
21999
-
22000
- // src/collector-tool-schemas.ts
22001
- init_open_tool_schema();
22002
- init_terminating_infrastructure();
22003
- import { Type as Type16 } from "typebox";
22004
- var collectorOutputBaseSchema = openToolObject(
22005
- Type16.Object({
22006
- groups: Type16.Unsafe({
22007
- description: "\u6309\u673A\u5668\u8EAB\u4EFD\u5F52\u7EC4\u7684\u51FA\u5E2D\u3001\u6750\u6599\u4E0E\u9010\u6761 findings\uFF08LLM \u81EA\u884C\u4ECE\u5BBF\u4E3B CLI \u53D6\u8BC1\u6574\u7406\uFF1B\u4EE3\u7801\u4E0D\u4EE3\u6536\u4E0D\u5F52\u5E76\uFF09\u3002"
22008
- }),
22009
- unfinishedReasons: Type16.Unknown({
22010
- description: "\u672A\u5B8C\u6210\u539F\u56E0\uFF1B\u53D6\u8BC1\u53D7\u9650\u65F6\u5982\u5B9E\u62A5\u544A\u3002"
22011
- })
22012
- })
22013
- );
22014
- var collectorOutputArgsSchema = withTerminatingOutputDeclarations(
22015
- collectorOutputBaseSchema
22016
- );
22017
-
22018
- // src/collector-role.ts
22019
22840
  var COLLECTOR_REQUIRED_TOOLS = [COLLECTOR_OUTPUT_TOOL];
22020
22841
  var COLLECTOR_CONSTRUCTION_TOOLS = Object.freeze(["write", "edit"]);
22021
22842
  var COLLECTOR_TRANSPORT_FLAGS = Object.freeze([
@@ -22041,7 +22862,6 @@ var COLLECTOR_TRANSPORT_FLAGS = Object.freeze([
22041
22862
  })
22042
22863
  })
22043
22864
  ]);
22044
- var outputSchema = collectorOutputArgsSchema;
22045
22865
  function buildMethodContext(activation) {
22046
22866
  const lines = [
22047
22867
  "<collector_method>",
@@ -22113,27 +22933,16 @@ function createCollectorRoleRuntime(pi, dependencies) {
22113
22933
  registerBusinessTools(getActivation) {
22114
22934
  if (toolsRegistered) return;
22115
22935
  toolsRegistered = true;
22116
- pi.registerTool({
22117
- name: COLLECTOR_OUTPUT_TOOL,
22118
- label: "\u901A\u8FDB\u53F8\u8F93\u51FA",
22119
- description: "\u63D0\u4EA4\u901A\u8FDB\u53F8\u56DE\u6267\u3002",
22120
- promptSnippet: "\u63D0\u4EA4\u901A\u8FDB\u53F8\u56DE\u6267",
22121
- parameters: outputSchema,
22122
- async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
22123
- const activation = getActivation();
22124
- if (activation === void 0) throw new Error("\u901A\u8FDB\u53F8\u672A\u6FC0\u6D3B");
22125
- return {
22126
- content: [],
22127
- details: params,
22128
- terminate: true
22129
- };
22130
- }
22936
+ registerFiledSubmissionTool(pi, roleSubmissionDeclaration("collector"), {
22937
+ readyError: () => getActivation() === void 0 ? "\u901A\u8FDB\u53F8\u672A\u6FC0\u6D3B" : void 0
22131
22938
  });
22132
22939
  }
22133
22940
  };
22134
22941
  }
22135
22942
 
22136
22943
  // src/doctor-role.ts
22944
+ init_filed_submission();
22945
+ init_role_submission_declarations();
22137
22946
  init_compliance_transport();
22138
22947
  init_dossier_resolution();
22139
22948
  init_doctor_contracts();
@@ -22180,17 +22989,20 @@ function createDoctorRoleRuntime(pi, dependencies, host) {
22180
22989
  const details = activation.store.read(params.evidenceId, params.offset, params.limit);
22181
22990
  return { content: [{ type: "text", text: JSON.stringify(details) }], details };
22182
22991
  } });
22183
- pi.registerTool({ name: DOCTOR_OUTPUT_TOOL_NAME, label: "\u592A\u533B\u7F72\u8F93\u51FA", description: DOCTOR_OUTPUT_TOOL_DESCRIPTION, parameters: doctorSubmissionSchema, async execute(id, params, _signal, _update, ctx) {
22184
- if (!activation) throw new Error("\u592A\u533B\u7F72\u672A\u6FC0\u6D3B");
22185
- const active2 = activation;
22186
- const testimony = validateDoctorOutput(params, active2.patient, active2.store);
22187
- try {
22188
- appendCandidate(ctx, { version: 1, testimony, cost: active2.patient.cost, readRecord: active2.store.readRecord(), patientIdentity: active2.patient.identity });
22189
- } catch (error) {
22190
- host.failInfrastructure(error, ctx, id);
22992
+ registerFiledSubmissionTool(pi, roleSubmissionDeclaration("doctor"), {
22993
+ readyError: () => activation === void 0 ? "\u592A\u533B\u7F72\u672A\u6FC0\u6D3B" : void 0,
22994
+ beforeAccept: async ({ toolCallId, parameters, ctx }) => {
22995
+ if (activation === void 0) throw new Error("\u592A\u533B\u7F72\u672A\u6FC0\u6D3B");
22996
+ const active2 = activation;
22997
+ const testimony = validateDoctorOutput(parameters, active2.patient, active2.store);
22998
+ try {
22999
+ appendCandidate(ctx, { version: 1, testimony, cost: active2.patient.cost, readRecord: active2.store.readRecord(), patientIdentity: active2.patient.identity });
23000
+ } catch (error) {
23001
+ host.failInfrastructure(error, ctx, toolCallId);
23002
+ }
23003
+ return testimony;
22191
23004
  }
22192
- return { content: [], details: testimony, terminate: true };
22193
- } });
23005
+ });
22194
23006
  pi.on("before_agent_start", (event) => {
22195
23007
  if (!activation) throw new Error("\u592A\u533B\u7F72\u672A\u6FC0\u6D3B");
22196
23008
  const catalog = { version: activation.patient.version, identity: activation.patient.identity, admittedMetrics: { cost: activation.patient.cost }, lawfulTargetKeys: ["case", ...activation.patient.cost.invocations.sources], evidence: activation.patient.evidence.map(({ id, kind, sha256, byteLength, contentLength }) => ({ id, kind, sha256, byteLength, contentLength })) };
@@ -22215,6 +23027,8 @@ ${JSON.stringify(catalog)}
22215
23027
  }
22216
23028
 
22217
23029
  // src/notary-role.ts
23030
+ init_filed_submission();
23031
+ init_role_submission_declarations();
22218
23032
  init_notary_contracts();
22219
23033
  function readNotaryTicketFlag(flag) {
22220
23034
  if (flag === void 0) return void 0;
@@ -22282,22 +23096,8 @@ function createNotaryRoleRuntime(pi, dependencies, host) {
22282
23096
  };
22283
23097
  if (!registered) {
22284
23098
  registered = true;
22285
- pi.registerTool({
22286
- name: NOTARY_OUTPUT_TOOL_NAME,
22287
- label: "\u7B26\u5B9D\u90CE\u8F93\u51FA",
22288
- description: "\u63D0\u4EA4\u5F15\u6587\u4FDD\u771F\u4E0E\u7968\u9762\u5BF9\u9F50\u7684 converged/continue/escalate \u51B3\u8BAE\u3002",
22289
- promptSnippet: "\u63D0\u4EA4\u7B26\u5B9D\u90CE\u51B3\u8BAE",
22290
- parameters: notaryOutputSchema,
22291
- async execute(toolCallId, parameters, _signal, _onUpdate, ctx) {
22292
- if (activation === void 0) {
22293
- throw new Error("\u7B26\u5B9D\u90CE\u672A\u6FC0\u6D3B");
22294
- }
22295
- return {
22296
- content: [],
22297
- details: parameters,
22298
- terminate: true
22299
- };
22300
- }
23099
+ registerFiledSubmissionTool(pi, roleSubmissionDeclaration("notary"), {
23100
+ readyError: () => activation === void 0 ? "\u7B26\u5B9D\u90CE\u672A\u6FC0\u6D3B" : void 0
22301
23101
  });
22302
23102
  pi.on("before_agent_start", (event) => {
22303
23103
  if (activation === void 0) {
@@ -22330,128 +23130,41 @@ init_notary_contracts();
22330
23130
 
22331
23131
  // src/countersign-role.ts
22332
23132
  init_review_submission();
23133
+ init_role_submission_declarations();
22333
23134
  init_countersign_contracts();
22334
23135
  init_countersign_contracts();
22335
- var countersignVerdictSchema = reviewSubmissionSchema;
22336
- var COUNTERSIGN_TOOL_SPEC = {
22337
- name: COUNTERSIGN_OUTPUT_TOOL_NAME,
22338
- label: "\u7ED9\u4E8B\u4E2D\u8F93\u51FA",
22339
- description: "\u7ED9\u4E8B\u4E2D\u51B3\u8BAE\u3002",
22340
- promptSnippet: "\u7ED9\u4E8B\u4E2D\u51B3\u8BAE",
22341
- parameters: countersignVerdictSchema
22342
- };
23136
+ var COUNTERSIGN_TOOL_SPEC = roleSubmissionDeclaration("countersign");
22343
23137
 
22344
23138
  // src/gleaner-left-role.ts
22345
- init_open_tool_schema();
22346
- init_terminating_infrastructure();
22347
23139
  init_gleaner_left_contracts();
23140
+ init_role_submission_declarations();
22348
23141
  init_gleaner_left_contracts();
22349
- import { Type as Type17 } from "typebox";
22350
- var gleanerLeftOutputSchema = withTerminatingOutputDeclarations(
22351
- openToolObject(
22352
- Type17.Object({
22353
- status: Type17.Unknown({
22354
- description: "completed"
22355
- }),
22356
- findings: Type17.Unknown({
22357
- description: "\u5F39\u7AE0\u5217\u8868\uFF1B\u6BCF\u6761\u53EF\u542B pointer\uFF08\u6587\u4EF6/\u884C\u6307\u9488\uFF09\u4E0E statement\uFF08\u7591\u70B9\u9648\u8FF0\uFF09\uFF0C\u539F\u6837\u7559\u5B58\u3002\u7A7A\u5217\u8868\u5408\u6CD5\u5B8C\u5C40\uFF1B\u673A\u5668\u4E0D\u5224\u5F39\u7AE0\u662F\u5426\u6210\u7ACB\u3002"
22358
- })
22359
- })
22360
- )
22361
- );
22362
- var GLEANER_LEFT_TOOL_SPEC = {
22363
- name: GLEANER_LEFT_OUTPUT_TOOL_NAME,
22364
- label: "\u5DE6\u62FE\u9057\u8F93\u51FA",
22365
- description: "\u5DE6\u62FE\u9057\u5F39\u7AE0\u3002",
22366
- promptSnippet: "\u5DE6\u62FE\u9057\u5F39\u7AE0",
22367
- parameters: gleanerLeftOutputSchema
22368
- };
23142
+ var GLEANER_LEFT_TOOL_SPEC = roleSubmissionDeclaration("gleaner-left");
22369
23143
 
22370
23144
  // src/role-runtime.ts
22371
23145
  init_gleaner_left_contracts();
22372
23146
 
22373
23147
  // src/inspector-role.ts
22374
23148
  init_review_submission();
23149
+ init_role_submission_declarations();
22375
23150
  init_inspector_contracts();
22376
- var inspectorOutputSchema = reviewSubmissionSchema;
22377
- var INSPECTOR_TOOL_SPEC = {
22378
- name: INSPECTOR_OUTPUT_TOOL_NAME,
22379
- label: "\u53F0\u9662\u8F93\u51FA",
22380
- description: "\u53F0\u9662\u7EC8\u5C40\u56DE\u6267\uFF0C\u72B6\u6001\u4E3A converged\u3001continue \u6216 escalate\u3002",
22381
- promptSnippet: "\u53F0\u9662\u7EC8\u5C40\u56DE\u6267",
22382
- parameters: inspectorOutputSchema
22383
- };
23151
+ var INSPECTOR_TOOL_SPEC = roleSubmissionDeclaration("inspector");
22384
23152
 
22385
23153
  // src/role-runtime.ts
22386
23154
  init_inspector_contracts();
22387
23155
 
22388
23156
  // src/diarist-role.ts
22389
- init_open_tool_schema();
22390
- init_terminating_infrastructure();
22391
23157
  init_diarist_contracts();
23158
+ init_role_submission_declarations();
22392
23159
  init_diarist_contracts();
22393
- import { Type as Type18 } from "typebox";
22394
- var DIARIST_SESSIONS_DESCRIPTION = "\u5BF9\u8BDD\u8FB9\u754C\u3002\u6BCF\u5377\u542B path\uFF08\u4F1A\u8BDD\u5377\u7EDD\u5BF9\u6216\u53EF\u8BFB\u8DEF\u5F84\uFF09\u4E0E ranges\uFF08\u672C\u5377\u672C\u8F6E\u5404\u533A\u95F4\uFF09\u3002\u6BCF\u6BB5\u533A\u95F4\u542B from / to\uFF1B\u8D77\u70B9\u4E0E\u7EC8\u70B9\u5404\u5199 id\uFF08\u539F\u751F id\uFF09\u6216 line\uFF08\u672C\u8F6E\u884C\u53F7\uFF09\uFF0C\u4E8C\u9009\u4E00\u3002\u7A7A\u5217\u8868\uFF1D\u672C\u8F6E\u65E0\u5BF9\u8BDD\u53EF\u5212\u3002\u7AEF\u70B9\u65E0\u6CD5\u6307\u540D\u65F6\u8D70 reask\uFF0C\u4E0D\u4E2D\u6B62\u3002";
22395
- var diaristOutputSchema = withTerminatingOutputDeclarations(
22396
- openToolObject(
22397
- Type18.Object({
22398
- status: Type18.Unknown({
22399
- description: "completed | escalate"
22400
- }),
22401
- ticketNumber: Type18.Optional(
22402
- Type18.Unknown({
22403
- description: "\u672C\u5EAD\u5BF9\u8C61\u7968\u53F7\uFF08\u6B63\u6574\u6570\uFF09\u6216 null/\u7701\u7565\uFF1D\u771F\u65E0\u7968\uFF1B\u4E0B\u6E38\u8D70 typed \u952E\uFF1B\u8BA4\u4E0D\u51FA\u7528 status=escalate\uFF0C\u4E0D\u6D17\u6210\u65E0\u5F55\u3002\u673A\u68B0\u5C42\u4E0D\u91CD\u5224\u3002"
22404
- })
22405
- ),
22406
- reason: Type18.Unknown({
22407
- description: "status \u4E3A escalate \u65F6\uFF1A\u8BA4\u4E0D\u51FA\u672C\u5EAD\u5BF9\u8C61\u7684\u539F\u56E0"
22408
- }),
22409
- sessions: Type18.Optional(Type18.Unknown({ description: DIARIST_SESSIONS_DESCRIPTION })),
22410
- ticketSessions: Type18.Unknown({
22411
- description: `\u591A\u7968\u5EAD\u9010\u7968\u5BF9\u8BDD\u8FB9\u754C\uFF1B\u6BCF\u7968\u542B ticketNumber\uFF08\u672C\u6761\u8FB9\u754C\u6240\u5F52\u7968\u53F7\uFF0C\u6B63\u6574\u6570\uFF09\u4E0E sessions\uFF08${DIARIST_SESSIONS_DESCRIPTION}\uFF09\u3002\u4E00\u6B21\u4EA4\u5377\u5404\u7968\u5404\u81EA\u5206\u5F55\u3002\u4E0E\u5355\u7968 sessions \u4E8C\u9009\u4E00\u3002`
22412
- })
22413
- })
22414
- )
22415
- );
22416
- var DIARIST_TOOL_SPEC = {
22417
- name: DIARIST_OUTPUT_TOOL_NAME,
22418
- label: "\u8D77\u5C45\u90CE\u8F93\u51FA",
22419
- description: "\u8D77\u5C45\u90CE\u4EA4\u5355\u7968 sessions \u6216\u591A\u7968\u9010\u7968 ticketSessions \u8FB9\u754C\uFF1B\u8BA4\u4E0D\u51FA\u672C\u5EAD\u5BF9\u8C61\u5219 escalate\u3002",
22420
- promptSnippet: "\u8D77\u5C45\u90CE\u4EA4\u8FB9\u754C",
22421
- parameters: diaristOutputSchema
22422
- };
23160
+ var DIARIST_TOOL_SPEC = roleSubmissionDeclaration("diarist");
22423
23161
 
22424
23162
  // src/secretariat-role.ts
22425
- init_terminating_infrastructure();
22426
23163
  init_secretariat_contracts();
23164
+ init_role_submission_declarations();
22427
23165
  init_secretariat_contracts();
22428
- import { Type as Type19 } from "typebox";
22429
- var secretariatVerdictSchema = withTerminatingOutputDeclarations(
22430
- Type19.Object(
22431
- {
22432
- secretariatStatus: Type19.Unknown({
22433
- description: "converged | escalate"
22434
- }),
22435
- ticketNumber: Type19.Optional(
22436
- Type19.Unknown({ description: "\u672C\u7968\u53F7\uFF1B\u7F72\u65F6\u6307\u5411\u6700\u7EC8\u6B63\u6587\u6240\u5728\u7968" })
22437
- ),
22438
- note: Type19.Unknown({ description: "\u9644\u6CE8" }),
22439
- evidence: Type19.Optional(Type19.Unknown({ description: "\u7559\u5B58\u8BC1\u636E" })),
22440
- decisionGate: Type19.Unknown({
22441
- description: "\u9700\u965B\u4E0B\u5904\u7F6E\u7684\u95EE\u9898\u4E0E\u9009\u9879\uFF1B\u53EF\u5199 question \u4E0E options\uFF0C\u539F\u6837\u7559\u5B58\u3002"
22442
- })
22443
- },
22444
- { additionalProperties: true }
22445
- )
22446
- );
22447
- secretariatVerdictSchema.required = [];
22448
- var SECRETARIAT_OUTPUT_TOOL_SPEC = {
22449
- name: SECRETARIAT_OUTPUT_TOOL_NAME,
22450
- label: "\u4E2D\u4E66\u7701\u8F93\u51FA",
22451
- description: "\u4E2D\u4E66\u7701\u7EC8\u5C40\u56DE\u6267\u3002",
22452
- promptSnippet: "\u4E2D\u4E66\u7701\u7EC8\u5C40\u56DE\u6267",
22453
- parameters: secretariatVerdictSchema
22454
- };
23166
+ init_secretariat_contracts();
23167
+ var SECRETARIAT_OUTPUT_TOOL_SPEC = roleSubmissionDeclaration("secretariat");
22455
23168
 
22456
23169
  // src/role-runtime.ts
22457
23170
  init_secretariat_contracts();
@@ -22469,24 +23182,13 @@ init_invocation();
22469
23182
  init_gatekeeper_role();
22470
23183
 
22471
23184
  // src/navigator-role.ts
22472
- init_navigator_output();
22473
- var NAVIGATOR_TOOL_SPEC = {
22474
- name: NAVIGATOR_OUTPUT_TOOL_NAME,
22475
- label: "\u6E38\u5955\u4F7F\u5EFA\u8BAE",
22476
- description: "\u6E38\u5955\u4F7F\u7EC8\u5C40\u56DE\u6267\uFF1A\u6563\u6587\u5EFA\u8BAE\uFF0C\u539F\u6837\u5448\u73B0\u3002",
22477
- promptSnippet: "\u6E38\u5955\u4F7F\u5EFA\u8BAE",
22478
- parameters: navigatorOutputSchema
22479
- };
23185
+ init_role_submission_declarations();
23186
+ var NAVIGATOR_TOOL_SPEC = roleSubmissionDeclaration("navigator");
22480
23187
 
22481
23188
  // src/auditor-role.ts
22482
23189
  init_auditor_output();
22483
- var AUDITOR_TOOL_SPEC = {
22484
- name: AUDITOR_OUTPUT_TOOL_NAME,
22485
- label: "\u5BA1\u5211\u9662\u8F93\u51FA",
22486
- description: "\u5BA1\u5211\u9662\u7EC8\u5C40\u56DE\u6267\uFF0Cstatus \u4E3A converged\u3001continue \u6216 escalate\u3002",
22487
- promptSnippet: "\u5BA1\u5211\u9662\u7EC8\u5C40\u56DE\u6267",
22488
- parameters: auditorOutputSchema
22489
- };
23190
+ init_role_submission_declarations();
23191
+ var AUDITOR_TOOL_SPEC = roleSubmissionDeclaration("auditor");
22490
23192
 
22491
23193
  // src/role-runtime.ts
22492
23194
  init_navigator_invocation_identity();
@@ -22496,22 +23198,9 @@ init_packaged_role_registry();
22496
23198
  init_judge_role();
22497
23199
 
22498
23200
  // src/reviewer-role.ts
22499
- init_open_tool_schema();
22500
- init_terminating_infrastructure();
23201
+ init_filed_submission();
23202
+ init_role_submission_declarations();
22501
23203
  init_reviewer_output();
22502
- import { Type as Type20 } from "typebox";
22503
- var REVIEWER_AMENDMENTS_DESCRIPTION = "\u5DF2\u8FD0\u884C lens \u7684 amendments \u627F\u8F7D candidates\u3001\u9010\u6761\u5904\u7F6E\u4E0E verdict \u7684\u5B8C\u6574\u62A5\u544A\uFF08\u975E\u4EC5 verdict \u884C\uFF09\uFF1B\u663E\u5F0F\u5355\u8F74\u65F6\u53E6\u4E00\u8F74\u53EF\u7701\u7565\uFF08completeness / correctness\uFF09\u3002hard-stop\uFF0Fusage error \u4E3A refused \u65F6\uFF0C\u5DF2\u4EA7\u51FA\u62A5\u544A\u4ECD\u7167\u5F55\u5BF9\u5E94 lens \u5B57\u6BB5\u3002";
22504
- var REVIEWER_STATUS_DESCRIPTION = "completed | refused\u3002\u4E24\u79CD\u6B63\u5E38 lens verdict\uFF08completeness / correctness\uFF09\u5747 completed\uFF1Bhard-stop \u4E0E usage error \u4E3A refused\uFF08\u5DF2\u4EA7\u51FA\u62A5\u544A\u4ECD\u7167\u5F55\u8FDB\u6240\u9009 lens amendments\uFF09\u3002";
22505
- var reviewerOutputObject = Type20.Object({
22506
- status: Type20.Unknown({ description: REVIEWER_STATUS_DESCRIPTION }),
22507
- amendments: Type20.Unknown({ description: REVIEWER_AMENDMENTS_DESCRIPTION }),
22508
- diagnostic: Type20.Unknown({
22509
- description: "\u62D2\u7EDD\u8BCA\u65AD\u8BF4\u660E\uFF1Bhard-stop\uFF0Fusage error \u539F\u56E0\u8FDB\u6B64\u5B57\u6BB5\uFF0C\u5DF2\u4EA7\u51FA\u62A5\u544A\u53E6\u7167\u5F55 amendments"
22510
- })
22511
- });
22512
- var reviewerOutputSchema = withTerminatingOutputDeclarations(
22513
- openToolObject(reviewerOutputObject)
22514
- );
22515
23204
  function createReviewerRoleRuntime(pi, dependencies, _hostActions) {
22516
23205
  let soul;
22517
23206
  let registered = false;
@@ -22523,20 +23212,8 @@ function createReviewerRoleRuntime(pi, dependencies, _hostActions) {
22523
23212
  fixedBaseRevision = admitted.baseRevision;
22524
23213
  if (!registered) {
22525
23214
  registered = true;
22526
- pi.registerTool({
22527
- name: REVIEWER_OUTPUT_TOOL_NAME,
22528
- label: "\u5FA1\u53F2\u53F0\u8F93\u51FA",
22529
- description: "\u63D0\u4EA4\u5FA1\u53F2\u53F0\u7EC8\u5C40\u56DE\u6267\u3002",
22530
- promptSnippet: "\u63D0\u4EA4\u5FA1\u53F2\u53F0\u7EC8\u5C40\u56DE\u6267",
22531
- parameters: reviewerOutputSchema,
22532
- async execute(_id, parameters) {
22533
- if (!soul) throw new Error("\u5FA1\u53F2\u53F0\u8F93\u5165\u672A\u88C5\u8F7D");
22534
- return {
22535
- content: [],
22536
- details: parameters,
22537
- terminate: true
22538
- };
22539
- }
23215
+ registerFiledSubmissionTool(pi, roleSubmissionDeclaration("reviewer"), {
23216
+ readyError: () => soul === void 0 || soul.length === 0 ? "\u5FA1\u53F2\u53F0\u8F93\u5165\u672A\u88C5\u8F7D" : void 0
22540
23217
  });
22541
23218
  }
22542
23219
  const activatedSoul = soul;
@@ -22550,18 +23227,18 @@ function createReviewerRoleRuntime(pi, dependencies, _hostActions) {
22550
23227
  }
22551
23228
 
22552
23229
  // src/worker-role.ts
22553
- init_open_tool_schema();
22554
- init_terminating_infrastructure();
22555
23230
  init_worker_output();
22556
23231
  init_fixer_output();
23232
+ init_filed_submission();
23233
+ init_role_submission_declarations();
22557
23234
  init_fixer_packet();
22558
- import { Type as Type21 } from "typebox";
22559
23235
 
22560
23236
  // src/worker-submission-gates.ts
22561
23237
  init_archivist_record_entry();
22562
23238
  init_sitian_facade();
22563
23239
  init_submission_errors();
22564
23240
  init_worker_submission_contracts();
23241
+ init_receipt_delivery_policy();
22565
23242
  init_unknown_value();
22566
23243
  init_submission_errors();
22567
23244
  init_worker_submission_contracts();
@@ -22572,11 +23249,11 @@ var WORKER_SUBMISSION_GATE_RECORD_KIND = WORKER_SUBMISSION_GATE_KIND;
22572
23249
  var WORKER_COMMIT_BASELINE_ENTRY_TYPE = "commit-baseline";
22573
23250
  var WORKER_COMMIT_REMINDER_BOUNCE_ENTRY_TYPE = "commit-reminder-bounce";
22574
23251
  var WORKER_PREFIX_REMINDER_BOUNCE_ENTRY_TYPE = "prefix-reminder-bounce";
23252
+ var WORKER_UNFINISHED_REASON_BOUNCE_ENTRY_TYPE = "unfinished-reason-bounce";
22575
23253
  var HOOK_MARKER = "ak-roles: worker-submission-gates reference-transaction";
22576
23254
  var HOOKS_DIR = "ak-roles-hooks";
22577
23255
  var HOOK_FILE = "reference-transaction";
22578
23256
  var PLATFORM_PREFIX = /^[A-Za-z][A-Za-z0-9_-]*:/;
22579
- var UNFINISHED_REASON_BOUNCE_LIMIT = 2;
22580
23257
  function git2(cwd, args) {
22581
23258
  return execFileSync3("git", args, {
22582
23259
  cwd,
@@ -22676,10 +23353,11 @@ function unfinishedReasonPresent(details) {
22676
23353
  if (!isRecord(details)) return false;
22677
23354
  return containsWrittenReason(details.reason);
22678
23355
  }
22679
- function readGateState(session) {
23356
+ function readGateState(session, invocationScopeId) {
22680
23357
  let baseline;
22681
23358
  let reminded = false;
22682
23359
  let prefixReminded = false;
23360
+ let unfinishedReasonBounces = 0;
22683
23361
  for (const entry of session.getEntries()) {
22684
23362
  if (entry.type !== "custom") continue;
22685
23363
  if (entry.customType === WORKER_COMMIT_BASELINE_ENTRY_TYPE) {
@@ -22691,9 +23369,11 @@ function readGateState(session) {
22691
23369
  reminded = true;
22692
23370
  } else if (entry.customType === WORKER_PREFIX_REMINDER_BOUNCE_ENTRY_TYPE) {
22693
23371
  prefixReminded = true;
23372
+ } else if (entry.customType === WORKER_UNFINISHED_REASON_BOUNCE_ENTRY_TYPE && invocationScopeId !== void 0 && isRecord(entry.data) && entry.data.invocationScopeId === invocationScopeId) {
23373
+ unfinishedReasonBounces += 1;
22694
23374
  }
22695
23375
  }
22696
- return { baseline, reminded, prefixReminded };
23376
+ return { baseline, reminded, prefixReminded, unfinishedReasonBounces };
22697
23377
  }
22698
23378
  function isAncestor(cwd, ancestor, descendant) {
22699
23379
  try {
@@ -22724,9 +23404,11 @@ function createWorkerSubmissionGate(options = {}) {
22724
23404
  let reminded = false;
22725
23405
  let prefixReminded = false;
22726
23406
  let unfinishedReasonBounces = 0;
23407
+ let invocationScopeId;
22727
23408
  let record;
22728
23409
  let sessionParent;
22729
23410
  const explicitHome = typeof options.home === "string" && options.home.length > 0 ? options.home : void 0;
23411
+ const unfinishedReasonBounceLimit = deliveryLimitFromConfig(options.unfinishedReasonBounceLimit);
22730
23412
  const head = (cwd) => {
22731
23413
  try {
22732
23414
  return git2(cwd, ["rev-parse", "HEAD"]);
@@ -22747,7 +23429,8 @@ function createWorkerSubmissionGate(options = {}) {
22747
23429
  });
22748
23430
  };
22749
23431
  return {
22750
- arm(cwd, parent) {
23432
+ arm(cwd, parent, scope) {
23433
+ invocationScopeId = scope;
22751
23434
  uninstallPackageWorkerHooks(cwd);
22752
23435
  root = cwd;
22753
23436
  sessionParent = parent.getSessionFile();
@@ -22756,7 +23439,8 @@ function createWorkerSubmissionGate(options = {}) {
22756
23439
  kind: WORKER_SUBMISSION_GATE_RECORD_KIND,
22757
23440
  parent
22758
23441
  });
22759
- const prior = readGateState(record);
23442
+ const prior = readGateState(record, invocationScopeId);
23443
+ unfinishedReasonBounces = prior.unfinishedReasonBounces;
22760
23444
  if (prior.baseline !== void 0) {
22761
23445
  baseline = prior.baseline;
22762
23446
  reminded = prior.reminded;
@@ -22778,7 +23462,11 @@ function createWorkerSubmissionGate(options = {}) {
22778
23462
  },
22779
23463
  assertAcceptable(status, details) {
22780
23464
  if (status === "unfinished" && !unfinishedReasonPresent(details)) {
22781
- if (unfinishedReasonBounces < UNFINISHED_REASON_BOUNCE_LIMIT) {
23465
+ if (unfinishedReasonBounces < unfinishedReasonBounceLimit) {
23466
+ record?.appendCustomEntry(WORKER_UNFINISHED_REASON_BOUNCE_ENTRY_TYPE, {
23467
+ version: 1,
23468
+ invocationScopeId
23469
+ });
22782
23470
  unfinishedReasonBounces += 1;
22783
23471
  throw new WorkerUnfinishedReasonReminderError();
22784
23472
  }
@@ -22812,6 +23500,9 @@ function createWorkerSubmissionGate(options = {}) {
22812
23500
  };
22813
23501
  }
22814
23502
 
23503
+ // src/worker-role.ts
23504
+ init_receipt_delivery_policy();
23505
+
22815
23506
  // src/fixer-bash-seatbelt.ts
22816
23507
  var FIXER_BASH_FORBIDDEN_LITERALS = [
22817
23508
  "rm -rf",
@@ -22828,18 +23519,7 @@ function fixerBashSeatbeltDenyReason(matched) {
22828
23519
 
22829
23520
  // src/worker-role.ts
22830
23521
  init_unknown_value();
22831
- var CODER_STATUS_DESCRIPTION = `planned | completed | refused | partially_completed | unfinished\u3002unfinished\uFF1A\u7F3A\u524D\u7F6E\u6216\u8FDD\u5BAA\u7EA6\u675F\u81F4\u672C\u5C40\u672A\u5B8C\u6210\u3002${PARTIALLY_COMPLETED_DEFINITION}`;
22832
- var coderOutputObject = Type21.Object({
22833
- status: Type21.Unknown({ description: CODER_STATUS_DESCRIPTION }),
22834
- report: Type21.Unknown({ description: "\u5982\u5B9E\u7ED3\u679C\u62A5\u544A" }),
22835
- remainingScope: Type21.Unknown({ description: "\u672C\u5C40\u540E\u5269\u4F59\u5DE5\u4F5C" }),
22836
- reason: Type21.Unknown({
22837
- 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"
22838
- })
22839
- });
22840
- var coderOutputSchema = withTerminatingOutputDeclarations(
22841
- openToolObject(coderOutputObject)
22842
- );
23522
+ init_worker_output();
22843
23523
  var FIXER_FLAG_DEFINITIONS = {
22844
23524
  packet: {
22845
23525
  name: "ak-fix-packet",
@@ -22879,6 +23559,28 @@ function validateWorkerOutput(output, phase, roleLabel) {
22879
23559
  if (roleLabel === "Fixer") return validateFixerOutput(output, phase);
22880
23560
  return validateAcceptedWorkerDetails(output, "Coder");
22881
23561
  }
23562
+ function registerWorkerSubmission(pi, role, options) {
23563
+ registerFiledSubmissionTool(pi, roleSubmissionDeclaration(role), {
23564
+ readyError: () => options.ready() ? void 0 : options.notReady,
23565
+ beforeAccept: async ({ toolCallId, parameters, ctx }) => {
23566
+ const phase = options.phase();
23567
+ if (phase === void 0) throw new Error(options.notReady);
23568
+ const output = options.project(parameters, phase);
23569
+ const status = workerStatusOf(output);
23570
+ if (status !== void 0) {
23571
+ assertAcceptableThroughHost(
23572
+ options.submissionGate,
23573
+ status,
23574
+ output,
23575
+ options.hostActions,
23576
+ ctx,
23577
+ toolCallId
23578
+ );
23579
+ }
23580
+ return output;
23581
+ }
23582
+ });
23583
+ }
22882
23584
  function assertAcceptableThroughHost(submissionGate, status, details, hostActions, ctx, toolCallId) {
22883
23585
  try {
22884
23586
  submissionGate.assertAcceptable(status, details);
@@ -22889,14 +23591,16 @@ function assertAcceptableThroughHost(submissionGate, status, details, hostAction
22889
23591
  hostActions.failInfrastructure(error, ctx, toolCallId);
22890
23592
  }
22891
23593
  }
22892
- function createFixerRoleRuntime(pi, dependencies, hostActions) {
23594
+ function createFixerRoleRuntime(pi, dependencies, hostActions, options) {
22893
23595
  let soul;
22894
23596
  let packet;
22895
23597
  let packetPath;
22896
23598
  let prerequisitesPath;
22897
23599
  let phase;
22898
23600
  let lifecycleRegistered = false;
22899
- const submissionGate = createWorkerSubmissionGate();
23601
+ const submissionGate = createWorkerSubmissionGate({
23602
+ unfinishedReasonBounceLimit: options?.unfinishedReasonBounceLimit ?? deliveryLimitFromEnv(process.env)
23603
+ });
22900
23604
  pi.registerFlag(
22901
23605
  FIXER_FLAG_DEFINITIONS.packet.name,
22902
23606
  FIXER_FLAG_DEFINITIONS.packet.definition
@@ -22940,30 +23644,13 @@ function createFixerRoleRuntime(pi, dependencies, hostActions) {
22940
23644
  packet = Object.freeze({ instructions, prerequisites });
22941
23645
  if (!lifecycleRegistered) {
22942
23646
  lifecycleRegistered = true;
22943
- pi.registerTool({
22944
- name: FIXER_OUTPUT_TOOL_NAME,
22945
- label: "\u4FEE\u5185\u53F8\u8F93\u51FA",
22946
- description: "\u63D0\u4EA4\u4FEE\u5185\u53F8\u7EC8\u5C40\u56DE\u6267\u3002",
22947
- promptSnippet: "\u63D0\u4EA4\u4FEE\u5185\u53F8\u7EC8\u5C40\u56DE\u6267",
22948
- parameters: fixerOutputSchema,
22949
- async execute(toolCallId, parameters, _signal, _onUpdate, ctx) {
22950
- if (packet === void 0 || phase === void 0) {
22951
- throw new Error("\u4FEE\u5185\u53F8\u4FEE\u7406\u5305\u4E0E\u9636\u6BB5\u672A\u88C5\u8F7D");
22952
- }
22953
- const output = deepFreeze2(validateFixerOutput(parameters, phase));
22954
- const status = workerStatusOf(output);
22955
- if (status !== void 0) {
22956
- assertAcceptableThroughHost(
22957
- submissionGate,
22958
- status,
22959
- output,
22960
- hostActions,
22961
- ctx,
22962
- toolCallId
22963
- );
22964
- }
22965
- return { content: [], details: output, terminate: true };
22966
- }
23647
+ registerWorkerSubmission(pi, "fixer", {
23648
+ notReady: "\u4FEE\u5185\u53F8\u4FEE\u7406\u5305\u4E0E\u9636\u6BB5\u672A\u88C5\u8F7D",
23649
+ ready: () => packet !== void 0 && phase !== void 0,
23650
+ phase: () => phase,
23651
+ project: (parameters, current) => deepFreeze2(validateFixerOutput(parameters, current)),
23652
+ submissionGate,
23653
+ hostActions
22967
23654
  });
22968
23655
  pi.on("tool_call", (event) => {
22969
23656
  if (event.toolName !== "bash") return;
@@ -23002,17 +23689,19 @@ ${packetPath}
23002
23689
  });
23003
23690
  }
23004
23691
  },
23005
- armSubmissionGate(cwd, parent) {
23006
- submissionGate.arm(cwd, parent);
23692
+ armSubmissionGate(cwd, parent, invocationScopeId) {
23693
+ submissionGate.arm(cwd, parent, invocationScopeId);
23007
23694
  }
23008
23695
  };
23009
23696
  }
23010
- function createCoderRoleRuntime(pi, dependencies, hostActions) {
23697
+ function createCoderRoleRuntime(pi, dependencies, hostActions, options) {
23011
23698
  let soul;
23012
23699
  let task;
23013
23700
  let phase;
23014
23701
  let lifecycleRegistered = false;
23015
- const submissionGate = createWorkerSubmissionGate();
23702
+ const submissionGate = createWorkerSubmissionGate({
23703
+ unfinishedReasonBounceLimit: options?.unfinishedReasonBounceLimit ?? deliveryLimitFromEnv(process.env)
23704
+ });
23016
23705
  pi.registerFlag("ak-coder-task", {
23017
23706
  description: "Markdown task assigned to the coder role",
23018
23707
  type: "string"
@@ -23040,30 +23729,13 @@ function createCoderRoleRuntime(pi, dependencies, hostActions) {
23040
23729
  if (task.length === 0) throw new Error("Coder task is empty");
23041
23730
  if (!lifecycleRegistered) {
23042
23731
  lifecycleRegistered = true;
23043
- pi.registerTool({
23044
- name: CODER_OUTPUT_TOOL_NAME,
23045
- label: "\u5C06\u4F5C\u76D1\u8F93\u51FA",
23046
- description: "\u63D0\u4EA4\u5C06\u4F5C\u76D1\u7EC8\u5C40\u56DE\u6267\u3002",
23047
- promptSnippet: "\u63D0\u4EA4\u5C06\u4F5C\u76D1\u7EC8\u5C40\u56DE\u6267",
23048
- parameters: coderOutputSchema,
23049
- async execute(toolCallId, parameters, _signal, _onUpdate, ctx2) {
23050
- if (task === void 0 || phase === void 0) {
23051
- throw new Error("\u5C06\u4F5C\u76D1\u4EFB\u52A1\u4E0E\u9636\u6BB5\u672A\u88C5\u8F7D");
23052
- }
23053
- const output = validateWorkerOutput(parameters, phase, "Coder");
23054
- const status = workerStatusOf(output);
23055
- if (status !== void 0) {
23056
- assertAcceptableThroughHost(
23057
- submissionGate,
23058
- status,
23059
- output,
23060
- hostActions,
23061
- ctx2,
23062
- toolCallId
23063
- );
23064
- }
23065
- return { content: [], details: output, terminate: true };
23066
- }
23732
+ registerWorkerSubmission(pi, "coder", {
23733
+ notReady: "\u5C06\u4F5C\u76D1\u4EFB\u52A1\u4E0E\u9636\u6BB5\u672A\u88C5\u8F7D",
23734
+ ready: () => task !== void 0 && phase !== void 0,
23735
+ phase: () => phase,
23736
+ project: (parameters, current) => validateWorkerOutput(parameters, current, "Coder"),
23737
+ submissionGate,
23738
+ hostActions
23067
23739
  });
23068
23740
  pi.on("before_agent_start", (event, ctx2) => {
23069
23741
  if (soul === void 0) throw new Error("\u5C06\u4F5C\u76D1\u804C\u5206\u672A\u88C5\u8F7D");
@@ -23085,8 +23757,8 @@ ${task ?? ""}
23085
23757
  });
23086
23758
  }
23087
23759
  },
23088
- armSubmissionGate(cwd, parent) {
23089
- submissionGate.arm(cwd, parent);
23760
+ armSubmissionGate(cwd, parent, invocationScopeId) {
23761
+ submissionGate.arm(cwd, parent, invocationScopeId);
23090
23762
  }
23091
23763
  };
23092
23764
  }
@@ -23099,6 +23771,8 @@ init_merger_contracts();
23099
23771
 
23100
23772
  // src/merger-role.ts
23101
23773
  init_merger_contracts();
23774
+ init_filed_submission();
23775
+ init_role_submission_declarations();
23102
23776
  init_exact_utf8();
23103
23777
  var MERGER_INPUT_FLAG = { name: "ak-merger-input", definition: { description: "Path to Merger assignment materials JSON", type: "string" } };
23104
23778
  function materialText(input, key) {
@@ -23118,16 +23792,8 @@ function createMergerRoleRuntime(pi, dependencies) {
23118
23792
  activation = { soul, input };
23119
23793
  if (!registered) {
23120
23794
  registered = true;
23121
- pi.registerTool({
23122
- name: MERGER_OUTPUT_TOOL_NAME,
23123
- label: "\u5408\u5E76\u8F93\u51FA",
23124
- description: "\u63D0\u4EA4\u5408\u5E76\u7ED3\u679C\uFF1B\u8F93\u51FA\u5206\u652F\u4E3A completed \u4E0E escalate\u3002",
23125
- promptSnippet: "\u63D0\u4EA4\u5408\u5E76\u7ED3\u679C",
23126
- parameters: mergerOutputSchema,
23127
- async execute(_id, params, _signal, _update, _ctx) {
23128
- if (!activation) throw new Error("\u6821\u4E66\u90CE\u672A\u6FC0\u6D3B");
23129
- return { content: [], details: params, terminate: true };
23130
- }
23795
+ registerFiledSubmissionTool(pi, roleSubmissionDeclaration("merger"), {
23796
+ readyError: () => activation === void 0 ? "\u6821\u4E66\u90CE\u672A\u6FC0\u6D3B" : void 0
23131
23797
  });
23132
23798
  pi.on("before_agent_start", (event) => {
23133
23799
  if (!activation) throw new Error("\u6821\u4E66\u90CE\u672A\u6FC0\u6D3B");
@@ -23396,21 +24062,9 @@ function createFiledOfficerRuntime(roleHost, spec, dependencies) {
23396
24062
  soul = loaded;
23397
24063
  if (!registered) {
23398
24064
  registered = true;
23399
- roleHost.registerTool({
23400
- name: spec.tool.name,
23401
- label: spec.tool.label,
23402
- description: spec.tool.description,
23403
- promptSnippet: spec.tool.promptSnippet,
23404
- parameters: spec.tool.parameters,
23405
- async execute(toolCallId, parameters, signal, _onUpdate, ctx) {
23406
- if (soul === void 0) throw new Error(`${spec.role} \u804C\u5206\u672A\u88C5\u8F7D`);
23407
- const projected = spec.beforeAccept === void 0 ? void 0 : await spec.beforeAccept({ toolCallId, parameters, signal, ctx });
23408
- return {
23409
- content: [],
23410
- details: projected === void 0 ? parameters : projected,
23411
- terminate: true
23412
- };
23413
- }
24065
+ registerFiledSubmissionTool(roleHost, spec.tool, {
24066
+ readyError: () => soul === void 0 ? `${spec.role} \u804C\u5206\u672A\u88C5\u8F7D` : void 0,
24067
+ ...spec.beforeAccept === void 0 ? {} : { beforeAccept: spec.beforeAccept }
23414
24068
  });
23415
24069
  roleHost.on("before_agent_start", (event) => {
23416
24070
  if (soul === void 0) throw new Error(`${spec.role} \u804C\u5206\u672A\u88C5\u8F7D`);
@@ -23695,7 +24349,8 @@ function lastAssistantProse(messages) {
23695
24349
  }
23696
24350
  return void 0;
23697
24351
  }
23698
- function createRoleRuntimeExtension(dependencies) {
24352
+ function createRoleRuntimeExtension(dependencies, deliveryRequestLimit) {
24353
+ const deliveryLimit = deliveryRequestLimit === void 0 ? deliveryLimitFromEnv(process.env) : deliveryLimitFromConfig(deliveryRequestLimit);
23699
24354
  return (envelopeHost) => {
23700
24355
  let projectClosedSubmission = async () => {
23701
24356
  throw new Error("\u89D2\u8272\u7EC8\u5C40\u6295\u5C04\u63A5\u7F1D\u5C1A\u672A\u521D\u59CB\u5316");
@@ -23752,7 +24407,7 @@ function createRoleRuntimeExtension(dependencies) {
23752
24407
  const pendingInfrastructureFailures = /* @__PURE__ */ new Map();
23753
24408
  const pendingSubmissionNonPassByToolCallId = /* @__PURE__ */ new Map();
23754
24409
  let engineDetourRegistered = false;
23755
- let receiptDelivery = createReceiptDeliveryPolicy();
24410
+ let receiptDelivery = createReceiptDeliveryPolicy(deliveryLimit);
23756
24411
  let noReceiptRecorded = false;
23757
24412
  let priorFetch;
23758
24413
  let fetchWrapped = false;
@@ -23915,7 +24570,7 @@ function createRoleRuntimeExtension(dependencies) {
23915
24570
  }
23916
24571
  };
23917
24572
  });
23918
- roleHost.on("tool_result", async (event) => {
24573
+ roleHost.on("tool_result", async (event, ctx) => {
23919
24574
  const role = selectedRole;
23920
24575
  if (role === void 0) return;
23921
24576
  const pendingInfra = pendingInfrastructureFailures.get(event.toolCallId);
@@ -23927,9 +24582,17 @@ function createRoleRuntimeExtension(dependencies) {
23927
24582
  const outputClassification = isOutputTool ? classifyPackagedRoleTerminalResult(classified) : void 0;
23928
24583
  if (isRoleInfrastructureFailure || outputClassification?.kind === "infrastructure") {
23929
24584
  receiptDelivery.stopForInfrastructure();
23930
- } else if (isOutputTool && outputClassification?.kind === "nonterminal" && event.isError) {
23931
- const reason = (event.content ?? []).map((part) => part.type === "text" && "text" in part ? part.text : "").join("").trim();
23932
- receiptDelivery.recordRejected(reason);
24585
+ } else if (isOutputTool) {
24586
+ const reason = packagedRoleOutputRejectionReason(classified);
24587
+ if (reason !== void 0) {
24588
+ receiptDelivery.recordRejected(reason);
24589
+ if (ctx.invocationScopeId !== void 0) {
24590
+ envelopeHost.appendEntry(RECEIPT_REJECTION_ENTRY, {
24591
+ invocationScopeId: ctx.invocationScopeId,
24592
+ reason
24593
+ });
24594
+ }
24595
+ }
23933
24596
  }
23934
24597
  const settlement = isRoleInfrastructureFailure || outputClassification?.kind === "infrastructure" ? publicNavigatorSettlement(role, navigatorPhase(roleHost, role), classified) : void 0;
23935
24598
  await settleNavigatorProjection(settlement);
@@ -23971,10 +24634,11 @@ function createRoleRuntimeExtension(dependencies) {
23971
24634
  const runPointer = runDirectoryFromHostContext(ctx);
23972
24635
  if (runPointer !== void 0) {
23973
24636
  noReceiptRecorded = true;
23974
- while (receiptDelivery.nextAction() === "request-delivery") {
23975
- receiptDelivery.recordDeliveryRequest();
23976
- }
23977
- const facts = receiptDelivery.facts({ runPointer, attemptPointer: `current:${runPointer}` });
24637
+ receiptDelivery.closeBudget();
24638
+ const facts = receiptDelivery.facts({
24639
+ runPointer,
24640
+ attemptPointer: receiptAttemptPointer(runPointer, ctx.invocationScopeId)
24641
+ });
23978
24642
  envelopeHost.appendEntry(NO_RECEIPT_LIFECYCLE_ENTRY_TYPE, facts);
23979
24643
  try {
23980
24644
  sitianReport({
@@ -23993,7 +24657,11 @@ function createRoleRuntimeExtension(dependencies) {
23993
24657
  }
23994
24658
  if (receiptDelivery.nextAction() === "request-delivery") {
23995
24659
  receiptDelivery.recordDeliveryRequest();
23996
- envelopeHost.appendEntry("ak-receipt-delivery-request");
24660
+ const scopeId = ctx.invocationScopeId?.trim() ?? "";
24661
+ envelopeHost.appendEntry(
24662
+ RECEIPT_DELIVERY_REQUEST_ENTRY,
24663
+ scopeId.length > 0 ? { invocationScopeId: scopeId } : void 0
24664
+ );
23997
24665
  try {
23998
24666
  sitianReport({
23999
24667
  level: "event",
@@ -24014,7 +24682,10 @@ function createRoleRuntimeExtension(dependencies) {
24014
24682
  const runPointer = runDirectoryFromHostContext(ctx);
24015
24683
  if (runPointer !== void 0) {
24016
24684
  noReceiptRecorded = true;
24017
- const facts = receiptDelivery.facts({ runPointer, attemptPointer: `current:${runPointer}` });
24685
+ const facts = receiptDelivery.facts({
24686
+ runPointer,
24687
+ attemptPointer: receiptAttemptPointer(runPointer, ctx.invocationScopeId)
24688
+ });
24018
24689
  envelopeHost.appendEntry(NO_RECEIPT_LIFECYCLE_ENTRY_TYPE, facts);
24019
24690
  try {
24020
24691
  sitianReport({
@@ -24101,7 +24772,8 @@ function createRoleRuntimeExtension(dependencies) {
24101
24772
  return dependencies.loadFixPacket(path);
24102
24773
  }
24103
24774
  },
24104
- hostActions
24775
+ hostActions,
24776
+ { unfinishedReasonBounceLimit: deliveryLimit }
24105
24777
  );
24106
24778
  const coder = createCoderRoleRuntime(
24107
24779
  roleHost,
@@ -24114,7 +24786,8 @@ function createRoleRuntimeExtension(dependencies) {
24114
24786
  return dependencies.loadCoderTask(path);
24115
24787
  }
24116
24788
  },
24117
- hostActions
24789
+ hostActions,
24790
+ { unfinishedReasonBounceLimit: deliveryLimit }
24118
24791
  );
24119
24792
  const reviewer = createReviewerRoleRuntime(
24120
24793
  roleHost,
@@ -24297,7 +24970,7 @@ function createRoleRuntimeExtension(dependencies) {
24297
24970
  roleReferenceMaterials = "";
24298
24971
  activeReviewerParent = void 0;
24299
24972
  activeCollector = void 0;
24300
- receiptDelivery = createReceiptDeliveryPolicy();
24973
+ receiptDelivery = createReceiptDeliveryPolicy(deliveryLimit);
24301
24974
  noReceiptRecorded = false;
24302
24975
  pendingNavigatorPresentation = void 0;
24303
24976
  navigatorActivation += 1;
@@ -24343,6 +25016,12 @@ function createRoleRuntimeExtension(dependencies) {
24343
25016
  try {
24344
25017
  resolveBookKeyFromGit(ctx.cwd);
24345
25018
  durableSessionPointer(ctx.sessionManager);
25019
+ const scopeId = ctx.invocationScopeId?.trim() ?? "";
25020
+ if (scopeId.length > 0) {
25021
+ receiptDelivery.continueIssued(
25022
+ priorReceiptContinuation(ctx.sessionManager.getEntries(), scopeId)
25023
+ );
25024
+ }
24346
25025
  const isStationChild = roleHost.getFlag(STATION_CHILD_FLAG.name) === true;
24347
25026
  if (dependencies.createNavigatorAttendance !== void 0 && entry.outputTool !== NAVIGATOR_TOOL_SPEC.name && !isStationChild) {
24348
25027
  navigatorSessionParent = ctx.sessionManager.getSessionFile();
@@ -24406,6 +25085,7 @@ function createRoleRuntimeExtension(dependencies) {
24406
25085
  subject: work.subject,
24407
25086
  authority: work.authority,
24408
25087
  invocationId,
25088
+ deliveryRequestLimit: deliveryLimit,
24409
25089
  ...contextError === void 0 ? {} : { contextError },
24410
25090
  onEvent: (navigatorEvent, report) => {
24411
25091
  if (activation === navigatorActivation && !navigatorDeliveryClosed) {
@@ -24429,7 +25109,7 @@ function createRoleRuntimeExtension(dependencies) {
24429
25109
  }
24430
25110
  if ("worker" in entry && entry.worker === true) {
24431
25111
  const workerArms = { coder, fixer };
24432
- workerArms[entry.role].armSubmissionGate(ctx.cwd, ctx.sessionManager);
25112
+ workerArms[entry.role].armSubmissionGate(ctx.cwd, ctx.sessionManager, ctx.invocationScopeId);
24433
25113
  }
24434
25114
  admitted = true;
24435
25115
  } catch (error) {
@@ -24459,11 +25139,11 @@ function createRoleRuntimeDependencies(packageRoot) {
24459
25139
  packageRoot,
24460
25140
  loadRoleReferenceMaterials: loadPackagedRoleReferenceMaterials,
24461
25141
  loadRoleSoul: loadRegisteredRoleSoul,
24462
- loadFixPacket: (path) => readFile24(path, "utf8"),
24463
- loadCoderTask: (path) => readFile24(path, "utf8"),
25142
+ loadFixPacket: (path) => readFile25(path, "utf8"),
25143
+ loadCoderTask: (path) => readFile25(path, "utf8"),
24464
25144
  loadDoctorCase,
24465
25145
  loadNotarySourceRun: loadNotarySourceRunLocator,
24466
- loadMergerInput: async (path) => JSON.parse(await readFile24(path, "utf8")),
25146
+ loadMergerInput: async (path) => JSON.parse(await readFile25(path, "utf8")),
24467
25147
  loadNavigatorWorkContext: (options) => loadNavigatorWorkContext({
24468
25148
  context: options.context,
24469
25149
  role: options.role,
@@ -24478,6 +25158,7 @@ function createRoleRuntimeDependencies(packageRoot) {
24478
25158
  authority: options.authority,
24479
25159
  invocationId: options.invocationId,
24480
25160
  createSession: navigatorSessionFactory,
25161
+ ...options.deliveryRequestLimit === void 0 ? {} : { deliveryRequestLimit: options.deliveryRequestLimit },
24481
25162
  ...options.contextError === void 0 ? {} : { contextError: options.contextError },
24482
25163
  onEvent: options.onEvent
24483
25164
  })
@@ -24487,6 +25168,7 @@ function createRoleRuntimeDependencies(packageRoot) {
24487
25168
  // src/role-envelope.ts
24488
25169
  init_engine_detour();
24489
25170
  init_packaged_role_registry();
25171
+ init_receipt_delivery_policy();
24490
25172
  import { randomUUID as randomUUID9 } from "node:crypto";
24491
25173
  import { appendFile as appendFile3, mkdir as mkdir5, writeFile as writeFile9 } from "node:fs/promises";
24492
25174
  import { createServer } from "node:net";
@@ -24672,7 +25354,10 @@ async function prepareRoleEnvelope(options) {
24672
25354
  stopKeepalive() {
24673
25355
  }
24674
25356
  };
24675
- createRoleRuntimeExtension(options.dependencies)(envelope);
25357
+ createRoleRuntimeExtension(
25358
+ options.dependencies,
25359
+ deliveryLimitFromConfig(options.request.deliveryRequestLimit)
25360
+ )(envelope);
24676
25361
  const token = randomUUID9();
24677
25362
  const server = createServer((socket) => serveSocket(socket));
24678
25363
  function rememberProjectedRejection(details, toolCallId, content) {
@@ -25064,8 +25749,9 @@ import { writeFile as writeFile10 } from "node:fs/promises";
25064
25749
  import { dirname as dirname26, isAbsolute as isAbsolute12, join as join45, resolve as resolve21 } from "node:path";
25065
25750
 
25066
25751
  // src/external-host-turn-loop.ts
25752
+ init_receipt_delivery_policy();
25753
+ init_submission_errors();
25067
25754
  init_unknown_value();
25068
- var EXTERNAL_ROLE_TURN_ROUND_LIMIT = 8;
25069
25755
  function mergeRoleTurnAbortSignals(prepared, request) {
25070
25756
  if (request === void 0) return prepared;
25071
25757
  if (prepared === void 0) return request;
@@ -25114,7 +25800,10 @@ async function driveExternalRoleTurnRounds(prepared, request, driver) {
25114
25800
  let prompt = prepared.prompt;
25115
25801
  const abortSignal = mergeRoleTurnAbortSignals(prepared.abortSignal, request.signal);
25116
25802
  let stderr = "";
25117
- for (let attempt = 0; attempt < EXTERNAL_ROLE_TURN_ROUND_LIMIT; attempt += 1) {
25803
+ const countedReaskLimit = deliveryLimitFromConfig(request.deliveryRequestLimit);
25804
+ const exemptReminders = /* @__PURE__ */ new Set();
25805
+ let countedReasks = 0;
25806
+ for (let attempt = 0; ; attempt += 1) {
25118
25807
  if (abortSignal?.aborted) return settleHostAborted(prepared, driver.currentSessionId());
25119
25808
  let round;
25120
25809
  try {
@@ -25135,14 +25824,22 @@ async function driveExternalRoleTurnRounds(prepared, request, driver) {
25135
25824
  return { code: 0, stderr, timedOut: false };
25136
25825
  }
25137
25826
  if ("failure" in closure) return asFailure(closure.failure, stderr);
25827
+ const reminderCode = closure.retry.code;
25828
+ const exempt = isOneShotWorkerReminderCode(reminderCode) && !exemptReminders.has(reminderCode);
25829
+ if (exempt) exemptReminders.add(reminderCode);
25830
+ else {
25831
+ countedReasks += 1;
25832
+ if (countedReasks > countedReaskLimit) {
25833
+ return asFailure({
25834
+ cause: "output",
25835
+ identity: { name: driver.roundLimitName, code: "round-retry-limit" },
25836
+ ...driver.currentSessionId() === void 0 ? {} : { details: { sessionId: driver.currentSessionId() } }
25837
+ });
25838
+ }
25839
+ }
25138
25840
  prompt = closure.retry.message;
25139
25841
  driver.afterRetry?.();
25140
25842
  }
25141
- return asFailure({
25142
- cause: "output",
25143
- identity: { name: driver.roundLimitName, code: "round-retry-limit" },
25144
- ...driver.currentSessionId() === void 0 ? {} : { details: { sessionId: driver.currentSessionId() } }
25145
- });
25146
25843
  }
25147
25844
  function createSerializedRoleTurnHost(execute) {
25148
25845
  let serial = Promise.resolve();