@attalabs/vinaya 0.39.0 → 0.41.0

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 (186) hide show
  1. package/README.md +9 -9
  2. package/aeg-root/contracts/developer-reviewer.md +2 -2
  3. package/aeg-root/contracts/planner-developer.md +5 -5
  4. package/aeg-root/enforcement.md +22 -22
  5. package/aeg-root/process.md +4 -4
  6. package/aeg-root/roles/archivist.md +1 -1
  7. package/aeg-root/roles/developer/reference.md +7 -1
  8. package/aeg-root/roles/developer.md +1 -1
  9. package/aeg-root/roles/planner/reference.md +18 -5
  10. package/aeg-root/roles/principal.md +1 -1
  11. package/aeg-root/roles/reviewer.md +3 -3
  12. package/aeg-root/roles/security.md +4 -4
  13. package/aeg-root/roles/tranche-archivist.md +2 -2
  14. package/aeg-root/skills/aeg/SKILL.md +1 -1
  15. package/aeg-root/state-machine.md +10 -15
  16. package/aeg-root/templates/brief-template.md +5 -2
  17. package/aeg-root/templates/decision-record-template.md +38 -0
  18. package/aeg-root/templates/issue-rationale-template.md +1 -1
  19. package/aeg-root/tranche-model.md +1 -1
  20. package/dist/checks/bin/check-body-bare-digits.js +1974 -354
  21. package/dist/checks/bin/check-branch-topology.js +1296 -243
  22. package/dist/checks/bin/check-brief-shape.js +2038 -460
  23. package/dist/checks/bin/check-changeset-coverage.js +2411 -564
  24. package/dist/checks/bin/check-ci-shard-coverage.js +12391 -15
  25. package/dist/checks/bin/check-closes-n.js +1296 -243
  26. package/dist/checks/bin/check-coherence.js +1914 -1155
  27. package/dist/checks/bin/check-dead-branch-push.js +1242 -230
  28. package/dist/checks/bin/check-dispatch-readiness.js +2222 -460
  29. package/dist/checks/bin/check-doc-claims.js +2233 -260
  30. package/dist/checks/bin/check-doc-coverage-push.js +2436 -550
  31. package/dist/checks/bin/check-doc-coverage.js +2434 -552
  32. package/dist/checks/bin/check-doctrine-no-procedures.js +1776 -353
  33. package/dist/checks/bin/check-doctrine-portability.js +2408 -561
  34. package/dist/checks/bin/check-evidence-fresh.js +2370 -508
  35. package/dist/checks/bin/check-exec-bits.js +2407 -560
  36. package/dist/checks/bin/check-first-push-dispatch.js +1984 -380
  37. package/dist/checks/bin/check-issue-assignment.js +712 -170
  38. package/dist/checks/bin/check-issue-milestone-attach.js +1233 -230
  39. package/dist/checks/bin/check-issue-objectives-numbering.js +1769 -346
  40. package/dist/checks/bin/check-issue-parts-coverage.js +1233 -230
  41. package/dist/checks/bin/check-issue-surface-globs.js +1926 -378
  42. package/dist/checks/bin/check-issue-title-grammar.js +1233 -230
  43. package/dist/checks/bin/check-issue-tranche-label.js +702 -170
  44. package/dist/checks/bin/check-main-branch-refusal.js +1245 -232
  45. package/dist/checks/bin/check-no-disk-state.js +1233 -230
  46. package/dist/checks/bin/check-pr-premise-reassert.js +1769 -346
  47. package/dist/checks/bin/check-pr-report-density.js +1233 -230
  48. package/dist/checks/bin/check-principal-test-plan-wait.js +2489 -259
  49. package/dist/checks/bin/check-quoted-command.js +2391 -544
  50. package/dist/checks/bin/check-reader-resolvable-prose.js +2437 -564
  51. package/dist/checks/bin/check-registry-gates.js +1380 -296
  52. package/dist/checks/bin/check-retired-vocabulary.js +2416 -550
  53. package/dist/checks/bin/check-review-gate.js +2073 -371
  54. package/dist/checks/bin/check-single-plan-pr.js +1297 -235
  55. package/dist/checks/bin/check-surface-scope.js +1531 -252
  56. package/dist/checks/bin/check-test-plan.js +2487 -258
  57. package/dist/checks/bin/check-token-collection-wired.js +1233 -230
  58. package/dist/checks/bin/check-workspace-escape.js +2408 -561
  59. package/dist/checks/bin/verify-coherence.js +597 -97
  60. package/dist/checks/bin/verify-dispatch.js +632 -152
  61. package/dist/checks/bin/verify-docs.js +642 -132
  62. package/dist/index.js +25948 -16630
  63. package/dist/lib/pre-push-cache-test-run.js +1813 -297
  64. package/dist/lib/pre-push-changed-files.js +65 -19
  65. package/dist/lib/pre-push-mode.js +466 -0
  66. package/dist/lib/pre-push-progress-dir.js +4205 -0
  67. package/dist/lib/pre-push-record-tests.js +446 -0
  68. package/dist/lib/pre-push-select-tests.js +2353 -632
  69. package/dist/lib/push-progress-observer.js +4213 -0
  70. package/package.json +22 -5
  71. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/anchored-region.ts +17 -3
  72. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/brief-render.ts +73 -30
  73. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/brief-validation.ts +3 -3
  74. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/coherence-checks.ts +2 -2
  75. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/local.ts +88 -5
  76. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/records.ts +34 -2
  77. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/assess-round.ts +26 -4
  78. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/fakes.ts +7 -2
  79. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/index.ts +7 -1
  80. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/types.ts +29 -3
  81. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dispatch-gate.ts +35 -18
  82. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/docs/index.ts +1 -1
  83. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/docs/published-prose.ts +70 -45
  84. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/doctrine-portability.ts +6 -1
  85. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/entry-point.ts +27 -0
  86. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/gate-audience.ts +3 -5
  87. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/index.ts +96 -9
  88. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/issue-assignment.ts +24 -54
  89. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/issue-validation.ts +809 -106
  90. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/live-record.ts +179 -0
  91. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/envelope.ts +8 -2
  92. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/index.ts +1 -0
  93. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/narration.ts +2 -0
  94. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/schema-digest.ts +225 -0
  95. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/schema.ts +7 -1
  96. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/main-branch-refusal.ts +23 -1
  97. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/pr-report-density.ts +6 -4
  98. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/principals-config.ts +44 -0
  99. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/prose-rules.ts +532 -0
  100. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/protected-paths.ts +31 -0
  101. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/reader-resolvable-prose.ts +157 -80
  102. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/registry-checks.ts +8 -12
  103. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/retired-vocabulary.ts +53 -93
  104. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-gate.ts +46 -17
  105. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-input-manifest.ts +85 -1
  106. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-policy.ts +32 -13
  107. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/ruling-ordinal.ts +46 -0
  108. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/task-branch-identity.ts +2 -4
  109. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/test-plan-gate.ts +63 -8
  110. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/verdict-extraction.ts +24 -0
  111. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/waiver-label.ts +0 -1
  112. package/studio-standalone/apps/vinaya-studio/web/.next/BUILD_ID +1 -1
  113. package/studio-standalone/apps/vinaya-studio/web/.next/build-manifest.json +3 -3
  114. package/studio-standalone/apps/vinaya-studio/web/.next/prerender-manifest.json +3 -3
  115. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.html +1 -1
  116. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.rsc +1 -1
  117. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  118. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  119. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  120. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  121. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  122. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page/server-reference-manifest.json +2 -2
  123. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page.js.nft.json +1 -1
  124. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  125. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page/server-reference-manifest.json +2 -2
  126. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page.js.nft.json +1 -1
  127. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page_client-reference-manifest.js +1 -1
  128. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page/server-reference-manifest.json +2 -2
  129. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page.js +1 -1
  130. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page.js.nft.json +1 -1
  131. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page_client-reference-manifest.js +1 -1
  132. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page/server-reference-manifest.json +2 -2
  133. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page.js +1 -1
  134. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page.js.nft.json +1 -1
  135. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page_client-reference-manifest.js +1 -1
  136. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page/server-reference-manifest.json +2 -2
  137. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page.js +1 -1
  138. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page.js.nft.json +1 -1
  139. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page_client-reference-manifest.js +1 -1
  140. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page/server-reference-manifest.json +3 -3
  141. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page.js +1 -1
  142. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page.js.nft.json +1 -1
  143. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page_client-reference-manifest.js +1 -1
  144. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page/server-reference-manifest.json +2 -2
  145. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page.js +2 -2
  146. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page.js.nft.json +1 -1
  147. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page_client-reference-manifest.js +1 -1
  148. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page/server-reference-manifest.json +2 -2
  149. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page.js +1 -1
  150. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page.js.nft.json +1 -1
  151. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page_client-reference-manifest.js +1 -1
  152. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page/server-reference-manifest.json +2 -2
  153. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page.js +1 -1
  154. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page.js.nft.json +1 -1
  155. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page_client-reference-manifest.js +1 -1
  156. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/1q96_modules_@clerk_nextjs_dist_esm_app-router_client_keyless-creator-reader_0lom2js.js +1 -1
  157. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__08e39jo._.js +1 -1
  158. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0ls23oh._.js +1 -1
  159. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0sxadt2._.js +13 -0
  160. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1a3j3n1._.js +57 -0
  161. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{[root-of-the-server]__1ug9syi._.js → [root-of-the-server]__1d4eth3._.js} +1 -1
  162. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1gjqmhq._.js +1 -1
  163. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1snpgaw._.js +3 -3
  164. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1wc4-ip._.js +1 -1
  165. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_08onyya._.js +2 -2
  166. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_096f46i._.js +1 -1
  167. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0af2one._.js +1 -1
  168. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0e5tkdd._.js +1 -1
  169. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0kf2g72._.js +1 -1
  170. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0zf4d27._.js +3 -3
  171. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1-wo68i._.js +1 -1
  172. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1achbh9._.js +1 -1
  173. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/node_modules_@clerk_nextjs_dist_esm_app-router_server-actions_1x7vfhn.js +2 -2
  174. package/studio-standalone/apps/vinaya-studio/web/.next/server/middleware-build-manifest.js +3 -3
  175. package/studio-standalone/apps/vinaya-studio/web/.next/server/pages/500.html +1 -1
  176. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.js +1 -1
  177. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.json +4 -4
  178. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{33rszkngkuoko.js → 0x7u6si-ai179.js} +1 -1
  179. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{06_55xbp7rcbi.js → 2fu7mfsj4oima.js} +1 -1
  180. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{2brkwv169ygep.js → 34b4ruddunn3q.js} +1 -1
  181. package/studio-standalone/apps/vinaya-studio/web/package.json +2 -2
  182. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__04adkz-._.js +0 -57
  183. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__19jyp3m._.js +0 -13
  184. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{D3LiJNIq5FWZxen7CpOSJ → 2ZARxTwpuRew8-SvYsRdU}/_buildManifest.js +0 -0
  185. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{D3LiJNIq5FWZxen7CpOSJ → 2ZARxTwpuRew8-SvYsRdU}/_clientMiddlewareManifest.js +0 -0
  186. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{D3LiJNIq5FWZxen7CpOSJ → 2ZARxTwpuRew8-SvYsRdU}/_ssgManifest.js +0 -0
@@ -2,7 +2,7 @@
2
2
 
3
3
  // src/checks/bin/check-exec-bits.ts
4
4
  import { execFileSync as execFileSync9 } from "node:child_process";
5
- import { readFileSync as readFileSync8 } from "node:fs";
5
+ import { readFileSync as readFileSync9 } from "node:fs";
6
6
 
7
7
  // src/checks/contract.ts
8
8
  var CHECK_SCHEMA_VERSION = 1;
@@ -13,7 +13,7 @@ function emitCheckError(error) {
13
13
 
14
14
  // src/lib/diff-evidence.ts
15
15
  import { execFileSync as execFileSync8 } from "node:child_process";
16
- import { join as join9, relative as relative2, resolve as resolve2 } from "node:path";
16
+ import { join as join10, relative as relative2, resolve as resolve2 } from "node:path";
17
17
 
18
18
  // ../../packages/aeg-core/src/entry-point.ts
19
19
  import { realpathSync } from "node:fs";
@@ -54,7 +54,6 @@ var GATE_AUDIENCE = {
54
54
  };
55
55
  var NON_GATE_BINS = [
56
56
  "archive-task",
57
- "assign-task-issue",
58
57
  "dead-branch-audit",
59
58
  "eval-agent-compliance",
60
59
  "open-issue",
@@ -317,6 +316,25 @@ async function runAsync(args) {
317
316
  function ghApiGet(path) {
318
317
  return JSON.parse(run(["api", path]));
319
318
  }
319
+ var MAX_PER_PAGE = 100;
320
+ var MAX_PAGES = 100;
321
+ async function ghApiGetAllPagesAsync(pathWithoutPage, opts) {
322
+ const [base = pathWithoutPage, query = ""] = pathWithoutPage.split("?");
323
+ const params = new URLSearchParams(query);
324
+ params.set("per_page", String(MAX_PER_PAGE));
325
+ const all = [];
326
+ for (let page = 1;page <= MAX_PAGES; page++) {
327
+ params.set("page", String(page));
328
+ const args = ["api", `${base}?${params.toString()}`];
329
+ if (opts?.jq)
330
+ args.push("-q", opts.jq);
331
+ const batch = JSON.parse(await runAsync(args));
332
+ all.push(...batch);
333
+ if (batch.length < MAX_PER_PAGE)
334
+ return all;
335
+ }
336
+ throw new Error(`ghApiGetAllPagesAsync: "${pathWithoutPage}" did not terminate within ${MAX_PAGES} pages (${MAX_PAGES * MAX_PER_PAGE} items) — refusing to keep walking.`);
337
+ }
320
338
  function issueListByLabelArgs(owner, repo, label) {
321
339
  return [
322
340
  "issue",
@@ -728,6 +746,10 @@ function intentGoalForSlug(description, slug) {
728
746
  function matchesLegacyMilestone(milestones, slug) {
729
747
  return milestones.find((m) => m.title === slug) ?? null;
730
748
  }
749
+ var TRANCHE_SLUG_SHAPE = /^[a-z0-9]+(?:-[a-z0-9]+)*-v\d+$/;
750
+ function slugShapedTitles(milestones) {
751
+ return milestones.map((m) => m.title).filter((t) => TRANCHE_SLUG_SHAPE.test(t));
752
+ }
731
753
  function factsFromLegacyMilestone(milestone) {
732
754
  return {
733
755
  goal: milestone.description ?? "",
@@ -761,6 +783,105 @@ function findMilestoneForSlug(owner, repo, slug) {
761
783
  return resolveLegacyFacts(legacy, issues);
762
784
  return { goal: goalFromMilestones(milestones, slug), lifecycle: lifecycleFromIssues(issues) };
763
785
  }
786
+ function trancheSlugsFromLabels(labels) {
787
+ const slugs = [];
788
+ for (const l of labels) {
789
+ const slug = trancheSlugOf(l.name);
790
+ if (slug !== null)
791
+ slugs.push(slug);
792
+ }
793
+ return slugs;
794
+ }
795
+ async function indexTrancheMilestonesAsync(owner, repo, options = {}) {
796
+ const read = (fetch2) => options.retryFailedReads ? retryOnce(fetch2) : fetch2();
797
+ const [milestones, labels] = await Promise.all([
798
+ read(() => ghApiGetAllPagesAsync(`repos/${owner}/${repo}/milestones?state=all&per_page=100`)),
799
+ read(() => ghApiGetAllPagesAsync(`repos/${owner}/${repo}/labels?per_page=100`))
800
+ ]);
801
+ const active = [];
802
+ const archived = [];
803
+ const facts = new Map;
804
+ const legacySlugs = new Set(slugShapedTitles(milestones));
805
+ const legacyMilestoneBySlug = new Map(milestones.filter((m) => legacySlugs.has(m.title)).map((m) => [m.title, m]));
806
+ const newPathSlugs = trancheSlugsFromLabels(labels).filter((slug) => !legacySlugs.has(slug));
807
+ const uniqueNewPathSlugs = [...new Set(newPathSlugs)];
808
+ const uniqueLegacySlugs = [...legacySlugs];
809
+ const [legacyIssuesBySlug, newPathIssuesBySlug] = await Promise.all([
810
+ Promise.all(uniqueLegacySlugs.map((slug) => read(() => ghIssueListByLabelAsync(owner, repo, trancheLabel(slug))))),
811
+ Promise.all(uniqueNewPathSlugs.map((slug) => read(() => ghIssueListByLabelAsync(owner, repo, trancheLabel(slug)))))
812
+ ]);
813
+ const issuesBySlug = new Map;
814
+ uniqueLegacySlugs.forEach((slug, i) => {
815
+ issuesBySlug.set(slug, legacyIssuesBySlug[i] ?? []);
816
+ });
817
+ uniqueNewPathSlugs.forEach((slug, i) => {
818
+ issuesBySlug.set(slug, newPathIssuesBySlug[i] ?? []);
819
+ });
820
+ uniqueLegacySlugs.forEach((slug, i) => {
821
+ const m = legacyMilestoneBySlug.get(slug);
822
+ if (!m)
823
+ return;
824
+ const ref = { slug, goal: m.description ?? "" };
825
+ const f = resolveLegacyFacts(m, legacyIssuesBySlug[i] ?? []);
826
+ if (f.lifecycle === "complete")
827
+ archived.push(ref);
828
+ else if (f.lifecycle === "active")
829
+ active.push(ref);
830
+ facts.set(slug, f);
831
+ });
832
+ uniqueNewPathSlugs.forEach((slug, i) => {
833
+ const issues = newPathIssuesBySlug[i] ?? [];
834
+ const lifecycle = lifecycleFromIssues(issues);
835
+ const goal = goalFromMilestones(milestones, slug);
836
+ const f = { goal, lifecycle };
837
+ facts.set(slug, f);
838
+ if (lifecycle === "active")
839
+ active.push({ slug, goal });
840
+ else if (lifecycle === "complete")
841
+ archived.push({ slug, goal });
842
+ });
843
+ return { active, archived, facts, legacySlugs, issuesBySlug };
844
+ }
845
+ async function retryOnce(fetch2) {
846
+ try {
847
+ return await fetch2();
848
+ } catch {
849
+ return fetch2();
850
+ }
851
+ }
852
+ async function indexTrancheMilestonesForSlugAsync(owner, repo, slug) {
853
+ const [milestones, labels, issues] = await Promise.all([
854
+ ghApiGetAllPagesAsync(`repos/${owner}/${repo}/milestones?state=all&per_page=100`),
855
+ ghApiGetAllPagesAsync(`repos/${owner}/${repo}/labels?per_page=100`),
856
+ ghIssueListByLabelAsync(owner, repo, trancheLabel(slug))
857
+ ]);
858
+ const active = [];
859
+ const archived = [];
860
+ const facts = new Map;
861
+ const legacySlugs = new Set;
862
+ const legacyMilestone = slugShapedTitles(milestones).includes(slug) ? matchesLegacyMilestone(milestones, slug) : null;
863
+ if (legacyMilestone) {
864
+ legacySlugs.add(slug);
865
+ const ref = { slug, goal: legacyMilestone.description ?? "" };
866
+ const f = resolveLegacyFacts(legacyMilestone, issues);
867
+ if (f.lifecycle === "complete")
868
+ archived.push(ref);
869
+ else if (f.lifecycle === "active")
870
+ active.push(ref);
871
+ facts.set(slug, f);
872
+ } else if (trancheSlugsFromLabels(labels).includes(slug)) {
873
+ const lifecycle = lifecycleFromIssues(issues);
874
+ const goal = goalFromMilestones(milestones, slug);
875
+ facts.set(slug, { goal, lifecycle });
876
+ if (lifecycle === "active")
877
+ active.push({ slug, goal });
878
+ else if (lifecycle === "complete")
879
+ archived.push({ slug, goal });
880
+ }
881
+ const openLegacyTitles = new Set(slugShapedTitles(milestones.filter((m) => m.state === "open")));
882
+ const otherOpenLegacySlugs = [...openLegacyTitles].filter((t) => t !== slug);
883
+ return { active, archived, facts, legacySlugs, otherOpenLegacySlugs };
884
+ }
764
885
 
765
886
  // ../../packages/aeg-forge-state/src/derive-from-forge.ts
766
887
  function trancheFromIssues(slug, issues, known) {
@@ -1421,6 +1542,125 @@ var graphql2 = withDefaults3(request, {
1421
1542
  method: "POST",
1422
1543
  url: "/graphql"
1423
1544
  });
1545
+
1546
+ // ../../packages/aeg-forge-state/src/fetch-provenance.ts
1547
+ var PROVENANCE_PATTERN = /^###\s+AEG provenance\b/im;
1548
+ function provenanceMatchesIssue(text, issueNum) {
1549
+ if (!PROVENANCE_PATTERN.test(text))
1550
+ return false;
1551
+ const m = text.match(/^-\s*Issue:\s*#(\d+)/im);
1552
+ return m !== null && Number(m[1]) === issueNum;
1553
+ }
1554
+ function isPrCloser(closer) {
1555
+ return closer !== null && typeof closer.number === "number";
1556
+ }
1557
+ async function fetchProvenanceViaCrossReferences(issueNums, owner, repo, token) {
1558
+ const result = new Map;
1559
+ if (issueNums.length === 0)
1560
+ return result;
1561
+ const client = graphql2.defaults({ headers: { authorization: `bearer ${token}` } });
1562
+ const perIssue = issueNums.map((n) => `
1563
+ i_${n}: issue(number: ${n}) {
1564
+ timelineItems(first: 50, itemTypes: [CROSS_REFERENCED_EVENT]) {
1565
+ nodes {
1566
+ ... on CrossReferencedEvent {
1567
+ source {
1568
+ ... on PullRequest {
1569
+ number
1570
+ body
1571
+ comments(first: 50) { nodes { body } }
1572
+ }
1573
+ }
1574
+ }
1575
+ }
1576
+ }
1577
+ }`).join("");
1578
+ const query = `query ProvenanceCrossRef($owner: String!, $repo: String!) {
1579
+ repository(owner: $owner, name: $repo) {${perIssue}
1580
+ }
1581
+ }`;
1582
+ let response;
1583
+ try {
1584
+ response = await client(query, { owner, repo });
1585
+ } catch {
1586
+ return result;
1587
+ }
1588
+ if (!response.repository)
1589
+ return result;
1590
+ for (const n of issueNums) {
1591
+ const raw = response.repository[`i_${n}`];
1592
+ const nodes = raw?.timelineItems?.nodes ?? [];
1593
+ const found = nodes.some(({ source }) => {
1594
+ if (!source || typeof source.number !== "number")
1595
+ return false;
1596
+ const pr = source;
1597
+ if (provenanceMatchesIssue(pr.body ?? "", n))
1598
+ return true;
1599
+ return pr.comments.nodes.some((c) => provenanceMatchesIssue(c.body, n));
1600
+ });
1601
+ result.set(n, found);
1602
+ }
1603
+ return result;
1604
+ }
1605
+ async function fetchProvenance(issueNums, owner, repo, token) {
1606
+ const result = new Map;
1607
+ if (issueNums.length === 0)
1608
+ return result;
1609
+ const client = graphql2.defaults({ headers: { authorization: `bearer ${token}` } });
1610
+ const perIssue = issueNums.map((n) => `
1611
+ i_${n}: issue(number: ${n}) {
1612
+ timelineItems(last: 1, itemTypes: [CLOSED_EVENT]) {
1613
+ nodes {
1614
+ ... on ClosedEvent {
1615
+ closer {
1616
+ ... on PullRequest {
1617
+ number
1618
+ body
1619
+ comments(first: 50) {
1620
+ nodes { body }
1621
+ }
1622
+ }
1623
+ }
1624
+ }
1625
+ }
1626
+ }
1627
+ }`).join("");
1628
+ const query = `query Provenance($owner: String!, $repo: String!) {
1629
+ repository(owner: $owner, name: $repo) {${perIssue}
1630
+ }
1631
+ }`;
1632
+ let response;
1633
+ try {
1634
+ response = await client(query, { owner, repo });
1635
+ } catch {
1636
+ return result;
1637
+ }
1638
+ if (!response.repository)
1639
+ return result;
1640
+ const needsFallback = [];
1641
+ for (const n of issueNums) {
1642
+ const raw = response.repository[`i_${n}`];
1643
+ if (!raw) {
1644
+ result.set(n, false);
1645
+ continue;
1646
+ }
1647
+ const closer = raw.timelineItems?.nodes?.[0]?.closer;
1648
+ const c = closer ?? null;
1649
+ if (!isPrCloser(c)) {
1650
+ needsFallback.push(n);
1651
+ continue;
1652
+ }
1653
+ const bodyHas = PROVENANCE_PATTERN.test(c.body ?? "");
1654
+ const commentHas = c.comments.nodes.some((x) => PROVENANCE_PATTERN.test(x.body));
1655
+ result.set(n, bodyHas || commentHas);
1656
+ }
1657
+ if (needsFallback.length > 0) {
1658
+ const fallback = await fetchProvenanceViaCrossReferences(needsFallback, owner, repo, token);
1659
+ for (const [n, found] of fallback)
1660
+ result.set(n, found);
1661
+ }
1662
+ return result;
1663
+ }
1424
1664
  // ../../packages/aeg-forge-state/src/github-token.ts
1425
1665
  import { execFile as execFile2 } from "node:child_process";
1426
1666
  import { promisify as promisify2 } from "node:util";
@@ -1650,6 +1890,52 @@ function describeError(err) {
1650
1890
  return err;
1651
1891
  return "unknown error";
1652
1892
  }
1893
+ // ../../packages/aeg-forge-state/src/prior-tranche-archival.ts
1894
+ function defaultPriorTrancheArchivalDeps() {
1895
+ return {
1896
+ activeTranches: async (excludeSlug, repo) => {
1897
+ const index = await indexTrancheMilestonesAsync(repo.owner, repo.repo, { retryFailedReads: true });
1898
+ return index.active.filter((m) => m.slug !== excludeSlug).map((m) => {
1899
+ const issues = index.issuesBySlug?.get(m.slug);
1900
+ if (!issues)
1901
+ throw new Error(`the Milestone index holds no Issue list for tranche \`${m.slug}\``);
1902
+ return { slug: m.slug, issues };
1903
+ });
1904
+ }
1905
+ };
1906
+ }
1907
+ function reason(err) {
1908
+ return err instanceof Error ? err.message.split(`
1909
+ `)[0] ?? "failed" : String(err);
1910
+ }
1911
+ async function resolvePriorTrancheArchival(projects, excludeSlug, repo, deps = defaultPriorTrancheArchivalDeps()) {
1912
+ if (projects.length === 0)
1913
+ return { facts: [], infraFailure: null };
1914
+ let candidates;
1915
+ try {
1916
+ candidates = await deps.activeTranches(excludeSlug, repo);
1917
+ } catch (err) {
1918
+ return {
1919
+ facts: [],
1920
+ infraFailure: `severity:infra — could not read the active tranches (${reason(err)}); whether a prior tranche is archived is unknown.`
1921
+ };
1922
+ }
1923
+ const tasksBySlug = new Map(candidates.map((c) => [c.slug, tasksFromIssues(c.issues)]));
1924
+ const facts = [];
1925
+ for (const project of projects) {
1926
+ let found = null;
1927
+ for (const { slug, issues } of candidates) {
1928
+ if (!(tasksBySlug.get(slug) ?? []).some((t) => t.projects.includes(project)))
1929
+ continue;
1930
+ if (!issues.some((issue) => issue.state === "OPEN")) {
1931
+ found = { project, priorTrancheSlug: slug, archived: false };
1932
+ break;
1933
+ }
1934
+ }
1935
+ facts.push(found ?? { project, priorTrancheSlug: null, archived: false });
1936
+ }
1937
+ return { facts, infraFailure: null };
1938
+ }
1653
1939
  // ../../packages/aeg-forge-state/src/fetch-open-issues.ts
1654
1940
  async function fetchOpenIssuesByLabel(slugs, owner, repo, token) {
1655
1941
  const result = new Map;
@@ -1724,6 +2010,10 @@ function buildQuery(issueNumbers) {
1724
2010
  }
1725
2011
  }`;
1726
2012
  }
2013
+ // ../../packages/aeg-forge-state/src/list-issue-milestones.ts
2014
+ function issueMilestonesFromIssues(issues) {
2015
+ return issues.filter((i) => i.state === "OPEN").map((i) => ({ issue: i.number, milestoneTitle: i.milestone?.title ?? null }));
2016
+ }
1727
2017
  // ../../packages/aeg-forge-state/src/resolve-repo.ts
1728
2018
  import { execFile as execFile3 } from "node:child_process";
1729
2019
  import { promisify as promisify3 } from "node:util";
@@ -1786,7 +2076,8 @@ var ANCHOR_FIELDS = [
1786
2076
  "PREMISE",
1787
2077
  "TEST-PLAN",
1788
2078
  "EVIDENCE",
1789
- "BEYOND-SURFACE"
2079
+ "BEYOND-SURFACE",
2080
+ "LIVE"
1790
2081
  ];
1791
2082
  function anchoredRegionBounds(body, field) {
1792
2083
  const masked = maskCode(body);
@@ -1987,7 +2278,6 @@ var DERIVABLE_STATUSES = DERIVED_STATUSES.filter((s) => s !== "backlog");
1987
2278
  // ../../packages/aeg-core/src/waiver-label.ts
1988
2279
  var WAIVER_LABEL = label("waiver-docs");
1989
2280
  var WAIVER_LABEL_REVIEW = label("waiver-review");
1990
- var PRINCIPAL_ALLOWLIST = ["daniboomerang"];
1991
2281
  function isPrincipal(login, principalAllowlist) {
1992
2282
  if (login === null)
1993
2283
  return false;
@@ -2006,6 +2296,14 @@ var RULING_ORDINAL_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Ruling ordinal:\s*(\d+)(
2006
2296
  var BRIEF_HASH_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Brief hash:\s*([0-9a-f]{64})(?![A-Za-z0-9])/im;
2007
2297
  var POLICY_DIGEST_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Policy digest:\s*([0-9a-f]{64})(?![A-Za-z0-9])/im;
2008
2298
  var BASE_SHA_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Judged base:\s*([0-9a-f]{7,40})(?![A-Za-z0-9])/im;
2299
+ var MANIFEST_VERSION_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Manifest version:\s*(\d+)\s*$/im;
2300
+ var PAUSE_BOUND_RULING_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Pause-bound ruling:\s*(?:(\S+)\|(\S+)\|([0-9a-f]{64})|\(none\))\s*$/im;
2301
+ function extractPauseBoundRuling(comment) {
2302
+ const m = comment.match(PAUSE_BOUND_RULING_PATTERN);
2303
+ if (!m)
2304
+ return;
2305
+ return m[1] ? { rulingId: m[1], pauseId: m[2], contentDigest: m[3] } : null;
2306
+ }
2009
2307
  function firstFiveLines(comment) {
2010
2308
  return comment.split(`
2011
2309
  `).slice(0, 5).join(`
@@ -2099,6 +2397,8 @@ function extractVerdict(comments, valuePattern, missingLabel) {
2099
2397
  danglingNote: `the most recent ${missingLabel} verdict comment carries a VERDICT-shaped line outside the first-five-line read window`
2100
2398
  };
2101
2399
  }
2400
+ const versionMatch = latest.match(MANIFEST_VERSION_PATTERN);
2401
+ const pauseBoundRuling = extractPauseBoundRuling(latest);
2102
2402
  return {
2103
2403
  value: m[1].toUpperCase().replace(/[_-]/g, " "),
2104
2404
  headSha: extractHeadSha(latest),
@@ -2107,6 +2407,8 @@ function extractVerdict(comments, valuePattern, missingLabel) {
2107
2407
  briefHash: extractBriefHash(latest),
2108
2408
  policyDigest: extractPolicyDigest(latest),
2109
2409
  baseSha: extractBaseSha(latest),
2410
+ ...versionMatch ? { manifestVersion: Number.parseInt(versionMatch[1], 10) } : {},
2411
+ ...pauseBoundRuling === undefined ? {} : { pauseBoundRuling },
2110
2412
  findingSeverities: extractFindingSeverities(latest),
2111
2413
  danglingNote: null
2112
2414
  };
@@ -2117,6 +2419,16 @@ function extractCodeReviewVerdict(comments) {
2117
2419
  function extractSecurityReviewVerdict(comments) {
2118
2420
  return extractVerdict(comments, /^[ \t]*(?:\*{1,3}|_{1,3})?VERDICT:\s*(PASS|FAIL)(?![A-Za-z0-9])/im, "security-review");
2119
2421
  }
2422
+
2423
+ // ../../packages/aeg-core/src/review-status.ts
2424
+ var DEVELOPER_ROUND_MARKER = /<!--\s*aeg:developer:round-(\d+)\s*-->/i;
2425
+ function parseDeveloperRoundMarker(body) {
2426
+ const m = body.match(DEVELOPER_ROUND_MARKER);
2427
+ if (!m)
2428
+ return null;
2429
+ const n = Number(m[1]);
2430
+ return Number.isFinite(n) ? n : null;
2431
+ }
2120
2432
  // ../../packages/aeg-core/src/report-tokens.ts
2121
2433
  var DASH_LOOKALIKES = {
2122
2434
  "-": "‑",
@@ -2448,11 +2760,13 @@ var CODE_REVIEW_SEVERITY_ORDER = ["BLOCKER", "MAJOR", "MINOR"];
2448
2760
  var SECURITY_SEVERITY_ORDER = ["CRITICAL", "HIGH", "MEDIUM", "LOW"];
2449
2761
  var DEFAULT_MAX_ROUNDS = 3;
2450
2762
  var DEFAULT_MAX_TASK_MINUTES = 180;
2763
+ var DEFAULT_READY_PUSH_TIMEOUT_MINUTES = 20;
2451
2764
  var DEFAULT_REVIEW_POLICY = {
2452
2765
  codeReviewThreshold: "BLOCKER",
2453
2766
  securityThreshold: "HIGH",
2454
2767
  maxRounds: DEFAULT_MAX_ROUNDS,
2455
- maxTaskMinutes: DEFAULT_MAX_TASK_MINUTES
2768
+ maxTaskMinutes: DEFAULT_MAX_TASK_MINUTES,
2769
+ readyPushTimeoutMinutes: DEFAULT_READY_PUSH_TIMEOUT_MINUTES
2456
2770
  };
2457
2771
  var FILE_SHAPED_LOCATION = /\.[a-zA-Z0-9]{1,10}(:\d+)?\s*$/;
2458
2772
  var PROSE_LOCATION_PATTERNS = [/\bpr\s*body\b/i, /\bcomment\b/i];
@@ -2812,14 +3126,14 @@ function checkTestPlan(prBody) {
2812
3126
  const region = located.found ? located.section : prBody;
2813
3127
  if (TEST_PLAN_UNIT_TESTS_ONLY_RE.test(region))
2814
3128
  return { status: "pass", errors: [] };
2815
- if (/\*\*\[(?:agent|principal)\]\*\*/.test(region))
3129
+ if (/\*\*\[(?:agent|principal|live)\]\*\*/.test(region))
2816
3130
  return { status: "pass", errors: [] };
2817
3131
  if (located.found && extractFencedBlocks(region).length > 0)
2818
3132
  return { status: "pass", errors: [] };
2819
3133
  return {
2820
3134
  status: "fail",
2821
3135
  errors: [
2822
- "brief-validation Test Plan: no Test Plan section found — expected `Test Plan: unit-tests-only`, a fenced `[agent]` command list, or at least one `**[agent]**`/`**[principal]**`-tagged checklist item."
3136
+ "brief-validation Test Plan: no Test Plan section found — expected `Test Plan: unit-tests-only`, a fenced `[agent]` command list, or at least one `**[agent]**`/`**[principal]**`/`**[live]**`-tagged item."
2823
3137
  ]
2824
3138
  };
2825
3139
  }
@@ -3441,6 +3755,375 @@ function checkPrReportDensity(prBody) {
3441
3755
  const results = [checkDecisionsDensity(prBody), checkScopeDensity(prBody)];
3442
3756
  return { errors: results.flatMap((r) => r.errors) };
3443
3757
  }
3758
+ // ../../packages/aeg-core/src/prose-rules.ts
3759
+ var RETIRED_GLOBAL_EXEMPTIONS = [
3760
+ "docs/decisions-legacy.md",
3761
+ "apps/herald-ai/docs/",
3762
+ "apps/vada-ai/docs/",
3763
+ "aeg-root/tranches/completed/",
3764
+ "packages/aeg-core/src/docs/published-prose",
3765
+ "packages/aeg-core/src/retired-vocabulary.test.ts",
3766
+ "packages/aeg-core/src/retired-vocabulary.ts",
3767
+ "/fixtures/",
3768
+ "/node_modules/",
3769
+ "/.next/",
3770
+ "/.turbo/"
3771
+ ];
3772
+ var PLAN_ON_DISK_PATTERNS = ["[Tt]opology files?", "aeg-root/tranches/", "aeg-project/"];
3773
+ var TRANCHE_MODEL_FILE = "/tranche-model.md";
3774
+ var RETIRED_PATTERN_EXEMPTIONS = {
3775
+ [String.raw`\bD-[0-9]{3}\b`]: ["./CLAUDE.md"],
3776
+ [String.raw`(^|[^-_a-zA-Z0-9])decisions\.md`]: [
3777
+ "docs-index.md",
3778
+ "apps/vada-ai/specs/legacy/README.md",
3779
+ "apps/vada-ai/specs/vada-product-spec.md",
3780
+ "apps/vada-ai/web/CLAUDE.md",
3781
+ "apps/vada-ai/CLAUDE.md"
3782
+ ],
3783
+ "decisions-legacy": [
3784
+ "packages/aeg-core/src/file-classify.ts",
3785
+ "packages/aeg-core/src/file-classify.test.ts",
3786
+ "packages/aeg-core/src/pr-tier.test.ts",
3787
+ "docs-index.md",
3788
+ ".claude/skills/database/SKILL.md",
3789
+ ".claude/skills/vada-architecture/SKILL.md",
3790
+ "apps/vada-ai/specs/vada-byok-principles.md",
3791
+ "apps/vada-ai/web/CLAUDE.md",
3792
+ "apps/vada-ai/CLAUDE.md"
3793
+ ],
3794
+ CONTRADICTION: ["apps/vada-ai/specs/vada-reviewers-spec.md"],
3795
+ ...Object.fromEntries(PLAN_ON_DISK_PATTERNS.map((pattern) => [pattern, [TRANCHE_MODEL_FILE]]))
3796
+ };
3797
+ var retiredPatterns = [
3798
+ String.raw`\bD-[0-9]{3}\b`,
3799
+ "D-(###|NNN|nnn|xxx)",
3800
+ "decision (entry|logged)",
3801
+ "decision-log entry",
3802
+ "decision log entry",
3803
+ "decision log(s|ged|ging)?([^a-z]|$)",
3804
+ "decision-log",
3805
+ "decision entr",
3806
+ "decisions? (are |is )?logged",
3807
+ "log entries",
3808
+ String.raw`(^|[^-_a-zA-Z0-9])decisions\.md`,
3809
+ "decisions-legacy",
3810
+ "CONTRADICTION",
3811
+ "assumes Tier 3",
3812
+ "Lock: ?YES",
3813
+ "Lock: ?NO",
3814
+ "lock approvals?",
3815
+ "approves locks",
3816
+ "Conforms to lock",
3817
+ "Challenges lock",
3818
+ "checkDecisionNumbersFresh",
3819
+ String.raw`roles/team-leader\.md`,
3820
+ String.raw`\(,`,
3821
+ String.raw`,\)`,
3822
+ String.raw`\(\.\)`,
3823
+ ...PLAN_ON_DISK_PATTERNS
3824
+ ];
3825
+ var published = [
3826
+ ["decision-id", "a decision id", /\bD-\d{3,}\b/],
3827
+ ["section-ref", "a section reference", /§/],
3828
+ ["forge-number", "a forge number", /#\d+/],
3829
+ ["retired-name", "the retired public name", /\bAEG\b/],
3830
+ ["tranche-slug", "a tranche slug", /\b[a-z][a-z0-9]*(?:-[a-z0-9]+)+-v\d+\b/],
3831
+ [
3832
+ "label-vocabulary",
3833
+ "forge label vocabulary",
3834
+ /(?:vinaya\/)?\b(?:tranche|iteration|tier|needs|waiver|project|aeg):(?![/\s]|$)/
3835
+ ],
3836
+ ["internal-path", "a repo-internal path", /\b(?:packages|apps|aeg-root|tools|scripts)\//],
3837
+ ["internal-path", "a repo-internal path", /\.(?:claude|husky|github)\//],
3838
+ [
3839
+ "internal-path",
3840
+ "a repo-internal file",
3841
+ /(?:^|[\s(`"'[])[\w.-]+(?:\/[\w.-]+)*\.(?:ts|tsx|js|jsx|mjs|cjs|sh|ya?ml|json|md)\b/
3842
+ ]
3843
+ ];
3844
+ var DEFAULT_PROSE_RULES = [
3845
+ {
3846
+ id: "forge-number",
3847
+ group: "reader-resolvable",
3848
+ scopes: ["ships", "reader-facing", "spec"],
3849
+ patterns: { prose: /#[0-9]{2,4}/g },
3850
+ flags: ["global"],
3851
+ message: "a forge number",
3852
+ severity: { ships: "warning", "reader-facing": "warning", spec: "error" },
3853
+ exemptions: []
3854
+ },
3855
+ {
3856
+ id: "tranche-slug",
3857
+ group: "reader-resolvable",
3858
+ scopes: ["ships", "reader-facing", "product", "spec"],
3859
+ patterns: { prose: /[a-z][a-z-]+-v[0-9]/g },
3860
+ flags: ["global"],
3861
+ message: "an internal tranche slug",
3862
+ severity: { ships: "warning", "reader-facing": "warning", product: "error", spec: "error" },
3863
+ exemptions: []
3864
+ },
3865
+ {
3866
+ id: "task-number",
3867
+ group: "reader-resolvable",
3868
+ scopes: ["spec"],
3869
+ patterns: { prose: /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi },
3870
+ flags: ["global", "ignore-case"],
3871
+ message: "a task number",
3872
+ severity: { spec: "error" },
3873
+ exemptions: []
3874
+ },
3875
+ {
3876
+ id: "source-comment-tranche-slug",
3877
+ group: "reader-resolvable",
3878
+ scopes: ["source-comment"],
3879
+ patterns: { comment: /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g },
3880
+ flags: ["global"],
3881
+ message: "a tranche-slug citation",
3882
+ severity: { "source-comment": "warning" },
3883
+ exemptions: []
3884
+ },
3885
+ {
3886
+ id: "source-comment-forge-number",
3887
+ group: "reader-resolvable",
3888
+ scopes: ["source-comment"],
3889
+ patterns: { comment: /#[0-9]{2,}/g },
3890
+ flags: ["global"],
3891
+ message: "a forge-number citation",
3892
+ severity: { "source-comment": "warning" },
3893
+ exemptions: []
3894
+ },
3895
+ {
3896
+ id: "legacy-batch-name",
3897
+ group: "reader-resolvable",
3898
+ scopes: ["ships", "reader-facing", "spec"],
3899
+ patterns: {},
3900
+ flags: ["built-in"],
3901
+ message: "an internal tranche slug",
3902
+ severity: { ships: "warning", "reader-facing": "warning", spec: "error" },
3903
+ exemptions: [],
3904
+ builtIn: true
3905
+ },
3906
+ {
3907
+ id: "coined-term",
3908
+ group: "reader-resolvable",
3909
+ scopes: ["ships", "reader-facing"],
3910
+ patterns: {},
3911
+ flags: ["built-in"],
3912
+ message: "uses coined term without defining it inline or linking the glossary",
3913
+ severity: { ships: "warning", "reader-facing": "warning" },
3914
+ exemptions: [],
3915
+ builtIn: true
3916
+ },
3917
+ ...retiredPatterns.map((pattern, index) => ({
3918
+ id: `retired-vocabulary-${index + 1}`,
3919
+ group: "retired-vocabulary",
3920
+ scopes: ["repository"],
3921
+ patterns: { repository: pattern },
3922
+ flags: [],
3923
+ message: "retired vocabulary",
3924
+ severity: { repository: "error" },
3925
+ exemptions: RETIRED_GLOBAL_EXEMPTIONS,
3926
+ patternExemptions: RETIRED_PATTERN_EXEMPTIONS
3927
+ })),
3928
+ ...published.map(([id, message, pattern]) => ({
3929
+ id,
3930
+ group: "published-prose",
3931
+ scopes: ["published"],
3932
+ patterns: { published: pattern },
3933
+ flags: [],
3934
+ message,
3935
+ severity: { published: "error" },
3936
+ exemptions: [".worktrees/task/<tranche>/<n>", "task/<tranche>/<n>", ".worktrees/"]
3937
+ }))
3938
+ ];
3939
+ var rulesForGroup = (group) => DEFAULT_PROSE_RULES.filter((rule) => rule.group === group);
3940
+ var RESOLVABLE_SCOPES = ["ships", "reader-facing", "product", "spec", "source-comment"];
3941
+ var RETIRED_SCOPES = ["repository"];
3942
+ var CONFIGURABLE_PROSE_SCOPES = [...RESOLVABLE_SCOPES, ...RETIRED_SCOPES];
3943
+ function groupOfScope(scope) {
3944
+ if (RESOLVABLE_SCOPES.includes(scope))
3945
+ return "reader-resolvable";
3946
+ if (RETIRED_SCOPES.includes(scope))
3947
+ return "retired-vocabulary";
3948
+ return;
3949
+ }
3950
+ var CONFIGURED_PROSE_FLAGS = ["i", "u"];
3951
+ var CONFIGURED_PATTERN_MAX_LENGTH = 200;
3952
+ var CONFIGURABLE_DEFAULT_RULES = DEFAULT_PROSE_RULES.filter((rule) => rule.group !== "published-prose");
3953
+ function allowedScopesFor(rule) {
3954
+ if (rule.builtIn)
3955
+ return rule.scopes;
3956
+ return rule.group === "retired-vocabulary" ? RETIRED_SCOPES : RESOLVABLE_SCOPES;
3957
+ }
3958
+ function normalizeRepoPath(entry) {
3959
+ let out = entry.replace(/\\/g, "/");
3960
+ while (out.startsWith("./"))
3961
+ out = out.slice(2);
3962
+ out = out.replace(/\/{2,}/g, "/");
3963
+ while (out.endsWith("/"))
3964
+ out = out.slice(0, -1);
3965
+ return out;
3966
+ }
3967
+ function isConfiguredExempt(path, exempt, repoRoot) {
3968
+ if (exempt.length === 0)
3969
+ return false;
3970
+ const root = repoRoot === undefined ? undefined : normalizeRepoPath(repoRoot);
3971
+ let rel = normalizeRepoPath(path);
3972
+ if (root && rel.startsWith(`${root}/`))
3973
+ rel = rel.slice(root.length + 1);
3974
+ return exempt.some((entry) => {
3975
+ const e = normalizeRepoPath(entry);
3976
+ return rel === e || rel.startsWith(`${e}/`);
3977
+ });
3978
+ }
3979
+ function ruleReads(set, rule, path) {
3980
+ return !isConfiguredExempt(path, set.exempt, set.repoRoot) && !isConfiguredExempt(path, rule.exempt, set.repoRoot);
3981
+ }
3982
+ var RESOLVABLE_RUN_ORDER = [
3983
+ "forge-number",
3984
+ "tranche-slug",
3985
+ "legacy-batch-name",
3986
+ "task-number",
3987
+ "source-comment-tranche-slug",
3988
+ "source-comment-forge-number",
3989
+ "coined-term"
3990
+ ];
3991
+ var REPORT_GROUPS = { "task-number": 2, "legacy-batch-name": 2 };
3992
+ function scopeDefaultSeverity(scope, sourceCommentSeverity) {
3993
+ if (scope === "source-comment")
3994
+ return sourceCommentSeverity ?? "warning";
3995
+ if (scope === "repository")
3996
+ return "error";
3997
+ return "warning";
3998
+ }
3999
+ function applySeverity(scopes, base, setting) {
4000
+ const out = {};
4001
+ for (const scope of scopes) {
4002
+ const configured = typeof setting === "string" ? setting : setting?.[scope];
4003
+ const value = configured ?? base[scope];
4004
+ if (value !== undefined)
4005
+ out[scope] = value;
4006
+ }
4007
+ return out;
4008
+ }
4009
+ function defaultPatternFor(rule) {
4010
+ const cache = new Map;
4011
+ return (scope) => {
4012
+ if (cache.has(scope))
4013
+ return cache.get(scope) ?? null;
4014
+ const own = rule.patterns[scope] ?? (scope === "source-comment" ? rule.patterns.comment : rule.patterns.prose) ?? Object.values(rule.patterns)[0];
4015
+ const compiled = own === undefined ? null : own instanceof RegExp ? own : new RegExp(own);
4016
+ cache.set(scope, compiled);
4017
+ return compiled;
4018
+ };
4019
+ }
4020
+ function customPatternFor(rule, global) {
4021
+ const cache = new Map;
4022
+ return (scope) => {
4023
+ if (cache.has(scope))
4024
+ return cache.get(scope) ?? null;
4025
+ const source = rule.patterns?.[scope] ?? rule.pattern;
4026
+ const compiled = source === undefined ? null : new RegExp(source, `${rule.flags ?? ""}${global ? "g" : ""}`);
4027
+ cache.set(scope, compiled);
4028
+ return compiled;
4029
+ };
4030
+ }
4031
+ function resolveProseRules(config = undefined, options = {}) {
4032
+ const rules = [];
4033
+ const defaults = config?.defaults ?? {};
4034
+ for (const rule of CONFIGURABLE_DEFAULT_RULES) {
4035
+ const override = defaults[rule.id];
4036
+ if (override === "off")
4037
+ continue;
4038
+ const group = rule.group;
4039
+ const scopes = override?.scopes ?? rule.scopes;
4040
+ const base = {};
4041
+ for (const scope of scopes) {
4042
+ base[scope] = scope === "source-comment" ? options.sourceCommentSeverity ?? rule.severity[scope] ?? "warning" : rule.severity[scope] ?? scopeDefaultSeverity(scope, options.sourceCommentSeverity);
4043
+ }
4044
+ rules.push({
4045
+ id: rule.id,
4046
+ group,
4047
+ custom: false,
4048
+ builtIn: rule.builtIn === true,
4049
+ scopes,
4050
+ message: rule.message,
4051
+ severity: applySeverity(scopes, base, override?.severity),
4052
+ exempt: override?.exempt ?? [],
4053
+ substringExempt: rule.exemptions,
4054
+ reportGroup: REPORT_GROUPS[rule.id],
4055
+ patternFor: defaultPatternFor(rule)
4056
+ });
4057
+ }
4058
+ for (const rule of config?.custom ?? []) {
4059
+ const group = groupOfScope(rule.scopes[0] ?? "") ?? "reader-resolvable";
4060
+ const base = {};
4061
+ for (const scope of rule.scopes)
4062
+ base[scope] = scopeDefaultSeverity(scope, options.sourceCommentSeverity);
4063
+ rules.push({
4064
+ id: rule.id,
4065
+ group,
4066
+ custom: true,
4067
+ builtIn: false,
4068
+ scopes: rule.scopes,
4069
+ message: rule.means,
4070
+ severity: applySeverity(rule.scopes, base, rule.severity),
4071
+ exempt: rule.exempt ?? [],
4072
+ substringExempt: [],
4073
+ patternFor: customPatternFor(rule, group === "reader-resolvable")
4074
+ });
4075
+ }
4076
+ if (options.decisionRecordsPath !== undefined)
4077
+ rules.push(decisionRecordCitationRule(options.decisionRecordsPath));
4078
+ const order = (rule) => {
4079
+ const at = RESOLVABLE_RUN_ORDER.indexOf(rule.id);
4080
+ return rule.custom || at === -1 ? RESOLVABLE_RUN_ORDER.length : at;
4081
+ };
4082
+ const resolvable = rules.filter((rule) => rule.group === "reader-resolvable");
4083
+ const sorted = resolvable.map((rule, index) => ({ rule, index })).sort((a, b) => order(a.rule) - order(b.rule) || a.index - b.index).map(({ rule }) => rule);
4084
+ return {
4085
+ rules: [...sorted, ...rules.filter((rule) => rule.group === "retired-vocabulary")],
4086
+ exempt: config?.exempt ?? [],
4087
+ repoRoot: options.repoRoot
4088
+ };
4089
+ }
4090
+ function rulesOfGroup(set, group) {
4091
+ return set.rules.filter((rule) => rule.group === group);
4092
+ }
4093
+ function rulesInScope(set, scope) {
4094
+ return set.rules.filter((rule) => rule.scopes.includes(scope));
4095
+ }
4096
+ var DEFAULT_PROSE_RULE_SET = resolveProseRules();
4097
+ var DECISION_RECORD_CITATION_ID = "decision-record-citation";
4098
+ var DECISION_RECORD_CITATION_SCOPES = ["ships", "product", "spec", "source-comment"];
4099
+ var DECISION_RECORD_CITATION_MESSAGE = "a decision-record number";
4100
+ function escapeRegExp(text) {
4101
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4102
+ }
4103
+ function decisionRecordCitationPattern(decisionRecordsPath) {
4104
+ const folder = escapeRegExp(normalizeRepoPath(decisionRecordsPath));
4105
+ return new RegExp(String.raw`\bADR[- ]?[0-9]+\b|(?<![A-Za-z0-9_-])${folder}/[0-9]+[A-Za-z0-9._-]*`, "g");
4106
+ }
4107
+ function decisionRecordCitationRule(decisionRecordsPath) {
4108
+ const folder = normalizeRepoPath(decisionRecordsPath);
4109
+ const pattern = decisionRecordCitationPattern(folder);
4110
+ const severity = {};
4111
+ for (const scope of DECISION_RECORD_CITATION_SCOPES)
4112
+ severity[scope] = "error";
4113
+ return {
4114
+ id: DECISION_RECORD_CITATION_ID,
4115
+ group: "reader-resolvable",
4116
+ custom: false,
4117
+ builtIn: false,
4118
+ scopes: DECISION_RECORD_CITATION_SCOPES,
4119
+ message: DECISION_RECORD_CITATION_MESSAGE,
4120
+ severity,
4121
+ exempt: [folder],
4122
+ substringExempt: [],
4123
+ patternFor: () => pattern
4124
+ };
4125
+ }
4126
+
3444
4127
  // ../../packages/aeg-core/src/reader-resolvable-prose.ts
3445
4128
  var PRODUCT_SLUG_SCOPE = [
3446
4129
  "apps/cli/src",
@@ -3452,8 +4135,8 @@ var PRODUCT_SLUG_SCOPE = [
3452
4135
  function isUnderOrEqual(path, prefix) {
3453
4136
  return path === prefix || path.startsWith(`${prefix}/`);
3454
4137
  }
3455
- function isProductScopeFile(path) {
3456
- return PRODUCT_SLUG_SCOPE.some((prefix) => isUnderOrEqual(path, prefix));
4138
+ function isProductScopeFile(path, productPaths) {
4139
+ return productPaths.some((prefix) => isUnderOrEqual(path, normalizeRepoPath(prefix)));
3457
4140
  }
3458
4141
  var SHIPS_PREFIX = "aeg-root/";
3459
4142
  function shipsArchivePrefix(shipsPrefix) {
@@ -3461,13 +4144,7 @@ function shipsArchivePrefix(shipsPrefix) {
3461
4144
  }
3462
4145
  var DEFAULT_SPEC_PATHS = ["SPEC.md", "CONTEXT.md", "docs/adr"];
3463
4146
  function normalizeSpecPath(entry) {
3464
- let out = entry.replace(/\\/g, "/");
3465
- while (out.startsWith("./"))
3466
- out = out.slice(2);
3467
- out = out.replace(/\/{2,}/g, "/");
3468
- while (out.endsWith("/"))
3469
- out = out.slice(0, -1);
3470
- return out;
4147
+ return normalizeRepoPath(entry);
3471
4148
  }
3472
4149
  function isSpecFile2(path, specPaths) {
3473
4150
  if (path.startsWith("apps/") && path.includes("/specs/") && path.endsWith(".md"))
@@ -3479,7 +4156,7 @@ function isSpecFile2(path, specPaths) {
3479
4156
  function isClaudeMdFile(path) {
3480
4157
  return path === "CLAUDE.md" || path.endsWith("/CLAUDE.md");
3481
4158
  }
3482
- function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS) {
4159
+ function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS, productPaths = PRODUCT_SLUG_SCOPE) {
3483
4160
  if (path.startsWith(shipsPrefix)) {
3484
4161
  return path.startsWith(shipsArchivePrefix(shipsPrefix)) ? "internal" : "ships";
3485
4162
  }
@@ -3490,7 +4167,7 @@ function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPr
3490
4167
  return "internal";
3491
4168
  if (isSpecFile2(path, specPaths))
3492
4169
  return "spec";
3493
- if (isProductScopeFile(path))
4170
+ if (isProductScopeFile(path, productPaths))
3494
4171
  return "product";
3495
4172
  return null;
3496
4173
  }
@@ -3515,9 +4192,16 @@ function lineAt(content, index) {
3515
4192
  }
3516
4193
  return line;
3517
4194
  }
3518
- var FORGE_NUMBER_PATTERN = /#[0-9]{2,4}/g;
3519
- var TRANCHE_SLUG_VN_PATTERN = /[a-z][a-z-]+-v[0-9]/g;
3520
- var TASK_NUMBER_PATTERN = /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi;
4195
+ var readerRules = rulesForGroup("reader-resolvable");
4196
+ var readerPattern = (id, scope = "prose") => {
4197
+ const pattern = readerRules.find((rule) => rule.id === id)?.patterns[scope];
4198
+ if (!(pattern instanceof RegExp))
4199
+ throw new Error(`default prose rule ${id} has no ${scope} pattern`);
4200
+ return pattern;
4201
+ };
4202
+ var FORGE_NUMBER_PATTERN = readerPattern("forge-number");
4203
+ var TRANCHE_SLUG_VN_PATTERN = readerPattern("tranche-slug");
4204
+ var TASK_NUMBER_PATTERN = readerPattern("task-number");
3521
4205
  function legacySlugPattern(legacySlugs) {
3522
4206
  if (legacySlugs.length === 0)
3523
4207
  return null;
@@ -3527,48 +4211,61 @@ function legacySlugPattern(legacySlugs) {
3527
4211
  function specGrandfatherPaths(specGrandfather) {
3528
4212
  return Array.isArray(specGrandfather) ? [...specGrandfather] : Object.keys(specGrandfather);
3529
4213
  }
3530
- function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4214
+ var REFERENCE_CLASSES = new Set(["ships", "reader-facing", "product", "spec"]);
4215
+ function referenceRulesFor(set, cls) {
4216
+ return rulesInScope(set, cls).filter((rule) => rule.group === "reader-resolvable" && rule.id !== "coined-term");
4217
+ }
4218
+ function citations(pattern, text, group) {
4219
+ const out = [];
4220
+ const re = pattern.global ? pattern : new RegExp(pattern.source, `${pattern.flags}g`);
4221
+ re.lastIndex = 0;
4222
+ let match = re.exec(text);
4223
+ while (match !== null) {
4224
+ if (match[0] === "") {
4225
+ re.lastIndex++;
4226
+ } else {
4227
+ const cited = group !== undefined ? match[group] ?? match[0] : match[0];
4228
+ out.push({ cited, index: match.index + match[0].indexOf(cited) });
4229
+ }
4230
+ match = re.exec(text);
4231
+ }
4232
+ re.lastIndex = 0;
4233
+ return out;
4234
+ }
4235
+ function customMessage(rule, cited) {
4236
+ return `${rule.id}: ${rule.message} ("${cited}")`;
4237
+ }
4238
+ function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS, options = {}) {
4239
+ const set = options.rules ?? DEFAULT_PROSE_RULE_SET;
4240
+ const productPaths = options.productPaths ?? PRODUCT_SLUG_SCOPE;
3531
4241
  const findings = [];
3532
4242
  const legacyPattern = legacySlugPattern(legacySlugs);
3533
4243
  const grandfatheredWhole = new Set(Array.isArray(specGrandfather) ? specGrandfather : []);
3534
4244
  const limits = new Map(Array.isArray(specGrandfather) ? [] : Object.entries(specGrandfather));
3535
- const patterns = [
3536
- { pattern: FORGE_NUMBER_PATTERN, what: "a forge number" },
3537
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug" },
3538
- ...legacyPattern ? [{ pattern: legacyPattern, what: "an internal tranche slug", group: 2 }] : []
3539
- ];
3540
- const productPatterns = [
3541
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug in product code" }
3542
- ];
3543
- const specPatterns = [
3544
- ...patterns,
3545
- { pattern: TASK_NUMBER_PATTERN, what: "a task number", group: 2 }
3546
- ];
3547
4245
  for (const file of files) {
3548
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths);
3549
- if (!cls || cls === "internal")
3550
- continue;
3551
- if (cls !== "product" && cls !== "spec" && !SWEPT_CLASSES.has(cls))
4246
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths, productPaths);
4247
+ if (!cls || !REFERENCE_CLASSES.has(cls))
3552
4248
  continue;
3553
4249
  if (cls === "spec" && grandfatheredWhole.has(file.path))
3554
4250
  continue;
3555
- const blocking = cls === "product" || cls === "spec";
3556
4251
  const scrubbed = cls === "product" ? stripNonProseForProduct(file.path, file.content) : stripNonProse(file.path, file.content);
3557
- const patternsToRun = cls === "product" ? productPatterns : cls === "spec" ? specPatterns : patterns;
3558
4252
  const fileFindings = [];
3559
- for (const { pattern, what, group } of patternsToRun) {
3560
- pattern.lastIndex = 0;
3561
- let match = pattern.exec(scrubbed);
3562
- while (match !== null) {
3563
- const cited = group !== undefined ? match[group] ?? match[0] : match[0];
3564
- const citedIndex = match.index + match[0].indexOf(cited);
4253
+ for (const rule of referenceRulesFor(set, cls)) {
4254
+ if (!ruleReads(set, rule, file.path))
4255
+ continue;
4256
+ const pattern = !rule.custom && rule.id === "legacy-batch-name" ? legacyPattern : rule.patternFor(cls);
4257
+ if (!pattern)
4258
+ continue;
4259
+ const blocking = rule.severity[cls] === "error";
4260
+ const what = cls === "product" ? `${rule.message} in product code` : rule.message;
4261
+ for (const { cited, index } of citations(pattern, scrubbed, rule.custom ? undefined : rule.reportGroup)) {
3565
4262
  fileFindings.push({
3566
4263
  file: file.path,
3567
- line: lineAt(scrubbed, citedIndex),
3568
- message: `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
3569
- blocking
4264
+ line: lineAt(scrubbed, index),
4265
+ message: rule.custom ? customMessage(rule, cited) : `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
4266
+ blocking,
4267
+ rule: rule.id
3570
4268
  });
3571
- match = pattern.exec(scrubbed);
3572
4269
  }
3573
4270
  }
3574
4271
  const limit = cls === "spec" ? limits.get(file.path) : undefined;
@@ -3609,11 +4306,17 @@ function definesOrLinksGlossary(content, term) {
3609
4306
  return true;
3610
4307
  return /docs\/glossary|glossary\.md/i.test(content);
3611
4308
  }
3612
- function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX) {
4309
+ function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, options = {}) {
3613
4310
  const findings = [];
4311
+ const set = options.rules ?? DEFAULT_PROSE_RULE_SET;
4312
+ const rule = set.rules.find((r) => !r.custom && r.id === "coined-term");
4313
+ if (!rule)
4314
+ return findings;
3614
4315
  for (const file of files) {
3615
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
3616
- if (!cls || !SWEPT_CLASSES.has(cls))
4316
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, DEFAULT_SPEC_PATHS, options.productPaths);
4317
+ if (!cls || !SWEPT_CLASSES.has(cls) || !rule.scopes.includes(cls))
4318
+ continue;
4319
+ if (!ruleReads(set, rule, file.path))
3617
4320
  continue;
3618
4321
  const scrubbed = stripNonProse(file.path, file.content);
3619
4322
  for (const term of glossaryTerms) {
@@ -3626,14 +4329,15 @@ function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, read
3626
4329
  file: file.path,
3627
4330
  line,
3628
4331
  message: `uses coined term "${term}" without defining it inline or linking the glossary`,
3629
- blocking: false
4332
+ blocking: rule.severity[cls] === "error",
4333
+ rule: rule.id
3630
4334
  });
3631
4335
  }
3632
4336
  }
3633
4337
  return findings;
3634
4338
  }
3635
- var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g;
3636
- var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = /#[0-9]{2,}/g;
4339
+ var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = readerPattern("source-comment-tranche-slug", "comment");
4340
+ var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = readerPattern("source-comment-forge-number", "comment");
3637
4341
  function extractComments(path, content) {
3638
4342
  if (!path.endsWith(".ts") && !path.endsWith(".tsx"))
3639
4343
  return content.replace(/[^\n]/g, "");
@@ -3730,39 +4434,40 @@ function extractComments(path, content) {
3730
4434
  }
3731
4435
  return out;
3732
4436
  }
3733
- function checkSourceComments(files, allowlist = []) {
4437
+ function checkSourceComments(files, allowlist = [], options = {}) {
3734
4438
  const findings = [];
3735
4439
  const allowed = new Set(allowlist);
3736
- const patterns = [
3737
- { pattern: SOURCE_COMMENT_TRANCHE_SLUG_PATTERN, what: "a tranche-slug citation" },
3738
- { pattern: SOURCE_COMMENT_FORGE_NUMBER_PATTERN, what: "a forge-number citation" }
3739
- ];
4440
+ const set = options.rules ?? DEFAULT_PROSE_RULE_SET;
4441
+ const rules = rulesInScope(set, "source-comment").filter((rule) => rule.group === "reader-resolvable");
3740
4442
  for (const file of files) {
3741
4443
  if (!file.path.endsWith(".ts"))
3742
4444
  continue;
3743
4445
  if (allowed.has(file.path))
3744
4446
  continue;
3745
4447
  const comments = extractComments(file.path, file.content);
3746
- for (const { pattern, what } of patterns) {
3747
- pattern.lastIndex = 0;
3748
- let match = pattern.exec(comments);
3749
- while (match !== null) {
3750
- findings.push({
4448
+ for (const rule of rules) {
4449
+ if (!ruleReads(set, rule, file.path))
4450
+ continue;
4451
+ const pattern = rule.patternFor("source-comment");
4452
+ if (!pattern)
4453
+ continue;
4454
+ for (const { cited, index } of citations(pattern, comments)) {
4455
+ findings.push({
3751
4456
  file: file.path,
3752
- line: lineAt(comments, match.index),
3753
- message: `comment cites ${what} ("${match[0]}") a reader outside this repo's tracker cannot resolve`,
3754
- blocking: false
4457
+ line: lineAt(comments, index),
4458
+ message: rule.custom ? customMessage(rule, cited) : `comment cites ${rule.message} ("${cited}") a reader outside this repo's tracker cannot resolve`,
4459
+ blocking: rule.severity["source-comment"] === "error",
4460
+ rule: rule.id
3755
4461
  });
3756
- match = pattern.exec(comments);
3757
4462
  }
3758
4463
  }
3759
4464
  }
3760
4465
  return findings;
3761
4466
  }
3762
- function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4467
+ function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS, options = {}) {
3763
4468
  return [
3764
- ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths),
3765
- ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix)
4469
+ ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths, options),
4470
+ ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix, options)
3766
4471
  ];
3767
4472
  }
3768
4473
  function parseGlossaryTerms(glossaryContent) {
@@ -3965,6 +4670,17 @@ function checkDocClaims(files, fileReader) {
3965
4670
  };
3966
4671
  }
3967
4672
 
4673
+ // ../../packages/aeg-core/src/protected-paths.ts
4674
+ import { posix as posixPath } from "node:path";
4675
+ var PROTECTED_ADMIN_PATHS = ["vinaya.config.json", ".vinaya/doc-owners", ".github/", "aeg-root/"];
4676
+ function normalizeTouchedPath(path) {
4677
+ return posixPath.resolve("/", path.replace(/\\/g, "/")).replace(/^\/+/, "");
4678
+ }
4679
+ function isProtectedAdminPath(path) {
4680
+ const normalized = normalizeTouchedPath(path);
4681
+ return PROTECTED_ADMIN_PATHS.some((prefix) => normalized === prefix || normalized.startsWith(prefix));
4682
+ }
4683
+
3968
4684
  // ../../packages/aeg-core/src/issue-validation.ts
3969
4685
  function hasRationaleField(body, labelPattern) {
3970
4686
  const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})`, "im");
@@ -4084,13 +4800,20 @@ function globCoversPath(glob, path) {
4084
4800
  return !p.includes("/");
4085
4801
  return g === p || g.startsWith(`${p}/`) || p.startsWith(`${g}/`);
4086
4802
  }
4803
+ function surfaceEntryResolves(entry, resolvesToFile, pinnedFiles) {
4804
+ if (resolvesToFile(entry))
4805
+ return true;
4806
+ const directory = entry.replace(/\/\*\*?$/, "").replace(/\/+$/, "");
4807
+ return pinnedFiles.some((path) => path.startsWith(`${directory}/`));
4808
+ }
4087
4809
  function checkSurfaceGlobsResolve(body, resolvesToFile) {
4088
4810
  const surface = parseIssueSurface(body);
4089
4811
  if (!surface.ok)
4090
4812
  return { status: "pass", errors: [] };
4813
+ const pinnedFiles = boundaryPinnedFiles(body);
4091
4814
  const errors = [];
4092
4815
  for (const glob of surface.value.in) {
4093
- if (!resolvesToFile(glob)) {
4816
+ if (!surfaceEntryResolves(glob, resolvesToFile, pinnedFiles)) {
4094
4817
  errors.push(`issue-validation Surface: \`${glob}\` in \`## Surface\`'s \`in:\` list matches no tracked file — a Surface that cannot resolve cannot render a brief's file list.`);
4095
4818
  }
4096
4819
  }
@@ -4120,6 +4843,14 @@ function recordedBeyondSurfacePaths(body) {
4120
4843
  return paths;
4121
4844
  }
4122
4845
  function checkSurfaceScope(changedFiles, surface, recorded) {
4846
+ for (const path of changedFiles) {
4847
+ if (!isProtectedAdminPath(path))
4848
+ continue;
4849
+ const normalized = normalizeTouchedPath(path);
4850
+ if (!surface.in.some((glob) => globCoversPath(glob, normalized))) {
4851
+ return { ok: false, violation: { path, reason: "protected" } };
4852
+ }
4853
+ }
4123
4854
  const listed = new Set(recorded);
4124
4855
  const violation = beyondSurfacePaths(changedFiles, surface).find((entry) => !listed.has(entry.path));
4125
4856
  return violation ? { ok: false, violation } : { ok: true };
@@ -4175,12 +4906,22 @@ function checkPartsCiteDefinedObjectives(body) {
4175
4906
  }
4176
4907
  return { status: errors.length > 0 ? "fail" : "pass", errors };
4177
4908
  }
4909
+ var ISSUE_LIVE_LINE_RE = /^-\s*\*{2}\[live\]\*{2}(.*)$/gim;
4910
+ function liveCommand(text) {
4911
+ const trimmed = text.trim();
4912
+ const span = /^(`+)(.+)\1$/.exec(trimmed);
4913
+ return span ? span[2].trim() : trimmed;
4914
+ }
4915
+ function liveItemsIn(region) {
4916
+ return [...region.matchAll(ISSUE_LIVE_LINE_RE)].map((m) => liveCommand(m[1] ?? "")).filter(Boolean);
4917
+ }
4918
+ function parseLiveTestPlanItems(body) {
4919
+ const located = locateTestPlanSection(body);
4920
+ return located.found ? liveItemsIn(located.section) : [];
4921
+ }
4178
4922
  function isTaskIssueLabelSet(labels) {
4179
4923
  return hasLabel("tranche", labels);
4180
4924
  }
4181
- function checkTrancheLabelPresence(_body, _labels) {
4182
- return { status: "pass", errors: [] };
4183
- }
4184
4925
  function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTitle) {
4185
4926
  if (!isTaskIssueLabelSet(labels))
4186
4927
  return { status: "pass", errors: [] };
@@ -4196,6 +4937,7 @@ function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTi
4196
4937
  };
4197
4938
  }
4198
4939
  var TYPE_LABEL_IDS = LABELS.filter((l) => l.category === "type").map((l) => l.id);
4940
+ var PATH_TEXT = (body) => stripCode(body, { inlineSpans: "keep" });
4199
4941
  function isControlCodePoint(codePoint) {
4200
4942
  return codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
4201
4943
  }
@@ -4256,8 +4998,14 @@ function checkProjectsRegistered(body, _labels, registeredNames) {
4256
4998
  }
4257
4999
  return errors.length > 0 ? { status: "fail", errors } : { status: "pass", errors: [] };
4258
5000
  }
5001
+ function rationaleFieldText(text, labelPattern) {
5002
+ const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})[^\\n]*\\n?([\\s\\S]*?)(?=\\n\\s*(?:\\*\\*[A-Z]|#{1,4}\\s)|(?![\\s\\S]))`, "im");
5003
+ const m = re.exec(text);
5004
+ return m ? m[0] : "";
5005
+ }
4259
5006
  var DOC_PATH_RE = /(?:(?:aeg-root|apps|packages|specs|docs|tools|\.claude|\.github)\/[\w./@-]*\.(?:md|mdx)|\.claude\/(?:skills|rules)\/[\w./-]+|\b(?:docs-index|decisions|projects|state-machine|enforcement|process|README|CLAUDE)\.md\b|\b[\w-]+-(?:spec|decisions|backlog)\.md\b)/i;
4260
5007
  var DOC_PATH_RE_GLOBAL = new RegExp(DOC_PATH_RE.source, "gi");
5008
+ var RATIONALE_PATH_RE_GLOBAL = /`([\w.@-]+(?:\/[\w.@-]+)+)`/g;
4261
5009
  function normalizeEdgeId(s) {
4262
5010
  const qualified = splitSlugQualifiedEdge(s);
4263
5011
  return (qualified ? qualified.bareId : s).replace(/^#/, "").trim();
@@ -4265,6 +5013,15 @@ function normalizeEdgeId(s) {
4265
5013
  function edgesNameEachOther(a, b) {
4266
5014
  return a.conflictsWith.map(normalizeEdgeId).includes(normalizeEdgeId(b.ref)) || b.conflictsWith.map(normalizeEdgeId).includes(normalizeEdgeId(a.ref));
4267
5015
  }
5016
+ var BOUNDARY_OUT_RE = /\bOut\s*:\s*([\s\S]*)$/im;
5017
+ function boundaryOutText(body) {
5018
+ const boundary = rationaleFieldText(PATH_TEXT(body), "Boundary");
5019
+ const m = BOUNDARY_OUT_RE.exec(boundary);
5020
+ return m ? m[1] : "";
5021
+ }
5022
+ function namedPathsIn(text) {
5023
+ return [...new Set([...text.matchAll(RATIONALE_PATH_RE_GLOBAL)].map((m) => m[1]))].filter((p) => !/^https?:\/\//i.test(p));
5024
+ }
4268
5025
  var FILE_EXTENSIONS = new Set([
4269
5026
  "ts",
4270
5027
  "tsx",
@@ -4286,6 +5043,11 @@ var FILE_EXTENSIONS = new Set([
4286
5043
  "html",
4287
5044
  "css"
4288
5045
  ]);
5046
+ function boundaryPinnedFiles(body) {
5047
+ const boundary = rationaleFieldText(PATH_TEXT(body), "Boundary");
5048
+ const excluded = new Set(namedPathsIn(boundaryOutText(body)));
5049
+ return namedPathsIn(boundary).filter((p) => looksLikeFilePath(p) && !excluded.has(p));
5050
+ }
4289
5051
  var CI_SHARD_DIR = "apps/cli/tests/ci-shards";
4290
5052
  var CI_SHARD_PROBE = `${CI_SHARD_DIR}/shard-1.txt`;
4291
5053
 
@@ -4310,7 +5072,7 @@ function isGrandfathered(isoDate) {
4310
5072
  return isoDate.slice(0, 10) < COHERENCE_ENFORCED_FROM;
4311
5073
  }
4312
5074
  var R1_GRANDFATHERED_ISSUES = new Set([279, 280, 281, 282]);
4313
- function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
5075
+ function checkA1(entries, principalAllowlist) {
4314
5076
  const failures = [];
4315
5077
  for (const e of entries) {
4316
5078
  if (!e.facts)
@@ -4340,6 +5102,37 @@ function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
4340
5102
  note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
4341
5103
  };
4342
5104
  }
5105
+ function checkA2(entries, hasProvenanceByKey) {
5106
+ const failures = [];
5107
+ for (const e of entries) {
5108
+ if (!e.facts)
5109
+ continue;
5110
+ if (e.facts.issueState !== "closed" || e.facts.prState !== "merged")
5111
+ continue;
5112
+ const key = `${e.trancheSlug}/${e.task.id}`;
5113
+ const hasProvenance = hasProvenanceByKey.get(key);
5114
+ if (hasProvenance === undefined)
5115
+ continue;
5116
+ if (!hasProvenance) {
5117
+ failures.push({
5118
+ code: "archived-without-provenance",
5119
+ issue: e.task.issue,
5120
+ tranche: e.trancheSlug,
5121
+ task: e.task.id,
5122
+ reason: "Closing PR has no `### AEG provenance` comment (Archivist close-out missing)",
5123
+ grandfathered: isGrandfathered(e.facts.mergedAt)
5124
+ });
5125
+ }
5126
+ }
5127
+ const activeFails = failures.filter((f) => !f.grandfathered);
5128
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
5129
+ return {
5130
+ check: "A2",
5131
+ status,
5132
+ failures,
5133
+ note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
5134
+ };
5135
+ }
4343
5136
  function checkA3(entries) {
4344
5137
  const failures = [];
4345
5138
  for (const e of entries) {
@@ -4555,6 +5348,33 @@ function checkL1(files, entriesBySlug) {
4555
5348
  note: failures.length > 0 ? `${failures.length} active tranche(s) with no open task-Issues — consider archiving (advisory)` : undefined
4556
5349
  };
4557
5350
  }
5351
+ function checkL2(files, entriesBySlug) {
5352
+ const failures = [];
5353
+ for (const f of files) {
5354
+ if (!f.archived)
5355
+ continue;
5356
+ const entries = entriesBySlug.get(f.slug) ?? [];
5357
+ for (const e of entries) {
5358
+ if (!e.facts)
5359
+ continue;
5360
+ if (e.facts.issueState === "open") {
5361
+ failures.push({
5362
+ code: "premature-archive",
5363
+ issue: e.task.issue,
5364
+ tranche: f.slug,
5365
+ task: e.task.id,
5366
+ reason: `Archived tranche has open task-Issue #${e.task.issue ?? "?"} (premature archive)`
5367
+ });
5368
+ }
5369
+ }
5370
+ }
5371
+ return {
5372
+ check: "L2",
5373
+ status: "info",
5374
+ failures,
5375
+ note: failures.length > 0 ? `${failures.length} archived tranche(s) with an open task-Issue — investigate (advisory)` : undefined
5376
+ };
5377
+ }
4558
5378
  function checkL3(files) {
4559
5379
  const active = files.filter((f) => !f.archived);
4560
5380
  return {
@@ -4564,6 +5384,51 @@ function checkL3(files) {
4564
5384
  note: `${active.length} active tranche(s): ${active.map((f) => f.slug).join(", ") || "(none)"}`
4565
5385
  };
4566
5386
  }
5387
+ function checkL4(activeTrancheSlugs, issueMilestones) {
5388
+ const activeSet = new Set(activeTrancheSlugs);
5389
+ const failures = [];
5390
+ for (const f of issueMilestones) {
5391
+ if (!activeSet.has(f.tranche))
5392
+ continue;
5393
+ if (f.milestoneTitle === f.tranche)
5394
+ continue;
5395
+ failures.push({
5396
+ code: "milestone-drift",
5397
+ issue: f.issue,
5398
+ tranche: f.tranche,
5399
+ reason: f.milestoneTitle === null ? `Issue #${f.issue} carries ${trancheLabel(f.tranche)} (active) but has no GitHub-native milestone attached` : `Issue #${f.issue} carries ${trancheLabel(f.tranche)} (active) but is attached to Milestone "${f.milestoneTitle}" instead`
5400
+ });
5401
+ }
5402
+ return {
5403
+ check: "L4",
5404
+ status: "info",
5405
+ failures,
5406
+ note: failures.length > 0 ? `${failures.length} open task-Issue(s) in an active tranche whose GitHub-native milestone doesn't match their ${label("tranche")}<slug> label (cosmetic drift, advisory)` : undefined
5407
+ };
5408
+ }
5409
+ function checkL5(activeTrancheSlugs, entriesBySlug) {
5410
+ const failures = [];
5411
+ for (const slug of activeTrancheSlugs) {
5412
+ const entries = entriesBySlug.get(slug) ?? [];
5413
+ const withFacts = entries.filter((e) => e.facts !== undefined);
5414
+ if (withFacts.length === 0)
5415
+ continue;
5416
+ const allClosed = withFacts.every((e) => e.facts?.issueState === "closed");
5417
+ if (allClosed) {
5418
+ failures.push({
5419
+ code: "tranche-not-archived",
5420
+ tranche: slug,
5421
+ reason: "Every task Issue is closed but the tranche is not recorded as complete — archive it"
5422
+ });
5423
+ }
5424
+ }
5425
+ return {
5426
+ check: "L5",
5427
+ status: failures.length > 0 ? "fail" : "pass",
5428
+ failures,
5429
+ note: failures.length > 0 ? `${failures.length} tranche(s) whose task Issues are all closed but were never archived` : undefined
5430
+ };
5431
+ }
4567
5432
  function extractClosesReferences(prBody) {
4568
5433
  const closesPattern = /(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s{0,8}:?\s{0,8}#(\d+)/gi;
4569
5434
  const stripped = stripCode(prBody);
@@ -4659,6 +5524,58 @@ function extractIssue(body) {
4659
5524
  }
4660
5525
  // ../../packages/aeg-core/src/review-input-manifest.ts
4661
5526
  import { createHash as createHash4 } from "node:crypto";
5527
+
5528
+ // ../../packages/aeg-core/src/ruling-ordinal.ts
5529
+ var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
5530
+ function newestPrincipalRulingOrdinal(comments, allowlist) {
5531
+ let best = 0;
5532
+ for (const c of comments) {
5533
+ if (!isPrincipal(c.author, allowlist))
5534
+ continue;
5535
+ const firstLine = (c.body.split(`
5536
+ `)[0] ?? "").trim();
5537
+ const m = RULING_MARKER_ORDINAL.exec(firstLine);
5538
+ if (!m)
5539
+ continue;
5540
+ const k = Number.parseInt(m[1], 10);
5541
+ if (k > best)
5542
+ best = k;
5543
+ }
5544
+ return best;
5545
+ }
5546
+ function parseRulingIdentity(rulingId) {
5547
+ const m = /^(issue-)?(\d+)-(\d+)$/.exec(rulingId);
5548
+ if (!m)
5549
+ return null;
5550
+ const ref = Number.parseInt(m[2], 10);
5551
+ const ordinal = Number.parseInt(m[3], 10);
5552
+ if (ref <= 0 || ordinal <= 0)
5553
+ return null;
5554
+ return { target: m[1] ? "issue" : "pr", ref, ordinal };
5555
+ }
5556
+ function principalRulingTextById(comments, allowlist, rulingId) {
5557
+ const identity = parseRulingIdentity(rulingId);
5558
+ if (identity === null)
5559
+ return null;
5560
+ const matches = comments.filter((c) => {
5561
+ if (!isPrincipal(c.author, allowlist))
5562
+ return false;
5563
+ const m = RULING_MARKER_ORDINAL.exec((c.body.split(`
5564
+ `)[0] ?? "").trim());
5565
+ return m !== null && Number.parseInt(m[1], 10) === identity.ordinal;
5566
+ });
5567
+ if (matches.length !== 1)
5568
+ return null;
5569
+ const body = matches[0].body;
5570
+ const idx = body.indexOf(`
5571
+ `);
5572
+ return idx === -1 ? "" : body.slice(idx + 1).trim();
5573
+ }
5574
+
5575
+ // ../../packages/aeg-core/src/review-input-manifest.ts
5576
+ function pauseBoundRulingDigest(rulingText) {
5577
+ return createHash4("sha256").update(rulingText).digest("hex");
5578
+ }
4662
5579
  function briefHash(brief) {
4663
5580
  return createHash4("sha256").update(`${brief}
4664
5581
  `).digest("hex");
@@ -4719,14 +5636,19 @@ function compareManifest(echoed, current, patchIdOf) {
4719
5636
  const briefHashBound = isBoundToBriefHash(echoed, current.briefHash);
4720
5637
  const objectivesVersion = isBoundToObjectives(echoed, current.objectivesVersion);
4721
5638
  const rulingOrdinal = isBoundToRulings(echoed, current.rulingOrdinal);
5639
+ const legacyCurrent = current.manifestVersion === undefined;
5640
+ const manifestVersion = legacyCurrent ? echoed.manifestVersion === undefined || echoed.manifestVersion === null : echoed.manifestVersion === current.manifestVersion;
5641
+ const pauseBoundRuling = legacyCurrent ? true : Object.hasOwn(echoed, "pauseBoundRuling") && JSON.stringify(echoed.pauseBoundRuling) === JSON.stringify(current.pauseBoundRuling);
4722
5642
  const policyDigestBound = isBoundToPolicy(echoed, current.policyDigest);
4723
5643
  return {
4724
- bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && policyDigestBound,
5644
+ bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && pauseBoundRuling && manifestVersion && policyDigestBound,
4725
5645
  head,
4726
5646
  base,
4727
5647
  briefHash: briefHashBound,
4728
5648
  objectivesVersion,
4729
5649
  rulingOrdinal,
5650
+ pauseBoundRuling,
5651
+ manifestVersion,
4730
5652
  policyDigest: policyDigestBound
4731
5653
  };
4732
5654
  }
@@ -4742,7 +5664,7 @@ function renderGateDeferred(deferred) {
4742
5664
  return ` ${deferred.length} finding(s) deferred, not blocking this round: ${items}.`;
4743
5665
  }
4744
5666
  function checkReviewGate(input) {
4745
- const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
5667
+ const { principalAllowlist } = input;
4746
5668
  const waived = isWaiverLabelActorVerified({
4747
5669
  label: WAIVER_LABEL_REVIEW,
4748
5670
  labels: input.labels,
@@ -4781,27 +5703,33 @@ function checkReviewGate(input) {
4781
5703
  const codeReviewClean = codeReviewTextClean && codeReviewPolicyClean;
4782
5704
  const securityClean = securityTextClean && securityPolicyClean;
4783
5705
  const currentManifest = {
5706
+ ...input.manifestVersion === undefined ? {} : { manifestVersion: input.manifestVersion },
4784
5707
  headSha: input.headSha,
4785
5708
  baseSha: input.baseSha ?? null,
4786
5709
  briefHash: input.briefHash ?? null,
4787
5710
  objectivesVersion: input.objectivesVersion,
4788
5711
  rulingOrdinal: input.rulingOrdinal,
5712
+ pauseBoundRuling: input.pauseBoundRuling ?? null,
4789
5713
  policyDigest: policyDigest(policy)
4790
5714
  };
4791
5715
  const codeReviewEchoed = {
5716
+ manifestVersion: codeReview.manifestVersion,
4792
5717
  headSha: codeReview.headSha,
4793
5718
  baseSha: codeReview.baseSha,
4794
5719
  briefHash: codeReview.briefHash,
4795
5720
  objectivesVersion: codeReview.objectivesVersion,
4796
5721
  rulingOrdinal: codeReview.rulingOrdinal,
5722
+ pauseBoundRuling: codeReview.pauseBoundRuling,
4797
5723
  policyDigest: codeReview.policyDigest
4798
5724
  };
4799
5725
  const securityEchoed = {
5726
+ manifestVersion: security.manifestVersion,
4800
5727
  headSha: security.headSha,
4801
5728
  baseSha: security.baseSha,
4802
5729
  briefHash: security.briefHash,
4803
5730
  objectivesVersion: security.objectivesVersion,
4804
5731
  rulingOrdinal: security.rulingOrdinal,
5732
+ pauseBoundRuling: security.pauseBoundRuling,
4805
5733
  policyDigest: security.policyDigest
4806
5734
  };
4807
5735
  const codeReviewBinding = compareManifest(codeReviewEchoed, currentManifest, input.patchIdOf);
@@ -4840,6 +5768,10 @@ function checkReviewGate(input) {
4840
5768
  problems.push(`the newest code-review verdict was cast against brief hash ${codeReview.briefHash ?? "none"}, the frozen brief's current hash is ${currentManifest.briefHash ?? "none"}`);
4841
5769
  } else if (!codeReviewBinding.policyDigest) {
4842
5770
  problems.push(`the newest code-review verdict was cast against review policy digest ${codeReview.policyDigest ?? "none"}, this repository's current policy digest is ${currentManifest.policyDigest}`);
5771
+ } else if (!codeReviewBinding.manifestVersion) {
5772
+ problems.push(`the newest code-review verdict echoes manifest version ${codeReview.manifestVersion ?? "none"}, the frozen review-input manifest is version ${currentManifest.manifestVersion ?? "unversioned"}`);
5773
+ } else if (!codeReviewBinding.pauseBoundRuling) {
5774
+ problems.push(`the newest code-review verdict echoes pauseBoundRuling ${renderBinding(codeReview.pauseBoundRuling)}, the frozen review-input manifest binds ${renderBinding(currentManifest.pauseBoundRuling)}`);
4843
5775
  }
4844
5776
  if (!securityTextClean) {
4845
5777
  problems.push(`security-review verdict is not a clean PASS (found: ${security.value})`);
@@ -4857,6 +5789,10 @@ function checkReviewGate(input) {
4857
5789
  problems.push(`the newest security-review verdict was cast against brief hash ${security.briefHash ?? "none"}, the frozen brief's current hash is ${currentManifest.briefHash ?? "none"}`);
4858
5790
  } else if (!securityBinding.policyDigest) {
4859
5791
  problems.push(`the newest security-review verdict was cast against review policy digest ${security.policyDigest ?? "none"}, this repository's current policy digest is ${currentManifest.policyDigest}`);
5792
+ } else if (!securityBinding.manifestVersion) {
5793
+ problems.push(`the newest security-review verdict echoes manifest version ${security.manifestVersion ?? "none"}, the frozen review-input manifest is version ${currentManifest.manifestVersion ?? "unversioned"}`);
5794
+ } else if (!securityBinding.pauseBoundRuling) {
5795
+ problems.push(`the newest security-review verdict echoes pauseBoundRuling ${renderBinding(security.pauseBoundRuling)}, the frozen review-input manifest binds ${renderBinding(currentManifest.pauseBoundRuling)}`);
4860
5796
  }
4861
5797
  const ignoredNote = ignoredCount > 0 ? ` ${ignoredCount} verdict-shaped comment(s) from authors outside the principal allowlist were ignored.` : "";
4862
5798
  return {
@@ -4865,29 +5801,16 @@ function checkReviewGate(input) {
4865
5801
  waived: false
4866
5802
  };
4867
5803
  }
5804
+ function renderBinding(binding) {
5805
+ if (binding === undefined)
5806
+ return "(absent)";
5807
+ return binding === null ? "(none)" : `${binding.rulingId}|${binding.pauseId}|${binding.contentDigest}`;
5808
+ }
4868
5809
  var CHANGESET_RELEASE_BRANCH = "changeset-release/main";
4869
5810
  var DEFAULT_RELEASE_ACTOR = "github-actions[bot]";
4870
5811
  function isChangesetsReleasePr(branch, author, expectedAuthor) {
4871
5812
  return branch === CHANGESET_RELEASE_BRANCH && author === expectedAuthor;
4872
5813
  }
4873
- // ../../packages/aeg-core/src/ruling-ordinal.ts
4874
- var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
4875
- function newestPrincipalRulingOrdinal(comments, allowlist) {
4876
- let best = 0;
4877
- for (const c of comments) {
4878
- if (!isPrincipal(c.author, allowlist))
4879
- continue;
4880
- const firstLine = (c.body.split(`
4881
- `)[0] ?? "").trim();
4882
- const m = RULING_MARKER_ORDINAL.exec(firstLine);
4883
- if (!m)
4884
- continue;
4885
- const k = Number.parseInt(m[1], 10);
4886
- if (k > best)
4887
- best = k;
4888
- }
4889
- return best;
4890
- }
4891
5814
  // ../../packages/aeg-core/src/markdown-table.ts
4892
5815
  function splitRow(line) {
4893
5816
  const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
@@ -5039,7 +5962,6 @@ var SCAFFOLD_PLACEHOLDER = "[undocumented — fill in why]";
5039
5962
  var NON_GATE_BIN_NAMES = NON_GATE_BINS;
5040
5963
  var TWIN_CANDIDATE_EXCEPTIONS = {
5041
5964
  "apps/cli/src/checks/bin/check-dead-branch-push.ts": 'Ring 0 "Pushing to a branch whose pull request already resolved" (implementation: check-push-target.ts)',
5042
- "apps/cli/src/checks/bin/check-issue-assignment.ts": `Ring 0 "A task branch's first push (Issue self-assignment)" (implementation: assign-task-issue.ts)`,
5043
5965
  "apps/cli/src/checks/bin/check-closes-n.ts": 'Ring 1 "Closes linkage" (implementation: verify-coherence.ts)'
5044
5966
  };
5045
5967
  var NON_GATE_HOOK_SCRIPTS = [".claude/hooks/track-transcript.sh"];
@@ -5263,72 +6185,10 @@ function compareToBaseline(current, baseline) {
5263
6185
  };
5264
6186
  }
5265
6187
  // ../../packages/aeg-core/src/retired-vocabulary.ts
5266
- var PLAN_ON_DISK_PATTERNS = ["[Tt]opology files?", "aeg-root/tranches/", "aeg-project/"];
5267
- var RETIRED_PATTERNS = [
5268
- String.raw`\bD-[0-9]{3}\b`,
5269
- "D-(###|NNN|nnn|xxx)",
5270
- "decision (entry|logged)",
5271
- "decision-log entry",
5272
- "decision log entry",
5273
- "decision log(s|ged|ging)?([^a-z]|$)",
5274
- "decision-log",
5275
- "decision entr",
5276
- "decisions? (are |is )?logged",
5277
- "log entries",
5278
- String.raw`decisions\.md`,
5279
- "decisions-legacy",
5280
- "CONTRADICTION",
5281
- "assumes Tier 3",
5282
- "Lock: ?YES",
5283
- "Lock: ?NO",
5284
- "lock approvals?",
5285
- "approves locks",
5286
- "Conforms to lock",
5287
- "Challenges lock",
5288
- "checkDecisionNumbersFresh",
5289
- String.raw`roles/team-leader\.md`,
5290
- String.raw`\(,`,
5291
- String.raw`,\)`,
5292
- String.raw`\(\.\)`,
5293
- ...PLAN_ON_DISK_PATTERNS
5294
- ];
5295
- var TRANCHE_MODEL_FILE = "/tranche-model.md";
5296
- var RETIRED_EXEMPT_SUBSTRINGS = [
5297
- "docs/decisions-legacy.md",
5298
- "apps/herald-ai/docs/",
5299
- "apps/vada-ai/docs/",
5300
- "aeg-root/tranches/completed/",
5301
- "packages/aeg-core/src/docs/published-prose",
5302
- "packages/aeg-core/src/retired-vocabulary.test.ts",
5303
- "packages/aeg-core/src/retired-vocabulary.ts",
5304
- "/fixtures/",
5305
- "/node_modules/",
5306
- "/.next/",
5307
- "/.turbo/"
5308
- ];
5309
- var PATTERN_EXEMPT = {
5310
- [String.raw`\bD-[0-9]{3}\b`]: ["./CLAUDE.md"],
5311
- [String.raw`decisions\.md`]: [
5312
- "docs-index.md",
5313
- "apps/vada-ai/specs/legacy/README.md",
5314
- "apps/vada-ai/specs/vada-product-spec.md",
5315
- "apps/vada-ai/web/CLAUDE.md",
5316
- "apps/vada-ai/CLAUDE.md"
5317
- ],
5318
- "decisions-legacy": [
5319
- "packages/aeg-core/src/file-classify.ts",
5320
- "packages/aeg-core/src/file-classify.test.ts",
5321
- "packages/aeg-core/src/pr-tier.test.ts",
5322
- "docs-index.md",
5323
- ".claude/skills/database/SKILL.md",
5324
- ".claude/skills/vada-architecture/SKILL.md",
5325
- "apps/vada-ai/specs/vada-byok-principles.md",
5326
- "apps/vada-ai/web/CLAUDE.md",
5327
- "apps/vada-ai/CLAUDE.md"
5328
- ],
5329
- CONTRADICTION: ["apps/vada-ai/specs/vada-reviewers-spec.md"],
5330
- ...Object.fromEntries(PLAN_ON_DISK_PATTERNS.map((pattern) => [pattern, [TRANCHE_MODEL_FILE]]))
5331
- };
6188
+ var retiredRules = rulesForGroup("retired-vocabulary");
6189
+ var RETIRED_PATTERNS = retiredRules.map((rule) => rule.patterns.repository);
6190
+ var PATTERN_EXEMPT = RETIRED_PATTERN_EXEMPTIONS;
6191
+ var DEFAULT_PATTERN_OF = new Map(retiredRules.map((rule) => [rule.id, rule.patterns.repository]));
5332
6192
  function lineNumbers(content, pattern) {
5333
6193
  const out = [];
5334
6194
  const lines = content.split(`
@@ -5339,22 +6199,29 @@ function lineNumbers(content, pattern) {
5339
6199
  }
5340
6200
  return out;
5341
6201
  }
5342
- function scanRetiredVocabulary(files) {
6202
+ function scanRetiredVocabulary(files, rules = DEFAULT_PROSE_RULE_SET) {
5343
6203
  const findings = [];
6204
+ const retired = rulesOfGroup(rules, "retired-vocabulary");
5344
6205
  for (const file of files) {
5345
- if (RETIRED_EXEMPT_SUBSTRINGS.some((e) => file.path.includes(e)))
5346
- continue;
5347
- for (const pattern of RETIRED_PATTERNS) {
5348
- const patternExempt = PATTERN_EXEMPT[pattern] ?? [];
5349
- if (patternExempt.some((e) => file.path.includes(e)))
6206
+ for (const rule of retired) {
6207
+ if (rule.substringExempt.some((e) => file.path.includes(e)))
6208
+ continue;
6209
+ if (!ruleReads(rules, rule, file.path))
6210
+ continue;
6211
+ const re = rule.patternFor("repository");
6212
+ if (!re)
6213
+ continue;
6214
+ const pattern = rule.custom ? re.source : DEFAULT_PATTERN_OF.get(rule.id) ?? re.source;
6215
+ if (!rule.custom && (PATTERN_EXEMPT[pattern] ?? []).some((e) => file.path.includes(e)))
5350
6216
  continue;
5351
- const re = new RegExp(pattern);
5352
6217
  for (const line of lineNumbers(file.content, re)) {
5353
6218
  findings.push({
5354
6219
  file: file.path,
5355
6220
  line,
5356
6221
  pattern,
5357
- message: `claims a retired AEG mechanism is still live (matches /${pattern}/)`
6222
+ message: rule.custom ? `${rule.id}: ${rule.message} (matches /${pattern}/)` : `claims a retired AEG mechanism is still live (matches /${pattern}/)`,
6223
+ rule: rule.id,
6224
+ blocking: rule.severity.repository === "error"
5358
6225
  });
5359
6226
  }
5360
6227
  }
@@ -5378,7 +6245,7 @@ function isSelfDependency(dep, task, issue) {
5378
6245
  function checkDispatchReadiness(input) {
5379
6246
  const { trancheSlug, task } = input;
5380
6247
  const taskLabel = `task ${task.id} (tranche ${trancheSlug})`;
5381
- const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
6248
+ const { principalAllowlist } = input;
5382
6249
  const blockerDetails = [];
5383
6250
  const push = (blockerClass, message) => {
5384
6251
  blockerDetails.push({ class: blockerClass, message });
@@ -5470,6 +6337,16 @@ function pushesAnyBranchRef(pushRefs) {
5470
6337
  return pushRefs.split(`
5471
6338
  `).map((line) => line.trim()).filter((line) => line.length > 0).some((line) => line.split(/\s+/)[2]?.startsWith("refs/heads/") === true);
5472
6339
  }
6340
+ function resolveDefaultBranch(facts) {
6341
+ const { originHead, hasOriginMain, hasOriginMaster } = facts;
6342
+ if (originHead !== null && originHead !== "")
6343
+ return originHead;
6344
+ if (hasOriginMain)
6345
+ return "main";
6346
+ if (hasOriginMaster)
6347
+ return "master";
6348
+ return null;
6349
+ }
5473
6350
  function checkMainBranchRefusal(facts) {
5474
6351
  const { currentSymbolicBranch, defaultBranch, pushRefs = null } = facts;
5475
6352
  if (currentSymbolicBranch === null)
@@ -5730,54 +6607,61 @@ function checkFirstPushDispatchGate(input) {
5730
6607
  reason: `verify-dispatch reports READY TO DISPATCH for \`${branch}\`.`
5731
6608
  };
5732
6609
  }
5733
- // ../../packages/aeg-core/src/issue-assignment.ts
5734
- function decideIssueAssignment(input) {
5735
- const { branch, remoteRefExists, issue, assignees, login } = input;
5736
- if (parseTaskBranch(branch) === null) {
5737
- return {
5738
- action: "skip",
5739
- reason: `Branch \`${branch}\` is not a task/<tranche>/<n> branch — Issue self-assignment only applies to task branches.`
5740
- };
5741
- }
5742
- if (remoteRefExists) {
5743
- return {
5744
- action: "skip",
5745
- reason: `Branch \`${branch}\` already exists on the remote — not its first push, nothing to assign.`
5746
- };
5747
- }
5748
- if (issue === null) {
5749
- return {
5750
- action: "skip",
5751
- reason: `No Issue resolved for \`${branch}\` from its topology row — skipping self-assignment (the gate owns refusing an unplanned branch).`
5752
- };
5753
- }
5754
- if (assignees === null) {
5755
- return {
5756
- action: "skip",
5757
- reason: `Could not read Issue #${issue}'s current assignees — skipping rather than risking a double-assign (fail-open, never a guess).`
5758
- };
5759
- }
5760
- if (assignees.length > 0) {
5761
- return {
5762
- action: "skip",
5763
- reason: `Issue #${issue} is already assigned (${assignees.join(", ")}) — no-op.`
5764
- };
5765
- }
5766
- if (login === null) {
5767
- return {
5768
- action: "skip",
5769
- reason: "Could not resolve the authenticated `gh` login — never assigning anyone other than the actual pusher, so skipping."
5770
- };
6610
+ // ../../packages/aeg-core/src/live-record.ts
6611
+ var RECORD_LINE_RE = /^-\s*\[([ xX])\]\s*\*\*\[live\]\*\*\s+(`+) ?(.+?) ?\2(?!`)\s+—\s+(passed|failed|unverified)\s+at\s+`([^`]+)`/;
6612
+ function liveMarkers(body) {
6613
+ const masked = maskCode(body);
6614
+ return [...masked.matchAll(/<!--\s*AEG:LIVE:(?:START|END)\s*-->/g)].map((m) => ({
6615
+ start: m.index,
6616
+ end: m.index + m[0].length
6617
+ }));
6618
+ }
6619
+ var AMBIGUOUS_RECORD_LINE = {
6620
+ line: "- [ ] **[live]** the pull request body carries more than one `AEG:LIVE` marker pair, so the driver's record cannot be told apart",
6621
+ ticked: false,
6622
+ command: "",
6623
+ outcome: "failed",
6624
+ head: ""
6625
+ };
6626
+ function readLiveRecord(body) {
6627
+ const markers = liveMarkers(body).length;
6628
+ if (markers === 0)
6629
+ return [];
6630
+ if (markers !== 2)
6631
+ return [AMBIGUOUS_RECORD_LINE];
6632
+ const region = anchoredRegion(body, "LIVE");
6633
+ if (region === null)
6634
+ return [];
6635
+ const lines = [];
6636
+ for (const raw of region.split(`
6637
+ `)) {
6638
+ const line = raw.trim();
6639
+ const m = RECORD_LINE_RE.exec(line);
6640
+ if (!m)
6641
+ continue;
6642
+ lines.push({
6643
+ line,
6644
+ ticked: m[1].toLowerCase() === "x",
6645
+ command: m[3],
6646
+ outcome: m[4],
6647
+ head: m[5]
6648
+ });
5771
6649
  }
5772
- return {
5773
- action: "assign",
5774
- issue,
5775
- login,
5776
- reason: `First push of \`${branch}\` — assigning Issue #${issue} to @${login} (the authenticated pusher).`
5777
- };
6650
+ return lines;
5778
6651
  }
5779
6652
  // ../../packages/aeg-core/src/test-plan-gate.ts
5780
- function evaluateTestPlanGate(body, branch) {
6653
+ function gradedLiveLines(record, live) {
6654
+ if (live === undefined)
6655
+ return record.map((entry) => entry.line);
6656
+ const commands = new Set(live.liveCommands);
6657
+ const others = record.filter((entry) => !commands.has(entry.command)).map((entry) => entry.line);
6658
+ const graded = live.liveCommands.map((command) => {
6659
+ const atHead = record.filter((entry) => entry.command === command && entry.head === live.head);
6660
+ return (atHead.find((entry) => entry.ticked) ?? atHead[0])?.line ?? `- [ ] **[live]** \`${command}\` — no passed run recorded at \`${live.head || "an unknown head"}\``;
6661
+ });
6662
+ return [...others, ...graded];
6663
+ }
6664
+ function evaluateTestPlanGate(body, branch, live) {
5781
6665
  if (!body) {
5782
6666
  return {
5783
6667
  verdict: "pass",
@@ -5788,7 +6672,9 @@ function evaluateTestPlanGate(body, branch) {
5788
6672
  };
5789
6673
  }
5790
6674
  const located = locateTestPlanSection(body);
5791
- if (!located.found) {
6675
+ const liveLines = gradedLiveLines(readLiveRecord(body), live);
6676
+ const liveUnticked = liveLines.some((line) => /^[-*]\s+\[\s\]/.test(line));
6677
+ if (!located.found && !liveUnticked) {
5792
6678
  if (parseTaskBranchIdentity(branch) !== null) {
5793
6679
  return {
5794
6680
  verdict: "fail",
@@ -5808,15 +6694,18 @@ function evaluateTestPlanGate(body, branch) {
5808
6694
  ]
5809
6695
  };
5810
6696
  }
5811
- const section = located.section;
5812
- if (/unit-tests-only/i.test(section)) {
6697
+ const section = located.found ? located.section : "";
6698
+ if (/unit-tests-only/i.test(section) && !liveUnticked) {
5813
6699
  return {
5814
6700
  verdict: "pass",
5815
6701
  messages: ["Test Plan: unit-tests-only — pure-logic brief, CI unit-tests are the proof.", "PASS."]
5816
6702
  };
5817
6703
  }
5818
- const checkboxLines = section.split(`
5819
- `).map((line) => line.trimStart()).filter((line) => /^[-*]\s+\[[ xX]\]\s*\*{0,2}\[principal\]\*{0,2}/i.test(line));
6704
+ const checkboxLines = [
6705
+ ...section.split(`
6706
+ `).map((line) => line.trimStart()).filter((line) => /^[-*]\s+\[[ xX]\]\s*\*{0,2}\[principal\]\*{0,2}/i.test(line)),
6707
+ ...liveLines
6708
+ ];
5820
6709
  if (checkboxLines.length === 0) {
5821
6710
  return {
5822
6711
  verdict: "pass",
@@ -5833,7 +6722,9 @@ function evaluateTestPlanGate(body, branch) {
5833
6722
  messages.push("", "FAIL — the following [principal] Test Plan items are unticked:");
5834
6723
  for (const line of unchecked)
5835
6724
  messages.push(` ${line}`);
5836
- messages.push("", "Per aeg-root/roles/developer.md (Verification), a PR is not mergeable while any [principal] Test Plan box is unticked.", "The Principal runs the item in a real signed-in browser and ticks the box.", "Note: editing the PR body does not retrigger most workflows. If your PR body changes do not surface here, push an empty commit to re-run.");
6725
+ messages.push("", "Per aeg-root/roles/developer.md (Verification), a PR is not mergeable while any [principal] Test Plan box is unticked.", "The Principal runs the item in a real signed-in browser and ticks the box.", ...liveUnticked ? [
6726
+ "An unticked [live] line is a live run that failed or that the review loop could not verify on its host: a later head re-runs it, or the Principal runs it and ticks the box."
6727
+ ] : [], "Note: editing the PR body does not retrigger most workflows. If your PR body changes do not surface here, push an empty commit to re-run.");
5837
6728
  return { verdict: "fail", messages };
5838
6729
  }
5839
6730
  messages.push("All [principal] Test Plan items ticked — runtime verification complete.", "PASS.");
@@ -6022,9 +6913,11 @@ var LineageSchema = z3.object({
6022
6913
  parent: z3.string().nullable()
6023
6914
  }).strict();
6024
6915
  var InputVersionsSchema = z3.object({
6916
+ manifest_version: z3.literal(2).nullable().optional(),
6025
6917
  objectives_version: z3.string().nullable(),
6026
6918
  brief_hash: z3.string().nullable(),
6027
6919
  ruling_ordinal: z3.number().int().nullable(),
6920
+ pause_bound_ruling: z3.object({ rulingId: z3.string().min(1), pauseId: z3.string().min(1), contentDigest: z3.string().min(1) }).strict().nullable().optional(),
6028
6921
  policy_digest: z3.string().nullable()
6029
6922
  }).strict();
6030
6923
  var ProvenanceSchema = z3.enum(["parent_attributed", "env_correlated", "self_reported", "unavailable"]);
@@ -6062,7 +6955,17 @@ var HeaderMetaV3Schema = z3.object({
6062
6955
  runtime: z3.string().nullable(),
6063
6956
  source: z3.string().nullable()
6064
6957
  }).strict();
6065
- var HeaderMetaSchema = z3.discriminatedUnion("schema", [HeaderMetaV1Schema, HeaderMetaV2Schema, HeaderMetaV3Schema]);
6958
+ var HeaderMetaV4Schema = HeaderMetaV3Schema.extend({
6959
+ schema: z3.literal(4),
6960
+ process: z3.object({ id: z3.string(), version: z3.string().nullable(), digest: z3.string().nullable() }).strict(),
6961
+ runner: z3.object({ id: z3.string(), version: z3.string().nullable() }).strict()
6962
+ }).strict();
6963
+ var HeaderMetaSchema = z3.discriminatedUnion("schema", [
6964
+ HeaderMetaV1Schema,
6965
+ HeaderMetaV2Schema,
6966
+ HeaderMetaV3Schema,
6967
+ HeaderMetaV4Schema
6968
+ ]);
6066
6969
  var SubjectSchema = z3.object({
6067
6970
  issue: z3.number().int().nullable(),
6068
6971
  pr: z3.number().int().optional(),
@@ -6282,6 +7185,75 @@ var DevReviewLoopEventSchema = z3.discriminatedUnion("event", [
6282
7185
  round: z3.number().int(),
6283
7186
  phase: z3.string()
6284
7187
  }).strict(),
7188
+ z3.object({
7189
+ ...loopShared,
7190
+ event: z3.literal("conflict_reentry"),
7191
+ task: z3.number().int(),
7192
+ pr: z3.number().int().positive(),
7193
+ attempt: z3.number().int().positive(),
7194
+ bound: z3.number().int().positive()
7195
+ }).strict(),
7196
+ z3.object({
7197
+ ...loopShared,
7198
+ event: z3.literal("storage_push"),
7199
+ round: z3.number().int(),
7200
+ branch: z3.string(),
7201
+ head: z3.string()
7202
+ }).strict(),
7203
+ z3.object({
7204
+ ...loopShared,
7205
+ event: z3.literal("local_checks_run"),
7206
+ round: z3.number().int(),
7207
+ head: z3.string().nullable(),
7208
+ passed: z3.boolean(),
7209
+ wall_ms: z3.number().nonnegative()
7210
+ }).strict(),
7211
+ z3.object({
7212
+ ...loopShared,
7213
+ event: z3.literal("ready_push"),
7214
+ round: z3.number().int(),
7215
+ head: z3.string(),
7216
+ outcome: z3.enum(["passed", "refused"]),
7217
+ selected: z3.number().int().nonnegative(),
7218
+ failed: z3.number().int().nonnegative(),
7219
+ rerun: z3.boolean(),
7220
+ wall_ms: z3.number().nonnegative()
7221
+ }).strict(),
7222
+ z3.object({
7223
+ ...loopShared,
7224
+ event: z3.literal("failed_tests_rerun"),
7225
+ round: z3.number().int(),
7226
+ head: z3.string(),
7227
+ rerun_of: z3.string(),
7228
+ failed_files: z3.number().int().nonnegative(),
7229
+ affected_files: z3.number().int().nonnegative(),
7230
+ full_count: z3.number().int().nonnegative()
7231
+ }).strict(),
7232
+ z3.object({
7233
+ ...loopShared,
7234
+ event: z3.literal("pr_opened"),
7235
+ round: z3.number().int(),
7236
+ pr: z3.number().int().positive(),
7237
+ head: z3.string()
7238
+ }).strict(),
7239
+ z3.object({
7240
+ ...loopShared,
7241
+ event: z3.literal("ci_result_read"),
7242
+ round: z3.number().int(),
7243
+ pr: z3.number().int().positive(),
7244
+ head: z3.string(),
7245
+ conclusion: z3.enum(["green", "red", "pending", "skipped"]),
7246
+ failing_checks: z3.array(z3.string()),
7247
+ wait_ms: z3.number().nonnegative()
7248
+ }).strict(),
7249
+ z3.object({
7250
+ ...loopShared,
7251
+ event: z3.literal("phase_time"),
7252
+ round: z3.number().int(),
7253
+ phase: z3.enum(["developer", "local_checks", "review", "push", "ci", "other"]),
7254
+ step: z3.string(),
7255
+ wall_ms: z3.number().nonnegative()
7256
+ }).strict(),
6285
7257
  z3.object({
6286
7258
  ...loopShared,
6287
7259
  event: z3.literal("driver_exited"),
@@ -6469,7 +7441,7 @@ var EffectEventSchema = z3.discriminatedUnion("event", [
6469
7441
  ]);
6470
7442
  var CustomFieldValueSchema = z3.union([z3.string().max(CUSTOM_TEXT_MAX_LENGTH), z3.number().finite(), z3.boolean()]);
6471
7443
  var customShared = {
6472
- meta: HeaderMetaV3Schema,
7444
+ meta: HeaderMetaSchema,
6473
7445
  subject: SubjectSchema,
6474
7446
  kind: z3.literal("custom"),
6475
7447
  ...envelopeTail
@@ -6554,7 +7526,7 @@ function buildHeader(input) {
6554
7526
  const issue = subject.issue;
6555
7527
  return {
6556
7528
  meta: {
6557
- schema: 3,
7529
+ schema: 4,
6558
7530
  ts: input.now.toISOString(),
6559
7531
  run_id: input.runId,
6560
7532
  seq: input.seq,
@@ -6572,23 +7544,34 @@ function buildHeader(input) {
6572
7544
  parent: lineageFieldFromEnv(input.env.parent)
6573
7545
  },
6574
7546
  input_versions: {
7547
+ manifest_version: input.inputVersions?.manifestVersion ?? null,
6575
7548
  objectives_version: input.inputVersions?.objectivesVersion ?? null,
6576
7549
  brief_hash: input.inputVersions?.briefHash ?? null,
6577
7550
  ruling_ordinal: input.inputVersions?.rulingOrdinal ?? null,
7551
+ pause_bound_ruling: input.inputVersions?.pauseBoundRuling ?? null,
6578
7552
  policy_digest: input.inputVersions?.policyDigest ?? null
6579
7553
  },
6580
7554
  provenance: provenanceFor(input),
6581
7555
  work: {
6582
7556
  ref: lineageFieldFromEnv(input.env.workRef) ?? (issue === null ? null : String(issue)),
6583
7557
  repo: input.repo,
6584
- change: null,
6585
- revision: null
7558
+ change: pr === undefined ? null : String(pr),
7559
+ revision: input.revision ?? null
6586
7560
  },
6587
7561
  flow: {
6588
7562
  id: lineageFieldFromEnv(input.env.flow) ?? "vinaya",
6589
7563
  version: lineageFieldFromEnv(input.env.flowVersion)
6590
7564
  },
6591
7565
  runtime: lineageFieldFromEnv(input.env.runtime),
7566
+ process: {
7567
+ id: lineageFieldFromEnv(input.env.processId) ?? "vinaya",
7568
+ version: lineageFieldFromEnv(input.env.processVersion),
7569
+ digest: lineageFieldFromEnv(input.env.processDigest)
7570
+ },
7571
+ runner: {
7572
+ id: lineageFieldFromEnv(input.env.runnerId) ?? "standalone",
7573
+ version: lineageFieldFromEnv(input.env.runnerVersion)
7574
+ },
6592
7575
  source: lineageFieldFromEnv(input.env.source)
6593
7576
  },
6594
7577
  subject
@@ -6632,7 +7615,7 @@ function redact(value, home) {
6632
7615
  return value;
6633
7616
  }
6634
7617
  // ../../packages/aeg-core/src/log/store.ts
6635
- var KNOWN_SCHEMA_VERSIONS = [1, 2, 3];
7618
+ var KNOWN_SCHEMA_VERSIONS = [1, 2, 3, 4];
6636
7619
  function metaOf(obj) {
6637
7620
  if (obj === null || typeof obj !== "object")
6638
7621
  return null;
@@ -6770,6 +7753,12 @@ var ManifestRecordSchema = z4.object({
6770
7753
  briefHash: z4.string().min(1).nullable(),
6771
7754
  objectivesVersion: z4.string().min(1).nullable(),
6772
7755
  rulingOrdinal: epochNumber,
7756
+ manifestVersion: z4.literal(2).optional(),
7757
+ pauseBoundRuling: z4.object({
7758
+ rulingId: z4.string().min(1),
7759
+ pauseId: z4.string().min(1),
7760
+ contentDigest: z4.string().min(1)
7761
+ }).strict().nullable().optional(),
6773
7762
  policyDigest: z4.string().min(1),
6774
7763
  recordedAt: isoTimestamp
6775
7764
  }).strict();
@@ -6791,7 +7780,11 @@ var LoopStateRecordSchema = z4.object({
6791
7780
  deliveredFindings: roundHeadIdentity.nullable(),
6792
7781
  repeatMemory: z4.object({
6793
7782
  blockingFindings: z4.array(z4.string()),
6794
- lastFailure: z4.object({ signature: z4.string(), message: z4.string() }).nullable()
7783
+ lastFailure: z4.object({ signature: z4.string(), message: z4.string(), developerAttemptedSince: z4.boolean().optional() }).nullable()
7784
+ }).strict().optional(),
7785
+ developerHandoff: z4.object({
7786
+ findings: z4.array(z4.object({ id: z4.string().min(1), description: z4.string().min(1) }).strict()),
7787
+ failingChecks: z4.array(z4.string().min(1))
6795
7788
  }).strict().optional(),
6796
7789
  publicationExpectedBase: z4.string().regex(/^[0-9a-f]{40}$/).nullable().optional(),
6797
7790
  taskStartedAt: isoTimestamp.optional(),
@@ -6846,37 +7839,331 @@ var ResolutionRecordSchema = z4.object({
6846
7839
  authenticatedFrom: z4.string().min(1),
6847
7840
  consumedAt: isoTimestamp
6848
7841
  }).strict();
7842
+ var ExecutionRoundMirrorRecordSchema = z4.object({
7843
+ version: z4.literal(1),
7844
+ kind: z4.literal("execution_round"),
7845
+ task: taskId,
7846
+ repository: z4.string().min(1),
7847
+ threadId: z4.string().min(1),
7848
+ checkpointId: z4.string().min(1),
7849
+ round: z4.number().int().positive(),
7850
+ recordedAt: isoTimestamp
7851
+ }).strict();
6849
7852
  // ../../packages/aeg-core/src/control-store/local.ts
6850
7853
  var CONTROL_AREA_DIRNAME = "control";
6851
7854
  // src/lib/config.ts
6852
7855
  import { execFile as execFile4, execFileSync as execFileSync2 } from "node:child_process";
6853
7856
  import { promisify as promisify4 } from "node:util";
6854
- import { existsSync, mkdirSync, readFileSync as readFileSync2, realpathSync as realpathSync2, writeFileSync } from "node:fs";
7857
+ import { existsSync, lstatSync, mkdirSync, readFileSync as readFileSync2, realpathSync as realpathSync2, writeFileSync } from "node:fs";
6855
7858
  import { homedir } from "node:os";
6856
- import { dirname, isAbsolute, join, resolve } from "node:path";
6857
- import { z as z5 } from "zod";
7859
+ import { basename as basename3, dirname, isAbsolute, join, resolve } from "node:path";
7860
+ import { z as z6 } from "zod";
6858
7861
 
6859
7862
  // src/lib/agent-vendors.ts
6860
7863
  var AGENT_VENDORS = ["skills", "claude", "gemini"];
6861
7864
 
7865
+ // src/lib/prose-rules-config.ts
7866
+ import safeRegex from "safe-regex2";
7867
+ import { z as z5 } from "zod";
7868
+ var SEVERITIES = ["error", "warning"];
7869
+ var OVERRIDE_KEYS = ["scopes", "severity", "exempt"];
7870
+ var FIXED_DEFAULT_KEYS = ["pattern", "patterns", "flags", "means", "message", "id"];
7871
+ var CUSTOM_KEYS = ["id", "pattern", "patterns", "flags", "means", "scopes", "severity", "exempt"];
7872
+ var DEFAULT_IDS = new Set([...DEFAULT_PROSE_RULES.map((rule) => rule.id), DECISION_RECORD_CITATION_ID]);
7873
+ function isPlainObject3(value) {
7874
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7875
+ }
7876
+ function outsideRepositoryReason(entry) {
7877
+ if (entry.startsWith("/") || /^[A-Za-z]:/.test(entry))
7878
+ return "must be a repository-relative path, not an absolute one";
7879
+ if (entry.split(/[\\/]/).includes(".."))
7880
+ return "must stay inside the repository — no `..` segment";
7881
+ return null;
7882
+ }
7883
+ var RepoRelativePathSchema = z5.string().min(1).superRefine((entry, ctx) => {
7884
+ const reason = outsideRepositoryReason(entry);
7885
+ if (reason)
7886
+ ctx.addIssue({ code: z5.ZodIssueCode.custom, message: reason });
7887
+ });
7888
+ function pathListIssues(value, path, issues) {
7889
+ if (!Array.isArray(value)) {
7890
+ issues.push({ path, message: "must be a list of repository-relative paths" });
7891
+ return;
7892
+ }
7893
+ value.forEach((entry, index) => {
7894
+ if (typeof entry !== "string" || entry.length === 0) {
7895
+ issues.push({ path: [...path, index], message: "must be a non-empty repository-relative path" });
7896
+ return;
7897
+ }
7898
+ const reason = outsideRepositoryReason(entry);
7899
+ if (reason)
7900
+ issues.push({ path: [...path, index], message: reason });
7901
+ });
7902
+ }
7903
+ function scopeListIssues(value, path, allowed, issues) {
7904
+ if (!Array.isArray(value) || value.length === 0) {
7905
+ issues.push({ path, message: "must name at least one scope" });
7906
+ return null;
7907
+ }
7908
+ const scopes = [];
7909
+ value.forEach((scope, index) => {
7910
+ if (typeof scope !== "string" || !CONFIGURABLE_PROSE_SCOPES.includes(scope)) {
7911
+ issues.push({
7912
+ path: [...path, index],
7913
+ message: scope === "published" ? 'scope "published" is not configurable here — the published pass is configured by proseGates.published.allow' : `unknown scope ${JSON.stringify(scope)} — the scopes are: ${CONFIGURABLE_PROSE_SCOPES.join(", ")}`
7914
+ });
7915
+ return;
7916
+ }
7917
+ if (!allowed.includes(scope)) {
7918
+ issues.push({
7919
+ path: [...path, index],
7920
+ message: `scope "${scope}" is not one this rule can run in — it can run in: ${allowed.join(", ")}`
7921
+ });
7922
+ return;
7923
+ }
7924
+ scopes.push(scope);
7925
+ });
7926
+ return scopes;
7927
+ }
7928
+ function severityIssues(value, path, scopes, issues) {
7929
+ if (typeof value === "string") {
7930
+ if (!SEVERITIES.includes(value)) {
7931
+ issues.push({ path, message: `unknown severity ${JSON.stringify(value)} — use "error" or "warning"` });
7932
+ }
7933
+ return;
7934
+ }
7935
+ if (!isPlainObject3(value)) {
7936
+ issues.push({ path, message: 'must be "error", "warning", or a map from scope to one of them' });
7937
+ return;
7938
+ }
7939
+ for (const [scope, severity] of Object.entries(value)) {
7940
+ if (!scopes.includes(scope)) {
7941
+ issues.push({ path: [...path, scope], message: `names scope "${scope}", which this rule's scopes do not cover` });
7942
+ }
7943
+ if (typeof severity !== "string" || !SEVERITIES.includes(severity)) {
7944
+ issues.push({
7945
+ path: [...path, scope],
7946
+ message: `unknown severity ${JSON.stringify(severity)} — use "error" or "warning"`
7947
+ });
7948
+ }
7949
+ }
7950
+ }
7951
+ function patternIssues(source, flags, path, issues) {
7952
+ if (typeof source !== "string" || source.length === 0) {
7953
+ issues.push({ path, message: "must be a non-empty regular expression" });
7954
+ return;
7955
+ }
7956
+ if (source.length > CONFIGURED_PATTERN_MAX_LENGTH) {
7957
+ issues.push({
7958
+ path,
7959
+ message: `is ${source.length} characters, over the ${CONFIGURED_PATTERN_MAX_LENGTH}-character limit for a configured pattern`
7960
+ });
7961
+ return;
7962
+ }
7963
+ try {
7964
+ new RegExp(source, flags);
7965
+ } catch (err) {
7966
+ issues.push({ path, message: `does not compile: ${err.message}` });
7967
+ return;
7968
+ }
7969
+ if (!safeRegex(source, { limit: Number.MAX_SAFE_INTEGER })) {
7970
+ issues.push({
7971
+ path,
7972
+ message: "has star height above one (a repeated group that itself repeats), which can take exponential time — " + "safe-regex2 refuses it. The shipped defaults are not held to this limit, so a pattern copied from one of " + "them can still be refused here; rewrite it without the nested repetition."
7973
+ });
7974
+ }
7975
+ }
7976
+ function flagIssues(value, path, issues) {
7977
+ if (value === undefined)
7978
+ return "";
7979
+ if (typeof value !== "string") {
7980
+ issues.push({ path, message: 'must be a string of flags, e.g. "i"' });
7981
+ return "";
7982
+ }
7983
+ const seen = new Set;
7984
+ for (const flag of value) {
7985
+ if (!CONFIGURED_PROSE_FLAGS.includes(flag)) {
7986
+ issues.push({
7987
+ path,
7988
+ message: `unknown flag ${JSON.stringify(flag)} — only ${CONFIGURED_PROSE_FLAGS.map((f) => `"${f}"`).join(" and ")} are allowed`
7989
+ });
7990
+ return "";
7991
+ }
7992
+ if (seen.has(flag)) {
7993
+ issues.push({ path, message: `repeats the flag "${flag}"` });
7994
+ return "";
7995
+ }
7996
+ seen.add(flag);
7997
+ }
7998
+ return value;
7999
+ }
8000
+ function defaultsIssues(value, issues) {
8001
+ const base = ["defaults"];
8002
+ if (!isPlainObject3(value)) {
8003
+ issues.push({ path: base, message: 'must map a default rule id to "off" or an override' });
8004
+ return;
8005
+ }
8006
+ for (const [id, override] of Object.entries(value)) {
8007
+ const path = [...base, id];
8008
+ const rule = CONFIGURABLE_DEFAULT_RULES.find((candidate) => candidate.id === id);
8009
+ if (!rule) {
8010
+ issues.push({
8011
+ path,
8012
+ message: `unknown default rule id "${id}" — \`vinaya check --plan\` lists the rules each prose check runs`
8013
+ });
8014
+ continue;
8015
+ }
8016
+ if (override === "off")
8017
+ continue;
8018
+ if (!isPlainObject3(override)) {
8019
+ issues.push({ path, message: 'must be "off" or an object with any of scopes, severity, exempt' });
8020
+ continue;
8021
+ }
8022
+ for (const key of Object.keys(override)) {
8023
+ if (OVERRIDE_KEYS.includes(key))
8024
+ continue;
8025
+ issues.push({
8026
+ path: [...path, key],
8027
+ message: FIXED_DEFAULT_KEYS.includes(key) ? `a default rule's ${key} is fixed — add a custom rule under proseGates.rules.custom instead` : `unknown key "${key}" — a default rule takes only scopes, severity and exempt`
8028
+ });
8029
+ }
8030
+ const scopes = override.scopes === undefined ? [...rule.scopes] : scopeListIssues(override.scopes, [...path, "scopes"], allowedScopesFor(rule), issues);
8031
+ if (override.severity !== undefined && scopes)
8032
+ severityIssues(override.severity, [...path, "severity"], scopes, issues);
8033
+ if (override.exempt !== undefined)
8034
+ pathListIssues(override.exempt, [...path, "exempt"], issues);
8035
+ }
8036
+ }
8037
+ function customIssues(value, issues) {
8038
+ if (!Array.isArray(value)) {
8039
+ issues.push({ path: ["custom"], message: "must be a list of rules" });
8040
+ return;
8041
+ }
8042
+ const ids = new Set;
8043
+ value.forEach((rule, index) => {
8044
+ const path = ["custom", index];
8045
+ if (!isPlainObject3(rule)) {
8046
+ issues.push({ path, message: "must be a rule object" });
8047
+ return;
8048
+ }
8049
+ for (const key of Object.keys(rule)) {
8050
+ if (!CUSTOM_KEYS.includes(key)) {
8051
+ issues.push({ path: [...path, key], message: `unknown key "${key}" — a rule takes ${CUSTOM_KEYS.join(", ")}` });
8052
+ }
8053
+ }
8054
+ if (typeof rule.id !== "string" || rule.id.length === 0) {
8055
+ issues.push({ path: [...path, "id"], message: "a custom rule needs an id" });
8056
+ } else if (DEFAULT_IDS.has(rule.id)) {
8057
+ issues.push({
8058
+ path: [...path, "id"],
8059
+ message: `"${rule.id}" is a default rule id — a custom rule needs its own id; retune the default under proseGates.rules.defaults instead`
8060
+ });
8061
+ } else if (ids.has(rule.id)) {
8062
+ issues.push({ path: [...path, "id"], message: `"${rule.id}" is used by an earlier custom rule` });
8063
+ } else {
8064
+ ids.add(rule.id);
8065
+ }
8066
+ if (typeof rule.means !== "string" || rule.means.trim().length === 0) {
8067
+ issues.push({ path: [...path, "means"], message: "a custom rule needs a message (`means`)" });
8068
+ }
8069
+ let scopes = null;
8070
+ if (rule.scopes === undefined) {
8071
+ issues.push({ path: [...path, "scopes"], message: "a custom rule needs at least one scope (`scopes`)" });
8072
+ } else {
8073
+ scopes = scopeListIssues(rule.scopes, [...path, "scopes"], CONFIGURABLE_PROSE_SCOPES, issues);
8074
+ }
8075
+ if (scopes && new Set(scopes.map(groupOfScope)).size > 1) {
8076
+ issues.push({
8077
+ path: [...path, "scopes"],
8078
+ message: 'mixes scopes of both prose checks — "repository" belongs to retired-vocabulary and every other scope to reader-resolvable-prose; write one rule per check'
8079
+ });
8080
+ }
8081
+ const flags = flagIssues(rule.flags, [...path, "flags"], issues);
8082
+ if (rule.pattern === undefined && rule.patterns === undefined) {
8083
+ issues.push({
8084
+ path: [...path, "pattern"],
8085
+ message: "a custom rule needs a `pattern` or a per-scope `patterns` map"
8086
+ });
8087
+ }
8088
+ if (rule.pattern !== undefined)
8089
+ patternIssues(rule.pattern, flags, [...path, "pattern"], issues);
8090
+ if (rule.patterns !== undefined) {
8091
+ if (!isPlainObject3(rule.patterns)) {
8092
+ issues.push({ path: [...path, "patterns"], message: "must map a scope to a regular expression" });
8093
+ } else {
8094
+ for (const [scope, source] of Object.entries(rule.patterns)) {
8095
+ if (scopes && !scopes.includes(scope)) {
8096
+ issues.push({
8097
+ path: [...path, "patterns", scope],
8098
+ message: `names scope "${scope}", which this rule's scopes do not cover`
8099
+ });
8100
+ continue;
8101
+ }
8102
+ patternIssues(source, flags, [...path, "patterns", scope], issues);
8103
+ }
8104
+ if (rule.pattern === undefined && scopes) {
8105
+ for (const scope of scopes) {
8106
+ if (!(scope in rule.patterns)) {
8107
+ issues.push({
8108
+ path: [...path, "patterns"],
8109
+ message: `has no pattern for scope "${scope}" — add one, or a \`pattern\` every other scope uses`
8110
+ });
8111
+ }
8112
+ }
8113
+ }
8114
+ }
8115
+ }
8116
+ if (rule.severity !== undefined && scopes)
8117
+ severityIssues(rule.severity, [...path, "severity"], scopes, issues);
8118
+ if (rule.exempt !== undefined)
8119
+ pathListIssues(rule.exempt, [...path, "exempt"], issues);
8120
+ });
8121
+ }
8122
+ function proseRulesIssues(value) {
8123
+ const issues = [];
8124
+ if (!isPlainObject3(value))
8125
+ return [{ path: [], message: "must be an object with any of exempt, defaults, custom" }];
8126
+ for (const key of Object.keys(value)) {
8127
+ if (!["exempt", "defaults", "custom"].includes(key)) {
8128
+ issues.push({ path: [key], message: `unknown key "${key}" — proseGates.rules takes exempt, defaults and custom` });
8129
+ }
8130
+ }
8131
+ if (value.exempt !== undefined)
8132
+ pathListIssues(value.exempt, ["exempt"], issues);
8133
+ if (value.defaults !== undefined)
8134
+ defaultsIssues(value.defaults, issues);
8135
+ if (value.custom !== undefined)
8136
+ customIssues(value.custom, issues);
8137
+ return issues;
8138
+ }
8139
+ var ProseRulesSchema = z5.unknown().superRefine((value, ctx) => {
8140
+ for (const issue of proseRulesIssues(value)) {
8141
+ ctx.addIssue({ code: z5.ZodIssueCode.custom, path: issue.path, message: issue.message });
8142
+ }
8143
+ }).transform((value) => value);
8144
+ var PublishedProseSchema = z5.object({
8145
+ allow: z5.array(z5.string().min(1)).optional()
8146
+ }).strict();
8147
+
6862
8148
  // src/lib/config.ts
6863
- var EnvEntrySchema = z5.union([
6864
- z5.literal(true),
6865
- z5.object({ optional: z5.literal(true) }),
6866
- z5.object({ anyOf: z5.array(z5.string()).min(2) }),
6867
- z5.string()
8149
+ var EnvEntrySchema = z6.union([
8150
+ z6.literal(true),
8151
+ z6.object({ optional: z6.literal(true) }),
8152
+ z6.object({ anyOf: z6.array(z6.string()).min(2) }),
8153
+ z6.string()
6868
8154
  ]);
6869
- var CheckEntrySchema = z5.object({
6870
- run: z5.string(),
6871
- scope: z5.enum(["diff", "full"]),
6872
- include: z5.array(z5.string()).optional(),
6873
- args: z5.array(z5.string()).optional(),
6874
- timeoutMs: z5.number().optional(),
6875
- env: z5.record(z5.string(), EnvEntrySchema).optional(),
6876
- requiresOpenPr: z5.boolean().optional(),
6877
- ownWorkflow: z5.boolean().optional(),
6878
- principalOwed: z5.literal(true).optional(),
6879
- validates: z5.enum(["body", "issue"]).optional()
8155
+ var CheckEntrySchema = z6.object({
8156
+ run: z6.string(),
8157
+ scope: z6.enum(["diff", "full"]),
8158
+ include: z6.array(z6.string()).optional(),
8159
+ args: z6.array(z6.string()).optional(),
8160
+ timeoutMs: z6.number().optional(),
8161
+ env: z6.record(z6.string(), EnvEntrySchema).optional(),
8162
+ requiresOpenPr: z6.boolean().optional(),
8163
+ ownWorkflow: z6.boolean().optional(),
8164
+ principalOwed: z6.literal(true).optional(),
8165
+ validates: z6.enum(["body", "issue"]).optional(),
8166
+ advisory: z6.literal(true).optional()
6880
8167
  }).superRefine((entry, ctx) => {
6881
8168
  if (!entry.env)
6882
8169
  return;
@@ -6886,22 +8173,22 @@ var CheckEntrySchema = z5.object({
6886
8173
  const members = value.anyOf;
6887
8174
  if (new Set(members).size !== members.length) {
6888
8175
  ctx.addIssue({
6889
- code: z5.ZodIssueCode.custom,
8176
+ code: z6.ZodIssueCode.custom,
6890
8177
  message: `env.${key}.anyOf has duplicate members`,
6891
8178
  path: ["env", key, "anyOf"]
6892
8179
  });
6893
8180
  }
6894
8181
  if (!members.includes(key)) {
6895
8182
  ctx.addIssue({
6896
- code: z5.ZodIssueCode.custom,
8183
+ code: z6.ZodIssueCode.custom,
6897
8184
  message: `env.${key}.anyOf must include "${key}" itself as a member`,
6898
8185
  path: ["env", key, "anyOf"]
6899
8186
  });
6900
8187
  }
6901
8188
  }
6902
8189
  });
6903
- var RoleEntrySchema = z5.object({
6904
- contract: z5.string().refine((p) => p.includes("/"), {
8190
+ var RoleEntrySchema = z6.object({
8191
+ contract: z6.string().refine((p) => p.includes("/"), {
6905
8192
  message: 'must be a path (contain at least one "/"), not a bare filename'
6906
8193
  })
6907
8194
  });
@@ -6925,17 +8212,17 @@ var BRIEF_BUILTINS = [
6925
8212
  "briefSections",
6926
8213
  "milestoneShape"
6927
8214
  ];
6928
- var BriefSectionSchema = z5.union([
6929
- z5.object({ builtin: z5.enum(BRIEF_BUILTINS) }),
6930
- z5.object({ heading: z5.string().min(1), name: z5.string().optional() }),
6931
- z5.object({ field: z5.string().min(1), name: z5.string().optional() }),
6932
- z5.object({ phrase: z5.string().min(1), name: z5.string().optional() })
8215
+ var BriefSectionSchema = z6.union([
8216
+ z6.object({ builtin: z6.enum(BRIEF_BUILTINS) }),
8217
+ z6.object({ heading: z6.string().min(1), name: z6.string().optional() }),
8218
+ z6.object({ field: z6.string().min(1), name: z6.string().optional() }),
8219
+ z6.object({ phrase: z6.string().min(1), name: z6.string().optional() })
6933
8220
  ]);
6934
- var BriefSchemaSchema = z5.object({
6935
- pr: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
6936
- issue: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
6937
- milestone: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
6938
- ack: z5.array(z5.enum(BRIEF_BUILTINS)).optional()
8221
+ var BriefSchemaSchema = z6.object({
8222
+ pr: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
8223
+ issue: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
8224
+ milestone: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
8225
+ ack: z6.array(z6.enum(BRIEF_BUILTINS)).optional()
6939
8226
  });
6940
8227
  function isSafeRepoRelPath(p) {
6941
8228
  if (p.length === 0)
@@ -6944,7 +8231,7 @@ function isSafeRepoRelPath(p) {
6944
8231
  return false;
6945
8232
  return p.split(/[\\/]/).every((seg) => seg !== ".." && seg !== "");
6946
8233
  }
6947
- var SafeRepoRelPath = z5.string().refine(isSafeRepoRelPath, {
8234
+ var SafeRepoRelPath = z6.string().refine(isSafeRepoRelPath, {
6948
8235
  message: "must be a repo-root-relative path with no `..` segment or absolute root"
6949
8236
  });
6950
8237
  var CANONICAL_HOOK_BLOCK_PREFIXES = [".git/", ".husky/", ".vinaya/hooks/", ".claude/hooks/"];
@@ -6954,22 +8241,22 @@ function isCanonicalHookBlockPath(p) {
6954
8241
  var ManagedHookBlockPath = SafeRepoRelPath.refine(isCanonicalHookBlockPath, {
6955
8242
  message: `must start with one of ${CANONICAL_HOOK_BLOCK_PREFIXES.join(", ")} (byte-exact, case-sensitive)`
6956
8243
  });
6957
- var ManagedBlockRecordSchema = z5.object({
8244
+ var ManagedBlockRecordSchema = z6.object({
6958
8245
  path: ManagedHookBlockPath,
6959
- marker: z5.string(),
6960
- comment: z5.enum(["hash", "html"])
8246
+ marker: z6.string(),
8247
+ comment: z6.enum(["hash", "html"])
6961
8248
  });
6962
- var ManagedManifestSchema = z5.object({
6963
- version: z5.number().int().positive(),
6964
- files: z5.array(SafeRepoRelPath),
6965
- blocks: z5.array(ManagedBlockRecordSchema),
6966
- labels: z5.array(z5.string()),
6967
- agents: z5.array(z5.enum(AGENT_VENDORS)).optional()
8249
+ var ManagedManifestSchema = z6.object({
8250
+ version: z6.number().int().positive(),
8251
+ files: z6.array(SafeRepoRelPath),
8252
+ blocks: z6.array(ManagedBlockRecordSchema),
8253
+ labels: z6.array(z6.string()),
8254
+ agents: z6.array(z6.enum(AGENT_VENDORS)).optional()
6968
8255
  });
6969
- var ProjectEntrySchema = z5.object({
6970
- name: z5.string().min(1),
6971
- description: z5.string().min(1).optional(),
6972
- path: z5.string().min(1).optional()
8256
+ var ProjectEntrySchema = z6.object({
8257
+ name: z6.string().min(1),
8258
+ description: z6.string().min(1).optional(),
8259
+ path: z6.string().min(1).optional()
6973
8260
  });
6974
8261
  function parseTokensCollectDeclaration(value) {
6975
8262
  const m = value.trim().match(/^(\S+)\s+(\S+)$/);
@@ -6980,90 +8267,101 @@ function parseTokensCollectDeclaration(value) {
6980
8267
  return null;
6981
8268
  return { interpreter, script };
6982
8269
  }
6983
- var VinayaConfigSchema = z5.object({
6984
- rings: z5.object({
6985
- ring1_forgeWriteInterception: z5.boolean(),
6986
- ring2_asyncAudits: z5.boolean()
8270
+ var VinayaConfigObjectSchema = z6.object({
8271
+ rings: z6.object({
8272
+ ring1_forgeWriteInterception: z6.boolean(),
8273
+ ring2_asyncAudits: z6.boolean()
6987
8274
  }).optional(),
6988
- checks: z5.record(z5.string(), CheckEntrySchema).optional(),
6989
- roles: z5.record(z5.string(), RoleEntrySchema).optional(),
8275
+ checks: z6.record(z6.string(), CheckEntrySchema).optional(),
8276
+ roles: z6.record(z6.string(), RoleEntrySchema).optional(),
6990
8277
  briefSchema: BriefSchemaSchema.optional(),
6991
8278
  managed: ManagedManifestSchema.optional(),
6992
- principals: z5.array(z5.string()).min(1).optional(),
6993
- releaseActor: z5.string().min(1).optional(),
6994
- ci: z5.object({ setup: z5.string().min(1) }).optional(),
6995
- tokens: z5.object({
6996
- collect: z5.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
8279
+ principals: z6.array(z6.string()).min(1).optional(),
8280
+ releaseActor: z6.string().min(1).optional(),
8281
+ ci: z6.object({ setup: z6.string().min(1) }).optional(),
8282
+ tokens: z6.object({
8283
+ collect: z6.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
6997
8284
  message: 'tokens.collect must be exactly "<interpreter> <repo-relative-script-path>" — two whitespace-separated tokens, no flags, no shell syntax, no quoting'
6998
8285
  })
6999
8286
  }).optional(),
7000
- blastRadius: z5.object({ extraDomains: z5.array(z5.string()).optional() }).optional(),
7001
- proseGates: z5.object({
7002
- doctrineRoot: z5.string().min(1).optional(),
7003
- readerFacingPrefix: z5.string().min(1).optional(),
7004
- readerFacingSuffix: z5.string().min(1).optional(),
7005
- legacySlugDir: z5.string().min(1).optional(),
7006
- sourceComments: z5.object({
7007
- globs: z5.array(z5.string().min(1)).optional(),
7008
- allowlist: z5.array(z5.string().min(1)).optional(),
7009
- severity: z5.enum(["warning", "error"]).optional()
8287
+ blastRadius: z6.object({ extraDomains: z6.array(z6.string()).optional() }).optional(),
8288
+ proseGates: z6.object({
8289
+ doctrineRoot: z6.string().min(1).optional(),
8290
+ readerFacingPrefix: z6.string().min(1).optional(),
8291
+ readerFacingSuffix: z6.string().min(1).optional(),
8292
+ legacySlugDir: z6.string().min(1).optional(),
8293
+ sourceComments: z6.object({
8294
+ globs: z6.array(z6.string().min(1)).optional(),
8295
+ allowlist: z6.array(z6.string().min(1)).optional(),
8296
+ severity: z6.enum(["warning", "error"]).optional()
7010
8297
  }).optional(),
7011
- specGrandfather: z5.union([z5.array(z5.string().min(1)), z5.record(z5.string().min(1), z5.number().int().min(0))]).optional(),
7012
- specPaths: z5.array(z5.string().min(1).refine((entry) => !entry.startsWith("/") && !/^[A-Za-z]:/.test(entry), {
7013
- message: "must be a repository-relative path, not an absolute one"
7014
- }).refine((entry) => !entry.split(/[\\/]/).includes(".."), {
7015
- message: "must stay inside the repository — no `..` segment"
7016
- })).optional()
8298
+ specGrandfather: z6.union([z6.array(z6.string().min(1)), z6.record(z6.string().min(1), z6.number().int().min(0))]).optional(),
8299
+ specPaths: z6.array(RepoRelativePathSchema).optional(),
8300
+ productPaths: z6.array(RepoRelativePathSchema).optional(),
8301
+ published: PublishedProseSchema.optional(),
8302
+ rules: ProseRulesSchema.optional()
7017
8303
  }).optional(),
7018
- projects: z5.array(ProjectEntrySchema).optional(),
7019
- dispatch: z5.object({
7020
- timeoutMs: z5.number().int().positive().optional(),
7021
- killGraceMs: z5.number().int().positive().optional(),
7022
- agent: z5.enum(["claude", "codex", "gemini"]).optional()
8304
+ projects: z6.array(ProjectEntrySchema).optional(),
8305
+ dispatch: z6.object({
8306
+ timeoutMs: z6.number().int().positive().optional(),
8307
+ reviewerTimeoutMs: z6.number().int().positive().optional(),
8308
+ killGraceMs: z6.number().int().positive().optional(),
8309
+ agent: z6.enum(["claude", "codex"]).optional()
7023
8310
  }).optional(),
7024
- reviewPolicy: z5.object({
7025
- codeReviewThreshold: z5.string().min(1).optional(),
7026
- securityThreshold: z5.string().min(1).optional(),
7027
- maxRounds: z5.number().optional(),
7028
- maxTaskMinutes: z5.number().optional()
8311
+ reviewPolicy: z6.object({
8312
+ codeReviewThreshold: z6.string().min(1).optional(),
8313
+ securityThreshold: z6.string().min(1).optional(),
8314
+ maxRounds: z6.number().optional(),
8315
+ maxTaskMinutes: z6.number().optional(),
8316
+ readyPushTimeoutMinutes: z6.number().optional()
7029
8317
  }).optional(),
7030
- securityScan: z5.object({
7031
- command: z5.array(z5.string().min(1)).min(1)
8318
+ securityScan: z6.object({
8319
+ command: z6.array(z6.string().min(1)).min(1)
7032
8320
  }).optional(),
7033
- gateCutovers: z5.object({
7034
- objectivesSinceIssue: z5.number().int().nonnegative().optional(),
7035
- briefSectionsSinceIssue: z5.number().int().nonnegative().optional(),
7036
- documentationSinceIssue: z5.number().int().nonnegative().optional(),
7037
- briefRulesSincePr: z5.number().int().nonnegative().optional(),
7038
- agentBoxesRefusedSincePr: z5.number().int().nonnegative().optional()
8321
+ gateCutovers: z6.object({
8322
+ objectivesSinceIssue: z6.number().int().nonnegative().optional(),
8323
+ briefSectionsSinceIssue: z6.number().int().nonnegative().optional(),
8324
+ documentationSinceIssue: z6.number().int().nonnegative().optional(),
8325
+ briefRulesSincePr: z6.number().int().nonnegative().optional(),
8326
+ agentBoxesRefusedSincePr: z6.number().int().nonnegative().optional()
7039
8327
  }).optional(),
7040
- planning: z5.object({
7041
- collisionThreshold: z5.number().int().nonnegative().optional()
8328
+ planning: z6.object({
8329
+ collisionThreshold: z6.number().int().nonnegative().optional()
7042
8330
  }).optional(),
7043
- prePush: z5.object({
7044
- alwaysRun: z5.array(z5.string()).optional()
8331
+ prePush: z6.object({
8332
+ alwaysRun: z6.array(z6.string()).optional(),
8333
+ readyTests: z6.object({
8334
+ mode: z6.literal("ci"),
8335
+ workflow: z6.literal(".github/workflows/ci.yml"),
8336
+ check: z6.literal("Vinaya CI")
8337
+ }).strict().optional(),
8338
+ requiredCi: z6.object({
8339
+ workflow: z6.literal(".github/workflows/ci.yml"),
8340
+ check: z6.literal("Vinaya CI")
8341
+ }).strict().optional()
7045
8342
  }).optional(),
7046
- report: z5.object({
7047
- commandTimeoutMs: z5.number().int().positive().optional()
8343
+ report: z6.object({
8344
+ commandTimeoutMs: z6.number().int().positive().optional()
7048
8345
  }).superRefine((report, ctx) => {
7049
8346
  const commandTimeoutMs = report.commandTimeoutMs;
7050
8347
  if (commandTimeoutMs !== undefined && commandTimeoutMs > MAX_REPORT_COMMAND_TIMEOUT_MS) {
7051
8348
  ctx.addIssue({
7052
- code: z5.ZodIssueCode.custom,
8349
+ code: z6.ZodIssueCode.custom,
7053
8350
  path: ["commandTimeoutMs"],
7054
8351
  message: "must be at most 3600000 (1 hour)"
7055
8352
  });
7056
8353
  }
7057
8354
  }).optional(),
7058
- logPublish: z5.unknown().refine((v) => v === undefined, {
8355
+ logPublish: z6.unknown().refine((v) => v === undefined, {
7059
8356
  message: "logPublish is removed — telemetry is never posted to a tracker or a code host; configure `logs` instead (a folder or a server destination)"
7060
8357
  }),
7061
- runtimeDir: z5.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
7062
- logs: z5.object({
7063
- folder: z5.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
7064
- url: z5.string().url().optional(),
7065
- headers: z5.record(z5.string()).optional(),
7066
- readHeaders: z5.record(z5.string()).optional(),
8358
+ runtimeDir: z6.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
8359
+ runner: z6.enum(["standalone", "atta-engine"]).optional(),
8360
+ logs: z6.object({
8361
+ folder: z6.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
8362
+ url: z6.string().url().optional(),
8363
+ headers: z6.record(z6.string()).optional(),
8364
+ readHeaders: z6.record(z6.string()).optional(),
7067
8365
  events: CustomEventDeclarationsSchema.optional()
7068
8366
  }).refine((v) => [v.folder, v.url].filter((x) => x !== undefined).length <= 1, {
7069
8367
  message: "logs: set at most one of folder/url"
@@ -7071,8 +8369,33 @@ var VinayaConfigSchema = z5.object({
7071
8369
  message: "logs: headers requires url"
7072
8370
  }).refine((v) => v.readHeaders === undefined || v.url !== undefined, {
7073
8371
  message: "logs: readHeaders requires url"
7074
- }).optional()
8372
+ }).or(z6.literal(false)).optional(),
8373
+ decisionRecords: z6.object({
8374
+ path: RepoRelativePathSchema
8375
+ }).strict().optional()
7075
8376
  });
8377
+ function decisionRecordsPathIssue(path, doctrineRoot) {
8378
+ const reason = outsideRepositoryReason(path);
8379
+ if (reason)
8380
+ return reason;
8381
+ const folder = normalizeSpecPath(path);
8382
+ if (folder === "" || folder === ".")
8383
+ return "must name a folder, not the repository root";
8384
+ const root = normalizeSpecPath(doctrineRoot ?? "aeg-root");
8385
+ if (folder === root || folder.startsWith(`${root}/`)) {
8386
+ return `must be outside the doctrine tree "${root}" — decision records belong to this repository, not to the doctrine it ships`;
8387
+ }
8388
+ return null;
8389
+ }
8390
+ var VinayaConfigSchema = VinayaConfigObjectSchema.superRefine((config, ctx) => {
8391
+ const path = config.decisionRecords?.path;
8392
+ if (path === undefined || outsideRepositoryReason(path))
8393
+ return;
8394
+ const issue = decisionRecordsPathIssue(path, config.proseGates?.doctrineRoot);
8395
+ if (issue)
8396
+ ctx.addIssue({ code: z6.ZodIssueCode.custom, path: ["decisionRecords", "path"], message: issue });
8397
+ });
8398
+ var VinayaConfigShape = VinayaConfigObjectSchema.shape;
7076
8399
  var GLOBAL_VINAYA_HOME = join(homedir(), ".vinaya");
7077
8400
  var GLOBAL_CONFIG_PATH = join(GLOBAL_VINAYA_HOME, "config.json");
7078
8401
  var LOCAL_CONFIG_FILENAME = "vinaya.config.json";
@@ -7153,9 +8476,6 @@ function stripGlobalOnlyKeys(config, path) {
7153
8476
  }
7154
8477
  return result;
7155
8478
  }
7156
- function resolvePrincipalAllowlist(config) {
7157
- return config?.principals ?? PRINCIPAL_ALLOWLIST;
7158
- }
7159
8479
  function resolveReleaseActor(config) {
7160
8480
  return config?.releaseActor ?? DEFAULT_RELEASE_ACTOR;
7161
8481
  }
@@ -7179,13 +8499,19 @@ function resolveReviewPolicy(config) {
7179
8499
  if (!Number.isInteger(maxTaskMinutes) || maxTaskMinutes < 0) {
7180
8500
  throw new Error(`vinaya.config.json: reviewPolicy.maxTaskMinutes "${maxTaskMinutes}" is not a non-negative integer (0 turns the budget off) — fix the config, this never falls back to a default.`);
7181
8501
  }
8502
+ const readyPushTimeoutMinutes = raw.readyPushTimeoutMinutes ?? DEFAULT_READY_PUSH_TIMEOUT_MINUTES;
8503
+ if (!Number.isInteger(readyPushTimeoutMinutes) || readyPushTimeoutMinutes < 1) {
8504
+ throw new Error(`vinaya.config.json: reviewPolicy.readyPushTimeoutMinutes "${readyPushTimeoutMinutes}" is not a positive integer — fix the config, this never falls back to a default.`);
8505
+ }
7182
8506
  return {
7183
8507
  codeReviewThreshold,
7184
8508
  securityThreshold,
7185
8509
  maxRounds,
7186
- maxTaskMinutes
8510
+ maxTaskMinutes,
8511
+ readyPushTimeoutMinutes
7187
8512
  };
7188
8513
  }
8514
+ var emittedLocalOverrideWarnings = new Set;
7189
8515
  function resolveGateCutovers(config) {
7190
8516
  const raw = config?.gateCutovers;
7191
8517
  if (!raw)
@@ -7291,13 +8617,14 @@ function readTrustAnchorConfigAtRef(ref) {
7291
8617
  });
7292
8618
  return Buffer.from(raw, "utf-8").toString("base64");
7293
8619
  }
8620
+ var NO_TRUST_ANCHOR_REPO_MESSAGE = "could not resolve repo identity for the trust-anchor read";
7294
8621
  function ghFetchTrustAnchorConfig() {
7295
8622
  const probeRef = resolveCiTrustAnchorProbeRef();
7296
8623
  if (probeRef)
7297
8624
  return readTrustAnchorConfigAtRef(probeRef);
7298
8625
  const repo = trustAnchorRepo();
7299
8626
  if (!repo)
7300
- throw new Error("could not resolve repo identity for the trust-anchor read");
8627
+ throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
7301
8628
  return execFileSync2("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], {
7302
8629
  encoding: "utf-8",
7303
8630
  stdio: ["ignore", "pipe", "pipe"]
@@ -7314,7 +8641,7 @@ async function ghFetchTrustAnchorConfigAsync() {
7314
8641
  }
7315
8642
  const repo = await trustAnchorRepoAsync();
7316
8643
  if (!repo)
7317
- throw new Error("could not resolve repo identity for the trust-anchor read");
8644
+ throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
7318
8645
  const { stdout } = await execFileAsync4("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], { encoding: "utf-8", timeout: 1e4, killSignal: "SIGKILL" });
7319
8646
  return stdout;
7320
8647
  }
@@ -7340,6 +8667,47 @@ function loadTrustAnchorConfig(fetcher = ghFetchTrustAnchorConfig) {
7340
8667
  }
7341
8668
  return parseTrustAnchorContent(base64);
7342
8669
  }
8670
+ class PrincipalsUnresolvedError extends Error {
8671
+ kind;
8672
+ constructor(kind, message) {
8673
+ super(message);
8674
+ this.name = "PrincipalsUnresolvedError";
8675
+ this.kind = kind;
8676
+ }
8677
+ }
8678
+ var PRINCIPALS_FIX = 'add "principals": [...] to vinaya.config.json on the default branch';
8679
+ function fetchFailureReason(err) {
8680
+ const stderr = err?.stderr;
8681
+ const text = (typeof stderr === "string" ? stderr : stderr?.toString() ?? "").trim();
8682
+ return text.split(`
8683
+ `)[0]?.trim() || firstLine(err);
8684
+ }
8685
+ function principalsNotConfigured(why) {
8686
+ return new PrincipalsUnresolvedError("not-configured", `no Principal is configured (${why}) — ${PRINCIPALS_FIX}.`);
8687
+ }
8688
+ function resolveTrustedPrincipals(fetcher = ghFetchTrustAnchorConfig) {
8689
+ let content;
8690
+ try {
8691
+ content = fetcher();
8692
+ } catch (err) {
8693
+ if (err?.message === NO_TRUST_ANCHOR_REPO_MESSAGE) {
8694
+ throw principalsNotConfigured("no repository resolves for the read");
8695
+ }
8696
+ if (isMissingFileError(err))
8697
+ throw principalsNotConfigured("the default branch has no vinaya.config.json");
8698
+ throw new PrincipalsUnresolvedError("read-failed", `could not read "principals" from vinaya.config.json on the default branch: ${fetchFailureReason(err)}`);
8699
+ }
8700
+ const unusable = { why: "" };
8701
+ const config = parseTrustAnchorContent(content, (why) => {
8702
+ unusable.why = why;
8703
+ });
8704
+ if (config === null) {
8705
+ throw principalsNotConfigured(`vinaya.config.json on the default branch ${unusable.why ? `is unusable: ${unusable.why}` : "is empty"}`);
8706
+ }
8707
+ if (!config.principals)
8708
+ throw principalsNotConfigured('vinaya.config.json on the default branch sets no "principals"');
8709
+ return config.principals;
8710
+ }
7343
8711
  async function loadTrustAnchorConfigAsync(fetcher = ghFetchTrustAnchorConfigAsync, options = {}) {
7344
8712
  const warn = options.quiet ? () => {} : warnTrustAnchorFallback;
7345
8713
  let base64;
@@ -7348,48 +8716,214 @@ async function loadTrustAnchorConfigAsync(fetcher = ghFetchTrustAnchorConfigAsyn
7348
8716
  } catch (err) {
7349
8717
  return trustAnchorFetchFailed(err, warn);
7350
8718
  }
7351
- return parseTrustAnchorContent(base64, warn);
8719
+ return parseTrustAnchorContent(base64, warn);
8720
+ }
8721
+ function warnTrustAnchorFallback(why) {
8722
+ process.stdout.write(`⚠ could not read the trust-anchor config (\`principals\`/\`releaseActor\`) from the default branch (${why}) — falling back to vinaya's built-in defaults.
8723
+ `);
8724
+ }
8725
+ function trustAnchorFetchFailed(err, warn = warnTrustAnchorFallback) {
8726
+ if (!isMissingFileError(err))
8727
+ warn(firstLine(err));
8728
+ return null;
8729
+ }
8730
+ function parseTrustAnchorContent(content, warn = warnTrustAnchorFallback) {
8731
+ const base64 = content.trim();
8732
+ if (!base64)
8733
+ return null;
8734
+ try {
8735
+ const raw = Buffer.from(base64, "base64").toString("utf-8");
8736
+ const parsed = VinayaConfigSchema.safeParse(JSON.parse(raw));
8737
+ if (parsed.success)
8738
+ return parsed.data;
8739
+ warn("it did not satisfy the config schema");
8740
+ return null;
8741
+ } catch {
8742
+ warn("it was not readable as JSON");
8743
+ return null;
8744
+ }
8745
+ }
8746
+ function loadConfig() {
8747
+ const path = configPath();
8748
+ if (!path)
8749
+ return null;
8750
+ let text;
8751
+ try {
8752
+ text = readFileSync2(path, "utf-8");
8753
+ } catch (err) {
8754
+ reportInvalidConfigOnce(path, `unreadable: ${err.message}`);
8755
+ return null;
8756
+ }
8757
+ let raw;
8758
+ try {
8759
+ raw = JSON.parse(text);
8760
+ } catch (err) {
8761
+ reportInvalidConfigOnce(path, `invalid JSON: ${err.message}`);
8762
+ return null;
8763
+ }
8764
+ const parsed = VinayaConfigSchema.safeParse(raw);
8765
+ if (!parsed.success) {
8766
+ reportInvalidConfigOnce(path, schemaIssueDetail(parsed.error));
8767
+ return null;
8768
+ }
8769
+ return stripGlobalOnlyKeys(parsed.data, path);
8770
+ }
8771
+ function schemaIssueDetail(error) {
8772
+ return error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
8773
+ }
8774
+ var emittedInvalidConfigReports = new Set;
8775
+ function reportInvalidConfigOnce(path, detail) {
8776
+ const key = `${path}
8777
+ ${detail}`;
8778
+ if (emittedInvalidConfigReports.has(key))
8779
+ return;
8780
+ emittedInvalidConfigReports.add(key);
8781
+ const message = `${path} is not a valid Vinaya configuration (${detail}) — falling back to built-in defaults.`;
8782
+ const checkName = process.env.VINAYA_CHECK_NAME;
8783
+ if (checkName) {
8784
+ emitCheckError({
8785
+ schema: CHECK_SCHEMA_VERSION,
8786
+ check: checkName,
8787
+ severity: "warning",
8788
+ message,
8789
+ agent_recovery_prompt: `Fix the failing keys in ${path} (${detail}) so the file parses and satisfies the configuration schema, then re-run.`,
8790
+ file: path
8791
+ });
8792
+ return;
8793
+ }
8794
+ console.error(`⚠ ${message}`);
8795
+ }
8796
+ function loadConfigChecked() {
8797
+ const path = configPath();
8798
+ if (!path)
8799
+ return { ok: true, config: null };
8800
+ let raw;
8801
+ try {
8802
+ raw = JSON.parse(readFileSync2(path, "utf-8"));
8803
+ } catch (err) {
8804
+ return { ok: false, path, error: `invalid JSON: ${err.message}` };
8805
+ }
8806
+ const parsed = VinayaConfigSchema.safeParse(raw);
8807
+ if (!parsed.success) {
8808
+ return { ok: false, path, error: schemaIssueDetail(parsed.error) };
8809
+ }
8810
+ return { ok: true, config: stripGlobalOnlyKeys(parsed.data, path) };
8811
+ }
8812
+ var TOKENS_COLLECT_TRUST_PATH = join(GLOBAL_VINAYA_HOME, "tokens-collect-trust.json");
8813
+
8814
+ // src/lib/forge-read.ts
8815
+ import { execFileSync as execFileSync3 } from "node:child_process";
8816
+
8817
+ // src/lib/forge-snapshot.ts
8818
+ import { existsSync as existsSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
8819
+ import { join as join2 } from "node:path";
8820
+ var FORGE_SNAPSHOT_DIR_ENV = "VINAYA_FORGE_SNAPSHOT_DIR";
8821
+ var PULL_FILE = "pull.json";
8822
+ var PULL_COMMENTS_FILE = "pull-comments.json";
8823
+ var ISSUE_FILE = "issue.json";
8824
+ var ISSUE_COMMENTS_FILE = "issue-comments.json";
8825
+ function forgeSnapshotDir(env = process.env) {
8826
+ if (env.GITHUB_ACTIONS !== "true")
8827
+ return null;
8828
+ const dir = env[FORGE_SNAPSHOT_DIR_ENV];
8829
+ return dir ? dir : null;
8830
+ }
8831
+
8832
+ class ForgeSnapshotIncompleteError extends Error {
8833
+ constructor(dir, file) {
8834
+ super(`the forge snapshot ${dir} has no ${file} — the pull request read that writes it did not complete, so this check refuses to read the forge in its place.`);
8835
+ this.name = "ForgeSnapshotIncompleteError";
8836
+ }
8837
+ }
8838
+
8839
+ class ForgeSnapshotIssueNotFoundError extends Error {
8840
+ constructor(issue) {
8841
+ super(`Issue #${issue} did not resolve (HTTP 404) when this run's forge snapshot was read.`);
8842
+ this.name = "ForgeSnapshotIssueNotFoundError";
8843
+ }
8844
+ }
8845
+ function readSnapshotFile(dir, file) {
8846
+ let text;
8847
+ try {
8848
+ text = readFileSync3(join2(dir, file), "utf8");
8849
+ } catch {
8850
+ throw new ForgeSnapshotIncompleteError(dir, file);
8851
+ }
8852
+ return JSON.parse(text);
7352
8853
  }
7353
- function warnTrustAnchorFallback(why) {
7354
- process.stdout.write(`⚠ could not read the trust-anchor config (\`principals\`/\`releaseActor\`) from the default branch (${why}) — falling back to vinaya's built-in defaults.
7355
- `);
8854
+ function readComments(dir, file, number) {
8855
+ const parsed = readSnapshotFile(dir, file);
8856
+ if (parsed.number !== number)
8857
+ throw new ForgeSnapshotIncompleteError(dir, `${file} for #${number}`);
8858
+ return parsed.comments;
7356
8859
  }
7357
- function trustAnchorFetchFailed(err, warn = warnTrustAnchorFallback) {
7358
- if (!isMissingFileError(err))
7359
- warn(firstLine(err));
7360
- return null;
8860
+ function snapshotPullRequest(number, env = process.env) {
8861
+ const dir = forgeSnapshotDir(env);
8862
+ if (dir === null)
8863
+ return null;
8864
+ const pull = readSnapshotFile(dir, PULL_FILE);
8865
+ return pull.number === number ? pull : null;
7361
8866
  }
7362
- function parseTrustAnchorContent(content, warn = warnTrustAnchorFallback) {
7363
- const base64 = content.trim();
7364
- if (!base64)
8867
+ function snapshotIssue(number, env = process.env) {
8868
+ const dir = forgeSnapshotDir(env);
8869
+ if (dir === null)
7365
8870
  return null;
7366
- try {
7367
- const raw = Buffer.from(base64, "base64").toString("utf-8");
7368
- const parsed = VinayaConfigSchema.safeParse(JSON.parse(raw));
7369
- if (parsed.success)
7370
- return parsed.data;
7371
- warn("it did not satisfy the config schema");
8871
+ const issue = readSnapshotFile(dir, ISSUE_FILE);
8872
+ if (issue.number !== number)
7372
8873
  return null;
7373
- } catch {
7374
- warn("it was not readable as JSON");
8874
+ if ("notFound" in issue)
8875
+ throw new ForgeSnapshotIssueNotFoundError(number);
8876
+ return issue;
8877
+ }
8878
+ function snapshotComments(number, env = process.env) {
8879
+ const dir = forgeSnapshotDir(env);
8880
+ if (dir === null)
7375
8881
  return null;
7376
- }
8882
+ if (snapshotPullRequest(number, env) !== null)
8883
+ return readComments(dir, PULL_COMMENTS_FILE, number);
8884
+ if (snapshotIssue(number, env) !== null)
8885
+ return readComments(dir, ISSUE_COMMENTS_FILE, number);
8886
+ return null;
7377
8887
  }
7378
- function loadConfig() {
7379
- const path = configPath();
7380
- if (!path)
8888
+ function snapshotBody(number, env = process.env) {
8889
+ const pull = snapshotPullRequest(number, env);
8890
+ if (pull !== null)
8891
+ return pull.body;
8892
+ return snapshotIssue(number, env)?.body ?? null;
8893
+ }
8894
+ function incompleteForgeSnapshot(env = process.env) {
8895
+ const dir = forgeSnapshotDir(env);
8896
+ if (dir === null)
7381
8897
  return null;
8898
+ for (const file of [PULL_FILE, PULL_COMMENTS_FILE, ISSUE_FILE]) {
8899
+ if (!existsSync2(join2(dir, file)))
8900
+ return new ForgeSnapshotIncompleteError(dir, file).message;
8901
+ }
7382
8902
  try {
7383
- const raw = JSON.parse(readFileSync2(path, "utf-8"));
7384
- return stripGlobalOnlyKeys(VinayaConfigSchema.parse(raw), path);
7385
- } catch {
7386
- return null;
8903
+ const issue = readSnapshotFile(dir, ISSUE_FILE);
8904
+ if (typeof issue.number === "number" && !("notFound" in issue) && !existsSync2(join2(dir, ISSUE_COMMENTS_FILE))) {
8905
+ return new ForgeSnapshotIncompleteError(dir, ISSUE_COMMENTS_FILE).message;
8906
+ }
8907
+ } catch (err) {
8908
+ return `the forge snapshot ${dir} has an unreadable ${ISSUE_FILE}: ${err.message}`;
7387
8909
  }
8910
+ return null;
8911
+ }
8912
+ function exitOnIncompleteForgeSnapshot(checkName, env = process.env) {
8913
+ const reason = incompleteForgeSnapshot(env);
8914
+ if (reason === null)
8915
+ return;
8916
+ emitCheckError({
8917
+ schema: CHECK_SCHEMA_VERSION,
8918
+ check: checkName,
8919
+ severity: "error",
8920
+ message: `${checkName}: ${reason}`,
8921
+ agent_recovery_prompt: `Re-run the whole workflow run so its pull request read step writes the snapshot again (its own log names the failed read), then let \`vinaya check ${checkName}\` re-run.`
8922
+ });
8923
+ process.exit(1);
7388
8924
  }
7389
- var TOKENS_COLLECT_TRUST_PATH = join(GLOBAL_VINAYA_HOME, "tokens-collect-trust.json");
7390
8925
 
7391
8926
  // src/lib/forge-read.ts
7392
- import { execFileSync as execFileSync3 } from "node:child_process";
7393
8927
  var FORGE_READ_CEILING_BYTES = 64 * 1024 * 1024;
7394
8928
  var PAGE_SIZE = 100;
7395
8929
  var ghRunner = (args, maxBuffer) => execFileSync3("gh", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer });
@@ -7412,7 +8946,7 @@ function isForgeReadOversize(err) {
7412
8946
  function isBufferOverflow(err) {
7413
8947
  return err?.code === "ENOBUFS";
7414
8948
  }
7415
- function run2(runner, args, subject, usedBytes) {
8949
+ function runBounded(runner, args, subject, usedBytes) {
7416
8950
  const remaining = FORGE_READ_CEILING_BYTES - usedBytes;
7417
8951
  let out;
7418
8952
  try {
@@ -7427,31 +8961,40 @@ function run2(runner, args, subject, usedBytes) {
7427
8961
  throw new ForgeReadOversizeError(subject, usedBytes + size);
7428
8962
  return out;
7429
8963
  }
7430
- function readIssueComments(issue, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
7431
- const number = resolveNumber(issue, subjectLabel, runner);
7432
- const comments = [];
8964
+ function readRestCommentRows(number, subjectLabel = `Issue ${number}`, runner = ghRunner) {
8965
+ const rows = [];
7433
8966
  let used = 0;
7434
8967
  for (let page = 1;; page++) {
7435
- const out = run2(runner, ["api", `repos/{owner}/{repo}/issues/${number}/comments?per_page=${PAGE_SIZE}&page=${page}`], subjectLabel, used);
8968
+ const out = runBounded(runner, ["api", `repos/{owner}/{repo}/issues/${number}/comments?per_page=${PAGE_SIZE}&page=${page}`], subjectLabel, used);
7436
8969
  used += Buffer.byteLength(out, "utf8");
7437
- const rows = JSON.parse(out);
7438
- for (const r of rows) {
7439
- comments.push({
7440
- body: r.body ?? "",
7441
- url: r.html_url ?? "",
7442
- author: r.user?.login ? { login: r.user.login } : null
7443
- });
7444
- }
7445
- if (rows.length < PAGE_SIZE)
7446
- return comments;
8970
+ const pageRows = JSON.parse(out);
8971
+ rows.push(...pageRows);
8972
+ if (pageRows.length < PAGE_SIZE)
8973
+ return rows;
7447
8974
  }
7448
8975
  }
8976
+ function readIssueComments(issue, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
8977
+ const number = resolveNumber(issue, subjectLabel, runner);
8978
+ const fromSnapshot = snapshotComments(number);
8979
+ if (fromSnapshot !== null)
8980
+ return fromSnapshot;
8981
+ return readRestCommentRows(number, subjectLabel, runner).map((r) => ({
8982
+ body: r.body ?? "",
8983
+ url: r.html_url ?? "",
8984
+ author: r.user?.login ? { login: r.user.login } : null
8985
+ }));
8986
+ }
7449
8987
  function readIssueBody(issue, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
7450
- const out = run2(runner, ["issue", "view", String(issue), "--json", "body"], subjectLabel, 0);
8988
+ if (forgeSnapshotDir() !== null) {
8989
+ const fromSnapshot = snapshotBody(resolveNumber(issue, subjectLabel, runner));
8990
+ if (fromSnapshot !== null)
8991
+ return fromSnapshot;
8992
+ }
8993
+ const out = runBounded(runner, ["issue", "view", String(issue), "--json", "body"], subjectLabel, 0);
7451
8994
  return JSON.parse(out).body ?? "";
7452
8995
  }
7453
8996
  function readIssueFields(issue, fields, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
7454
- return JSON.parse(run2(runner, ["issue", "view", String(issue), "--json", fields], subjectLabel, 0));
8997
+ return JSON.parse(runBounded(runner, ["issue", "view", String(issue), "--json", fields], subjectLabel, 0));
7455
8998
  }
7456
8999
  function resolveNumber(issue, subjectLabel, runner) {
7457
9000
  if (typeof issue === "number")
@@ -7463,8 +9006,8 @@ function resolveNumber(issue, subjectLabel, runner) {
7463
9006
 
7464
9007
  // src/lib/brief-assembly.ts
7465
9008
  import { execFileSync as execFileSync6 } from "node:child_process";
7466
- import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync as readdirSync2 } from "node:fs";
7467
- import { join as join4 } from "node:path";
9009
+ import { existsSync as existsSync5, readFileSync as readFileSync5, readdirSync as readdirSync2 } from "node:fs";
9010
+ import { join as join5 } from "node:path";
7468
9011
 
7469
9012
  // ../../packages/sources/src/commands.ts
7470
9013
  var COMMANDS = [
@@ -7580,6 +9123,16 @@ var COMMANDS = [
7580
9123
  ],
7581
9124
  status: "shipped"
7582
9125
  },
9126
+ {
9127
+ name: "new adr",
9128
+ needs: [],
9129
+ description: "Write the next numbered decision record into the folder decisionRecords.path names",
9130
+ details: [
9131
+ "`vinaya new adr <title>` writes `<decisionRecords.path>/NNNN-<kebab-title>.md` from the shipped decision-record template (`vinaya doctrine --template decision-record`), with status Proposed and today's date, and adds a row for it to the folder's `README.md` index page, creating that page on the first record. Numbers start at `0001` and are one past the highest number any file in the folder or any row of the index carries, so a number is never reused, even after its file is removed.",
9132
+ "Refuses, naming the key, while `decisionRecords.path` is unset: decision records are opt-in. The same key switches on the `decision-record-citation` writing rule — see `decisionRecords.path` in the configuration reference."
9133
+ ],
9134
+ status: "shipped"
9135
+ },
7583
9136
  {
7584
9137
  name: "brief render",
7585
9138
  needs: ["forge", "default-branch"],
@@ -7598,9 +9151,7 @@ var COMMANDS = [
7598
9151
  name: "task dispatch",
7599
9152
  needs: ["forge", "operator-seat"],
7600
9153
  description: "Deprecated — render, pin, and post the brief on the Issue as the frozen original; start the developer",
7601
- flags: [
7602
- { flag: "--agent <claude|codex|gemini>", description: "Start the developer through dispatchRole once posted" }
7603
- ],
9154
+ flags: [{ flag: "--agent <claude|codex>", description: "Start the developer through dispatchRole once posted" }],
7604
9155
  details: [
7605
9156
  "Renders the brief from the Issue and the tree (the same assembly `brief render` uses) and posts it once as an Issue comment whose first line is `<!-- aeg:brief:v1 -->` and whose second line is `Brief hash: <sha256>` — the hash covers only the body below those two lines, so any reader recomputes it. Refuses outright, naming the existing comment's URL, when a `v1` comment already exists on the Issue — the brief is frozen by design, never overwritten or silently reissued.",
7606
9157
  "With `--agent`, starts the Developer through `dispatchRole` when `apps/cli/src/lib/dispatch.ts` exports it; otherwise prints the rendered brief and the manual dispatch instruction and exits `0` — a soft dependency, never a hard block.",
@@ -7625,7 +9176,11 @@ var COMMANDS = [
7625
9176
  description: "One command from a planned Issue to a reviewed pull request — exactly one developer started",
7626
9177
  flags: [
7627
9178
  {
7628
- flag: "--agent <claude|codex|gemini>",
9179
+ flag: "--runner <standalone|atta-engine>",
9180
+ description: "Override runner config for this invocation; absent uses config, whose default is standalone"
9181
+ },
9182
+ {
9183
+ flag: "--agent <claude|codex>",
7629
9184
  description: "Vendor for the developer and both reviewers this run dispatches"
7630
9185
  },
7631
9186
  {
@@ -7635,17 +9190,39 @@ var COMMANDS = [
7635
9190
  {
7636
9191
  flag: "--widen-surface <glob,...> --reason <text>",
7637
9192
  description: "Continue a pre-pull-request escalation whose Developer asked for `widen_surface`: supersede the frozen brief with the globs added to `## Surface`, record that as the escalation's resolution, grade the widened Issue through the write gate, then start the run"
9193
+ },
9194
+ {
9195
+ flag: "--rollback",
9196
+ description: "Run the terminate-and-restart procedure for this task: cancel its in-flight Engine run, reconcile every prepared and uncertain effect by its identity, then start a fresh standalone run from the same frozen brief. Refuses a task whose recorded runner is not `atta-engine`"
7638
9197
  }
7639
9198
  ],
7640
9199
  details: [
9200
+ "The atta-engine runner starts the workspace Engine script with Bun, streams its output and returns its exit code. A published install without the script prints one notice and falls back to standalone. Engine Log events use the local folder only; logs: false disables all Log destinations for both runners.",
9201
+ "A run's runner is recorded when it starts and never changes: switching `runner` in config changes only the runner of new runs, and a run recorded on `atta-engine` keeps routing to the Engine for `task status`, `task_resume` and `task_cancel`. A start on a pause another runner holds is refused with a typed reason naming the recorded runner and the requested one, and so is a start on another runner's Engine run that is still in flight with no pause held — halted or stopped short of completed or cancelled.",
9202
+ "`--rollback` ends the Engine run first: a held pause through the shared cancel `task_cancel` uses, which needs a Principal ruling newer than the pause as any cancel does; a run halted with no pause held has its started effects fenced; a run that already completed or was cancelled is refused, as is a driver still running with no pause held, which is never signalled; and the standalone run never starts while the Engine driver lives, a cancelled run's driver given a bounded wait to release its lock. Every started and uncertain effect is then reconciled by its identity: one the forge carries is recorded verified, one it does not carry is left for the restarted run to complete, and one the forge read cannot settle refuses the restart. Each rehearsal appends a record — task, recorded runner, action, reconciled effect identities, the restarted run's runner and terminal state — to `backend-rollback-rehearsals.jsonl` in the task's runtime directory, whether it completed, was refused or failed at a later step, and nothing removes it.",
7641
9203
  "`--widen-surface` is the Planner's one command for a widen-surface escalation, and refuses before any write when the held pause is not one (no pause, a pause with a pull request — whose continuation is the ruling on that pull request — or a round whose Developer asked for no `widen_surface`), when a driver is still alive for the task, when the escalation's resolution is already consumed (a replay — the Surface is never widened twice), or when the widened body fails the write gate, whose findings name the field to edit first. The escalation packet's permitted next actions name this command with the globs the Developer asked for, and `task_resume` refuses such an escalation naming it.",
7642
- "Composes `task brief`'s own preparation (`prepareTask`) with the watching driver (`runDriverLoop`, `dev-review-loop.ts`) — nothing else. Preparation starts no agent; the loop's own round 1 reads the frozen brief off the Issue and is the only place a developer is ever dispatched from a fresh task, so exactly one developer is started by construction.",
9204
+ "Prepares the frozen brief and resolves the task, branch and model once. The standalone runner then starts the watching driver (`runDriverLoop`, `dev-review-loop.ts`). Preparation starts no agent; the loop's own round 1 reads the frozen brief off the Issue and is the only place a developer is ever dispatched from a fresh task, so exactly one developer is started by construction.",
7643
9205
  "A brief already frozen on the Issue is reused, never re-posted — the second `task dispatch`/`task brief` call this composes around does not fail the whole run, it just skips straight to running the loop. A task whose Issue refuses preparation (a missing brief section, an unmet dispatch gate) is refused before any agent starts, with nothing posted.",
7644
9206
  "Refuses when the frozen brief's developer branch already has an open pull request AND a driver is still live for it — a driver that crashed or was killed leaves its PR behind, and this command is the one that revives it, in any state, pause held or not.",
7645
9207
  "issue-711 O4: a pause never ends this process — it keeps running and watches the pull request, continuing on its own once a newer Principal ruling appears (or, for an `'infrastructure'`/`'stale_driver'` pause, after a bounded backoff), with no `--resume` command needed for the ordinary case. Exit and printed summary distinguish a published pull request OR a watched pause's own genuine end — merged, closed, or an operator's own `--cancel` (exit `0` either way, the PR URL) — from the one pause this process can never watch (no pull request exists yet — exit `1`, with the working `vinaya task run` command for this task's own branch to continue by hand — `<tranche> <n>` for a tranche task, `--issue <n>` for a backlog one — never a `dev-review-loop --resume` line naming a pull-request number this pause does not have), a usage/argv error (exit `2`), and any other failure (exit `3`)."
7646
9208
  ],
7647
9209
  status: "shipped"
7648
9210
  },
9211
+ {
9212
+ name: "task switch",
9213
+ needs: ["forge"],
9214
+ description: "Change a task's agent or model by setting its Engine checkpoint aside, so the next `task run` is accepted",
9215
+ flags: [
9216
+ { flag: "--issue <n>", description: "Address the task by its Issue number instead of `<tranche> <n>`" },
9217
+ { flag: "--agent <claude|codex>", description: "Vendor the next `task run` of the task continues on" },
9218
+ { flag: "--model <model>", description: "Model the next `task run` is meant to use; absent, the vendor default" }
9219
+ ],
9220
+ details: [
9221
+ "Refuses, changing nothing, while a driver for the task is alive, naming its pid. Otherwise moves the task's Engine checkpoint (`checkpoints.sqlite` with its `-wal` and `-shm` files) into a timestamped `switched-*` folder of the task's run directory and never deletes it; the branch, its commits and its pull request are untouched, so the next `task run` with the new agent continues the same branch on a fresh checkpoint.",
9222
+ "Writes one driver-log line naming the from and to agent, the from and to model and the folder the checkpoint went to. On the standalone runner it changes nothing on disk and says that runner already continues a task on a new `--agent` by itself. `task run` and `run-engine --resume` still refuse an agent other than the checkpoint's, and their refusal names this command."
9223
+ ],
9224
+ status: "shipped"
9225
+ },
7649
9226
  {
7650
9227
  name: "task status",
7651
9228
  needs: ["forge"],
@@ -7800,6 +9377,22 @@ var COMMANDS = [
7800
9377
  ],
7801
9378
  status: "shipped"
7802
9379
  },
9380
+ {
9381
+ name: "pr snapshot",
9382
+ needs: ["forge"],
9383
+ description: "CI plumbing: write a run's forge snapshot of the pull request and its task Issue, read over REST",
9384
+ flags: [
9385
+ {
9386
+ flag: "--dir",
9387
+ description: "The snapshot directory; its `raw/` holds the REST pull request and comment pages the read step wrote"
9388
+ }
9389
+ ],
9390
+ details: [
9391
+ "Run by the generated workflows' read step, never by hand. Maps the REST pull request and its comments to the shape `gh pr view --json` prints, resolves the task Issue from the body's `Closes #N`, and reads that Issue and its comments over REST — never GraphQL.",
9392
+ "A check reads the snapshot only when `GITHUB_ACTIONS` is `true` and the step running it sets `VINAYA_FORGE_SNAPSHOT_DIR`; anywhere else every read goes to the forge as before. Exits 1, naming what it could not read and both token budgets, on a failed read; 2 on a usage error."
9393
+ ],
9394
+ status: "shipped"
9395
+ },
7803
9396
  {
7804
9397
  name: "issue create",
7805
9398
  needs: ["forge"],
@@ -7920,14 +9513,14 @@ var COMMANDS = [
7920
9513
  {
7921
9514
  name: "milestone close",
7922
9515
  needs: ["forge"],
7923
- description: "Close a tranche's Milestone after verifying every labeled Issue is actually attached",
9516
+ description: "Close a tranche's Milestone after verifying every labeled Issue is attached and every tranche it declares is complete",
7924
9517
  flags: [
7925
9518
  { flag: "--slug", description: "The tranche whose Milestone is being closed" },
7926
9519
  { flag: "--validate-only", description: "Run every gate and report PASS without closing the Milestone" },
7927
9520
  { flag: "--json", description: "Enveloped JSON output (schema: 1)" }
7928
9521
  ],
7929
9522
  details: [
7930
- "Resolves the target Milestone the same legacy-or-intent-declared way Issue create auto-attach does, then refuses to close on any mismatch between the label's Issues and the Milestone's natively attached Issues — naming each unattached or foreign Issue and its repair path (`gh issue edit <n> --milestone <title>`, or `vinaya milestone adopt`) — before the PATCH ever reaches the forge."
9523
+ "Resolves the target Milestone the same legacy-or-intent-declared way Issue create auto-attach does, then refuses to close on any mismatch between the label's Issues and the Milestone's natively attached Issues — naming each unattached or foreign Issue and its repair path (`gh issue edit <n> --milestone <title>`, or `vinaya milestone adopt`) — before the PATCH ever reaches the forge. It also holds the Milestone open while a tranche its `### Tranche intents` section declares is not complete — naming each unfinished tranche and its lifecycle — or while that section carries no readable tranche line; a Milestone with no such section closes on attachment alone. `--validate-only` refuses with the same reasons."
7931
9524
  ],
7932
9525
  status: "shipped"
7933
9526
  },
@@ -8216,7 +9809,7 @@ var COMMANDS = [
8216
9809
  }
8217
9810
  ],
8218
9811
  details: [
8219
- "Refuses unless HEAD is the default branch, the working tree is clean, HEAD equals `origin/<default>` (after `git fetch origin`), HEAD's commit subject starts with `Chore(release): Version packages` (unless `--allow-any-commit`), and `npm whoami` exits `0` — each its own refusal naming the fix.",
9812
+ "Refuses unless HEAD is the default branch, the working tree is clean, HEAD equals `origin/<default>` (after `git fetch origin`), HEAD's commit subject starts with `Chore(release): Version packages` (unless `--allow-any-commit`), and `npm whoami` exits `0`. Before any plan step, including under `--dry-run`, every package in `.changeset/config.json` fixed groups must have an unpublished working-tree version. Exact-version registry queries refuse with every already-published package and version; workspace read failures and registry errors other than E404 also refuse with their reason. E404 for a missing package or version counts as unpublished.",
8220
9813
  "Then streams `bun install --frozen-lockfile`, `bun run build`, `bun run changeset:publish`, and `git push origin --tags` — a real push, so the repo's own generated pre-push hook sees it exactly as any other push would. After it, prints `npm view <pkg> version` for every tag now on HEAD, noting registry lag on `@attalabs/vinaya` (observed ~20 minutes) when it still shows the previous version.",
8221
9814
  'This is the one procedure named in `apps/cli/specs/self-hosting.md`, "How the published version is produced" — publishing itself stays manual and human-triggered; this command only removes the hand-typed four-step recipe.'
8222
9815
  ],
@@ -8225,11 +9818,11 @@ var COMMANDS = [
8225
9818
  {
8226
9819
  name: "dispatch",
8227
9820
  needs: ["operator-seat"],
8228
- description: "Start a role's headless agent session (claude/codex/gemini) with attribution set on its environment, recording the outcome through the Vinaya Log",
9821
+ description: "Start a role's headless agent session (claude/codex) with attribution set on its environment, recording the outcome through the Vinaya Log",
8229
9822
  flags: [
8230
9823
  {
8231
9824
  flag: "--agent",
8232
- description: "Vendor to start: `claude`, `codex`, or `gemini` (falls back to `dispatch.agent` in config)"
9825
+ description: "Vendor to start: `claude` or `codex` (falls back to `dispatch.agent` in config)"
8233
9826
  },
8234
9827
  { flag: "--prompt-file", description: "Path to the prompt text sent to the agent (never on argv)" },
8235
9828
  { flag: "--task", description: "This dispatch's task Issue number — mutually exclusive with `--pr`" },
@@ -8246,9 +9839,9 @@ var COMMANDS = [
8246
9839
  ],
8247
9840
  details: [
8248
9841
  "Sets `VINAYA_RUN_ID`/`VINAYA_ROLE`/`VINAYA_TASK`/`VINAYA_ROUND` on the child only — never on this process's own environment — and refuses by name, before any spawn attempt, when the named vendor binary is absent from `PATH` or present but not executable.",
8249
- "Records `dispatched` (with the prompt's sha256), `outcome_received` (duration, the vendor's own usage when its stdout prints a recognizable shape), or `dispatch_failed` (`timeout`, `crash`, or `refused`) through the Vinaya Log's one `dispatch` family writer, `dispatchRole`. A wall-time ceiling (`dispatch.timeoutMs` in config, default one hour) sends `SIGTERM` then, after a grace window, `SIGKILL`.",
9842
+ "Records `dispatched` (with the prompt's sha256), `outcome_received` (duration, the vendor's own usage when its stdout prints a recognizable shape), or `dispatch_failed` (`timeout`, `crash`, `refused`, or `usage_limit`) through the Vinaya Log's one `dispatch` family writer, `dispatchRole`. A wall-time ceiling (`dispatch.timeoutMs` in config, default one hour) sends `SIGTERM` then, after a grace window, `SIGKILL`.",
8250
9843
  "Runs no flush of its own after the dispatch returns: every log line `dispatchRole` emits reaches its configured `logs` destination live, as it is emitted, so there is nothing left to ship in a trailing step. `--task`/`--pr` are attribution only, and remain mutually exclusive.",
8251
- "A successful dispatch's `DispatchHandle` carries `resumeId` — the vendor's own session/thread identifier (claude/gemini: `session_id`; codex: `thread_id`), parsed from its stdout, `null` on any failure. Passing that value as `--resume <id>` on a later call swaps in that vendor's own resume invocation (`claude -p -r <id> ...`; `codex exec resume <id> ...`; `gemini ... --resume <id> ...`) in place of its first-dispatch args."
9844
+ "A successful dispatch's `DispatchHandle` carries `resumeId` — the vendor's own session/thread identifier (claude: `session_id`; codex: `thread_id`), parsed from its stdout, `null` on any failure. Passing that value as `--resume <id>` on a later call swaps in that vendor's own resume invocation (`claude -p -r <id> ...`; `codex exec resume <id> ...`) in place of its first-dispatch args."
8252
9845
  ],
8253
9846
  status: "shipped"
8254
9847
  },
@@ -8259,7 +9852,7 @@ var COMMANDS = [
8259
9852
  flags: [
8260
9853
  { flag: "--task <n>", description: "This task's Issue number — its frozen `aeg:brief:v1` comment is the brief" },
8261
9854
  {
8262
- flag: "--agent <claude|codex|gemini>",
9855
+ flag: "--agent <claude|codex>",
8263
9856
  description: "Vendor for every dispatch this loop makes (falls back to `dispatch.agent` in config)"
8264
9857
  },
8265
9858
  { flag: "--json", description: "Enveloped JSON output (schema: 1)" }
@@ -8338,22 +9931,78 @@ function createForgeSource(config) {
8338
9931
  };
8339
9932
  }
8340
9933
  // ../../packages/sources/src/select-source.ts
8341
- import { z as z6 } from "zod";
8342
- var StateSourceConfigSchema = z6.discriminatedUnion("kind", [
8343
- z6.object({ kind: z6.literal("forge"), owner: z6.string(), repo: z6.string() }),
8344
- z6.object({ kind: z6.literal("file"), root: z6.string().optional() })
9934
+ import { z as z7 } from "zod";
9935
+ var StateSourceConfigSchema = z7.discriminatedUnion("kind", [
9936
+ z7.object({ kind: z7.literal("forge"), owner: z7.string(), repo: z7.string() }),
9937
+ z7.object({ kind: z7.literal("file"), root: z7.string().optional() })
8345
9938
  ]);
8346
9939
  // src/checks/edge-resolve.ts
9940
+ import { execFile as execFile5 } from "node:child_process";
9941
+ import { promisify as promisify5 } from "node:util";
9942
+
9943
+ // src/lib/github-rate-limit.ts
8347
9944
  import { execFileSync as execFileSync4 } from "node:child_process";
9945
+ var GITHUB_RATE_LIMIT_WORDING = /api rate limit (?:already )?exceeded|secondary rate limit|rate limit exceeded/i;
9946
+ var SECONDARY_RATE_LIMIT_WORDING = /secondary rate limit/i;
9947
+ function isGithubRateLimitError(text) {
9948
+ return GITHUB_RATE_LIMIT_WORDING.test(text);
9949
+ }
9950
+ function rateLimitBudget(errorText) {
9951
+ return errorText.trimStart().startsWith("GraphQL:") ? "GraphQL" : "REST";
9952
+ }
9953
+ var defaultReader = () => execFileSync4("gh", ["api", "rate_limit"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
9954
+ function readRateLimitReset(budget, read = defaultReader) {
9955
+ let parsed;
9956
+ try {
9957
+ parsed = JSON.parse(read());
9958
+ } catch {
9959
+ return null;
9960
+ }
9961
+ const resources = parsed.resources;
9962
+ const entry = resources?.[budget === "GraphQL" ? "graphql" : "core"];
9963
+ if (!entry || typeof entry.reset !== "number" || !Number.isFinite(entry.reset) || entry.reset <= 0)
9964
+ return null;
9965
+ if (typeof entry.remaining === "number" && entry.remaining > 0)
9966
+ return null;
9967
+ return entry.reset;
9968
+ }
9969
+ function formatResetUtc(epochSeconds) {
9970
+ const d = new Date(epochSeconds * 1000);
9971
+ const hh = String(d.getUTCHours()).padStart(2, "0");
9972
+ const mm = String(d.getUTCMinutes()).padStart(2, "0");
9973
+ return `${hh}:${mm} UTC`;
9974
+ }
9975
+ function rateLimitMessage(errorText, read = defaultReader) {
9976
+ const budget = rateLimitBudget(errorText);
9977
+ const reset = SECONDARY_RATE_LIMIT_WORDING.test(errorText) ? null : readRateLimitReset(budget, read);
9978
+ const when = reset === null ? "resets in a few minutes" : `resets at ${formatResetUtc(reset)}`;
9979
+ return `GitHub rate limit (${budget}), ${when}`;
9980
+ }
9981
+ function execErrorText(err) {
9982
+ const e = err;
9983
+ const stderr = e?.stderr === undefined || e.stderr === null ? "" : String(e.stderr);
9984
+ const message = typeof e?.message === "string" ? e.message : "";
9985
+ return stderr.trim() !== "" ? `${stderr}
9986
+ ${message}` : message;
9987
+ }
9988
+
9989
+ // src/checks/edge-resolve.ts
8348
9990
  var DIRECT_ISSUE_REF = /#(\d+)/;
8349
9991
  var issueCache = new Map;
9992
+ var execFileAsync5 = promisify5(execFile5);
9993
+ var ISSUE_NOT_FOUND = /could not resolve to an issue/i;
8350
9994
  function fetchIssueState(num, repo) {
8351
9995
  const key = `${repo.owner}/${repo.repo}#${num}`;
8352
- if (issueCache.has(key))
8353
- return issueCache.get(key) ?? null;
8354
- let out = null;
9996
+ const cached = issueCache.get(key);
9997
+ if (cached)
9998
+ return cached;
9999
+ const out = readIssueOnce(num, repo).then((first) => first.readFailed ? readIssueOnce(num, repo) : first);
10000
+ issueCache.set(key, out);
10001
+ return out;
10002
+ }
10003
+ async function readIssueOnce(num, repo) {
8355
10004
  try {
8356
- const raw = execFileSync4("gh", [
10005
+ const { stdout } = await execFileAsync5("gh", [
8357
10006
  "issue",
8358
10007
  "view",
8359
10008
  String(num),
@@ -8361,13 +10010,11 @@ function fetchIssueState(num, repo) {
8361
10010
  `${repo.owner}/${repo.repo}`,
8362
10011
  "--json",
8363
10012
  "state,stateReason,closedByPullRequestsReferences"
8364
- ], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
8365
- out = JSON.parse(raw);
8366
- } catch {
8367
- out = null;
10013
+ ], { encoding: "utf8" });
10014
+ return { json: JSON.parse(stdout), readFailed: false };
10015
+ } catch (err) {
10016
+ return { json: null, readFailed: !ISSUE_NOT_FOUND.test(execErrorText(err)) };
8368
10017
  }
8369
- issueCache.set(key, out);
8370
- return out;
8371
10018
  }
8372
10019
  var defaultResolveSiblingTranche = async (slug, repo) => {
8373
10020
  let tranche;
@@ -8384,7 +10031,7 @@ var defaultResolveSiblingTranche = async (slug, repo) => {
8384
10031
  };
8385
10032
  };
8386
10033
  var siblingTrancheCache = new Map;
8387
- function edgeFromIssueJson(num, json) {
10034
+ function edgeFromIssueJson(num, json, readFailed = false) {
8388
10035
  if (json === null) {
8389
10036
  return {
8390
10037
  issue: num,
@@ -8393,7 +10040,8 @@ function edgeFromIssueJson(num, json) {
8393
10040
  issueState: null,
8394
10041
  stateReason: null,
8395
10042
  closedByActor: null,
8396
- resolved: true
10043
+ resolved: true,
10044
+ ...readFailed ? { readFailed: true } : {}
8397
10045
  };
8398
10046
  }
8399
10047
  const state = json.state === "CLOSED" ? "closed" : json.state === "OPEN" ? "open" : null;
@@ -8426,7 +10074,8 @@ async function resolveEdge(id, taskById, factsByTaskId, repo, resolveSibling = d
8426
10074
  const direct = id.match(DIRECT_ISSUE_REF);
8427
10075
  if (direct) {
8428
10076
  const num = Number(direct[1]);
8429
- return edgeFromIssueJson(num, fetchIssueState(num, repo));
10077
+ const read = await fetchIssueState(num, repo);
10078
+ return edgeFromIssueJson(num, read.json, read.readFailed);
8430
10079
  }
8431
10080
  const qualified = splitSlugQualifiedEdge(id);
8432
10081
  if (qualified) {
@@ -8460,15 +10109,27 @@ async function resolveEdge(id, taskById, factsByTaskId, repo, resolveSibling = d
8460
10109
  resolved: false
8461
10110
  };
8462
10111
  }
10112
+ function dependsOnFactFromEdge(id, r) {
10113
+ return {
10114
+ id,
10115
+ issue: r.issue,
10116
+ merged: r.merged,
10117
+ resolved: r.resolved,
10118
+ issueState: r.issueState,
10119
+ stateReason: r.stateReason,
10120
+ closedByActor: r.closedByActor,
10121
+ ...r.readFailed ? { readFailed: true } : {}
10122
+ };
10123
+ }
8463
10124
 
8464
10125
  // src/lib/package-root.ts
8465
- import { existsSync as existsSync2 } from "node:fs";
8466
- import { dirname as dirname2, join as join2 } from "node:path";
10126
+ import { existsSync as existsSync3 } from "node:fs";
10127
+ import { dirname as dirname2, join as join3 } from "node:path";
8467
10128
  import { fileURLToPath as fileURLToPath2 } from "node:url";
8468
10129
  function packageRoot(moduleUrl) {
8469
10130
  let dir = dirname2(fileURLToPath2(moduleUrl));
8470
- while (!existsSync2(join2(dir, "package.json"))) {
8471
- if (existsSync2(join2(dir, ".git")))
10131
+ while (!existsSync3(join3(dir, "package.json"))) {
10132
+ if (existsSync3(join3(dir, ".git")))
8472
10133
  break;
8473
10134
  const parent = dirname2(dir);
8474
10135
  if (parent === dir)
@@ -8480,14 +10141,21 @@ function packageRoot(moduleUrl) {
8480
10141
 
8481
10142
  // src/commands/doctrine.ts
8482
10143
  import { execFileSync as execFileSync5 } from "node:child_process";
8483
- import { existsSync as existsSync3, readdirSync, readFileSync as readFileSync3 } from "node:fs";
8484
- import { dirname as dirname3, join as join3, sep } from "node:path";
10144
+ import { existsSync as existsSync4, readdirSync, readFileSync as readFileSync4 } from "node:fs";
10145
+ import { dirname as dirname3, join as join4, sep } from "node:path";
8485
10146
  import matter4 from "gray-matter";
8486
10147
 
8487
10148
  // ../../packages/aeg-core/src/docs/parse-doc.ts
8488
10149
  import matter2 from "gray-matter";
8489
10150
  // ../../packages/aeg-core/src/docs/surfaced-manifest.ts
8490
10151
  var NO_MODEL_BACKED_PATHS = new Set;
10152
+ // ../../packages/aeg-core/src/docs/published-prose.ts
10153
+ var ALLOWED_MECHANICS = rulesForGroup("published-prose")[0]?.exemptions ?? [];
10154
+ var PROSE_RULES = rulesForGroup("published-prose").map((rule) => ({
10155
+ id: rule.id,
10156
+ what: rule.message,
10157
+ pattern: rule.patterns.published
10158
+ }));
8491
10159
  // src/roles/contract.ts
8492
10160
  import matter3 from "gray-matter";
8493
10161
 
@@ -8509,22 +10177,22 @@ function gitToplevel(cwd) {
8509
10177
  function resolveDoctrineRootInfo(pkg = packageRoot(import.meta.url), cwd = process.cwd()) {
8510
10178
  const toplevel = gitToplevel(cwd);
8511
10179
  if (toplevel !== null) {
8512
- const treeRoot = join3(toplevel, "aeg-root");
8513
- if (existsSync3(join3(treeRoot, "roles")))
10180
+ const treeRoot = join4(toplevel, "aeg-root");
10181
+ if (existsSync4(join4(treeRoot, "roles")))
8514
10182
  return { root: treeRoot, source: "tree" };
8515
10183
  }
8516
10184
  const fromSource = !pkg.split(sep).includes("node_modules");
8517
- const bundleRoot = fromSource ? join3(dirname3(dirname3(pkg)), "aeg-root") : join3(pkg, "aeg-root");
10185
+ const bundleRoot = fromSource ? join4(dirname3(dirname3(pkg)), "aeg-root") : join4(pkg, "aeg-root");
8518
10186
  return hasDoctrineEntry(bundleRoot) ? { root: bundleRoot, source: "bundle" } : null;
8519
10187
  }
8520
10188
  function hasDoctrineEntry(root) {
8521
- return existsSync3(join3(root, ...ENTRY_SEGMENTS));
10189
+ return existsSync4(join4(root, ...ENTRY_SEGMENTS));
8522
10190
  }
8523
10191
 
8524
10192
  // src/lib/brief-assembly.ts
8525
10193
  var PACKAGE_ROOT = packageRoot(import.meta.url);
8526
- var PACKAGED_TEMPLATE_PATH = join4(PACKAGE_ROOT, "aeg-root", "templates", "brief-template.md");
8527
- var TEMPLATE_PATH = existsSync4(PACKAGED_TEMPLATE_PATH) ? PACKAGED_TEMPLATE_PATH : join4(PACKAGE_ROOT, "..", "..", "aeg-root", "templates", "brief-template.md");
10194
+ var PACKAGED_TEMPLATE_PATH = join5(PACKAGE_ROOT, "aeg-root", "templates", "brief-template.md");
10195
+ var TEMPLATE_PATH = existsSync5(PACKAGED_TEMPLATE_PATH) ? PACKAGED_TEMPLATE_PATH : join5(PACKAGE_ROOT, "..", "..", "aeg-root", "templates", "brief-template.md");
8528
10196
  function git(args) {
8529
10197
  try {
8530
10198
  return execFileSync6("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
@@ -8540,24 +10208,25 @@ function expandGlob(glob) {
8540
10208
  var DRAFT_ISSUE_SENTINEL = Number.MAX_SAFE_INTEGER;
8541
10209
 
8542
10210
  // src/checks/registry.ts
8543
- import { join as join5, relative, sep as sep2 } from "node:path";
10211
+ import { join as join6, relative, sep as sep2 } from "node:path";
8544
10212
  import { fileURLToPath as fileURLToPath3 } from "node:url";
8545
10213
  function resolveCheckBin(packageDir, moduleUrl) {
8546
10214
  const fromPackage = relative(packageDir, fileURLToPath3(moduleUrl));
8547
10215
  const bundled = fromPackage === "dist" || fromPackage.startsWith(`dist${sep2}`);
8548
- return bundled ? { dir: join5(packageDir, "dist", "checks", "bin"), ext: ".js" } : { dir: join5(packageDir, "src", "checks", "bin"), ext: ".ts" };
10216
+ return bundled ? { dir: join6(packageDir, "dist", "checks", "bin"), ext: ".js" } : { dir: join6(packageDir, "src", "checks", "bin"), ext: ".ts" };
8549
10217
  }
8550
10218
  var CHECK_BIN = resolveCheckBin(packageRoot(import.meta.url), import.meta.url);
8551
10219
  var BIN_DIR = CHECK_BIN.dir;
8552
10220
  var BIN_EXT = CHECK_BIN.ext;
8553
10221
  function bin(name) {
8554
- return join5(BIN_DIR, `${name}${BIN_EXT}`);
10222
+ return join6(BIN_DIR, `${name}${BIN_EXT}`);
8555
10223
  }
8556
10224
  var REGISTRY = [
8557
10225
  [
8558
10226
  {
8559
10227
  name: "brief-shape",
8560
10228
  validates: "body",
10229
+ requiresOpenPr: true,
8561
10230
  run: bin("check-brief-shape"),
8562
10231
  scope: "diff",
8563
10232
  timeoutMs: 15000,
@@ -8566,7 +10235,9 @@ var REGISTRY = [
8566
10235
  BRANCH: { optional: true },
8567
10236
  PR_NUMBER: { optional: true },
8568
10237
  GITHUB_TOKEN: { optional: true },
8569
- GH_TOKEN: { optional: true }
10238
+ GH_TOKEN: { optional: true },
10239
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10240
+ GITHUB_ACTIONS: { optional: true }
8570
10241
  }
8571
10242
  },
8572
10243
  0
@@ -8575,6 +10246,7 @@ var REGISTRY = [
8575
10246
  {
8576
10247
  name: "pr-report-density",
8577
10248
  validates: "body",
10249
+ requiresOpenPr: true,
8578
10250
  run: bin("check-pr-report-density"),
8579
10251
  scope: "diff",
8580
10252
  timeoutMs: 15000,
@@ -8600,7 +10272,9 @@ var REGISTRY = [
8600
10272
  PR_NUMBER: { optional: true },
8601
10273
  GITHUB_REPOSITORY: { optional: true },
8602
10274
  GITHUB_TOKEN: { optional: true },
8603
- GH_TOKEN: { optional: true }
10275
+ GH_TOKEN: { optional: true },
10276
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10277
+ GITHUB_ACTIONS: { optional: true }
8604
10278
  }
8605
10279
  },
8606
10280
  0
@@ -8624,6 +10298,7 @@ var REGISTRY = [
8624
10298
  {
8625
10299
  name: "pr-premise-reassert",
8626
10300
  validates: "body",
10301
+ requiresOpenPr: true,
8627
10302
  run: bin("check-pr-premise-reassert"),
8628
10303
  scope: "diff",
8629
10304
  timeoutMs: 15000,
@@ -8644,7 +10319,9 @@ var REGISTRY = [
8644
10319
  BRANCH: { optional: true },
8645
10320
  GITHUB_TOKEN: { optional: true },
8646
10321
  GH_TOKEN: { optional: true },
8647
- PREMISE_FILE: { optional: true }
10322
+ PREMISE_FILE: { optional: true },
10323
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10324
+ GITHUB_ACTIONS: { optional: true }
8648
10325
  }
8649
10326
  },
8650
10327
  0
@@ -8696,7 +10373,9 @@ var REGISTRY = [
8696
10373
  PR_BODY: { optional: true },
8697
10374
  PR_BODY_FILE: { optional: true },
8698
10375
  GITHUB_TOKEN: { optional: true },
8699
- GH_TOKEN: { optional: true }
10376
+ GH_TOKEN: { optional: true },
10377
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10378
+ GITHUB_ACTIONS: { optional: true }
8700
10379
  }
8701
10380
  },
8702
10381
  1
@@ -8712,7 +10391,13 @@ var REGISTRY = [
8712
10391
  principalOwed: true,
8713
10392
  env: {
8714
10393
  PR_BODY: { optional: true },
8715
- BRANCH: { optional: true }
10394
+ BRANCH: { optional: true },
10395
+ PULL_REQUEST_HEAD_SHA: { optional: true },
10396
+ GITHUB_REPOSITORY: { optional: true },
10397
+ GITHUB_TOKEN: { optional: true },
10398
+ GH_TOKEN: { optional: true },
10399
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10400
+ GITHUB_ACTIONS: { optional: true }
8716
10401
  }
8717
10402
  },
8718
10403
  1
@@ -8728,7 +10413,13 @@ var REGISTRY = [
8728
10413
  ownWorkflow: true,
8729
10414
  env: {
8730
10415
  PR_BODY: { optional: true },
8731
- BRANCH: { optional: true }
10416
+ BRANCH: { optional: true },
10417
+ PULL_REQUEST_HEAD_SHA: { optional: true },
10418
+ GITHUB_REPOSITORY: { optional: true },
10419
+ GITHUB_TOKEN: { optional: true },
10420
+ GH_TOKEN: { optional: true },
10421
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10422
+ GITHUB_ACTIONS: { optional: true }
8732
10423
  }
8733
10424
  },
8734
10425
  1
@@ -8747,7 +10438,9 @@ var REGISTRY = [
8747
10438
  PR_NUMBER: { optional: true },
8748
10439
  GITHUB_REPOSITORY: { optional: true },
8749
10440
  GITHUB_TOKEN: { optional: true },
8750
- GH_TOKEN: { optional: true }
10441
+ GH_TOKEN: { optional: true },
10442
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10443
+ GITHUB_ACTIONS: { optional: true }
8751
10444
  }
8752
10445
  },
8753
10446
  1
@@ -8787,7 +10480,9 @@ var REGISTRY = [
8787
10480
  PR_NUMBER: { optional: true },
8788
10481
  GITHUB_REPOSITORY: { optional: true },
8789
10482
  GITHUB_TOKEN: { optional: true },
8790
- GH_TOKEN: { optional: true }
10483
+ GH_TOKEN: { optional: true },
10484
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10485
+ GITHUB_ACTIONS: { optional: true }
8791
10486
  }
8792
10487
  },
8793
10488
  1
@@ -8840,12 +10535,15 @@ var REGISTRY = [
8840
10535
  {
8841
10536
  name: "doc-coverage-push",
8842
10537
  validates: "body",
10538
+ advisory: true,
8843
10539
  run: bin("check-doc-coverage-push"),
8844
10540
  scope: "diff",
8845
10541
  timeoutMs: 15000,
8846
10542
  env: {
8847
10543
  OVERRIDE_DOCS: { optional: true },
8848
10544
  BASE_SHA: { optional: true },
10545
+ GIT_INDEX_FILE: { optional: true },
10546
+ VINAYA_COMMIT_HOOK: { optional: true },
8849
10547
  PR_BODY: { optional: true },
8850
10548
  PR_BODY_FILE: { optional: true },
8851
10549
  PR_LABELS: { optional: true },
@@ -8857,21 +10555,6 @@ var REGISTRY = [
8857
10555
  },
8858
10556
  0
8859
10557
  ],
8860
- [
8861
- {
8862
- name: "issue-assignment",
8863
- run: bin("check-issue-assignment"),
8864
- scope: "full",
8865
- timeoutMs: 30000,
8866
- env: {
8867
- AEG_REPO: { optional: true },
8868
- BRANCH: { optional: true },
8869
- GITHUB_TOKEN: { optional: true },
8870
- GH_TOKEN: { optional: true }
8871
- }
8872
- },
8873
- 0
8874
- ],
8875
10558
  [
8876
10559
  {
8877
10560
  name: "evidence-fresh",
@@ -8885,7 +10568,9 @@ var REGISTRY = [
8885
10568
  PR_BODY: { optional: true },
8886
10569
  BASE_SHA: { optional: true },
8887
10570
  GITHUB_TOKEN: { optional: true },
8888
- GH_TOKEN: { optional: true }
10571
+ GH_TOKEN: { optional: true },
10572
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10573
+ GITHUB_ACTIONS: { optional: true }
8889
10574
  }
8890
10575
  },
8891
10576
  1
@@ -8896,7 +10581,11 @@ var REGISTRY = [
8896
10581
  run: bin("check-reader-resolvable-prose"),
8897
10582
  scope: "full",
8898
10583
  timeoutMs: 30000,
8899
- env: {},
10584
+ env: {
10585
+ BASE_SHA: { optional: true },
10586
+ GIT_INDEX_FILE: { optional: true },
10587
+ VINAYA_COMMIT_HOOK: { optional: true }
10588
+ },
8900
10589
  include: [
8901
10590
  "aeg-root/**/*.md",
8902
10591
  "apps/cli/src/**",
@@ -8914,7 +10603,11 @@ var REGISTRY = [
8914
10603
  run: bin("check-retired-vocabulary"),
8915
10604
  scope: "full",
8916
10605
  timeoutMs: 30000,
8917
- env: {},
10606
+ env: {
10607
+ BASE_SHA: { optional: true },
10608
+ GIT_INDEX_FILE: { optional: true },
10609
+ VINAYA_COMMIT_HOOK: { optional: true }
10610
+ },
8918
10611
  include: ["aeg-root/**/*.md"]
8919
10612
  },
8920
10613
  0
@@ -8922,10 +10615,15 @@ var REGISTRY = [
8922
10615
  [
8923
10616
  {
8924
10617
  name: "doctrine-portability",
10618
+ advisory: true,
8925
10619
  run: bin("check-doctrine-portability"),
8926
10620
  scope: "full",
8927
10621
  timeoutMs: 30000,
8928
- env: { BASE_SHA: { optional: true } },
10622
+ env: {
10623
+ BASE_SHA: { optional: true },
10624
+ GIT_INDEX_FILE: { optional: true },
10625
+ VINAYA_COMMIT_HOOK: { optional: true }
10626
+ },
8929
10627
  include: ["aeg-root/**/*.md"]
8930
10628
  },
8931
10629
  0
@@ -8958,7 +10656,11 @@ var REGISTRY = [
8958
10656
  run: bin("check-exec-bits"),
8959
10657
  scope: "diff",
8960
10658
  timeoutMs: 30000,
8961
- env: {}
10659
+ env: {
10660
+ BASE_SHA: { optional: true },
10661
+ GIT_INDEX_FILE: { optional: true },
10662
+ VINAYA_COMMIT_HOOK: { optional: true }
10663
+ }
8962
10664
  },
8963
10665
  0
8964
10666
  ],
@@ -8968,17 +10670,26 @@ var REGISTRY = [
8968
10670
  run: bin("check-ci-shard-coverage"),
8969
10671
  scope: "diff",
8970
10672
  timeoutMs: 15000,
8971
- env: {}
10673
+ env: {
10674
+ BASE_SHA: { optional: true },
10675
+ GIT_INDEX_FILE: { optional: true },
10676
+ VINAYA_COMMIT_HOOK: { optional: true }
10677
+ }
8972
10678
  },
8973
10679
  0
8974
10680
  ],
8975
10681
  [
8976
10682
  {
8977
10683
  name: "workspace-escape",
10684
+ advisory: true,
8978
10685
  run: bin("check-workspace-escape"),
8979
10686
  scope: "full",
8980
10687
  timeoutMs: 30000,
8981
- env: {},
10688
+ env: {
10689
+ BASE_SHA: { optional: true },
10690
+ GIT_INDEX_FILE: { optional: true },
10691
+ VINAYA_COMMIT_HOOK: { optional: true }
10692
+ },
8982
10693
  include: ["aeg-root/**/*.md"]
8983
10694
  },
8984
10695
  0
@@ -8989,17 +10700,23 @@ var REGISTRY = [
8989
10700
  run: bin("check-changeset-coverage"),
8990
10701
  scope: "diff",
8991
10702
  timeoutMs: 15000,
8992
- env: {}
10703
+ env: {
10704
+ BASE_SHA: { optional: true },
10705
+ GIT_INDEX_FILE: { optional: true },
10706
+ VINAYA_COMMIT_HOOK: { optional: true }
10707
+ }
8993
10708
  },
8994
10709
  0
8995
10710
  ],
8996
10711
  [
8997
10712
  {
8998
10713
  name: "quoted-command",
10714
+ advisory: true,
8999
10715
  run: bin("check-quoted-command"),
9000
- scope: "diff",
10716
+ scope: "full",
9001
10717
  timeoutMs: 15000,
9002
- env: {}
10718
+ env: {},
10719
+ include: ["aeg-root/**/*.md"]
9003
10720
  },
9004
10721
  0
9005
10722
  ],
@@ -9007,7 +10724,7 @@ var REGISTRY = [
9007
10724
  {
9008
10725
  name: "main-branch-refusal",
9009
10726
  run: bin("check-main-branch-refusal"),
9010
- scope: "full",
10727
+ scope: "diff",
9011
10728
  timeoutMs: 15000,
9012
10729
  env: { VINAYA_PUSH_REFS: { optional: true } }
9013
10730
  },
@@ -9074,18 +10791,6 @@ var REGISTRY = [
9074
10791
  },
9075
10792
  1
9076
10793
  ],
9077
- [
9078
- {
9079
- name: "issue-tranche-label",
9080
- run: bin("check-issue-tranche-label"),
9081
- validates: "issue",
9082
- scope: "full",
9083
- ownWorkflow: true,
9084
- timeoutMs: 15000,
9085
- env: { ISSUE_BODY: { optional: true }, ISSUE_LABELS: { optional: true } }
9086
- },
9087
- 1
9088
- ],
9089
10794
  [
9090
10795
  {
9091
10796
  name: "issue-milestone-attach",
@@ -9109,30 +10814,30 @@ function coreCheckRegistry() {
9109
10814
  var CORE_CHECK_RING = Object.fromEntries(REGISTRY.map(([spec, ring]) => [spec.name, ring]));
9110
10815
 
9111
10816
  // src/lib/log-sink.ts
9112
- import { execFile as execFile5 } from "node:child_process";
10817
+ import { execFile as execFile6 } from "node:child_process";
9113
10818
  import { randomUUID as randomUUID2 } from "node:crypto";
9114
10819
  import {
9115
10820
  appendFileSync,
9116
10821
  closeSync as closeSync4,
9117
10822
  constants as fsConstants4,
9118
- existsSync as existsSync7,
10823
+ existsSync as existsSync8,
9119
10824
  fstatSync as fstatSync3,
9120
10825
  mkdirSync as mkdirSync4,
9121
- lstatSync as lstatSync2,
10826
+ lstatSync as lstatSync3,
9122
10827
  openSync as openSync4,
9123
- readFileSync as readFileSync7,
10828
+ readFileSync as readFileSync8,
9124
10829
  renameSync as renameSync2,
9125
- writeFileSync as writeFileSync3,
10830
+ writeFileSync as writeFileSync4,
9126
10831
  writeSync as writeSync3
9127
10832
  } from "node:fs";
9128
10833
  import { hostname as osHostname, homedir as homedir3 } from "node:os";
9129
- import { dirname as dirname7, join as join8 } from "node:path";
9130
- import { promisify as promisify5 } from "node:util";
10834
+ import { dirname as dirname7, join as join9 } from "node:path";
10835
+ import { promisify as promisify6 } from "node:util";
9131
10836
 
9132
10837
  // src/lib/run-paths.ts
9133
10838
  import { execFileSync as execFileSync7 } from "node:child_process";
9134
- import { chmodSync, existsSync as existsSync5, realpathSync as realpathSync3 } from "node:fs";
9135
- import { dirname as dirname4, join as join6, resolve as resolvePath } from "node:path";
10839
+ import { chmodSync, existsSync as existsSync6, realpathSync as realpathSync3 } from "node:fs";
10840
+ import { dirname as dirname4, join as join7, resolve as resolvePath } from "node:path";
9136
10841
  var TASKS_EXECUTION_DIRNAME = "tasks-execution";
9137
10842
  var RUN_AREA_DIRNAMES = {
9138
10843
  control: CONTROL_AREA_DIRNAME,
@@ -9151,7 +10856,7 @@ function repoSegment(repo) {
9151
10856
  return `${repo.owner}-${repo.repo}`;
9152
10857
  }
9153
10858
  function defaultRuntimeDir(repo, home = GLOBAL_VINAYA_HOME) {
9154
- return join6(home, "runtime", repoSegment(repo));
10859
+ return join7(home, "runtime", repoSegment(repo));
9155
10860
  }
9156
10861
  function resolveRuntimeDir(input) {
9157
10862
  const local = resolveRuntimeDirSetting(input.localConfig);
@@ -9172,27 +10877,27 @@ function isInsideRepo(candidate, repoRoot) {
9172
10877
  return target === root || target.startsWith(`${root}/`);
9173
10878
  }
9174
10879
  function runPath(runtimeDir, scope, location) {
9175
- const dir = join6(runtimeDir, TASKS_EXECUTION_DIRNAME, scopeSegment(scope));
10880
+ const dir = join7(runtimeDir, TASKS_EXECUTION_DIRNAME, scopeSegment(scope));
9176
10881
  switch (location.area) {
9177
10882
  case "task":
9178
- return location.file ? join6(dir, location.file) : dir;
10883
+ return location.file ? join7(dir, location.file) : dir;
9179
10884
  case "control": {
9180
- const controlDir = join6(dir, RUN_AREA_DIRNAMES.control);
9181
- return location.file ? join6(controlDir, location.file) : controlDir;
10885
+ const controlDir = join7(dir, RUN_AREA_DIRNAMES.control);
10886
+ return location.file ? join7(controlDir, location.file) : controlDir;
9182
10887
  }
9183
10888
  case "rounds":
9184
- return join6(dir, RUN_AREA_DIRNAMES.rounds);
10889
+ return join7(dir, RUN_AREA_DIRNAMES.rounds);
9185
10890
  case "round": {
9186
- const roundDir = join6(dir, RUN_AREA_DIRNAMES.rounds, String(location.round));
9187
- return location.file ? join6(roundDir, location.file) : roundDir;
10891
+ const roundDir = join7(dir, RUN_AREA_DIRNAMES.rounds, String(location.round));
10892
+ return location.file ? join7(roundDir, location.file) : roundDir;
9188
10893
  }
9189
10894
  case "developer": {
9190
- const developerDir = join6(dir, RUN_AREA_DIRNAMES.rounds, String(location.round), "developer");
9191
- return location.file ? join6(developerDir, location.file) : developerDir;
10895
+ const developerDir = join7(dir, RUN_AREA_DIRNAMES.rounds, String(location.round), "developer");
10896
+ return location.file ? join7(developerDir, location.file) : developerDir;
9192
10897
  }
9193
10898
  default: {
9194
- const areaDir = join6(dir, RUN_AREA_DIRNAMES[location.area]);
9195
- return location.file ? join6(areaDir, location.file) : areaDir;
10899
+ const areaDir = join7(dir, RUN_AREA_DIRNAMES[location.area]);
10900
+ return location.file ? join7(areaDir, location.file) : areaDir;
9196
10901
  }
9197
10902
  }
9198
10903
  }
@@ -9261,7 +10966,7 @@ function repoRootSync(start = process.cwd()) {
9261
10966
  return null;
9262
10967
  }
9263
10968
  for (;; ) {
9264
- if (existsSync5(join6(dir, ".git")))
10969
+ if (existsSync6(join7(dir, ".git")))
9265
10970
  return dir;
9266
10971
  const parent = dirname4(dir);
9267
10972
  if (parent === dir)
@@ -9305,11 +11010,11 @@ function runtimeDirForThisRepo() {
9305
11010
  import {
9306
11011
  closeSync as closeSync2,
9307
11012
  constants as fsConstants2,
9308
- existsSync as existsSync6,
11013
+ existsSync as existsSync7,
9309
11014
  fstatSync as fstatSync2,
9310
11015
  mkdirSync as mkdirSync2,
9311
11016
  openSync as openSync2,
9312
- readFileSync as readFileSync5,
11017
+ readFileSync as readFileSync6,
9313
11018
  readSync,
9314
11019
  statSync,
9315
11020
  writeSync
@@ -9342,21 +11047,21 @@ function appendLoopLogLine(path, line) {
9342
11047
  import {
9343
11048
  closeSync as closeSync3,
9344
11049
  constants as fsConstants3,
9345
- lstatSync,
11050
+ lstatSync as lstatSync2,
9346
11051
  mkdirSync as mkdirSync3,
9347
11052
  openSync as openSync3,
9348
11053
  linkSync,
9349
- readFileSync as readFileSync6,
11054
+ readFileSync as readFileSync7,
9350
11055
  renameSync,
9351
11056
  statSync as statSync2,
9352
11057
  unlinkSync,
9353
11058
  utimesSync,
9354
- writeFileSync as writeFileSync2,
11059
+ writeFileSync as writeFileSync3,
9355
11060
  writeSync as writeSync2
9356
11061
  } from "node:fs";
9357
11062
  import { randomUUID } from "node:crypto";
9358
11063
  import { homedir as homedir2 } from "node:os";
9359
- import { dirname as dirname6, join as join7 } from "node:path";
11064
+ import { dirname as dirname6, join as join8 } from "node:path";
9360
11065
  var MAX_WEBHOOK_BODY_BYTES = 5 * 1024 * 1024;
9361
11066
  var WEBHOOK_FETCH_TIMEOUT_MS = 30000;
9362
11067
  var SAFE_PATH_SEGMENT2 = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
@@ -9437,7 +11142,7 @@ function acquireDrainLock(lockPath) {
9437
11142
  function renewDrainLock(lockPath, token) {
9438
11143
  let holder;
9439
11144
  try {
9440
- holder = readFileSync6(lockPath, "utf8").trim();
11145
+ holder = readFileSync7(lockPath, "utf8").trim();
9441
11146
  } catch (err) {
9442
11147
  if (!isEnoent(err))
9443
11148
  throw err;
@@ -9457,7 +11162,7 @@ function renewDrainLock(lockPath, token) {
9457
11162
  }
9458
11163
  function releaseDrainLock(lockPath, token) {
9459
11164
  try {
9460
- const holder = readFileSync6(lockPath, "utf8").trim();
11165
+ const holder = readFileSync7(lockPath, "utf8").trim();
9461
11166
  if (holder !== token)
9462
11167
  return;
9463
11168
  unlinkSync(lockPath);
@@ -9507,13 +11212,13 @@ function queueLines(buf) {
9507
11212
  return lines;
9508
11213
  }
9509
11214
  function removeQueueHead(path, cut) {
9510
- const remaining = readFileSync6(path);
9511
- writeFileSync2(path, remaining.subarray(Math.min(cut, remaining.byteLength)));
11215
+ const remaining = readFileSync7(path);
11216
+ writeFileSync3(path, remaining.subarray(Math.min(cut, remaining.byteLength)));
9512
11217
  }
9513
11218
  function queueBucketSize(path) {
9514
11219
  let lstat;
9515
11220
  try {
9516
- lstat = lstatSync(path);
11221
+ lstat = lstatSync2(path);
9517
11222
  } catch (err) {
9518
11223
  if (!isEnoent(err))
9519
11224
  throw err;
@@ -9528,7 +11233,7 @@ function queueBucketSize(path) {
9528
11233
  function readQueueFile(path) {
9529
11234
  if (queueBucketSize(path) === null)
9530
11235
  return null;
9531
- return readFileSync6(path);
11236
+ return readFileSync7(path);
9532
11237
  }
9533
11238
  function rejectLine(rejectedPath, reason, status, identity, raw) {
9534
11239
  const record = JSON.stringify({
@@ -9643,7 +11348,7 @@ async function drainRenamedAside(args, livePath, source) {
9643
11348
  async function drainOutboxToWebhook(outboxTask, webhookUrl, headers, fetchTimeoutMs = WEBHOOK_FETCH_TIMEOUT_MS) {
9644
11349
  const resolved = await resolveRepo();
9645
11350
  const repo = resolved && isSafeRepoSegment2(resolved.owner) && isSafeRepoSegment2(resolved.repo) ? resolved : null;
9646
- const outboxRoot = () => join7(GLOBAL_VINAYA_HOME, "outbox");
11351
+ const outboxRoot = () => join8(GLOBAL_VINAYA_HOME, "outbox");
9647
11352
  const path = outboxPathFor({ outboxRoot }, repo, outboxTask);
9648
11353
  const lockPath = `${path}.flush-lock`;
9649
11354
  const lockToken = acquireDrainLock(lockPath);
@@ -9680,6 +11385,7 @@ async function drainOutboxToWebhook(outboxTask, webhookUrl, headers, fetchTimeou
9680
11385
 
9681
11386
  // src/lib/log-sink.ts
9682
11387
  var OUTBOX_MAX_BYTES = 8 * 1024 * 1024;
11388
+ var LOG_FOLDER_ONLY_ENV = "VINAYA_LOG_FOLDER_ONLY";
9683
11389
  function describeFolderFallback(reason) {
9684
11390
  if (reason.kind === "anchor-unreadable") {
9685
11391
  return `not delivering to the configured log server ${reason.intendedUrl} — the default branch's ` + "vinaya.config.json could not be read to confirm it (the trust-anchor read via `gh` was offline, " + "unauthenticated, or slower than its deadline); events are written to the local folder and can be " + "delivered later with `vinaya log send`";
@@ -9719,6 +11425,9 @@ function logsCredentialMissing(headers, env) {
9719
11425
  return false;
9720
11426
  }
9721
11427
  function resolveLogDestinationFrom(input) {
11428
+ if (input.localConfig?.logs === false || input.unattended && input.trustAnchorConfig?.logs === false) {
11429
+ return { kind: "none", reason: "logs: false disables Log recording" };
11430
+ }
9722
11431
  const spoolDir = input.env.VINAYA_LOG_SPOOL_DIR;
9723
11432
  if (spoolDir !== undefined && spoolDir.trim() !== "") {
9724
11433
  return { kind: "folder", folder: spoolDir };
@@ -9738,6 +11447,10 @@ function resolveLogDestinationFrom(input) {
9738
11447
  } else {
9739
11448
  effective = local;
9740
11449
  }
11450
+ if (input.folderOnly || input.env[LOG_FOLDER_ONLY_ENV] === "1") {
11451
+ const folder = effective && "folder" in effective && !isInsideRepo(effective.folder, input.repoRoot) ? effective.folder : input.defaultFolder;
11452
+ return { kind: "folder", folder };
11453
+ }
9741
11454
  if (hostFromEnv(input.env) === "ci") {
9742
11455
  if (effective && "url" in effective) {
9743
11456
  if (logsCredentialMissing(effective.headers, input.env)) {
@@ -9762,41 +11475,73 @@ function resolveLogDestinationFrom(input) {
9762
11475
  const folder = effective && "folder" in effective ? effective.folder : input.defaultFolder;
9763
11476
  return fallbackReason ? { kind: "folder", folder, fallbackReason } : { kind: "folder", folder };
9764
11477
  }
9765
- var processTrustAnchorByRepo = new Map;
11478
+ var LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS = 30000;
11479
+ var LOG_DESTINATION_ANCHOR_MAX_RETRIES = 5;
11480
+ function createTrustAnchorCache(read, now = Date.now, bounds = {
11481
+ retryIntervalMs: LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS,
11482
+ maxRetries: LOG_DESTINATION_ANCHOR_MAX_RETRIES
11483
+ }) {
11484
+ const slots = new Map;
11485
+ const start = (repoRoot, retries) => {
11486
+ const slot = {
11487
+ reading: Promise.resolve().then(read).catch(() => null),
11488
+ retries,
11489
+ missedAt: null
11490
+ };
11491
+ slots.set(repoRoot, slot);
11492
+ slot.reading.then((config) => {
11493
+ if (config === null)
11494
+ slot.missedAt = now();
11495
+ });
11496
+ return slot.reading;
11497
+ };
11498
+ return {
11499
+ get: (repoRoot) => {
11500
+ const slot = slots.get(repoRoot);
11501
+ if (slot === undefined)
11502
+ return start(repoRoot, 0);
11503
+ if (slot.missedAt === null)
11504
+ return slot.reading;
11505
+ if (slot.retries >= bounds.maxRetries || now() - slot.missedAt < bounds.retryIntervalMs)
11506
+ return slot.reading;
11507
+ return start(repoRoot, slot.retries + 1);
11508
+ },
11509
+ clear: () => slots.clear()
11510
+ };
11511
+ }
11512
+ var processTrustAnchorByRepo = createTrustAnchorCache(safeLoadTrustAnchorConfig);
9766
11513
  function processTrustAnchor(repoRoot) {
9767
- const cached = processTrustAnchorByRepo.get(repoRoot);
9768
- if (cached !== undefined)
9769
- return cached;
9770
- const reading = safeLoadTrustAnchorConfig();
9771
- processTrustAnchorByRepo.set(repoRoot, reading);
9772
- return reading;
11514
+ return processTrustAnchorByRepo.get(repoRoot);
9773
11515
  }
9774
- async function defaultResolveLogDestination(repo, env) {
11516
+ async function defaultResolveLogDestination(repo, env, folderOnly = false) {
9775
11517
  const localConfig = loadConfig();
9776
11518
  const unattended = isUnattendedProcess(process.env);
9777
11519
  const repoRoot = repoRootSync();
9778
11520
  return resolveLogDestinationFrom({
9779
11521
  localConfig,
11522
+ folderOnly,
9780
11523
  trustAnchorConfig: unattended ? await processTrustAnchor(repoRoot) : null,
9781
11524
  unattended,
9782
11525
  env,
9783
- defaultFolder: join8(await runtimeDirForRepoAsync(repo), "logs"),
11526
+ defaultFolder: join9(await runtimeDirForRepoAsync(repo), "logs"),
9784
11527
  repoRoot
9785
11528
  });
9786
11529
  }
9787
11530
  function unresolvedLogDestination(env) {
11531
+ const loaded = loadConfig();
11532
+ if (loaded?.logs === false)
11533
+ return { kind: "none", reason: "logs: false disables Log recording" };
9788
11534
  if (hostFromEnv(env) === "ci") {
9789
11535
  return {
9790
11536
  kind: "none",
9791
11537
  reason: "the process ended before its log destination was resolved, and a CI job never records to a folder"
9792
11538
  };
9793
11539
  }
9794
- const loaded = loadConfig();
9795
- const localConfig = loaded?.logs?.url !== undefined ? { ...loaded, logs: undefined } : loaded;
11540
+ const localConfig = loaded?.logs && loaded.logs.url !== undefined ? { ...loaded, logs: undefined } : loaded;
9796
11541
  const unattended = isUnattendedProcess(process.env);
9797
11542
  const repoRoot = repoRootSync();
9798
11543
  const runtimeDir = process.env[RUNTIME_DIR_ENV_KEY] || resolveRuntimeDir({ repo: null, localConfig, trustAnchorConfig: null, unattended, repoRoot });
9799
- const defaultFolder = join8(runtimeDir, "logs");
11544
+ const defaultFolder = join9(runtimeDir, "logs");
9800
11545
  const resolved = resolveLogDestinationFrom({
9801
11546
  localConfig,
9802
11547
  trustAnchorConfig: null,
@@ -9809,7 +11554,7 @@ function unresolvedLogDestination(env) {
9809
11554
  }
9810
11555
  function folderFallbackStatePath(repo, stateRoot = GLOBAL_VINAYA_HOME) {
9811
11556
  const dirName = repo ? `${repo.owner}-${repo.repo}` : "unresolved";
9812
- return join8(stateRoot, "fallback", `${dirName}.json`);
11557
+ return join9(stateRoot, "fallback", `${dirName}.json`);
9813
11558
  }
9814
11559
  function recordFolderFallback(repo, issue, reason, now, runtimeDir, stateRoot = GLOBAL_VINAYA_HOME) {
9815
11560
  const message = describeFolderFallback(reason);
@@ -9825,25 +11570,25 @@ function recordFolderFallback(repo, issue, reason, now, runtimeDir, stateRoot =
9825
11570
  };
9826
11571
  const path = folderFallbackStatePath(repo, stateRoot);
9827
11572
  mkdirSync4(dirname7(path), { recursive: true, mode: 448 });
9828
- writeFileSync3(path, `${JSON.stringify(record)}
11573
+ writeFileSync4(path, `${JSON.stringify(record)}
9829
11574
  `, { mode: 384 });
9830
11575
  } catch {}
9831
11576
  }
9832
11577
  function isEnoent2(err) {
9833
11578
  return typeof err === "object" && err !== null && err.code === "ENOENT";
9834
11579
  }
9835
- var execFileAsync5 = promisify5(execFile5);
11580
+ var execFileAsync6 = promisify6(execFile6);
9836
11581
  async function resolveDoctrine(cwd, vinayaVersion) {
9837
11582
  let toplevel;
9838
11583
  try {
9839
- toplevel = (await execFileAsync5("git", ["-C", cwd, "rev-parse", "--show-toplevel"], { encoding: "utf8" })).stdout.trim();
11584
+ toplevel = (await execFileAsync6("git", ["-C", cwd, "rev-parse", "--show-toplevel"], { encoding: "utf8" })).stdout.trim();
9840
11585
  } catch (err) {
9841
11586
  return isEnoent2(err) ? "unknown" : vinayaVersion;
9842
11587
  }
9843
- if (!existsSync7(join8(toplevel, "aeg-root", "roles")))
11588
+ if (!existsSync8(join9(toplevel, "aeg-root", "roles")))
9844
11589
  return vinayaVersion;
9845
11590
  try {
9846
- const sha = (await execFileAsync5("git", ["-C", toplevel, "rev-parse", "HEAD:aeg-root"], { encoding: "utf8" })).stdout.trim();
11591
+ const sha = (await execFileAsync6("git", ["-C", toplevel, "rev-parse", "HEAD:aeg-root"], { encoding: "utf8" })).stdout.trim();
9847
11592
  return `aeg-root@${sha}`;
9848
11593
  } catch {
9849
11594
  return vinayaVersion;
@@ -9866,7 +11611,7 @@ var TRANCHE_ISSUE_LIST_LIMIT = 200;
9866
11611
  async function issueForTrancheTask(tranche, taskId, cwd, repo) {
9867
11612
  let stdout;
9868
11613
  try {
9869
- ({ stdout } = await execFileAsync5("gh", [
11614
+ ({ stdout } = await execFileAsync6("gh", [
9870
11615
  "issue",
9871
11616
  "list",
9872
11617
  "--state",
@@ -9904,7 +11649,7 @@ async function issueForTrancheTask(tranche, taskId, cwd, repo) {
9904
11649
  async function confirmBacklogIssue(issue, cwd, repo) {
9905
11650
  let stdout;
9906
11651
  try {
9907
- ({ stdout } = await execFileAsync5("gh", ["issue", "view", String(issue), "--json", "number", ...repo === null ? [] : ["--repo", repo]], {
11652
+ ({ stdout } = await execFileAsync6("gh", ["issue", "view", String(issue), "--json", "number", ...repo === null ? [] : ["--repo", repo]], {
9908
11653
  cwd,
9909
11654
  encoding: "utf8",
9910
11655
  timeout: LOG_CONTEXT_LOOKUP_DEADLINE_MS,
@@ -9923,7 +11668,7 @@ async function confirmBacklogIssue(issue, cwd, repo) {
9923
11668
  async function resolveBranchIssue(cwd, env = process.env, repo = null) {
9924
11669
  let branch;
9925
11670
  try {
9926
- branch = (await execFileAsync5("git", ["-C", cwd, "rev-parse", "--abbrev-ref", "HEAD"], {
11671
+ branch = (await execFileAsync6("git", ["-C", cwd, "rev-parse", "--abbrev-ref", "HEAD"], {
9927
11672
  encoding: "utf8",
9928
11673
  timeout: LOG_CONTEXT_LOOKUP_DEADLINE_MS,
9929
11674
  killSignal: "SIGKILL"
@@ -9941,7 +11686,7 @@ async function resolveBranchIssue(cwd, env = process.env, repo = null) {
9941
11686
  }
9942
11687
  function readVinayaVersion() {
9943
11688
  try {
9944
- const pkg = JSON.parse(readFileSync7(join8(packageRoot(import.meta.url), "package.json"), "utf8"));
11689
+ const pkg = JSON.parse(readFileSync8(join9(packageRoot(import.meta.url), "package.json"), "utf8"));
9945
11690
  return pkg.version ?? "unknown";
9946
11691
  } catch {
9947
11692
  return "unknown";
@@ -9959,7 +11704,7 @@ function safeRepoSlug(repo) {
9959
11704
  function outboxPathFor(deps, repo, issue) {
9960
11705
  const dirName = repo ? `${repo.owner}-${repo.repo}` : "unresolved";
9961
11706
  const fileName = `${issue ?? "none"}.ndjson`;
9962
- return join8(deps.outboxRoot(), dirName, fileName);
11707
+ return join9(deps.outboxRoot(), dirName, fileName);
9963
11708
  }
9964
11709
  function hostFromEnv(env) {
9965
11710
  if (env.GITHUB_ACTIONS)
@@ -10006,7 +11751,7 @@ function headShaRead(key, read, shared) {
10006
11751
  }
10007
11752
  async function resolveHeadSha(cwd) {
10008
11753
  try {
10009
- const out = (await execFileAsync5("git", ["-C", cwd, "rev-parse", "HEAD"], { encoding: "utf8" })).stdout.trim();
11754
+ const out = (await execFileAsync6("git", ["-C", cwd, "rev-parse", "HEAD"], { encoding: "utf8" })).stdout.trim();
10010
11755
  return /^[0-9a-f]{40}$/.test(out) ? out : null;
10011
11756
  } catch {
10012
11757
  return null;
@@ -10014,7 +11759,8 @@ async function resolveHeadSha(cwd) {
10014
11759
  }
10015
11760
  function defaultDeps() {
10016
11761
  return {
10017
- outboxRoot: () => join8(GLOBAL_VINAYA_HOME, "outbox"),
11762
+ readConfig: loadConfig,
11763
+ outboxRoot: () => join9(GLOBAL_VINAYA_HOME, "outbox"),
10018
11764
  home: () => homedir3(),
10019
11765
  hostname: () => osHostname(),
10020
11766
  cwd: () => process.cwd(),
@@ -10059,7 +11805,7 @@ function appendHardenedLine(path, line) {
10059
11805
  function reportRotationOverflow(backupPath, warn) {
10060
11806
  let raw;
10061
11807
  try {
10062
- raw = readFileSync7(backupPath, "utf8");
11808
+ raw = readFileSync8(backupPath, "utf8");
10063
11809
  } catch {
10064
11810
  return;
10065
11811
  }
@@ -10197,23 +11943,59 @@ function createLogSink(overrides = {}) {
10197
11943
  };
10198
11944
  let contextCache;
10199
11945
  let settledContext;
11946
+ let contextEnv = {};
11947
+ const resolveDestination = async (repo, env) => deps.readConfig()?.logs === false ? { kind: "none", reason: "logs: false disables Log recording" } : await deps.resolveLogDestination(repo, env, deps.folderOnly);
10200
11948
  const context = () => {
10201
11949
  if (contextCache === undefined) {
10202
11950
  const env = deps.env();
11951
+ contextEnv = env;
10203
11952
  contextCache = Promise.all([
10204
11953
  withDeadline(resolveRepoOnce(), LOG_CONTEXT_LOOKUP_DEADLINE_MS, null),
10205
11954
  doctrine()
10206
11955
  ]).then(async ([resolved, doctrineValue]) => {
10207
11956
  const repo = resolved && isSafeRepoSegment3(resolved.owner) && isSafeRepoSegment3(resolved.repo) ? resolved : null;
10208
- settledContext = { repo, doctrine: doctrineValue, destination: await deps.resolveLogDestination(repo, env) };
11957
+ settledContext = { repo, doctrine: doctrineValue, destination: await resolveDestination(repo, env) };
11958
+ destinationRetryDueAt = deps.now().getTime() + LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS;
10209
11959
  return settledContext;
10210
11960
  });
10211
11961
  }
10212
11962
  return contextCache;
10213
11963
  };
11964
+ let destinationRetries = 0;
11965
+ let destinationRetryDueAt = 0;
11966
+ let destinationRetryInFlight = false;
11967
+ const retryDestinationIfDue = (ctx) => {
11968
+ if (ctx.destination.kind !== "folder" || ctx.destination.fallbackReason?.kind !== "anchor-unreadable")
11969
+ return;
11970
+ if (destinationRetryInFlight || destinationRetries >= LOG_DESTINATION_ANCHOR_MAX_RETRIES)
11971
+ return;
11972
+ if (deps.now().getTime() < destinationRetryDueAt)
11973
+ return;
11974
+ destinationRetryInFlight = true;
11975
+ destinationRetries++;
11976
+ const generation = contextCache;
11977
+ Promise.resolve().then(() => resolveDestination(ctx.repo, contextEnv)).then((destination) => {
11978
+ if (contextCache !== generation)
11979
+ return;
11980
+ if (destination.kind === "server") {
11981
+ settledContext = { ...ctx, destination };
11982
+ contextCache = Promise.resolve(settledContext);
11983
+ return;
11984
+ }
11985
+ if (destination.kind !== "folder" || destination.fallbackReason?.kind !== "anchor-unreadable") {
11986
+ destinationRetries = LOG_DESTINATION_ANCHOR_MAX_RETRIES;
11987
+ }
11988
+ }, () => {
11989
+ return;
11990
+ }).finally(() => {
11991
+ destinationRetryInFlight = false;
11992
+ destinationRetryDueAt = deps.now().getTime() + LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS;
11993
+ });
11994
+ };
10214
11995
  const resetContext = () => {
10215
11996
  contextCache = undefined;
10216
11997
  settledContext = undefined;
11998
+ destinationRetries = 0;
10217
11999
  };
10218
12000
  let drainChain = Promise.resolve();
10219
12001
  const pendingWrites = new Set;
@@ -10226,24 +12008,30 @@ function createLogSink(overrides = {}) {
10226
12008
  `);
10227
12009
  });
10228
12010
  };
10229
- const snapshot = () => {
12011
+ const snapshot = (attribution) => {
10230
12012
  const env = deps.env();
10231
12013
  return {
12014
+ attributed: attribution !== undefined,
10232
12015
  host: hostFromEnv(env),
10233
12016
  now: deps.now(),
10234
12017
  seq: seq++,
10235
12018
  envFields: {
10236
- role: env.VINAYA_ROLE,
12019
+ role: attribution?.role ?? env.VINAYA_ROLE,
10237
12020
  task: env.VINAYA_TASK,
10238
- round: env.VINAYA_ROUND,
12021
+ round: attribution ? String(attribution.round) : env.VINAYA_ROUND,
10239
12022
  pr: env.VINAYA_PR,
10240
12023
  run: env.VINAYA_RUN || runId,
10241
- attempt: env.VINAYA_ATTEMPT,
12024
+ attempt: attribution ? String(attribution.attempt) : env.VINAYA_ATTEMPT,
10242
12025
  parent: env.VINAYA_PARENT_EVENT,
10243
12026
  workRef: env.VINAYA_WORK_REF,
10244
12027
  flow: env.VINAYA_FLOW,
10245
12028
  flowVersion: env.VINAYA_FLOW_VERSION,
10246
12029
  runtime: env.VINAYA_RUNTIME,
12030
+ processId: env.VINAYA_PROCESS_ID,
12031
+ processVersion: env.VINAYA_PROCESS_VERSION,
12032
+ processDigest: env.VINAYA_PROCESS_DIGEST,
12033
+ runnerId: env.VINAYA_RUNNER_ID,
12034
+ runnerVersion: env.VINAYA_RUNNER_VERSION,
10247
12035
  source: env.VINAYA_SOURCE
10248
12036
  }
10249
12037
  };
@@ -10272,12 +12060,14 @@ function createLogSink(overrides = {}) {
10272
12060
  branchIssue,
10273
12061
  eventId: randomUUID2(),
10274
12062
  processId,
12063
+ revision: headSha,
12064
+ provenance: call.attributed ? "parent_attributed" : deps.provenance,
10275
12065
  inputVersions: deps.inputVersions()
10276
12066
  });
10277
12067
  const header = headSha === null ? built : { ...built, subject: { ...built.subject, sha: headSha } };
10278
12068
  if (destination.kind === "folder" && destination.fallbackReason && !folderFallbackRecorded) {
10279
12069
  folderFallbackRecorded = true;
10280
- recordFolderFallback(repo, header.subject.issue, destination.fallbackReason, call.now, dirname7(destination.folder), join8(deps.home(), ".vinaya"));
12070
+ recordFolderFallback(repo, header.subject.issue, destination.fallbackReason, call.now, dirname7(destination.folder), join9(deps.home(), ".vinaya"));
10281
12071
  }
10282
12072
  const full = { ...e, ...header };
10283
12073
  const parsed = LogEventSchema.safeParse(full);
@@ -10296,11 +12086,14 @@ function createLogSink(overrides = {}) {
10296
12086
  appendLine(outboxPathFor({ outboxRoot: () => destination.folder }, repo, header.subject.issue), line, warnOnce);
10297
12087
  }
10298
12088
  };
10299
- function log(e) {
12089
+ function log(e, attribution) {
10300
12090
  try {
10301
- const call = snapshot();
12091
+ const call = snapshot(attribution);
10302
12092
  const write = async () => {
10303
12093
  const ctx = await context();
12094
+ try {
12095
+ retryDestinationIfDue(ctx);
12096
+ } catch {}
10304
12097
  if (ctx.destination.kind === "none") {
10305
12098
  writeEvent(e, call, ctx, null, null, true);
10306
12099
  return;
@@ -10324,9 +12117,13 @@ function createLogSink(overrides = {}) {
10324
12117
  function logSync(e, opts = {}) {
10325
12118
  try {
10326
12119
  const call = snapshot();
10327
- let ctx = settledContext;
12120
+ let ctx = deps.readConfig()?.logs === false ? {
12121
+ repo: null,
12122
+ doctrine: "unknown",
12123
+ destination: { kind: "none", reason: "logs: false disables Log recording" }
12124
+ } : settledContext;
10328
12125
  if (ctx === undefined) {
10329
- const destination = deps.unresolvedLogDestination(deps.env());
12126
+ const destination = deps.readConfig()?.logs === false ? { kind: "none", reason: "logs: false disables Log recording" } : deps.unresolvedLogDestination(deps.env());
10330
12127
  if (destination.kind === "folder" && !opts.quiet) {
10331
12128
  warnOnce(`vinaya: the process ended before its log destination was resolved — the event is written to ${destination.folder}; \`vinaya log send\` delivers it to a configured server later
10332
12129
  `);
@@ -10402,17 +12199,37 @@ function parseChangedLineRanges(diffOutput) {
10402
12199
 
10403
12200
  // src/lib/diff-evidence.ts
10404
12201
  function fileDiffAgainst(ref, path) {
10405
- let out;
12202
+ let committed;
10406
12203
  try {
10407
- out = execFileSync8("git", ["diff", `${ref}...HEAD`, "--", path], {
12204
+ committed = execFileSync8("git", ["diff", `${ref}...HEAD`, "--", path], {
10408
12205
  encoding: "utf8",
10409
12206
  stdio: ["ignore", "pipe", "pipe"]
10410
12207
  }).trim();
10411
12208
  } catch {
10412
12209
  return null;
10413
12210
  }
12211
+ const staged = stagedDiff(["--", path]);
12212
+ if (staged === null)
12213
+ return null;
12214
+ const out = [committed, staged].filter(Boolean).join(`
12215
+ `);
10414
12216
  return out === "" ? null : out;
10415
12217
  }
12218
+ function readsStagedDiff() {
12219
+ return process.env.VINAYA_COMMIT_HOOK === "1" && Boolean(process.env.GIT_INDEX_FILE);
12220
+ }
12221
+ function stagedDiff(args) {
12222
+ if (!readsStagedDiff())
12223
+ return "";
12224
+ try {
12225
+ return execFileSync8("git", ["diff", "--cached", ...args], {
12226
+ encoding: "utf8",
12227
+ stdio: ["ignore", "pipe", "pipe"]
12228
+ }).trim();
12229
+ } catch {
12230
+ return null;
12231
+ }
12232
+ }
10416
12233
  function revParse(ref) {
10417
12234
  try {
10418
12235
  return execFileSync8("git", ["rev-parse", "--verify", ref], {
@@ -10446,6 +12263,13 @@ function changedFiles(base) {
10446
12263
  return out === "" ? [] : out.split(`
10447
12264
  `).map((s) => s.trim()).filter(Boolean);
10448
12265
  }
12266
+ function stagedChangedFiles() {
12267
+ const out = stagedDiff(["--name-only"]);
12268
+ if (out === null)
12269
+ return null;
12270
+ return out === "" ? [] : out.split(`
12271
+ `).map((s) => s.trim()).filter(Boolean);
12272
+ }
10449
12273
  function resolveChangedFiles(base = process.env.BASE_SHA || "origin/main") {
10450
12274
  return resolveDiff(base)?.files ?? null;
10451
12275
  }
@@ -10461,7 +12285,30 @@ function resolveDiff(base = process.env.BASE_SHA || "origin/main") {
10461
12285
  const relPaths = changedFiles(ref);
10462
12286
  if (relPaths === null)
10463
12287
  continue;
10464
- return { base: ref, root, files: relPaths.map((p) => join9(root, p)) };
12288
+ const stagedPaths = stagedChangedFiles();
12289
+ if (stagedPaths === null)
12290
+ return null;
12291
+ const paths = [...new Set([...relPaths, ...stagedPaths])];
12292
+ return { base: ref, root, files: paths.map((p) => join10(root, p)) };
12293
+ }
12294
+ return null;
12295
+ }
12296
+ function resolveAddedFiles(base = process.env.BASE_SHA || "origin/main") {
12297
+ if (repoRoot() === null)
12298
+ return null;
12299
+ const head = revParse("HEAD");
12300
+ for (const ref of new Set([base, "origin/main", "main"])) {
12301
+ const resolved = revParse(ref);
12302
+ if (resolved === null || resolved === head)
12303
+ continue;
12304
+ try {
12305
+ const out = execFileSync8("git", ["diff", "--name-only", "--diff-filter=A", `${ref}...HEAD`], {
12306
+ encoding: "utf8",
12307
+ stdio: ["ignore", "pipe", "pipe"]
12308
+ }).trim();
12309
+ return out === "" ? [] : out.split(`
12310
+ `).map((p) => p.trim()).filter(Boolean);
12311
+ } catch {}
10465
12312
  }
10466
12313
  return null;
10467
12314
  }
@@ -10511,7 +12358,7 @@ function indexMode(path) {
10511
12358
  }
10512
12359
  function hasShebang(path) {
10513
12360
  try {
10514
- return readFileSync8(path, "utf8").startsWith("#!");
12361
+ return readFileSync9(path, "utf8").startsWith("#!");
10515
12362
  } catch {
10516
12363
  return false;
10517
12364
  }