@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
@@ -1,132 +1,4 @@
1
1
  #!/usr/bin/env node
2
-
3
- // src/lib/changed-names.ts
4
- var ALL_NAMES = "all";
5
- var PARSEABLE = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
6
- function namesForRanges(ts, fileName, source, ranges) {
7
- if (ranges.length === 0)
8
- return new Set;
9
- const sourceFile = ts.createSourceFile(fileName, source, ts.ScriptTarget.ES2022, true);
10
- const lineOf = (pos) => sourceFile.getLineAndCharacterOfPosition(pos).line + 1;
11
- const declarations = [];
12
- const declarationStart = (statement) => {
13
- const comments = ts.getLeadingCommentRanges(source, statement.getFullStart());
14
- return comments && comments.length > 0 ? comments[0].pos : statement.getStart(sourceFile);
15
- };
16
- for (const statement of sourceFile.statements) {
17
- const span = { start: lineOf(declarationStart(statement)), end: lineOf(statement.getEnd()) };
18
- if (ts.isVariableStatement(statement)) {
19
- for (const declaration of statement.declarationList.declarations) {
20
- declarations.push({
21
- name: ts.isIdentifier(declaration.name) ? declaration.name.text : null,
22
- ...span,
23
- node: statement
24
- });
25
- }
26
- continue;
27
- }
28
- const named = ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement) || ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) || ts.isEnumDeclaration(statement) || ts.isModuleDeclaration(statement);
29
- const name = named && statement.name && ts.isIdentifier(statement.name) ? statement.name.text : null;
30
- declarations.push({ name, ...span, node: statement });
31
- }
32
- const topLevelNames = new Set(declarations.map((d) => d.name).filter((n) => n !== null));
33
- const seeded = new Set;
34
- for (const range of ranges) {
35
- if (range.end < range.start)
36
- continue;
37
- const overlapping = declarations.filter((d) => d.start <= range.end && range.start <= d.end);
38
- if (overlapping.length === 0)
39
- return null;
40
- for (const d of overlapping) {
41
- if (d.name === null)
42
- return null;
43
- seeded.add(d.name);
44
- }
45
- }
46
- const references = new Map;
47
- for (const d of declarations) {
48
- if (d.name === null)
49
- continue;
50
- const used = references.get(d.name) ?? new Set;
51
- const visit = (node) => {
52
- if (ts.isIdentifier(node) && node.text !== d.name && topLevelNames.has(node.text))
53
- used.add(node.text);
54
- ts.forEachChild(node, visit);
55
- };
56
- ts.forEachChild(d.node, visit);
57
- references.set(d.name, used);
58
- }
59
- const affected = new Set(seeded);
60
- for (let grew = true;grew; ) {
61
- grew = false;
62
- for (const [name, used] of references) {
63
- if (affected.has(name))
64
- continue;
65
- for (const u of used) {
66
- if (!affected.has(u))
67
- continue;
68
- affected.add(name);
69
- grew = true;
70
- break;
71
- }
72
- }
73
- }
74
- return affected;
75
- }
76
- function affectedNamesForFile(ts, diff) {
77
- if (!PARSEABLE.some((ext) => diff.file.endsWith(ext)))
78
- return ALL_NAMES;
79
- const names = new Set;
80
- for (const [source, ranges] of [
81
- [diff.after, diff.afterRanges],
82
- [diff.before, diff.beforeRanges]
83
- ]) {
84
- if (source === null) {
85
- if (ranges.some((r) => r.end >= r.start))
86
- return ALL_NAMES;
87
- continue;
88
- }
89
- let attributed;
90
- try {
91
- attributed = namesForRanges(ts, diff.file, source, ranges);
92
- } catch {
93
- attributed = null;
94
- }
95
- if (attributed === null)
96
- return ALL_NAMES;
97
- for (const n of attributed)
98
- names.add(n);
99
- }
100
- return names;
101
- }
102
- function affectedNames(ts, diffs) {
103
- const out = new Map;
104
- for (const diff of diffs)
105
- out.set(diff.file, affectedNamesForFile(ts, diff));
106
- return out;
107
- }
108
- function parseHunkRanges(patch) {
109
- const beforeRanges = [];
110
- const afterRanges = [];
111
- const header = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/gm;
112
- for (let m = header.exec(patch);m !== null; m = header.exec(patch)) {
113
- const oldStart = Number(m[1]);
114
- const oldCount = m[2] === undefined ? 1 : Number(m[2]);
115
- const newStart = Number(m[3]);
116
- const newCount = m[4] === undefined ? 1 : Number(m[4]);
117
- beforeRanges.push({ start: oldStart, end: oldStart + oldCount - 1 });
118
- afterRanges.push({ start: newStart, end: newStart + newCount - 1 });
119
- }
120
- return { beforeRanges, afterRanges };
121
- }
122
-
123
- // src/lib/config.ts
124
- import { execFile as execFile4, execFileSync as execFileSync2 } from "node:child_process";
125
- import { promisify as promisify4 } from "node:util";
126
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync3, realpathSync, writeFileSync } from "node:fs";
127
- import { homedir } from "node:os";
128
- import { dirname as dirname2, isAbsolute, join as join2, resolve as resolve2 } from "node:path";
129
- import { z as z5 } from "zod";
130
2
  // ../../packages/aeg-forge-state/src/gh.ts
131
3
  import { execFile, execFileSync } from "node:child_process";
132
4
  import { promisify } from "node:util";
@@ -571,8 +443,372 @@ var NON_PATH_TOP_SEGMENTS = new Set(["origin", "refs", "HEAD", "vinaya", "fix"])
571
443
 
572
444
  // ../../packages/aeg-core/src/doctrine-no-procedures.ts
573
445
  var SHELL_LANGS = new Set(["", "sh", "bash", "shell", "console"]);
446
+ // ../../packages/aeg-core/src/prose-rules.ts
447
+ var RETIRED_GLOBAL_EXEMPTIONS = [
448
+ "docs/decisions-legacy.md",
449
+ "apps/herald-ai/docs/",
450
+ "apps/vada-ai/docs/",
451
+ "aeg-root/tranches/completed/",
452
+ "packages/aeg-core/src/docs/published-prose",
453
+ "packages/aeg-core/src/retired-vocabulary.test.ts",
454
+ "packages/aeg-core/src/retired-vocabulary.ts",
455
+ "/fixtures/",
456
+ "/node_modules/",
457
+ "/.next/",
458
+ "/.turbo/"
459
+ ];
460
+ var PLAN_ON_DISK_PATTERNS = ["[Tt]opology files?", "aeg-root/tranches/", "aeg-project/"];
461
+ var TRANCHE_MODEL_FILE = "/tranche-model.md";
462
+ var RETIRED_PATTERN_EXEMPTIONS = {
463
+ [String.raw`\bD-[0-9]{3}\b`]: ["./CLAUDE.md"],
464
+ [String.raw`(^|[^-_a-zA-Z0-9])decisions\.md`]: [
465
+ "docs-index.md",
466
+ "apps/vada-ai/specs/legacy/README.md",
467
+ "apps/vada-ai/specs/vada-product-spec.md",
468
+ "apps/vada-ai/web/CLAUDE.md",
469
+ "apps/vada-ai/CLAUDE.md"
470
+ ],
471
+ "decisions-legacy": [
472
+ "packages/aeg-core/src/file-classify.ts",
473
+ "packages/aeg-core/src/file-classify.test.ts",
474
+ "packages/aeg-core/src/pr-tier.test.ts",
475
+ "docs-index.md",
476
+ ".claude/skills/database/SKILL.md",
477
+ ".claude/skills/vada-architecture/SKILL.md",
478
+ "apps/vada-ai/specs/vada-byok-principles.md",
479
+ "apps/vada-ai/web/CLAUDE.md",
480
+ "apps/vada-ai/CLAUDE.md"
481
+ ],
482
+ CONTRADICTION: ["apps/vada-ai/specs/vada-reviewers-spec.md"],
483
+ ...Object.fromEntries(PLAN_ON_DISK_PATTERNS.map((pattern) => [pattern, [TRANCHE_MODEL_FILE]]))
484
+ };
485
+ var retiredPatterns = [
486
+ String.raw`\bD-[0-9]{3}\b`,
487
+ "D-(###|NNN|nnn|xxx)",
488
+ "decision (entry|logged)",
489
+ "decision-log entry",
490
+ "decision log entry",
491
+ "decision log(s|ged|ging)?([^a-z]|$)",
492
+ "decision-log",
493
+ "decision entr",
494
+ "decisions? (are |is )?logged",
495
+ "log entries",
496
+ String.raw`(^|[^-_a-zA-Z0-9])decisions\.md`,
497
+ "decisions-legacy",
498
+ "CONTRADICTION",
499
+ "assumes Tier 3",
500
+ "Lock: ?YES",
501
+ "Lock: ?NO",
502
+ "lock approvals?",
503
+ "approves locks",
504
+ "Conforms to lock",
505
+ "Challenges lock",
506
+ "checkDecisionNumbersFresh",
507
+ String.raw`roles/team-leader\.md`,
508
+ String.raw`\(,`,
509
+ String.raw`,\)`,
510
+ String.raw`\(\.\)`,
511
+ ...PLAN_ON_DISK_PATTERNS
512
+ ];
513
+ var published = [
514
+ ["decision-id", "a decision id", /\bD-\d{3,}\b/],
515
+ ["section-ref", "a section reference", /§/],
516
+ ["forge-number", "a forge number", /#\d+/],
517
+ ["retired-name", "the retired public name", /\bAEG\b/],
518
+ ["tranche-slug", "a tranche slug", /\b[a-z][a-z0-9]*(?:-[a-z0-9]+)+-v\d+\b/],
519
+ [
520
+ "label-vocabulary",
521
+ "forge label vocabulary",
522
+ /(?:vinaya\/)?\b(?:tranche|iteration|tier|needs|waiver|project|aeg):(?![/\s]|$)/
523
+ ],
524
+ ["internal-path", "a repo-internal path", /\b(?:packages|apps|aeg-root|tools|scripts)\//],
525
+ ["internal-path", "a repo-internal path", /\.(?:claude|husky|github)\//],
526
+ [
527
+ "internal-path",
528
+ "a repo-internal file",
529
+ /(?:^|[\s(`"'[])[\w.-]+(?:\/[\w.-]+)*\.(?:ts|tsx|js|jsx|mjs|cjs|sh|ya?ml|json|md)\b/
530
+ ]
531
+ ];
532
+ var DEFAULT_PROSE_RULES = [
533
+ {
534
+ id: "forge-number",
535
+ group: "reader-resolvable",
536
+ scopes: ["ships", "reader-facing", "spec"],
537
+ patterns: { prose: /#[0-9]{2,4}/g },
538
+ flags: ["global"],
539
+ message: "a forge number",
540
+ severity: { ships: "warning", "reader-facing": "warning", spec: "error" },
541
+ exemptions: []
542
+ },
543
+ {
544
+ id: "tranche-slug",
545
+ group: "reader-resolvable",
546
+ scopes: ["ships", "reader-facing", "product", "spec"],
547
+ patterns: { prose: /[a-z][a-z-]+-v[0-9]/g },
548
+ flags: ["global"],
549
+ message: "an internal tranche slug",
550
+ severity: { ships: "warning", "reader-facing": "warning", product: "error", spec: "error" },
551
+ exemptions: []
552
+ },
553
+ {
554
+ id: "task-number",
555
+ group: "reader-resolvable",
556
+ scopes: ["spec"],
557
+ patterns: { prose: /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi },
558
+ flags: ["global", "ignore-case"],
559
+ message: "a task number",
560
+ severity: { spec: "error" },
561
+ exemptions: []
562
+ },
563
+ {
564
+ id: "source-comment-tranche-slug",
565
+ group: "reader-resolvable",
566
+ scopes: ["source-comment"],
567
+ patterns: { comment: /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g },
568
+ flags: ["global"],
569
+ message: "a tranche-slug citation",
570
+ severity: { "source-comment": "warning" },
571
+ exemptions: []
572
+ },
573
+ {
574
+ id: "source-comment-forge-number",
575
+ group: "reader-resolvable",
576
+ scopes: ["source-comment"],
577
+ patterns: { comment: /#[0-9]{2,}/g },
578
+ flags: ["global"],
579
+ message: "a forge-number citation",
580
+ severity: { "source-comment": "warning" },
581
+ exemptions: []
582
+ },
583
+ {
584
+ id: "legacy-batch-name",
585
+ group: "reader-resolvable",
586
+ scopes: ["ships", "reader-facing", "spec"],
587
+ patterns: {},
588
+ flags: ["built-in"],
589
+ message: "an internal tranche slug",
590
+ severity: { ships: "warning", "reader-facing": "warning", spec: "error" },
591
+ exemptions: [],
592
+ builtIn: true
593
+ },
594
+ {
595
+ id: "coined-term",
596
+ group: "reader-resolvable",
597
+ scopes: ["ships", "reader-facing"],
598
+ patterns: {},
599
+ flags: ["built-in"],
600
+ message: "uses coined term without defining it inline or linking the glossary",
601
+ severity: { ships: "warning", "reader-facing": "warning" },
602
+ exemptions: [],
603
+ builtIn: true
604
+ },
605
+ ...retiredPatterns.map((pattern, index) => ({
606
+ id: `retired-vocabulary-${index + 1}`,
607
+ group: "retired-vocabulary",
608
+ scopes: ["repository"],
609
+ patterns: { repository: pattern },
610
+ flags: [],
611
+ message: "retired vocabulary",
612
+ severity: { repository: "error" },
613
+ exemptions: RETIRED_GLOBAL_EXEMPTIONS,
614
+ patternExemptions: RETIRED_PATTERN_EXEMPTIONS
615
+ })),
616
+ ...published.map(([id, message, pattern]) => ({
617
+ id,
618
+ group: "published-prose",
619
+ scopes: ["published"],
620
+ patterns: { published: pattern },
621
+ flags: [],
622
+ message,
623
+ severity: { published: "error" },
624
+ exemptions: [".worktrees/task/<tranche>/<n>", "task/<tranche>/<n>", ".worktrees/"]
625
+ }))
626
+ ];
627
+ var rulesForGroup = (group) => DEFAULT_PROSE_RULES.filter((rule) => rule.group === group);
628
+ var RESOLVABLE_SCOPES = ["ships", "reader-facing", "product", "spec", "source-comment"];
629
+ var RETIRED_SCOPES = ["repository"];
630
+ var CONFIGURABLE_PROSE_SCOPES = [...RESOLVABLE_SCOPES, ...RETIRED_SCOPES];
631
+ function groupOfScope(scope) {
632
+ if (RESOLVABLE_SCOPES.includes(scope))
633
+ return "reader-resolvable";
634
+ if (RETIRED_SCOPES.includes(scope))
635
+ return "retired-vocabulary";
636
+ return;
637
+ }
638
+ var CONFIGURED_PROSE_FLAGS = ["i", "u"];
639
+ var CONFIGURED_PATTERN_MAX_LENGTH = 200;
640
+ var CONFIGURABLE_DEFAULT_RULES = DEFAULT_PROSE_RULES.filter((rule) => rule.group !== "published-prose");
641
+ function allowedScopesFor(rule) {
642
+ if (rule.builtIn)
643
+ return rule.scopes;
644
+ return rule.group === "retired-vocabulary" ? RETIRED_SCOPES : RESOLVABLE_SCOPES;
645
+ }
646
+ function normalizeRepoPath(entry) {
647
+ let out = entry.replace(/\\/g, "/");
648
+ while (out.startsWith("./"))
649
+ out = out.slice(2);
650
+ out = out.replace(/\/{2,}/g, "/");
651
+ while (out.endsWith("/"))
652
+ out = out.slice(0, -1);
653
+ return out;
654
+ }
655
+ var RESOLVABLE_RUN_ORDER = [
656
+ "forge-number",
657
+ "tranche-slug",
658
+ "legacy-batch-name",
659
+ "task-number",
660
+ "source-comment-tranche-slug",
661
+ "source-comment-forge-number",
662
+ "coined-term"
663
+ ];
664
+ var REPORT_GROUPS = { "task-number": 2, "legacy-batch-name": 2 };
665
+ function scopeDefaultSeverity(scope, sourceCommentSeverity) {
666
+ if (scope === "source-comment")
667
+ return sourceCommentSeverity ?? "warning";
668
+ if (scope === "repository")
669
+ return "error";
670
+ return "warning";
671
+ }
672
+ function applySeverity(scopes, base, setting) {
673
+ const out = {};
674
+ for (const scope of scopes) {
675
+ const configured = typeof setting === "string" ? setting : setting?.[scope];
676
+ const value = configured ?? base[scope];
677
+ if (value !== undefined)
678
+ out[scope] = value;
679
+ }
680
+ return out;
681
+ }
682
+ function defaultPatternFor(rule) {
683
+ const cache = new Map;
684
+ return (scope) => {
685
+ if (cache.has(scope))
686
+ return cache.get(scope) ?? null;
687
+ const own = rule.patterns[scope] ?? (scope === "source-comment" ? rule.patterns.comment : rule.patterns.prose) ?? Object.values(rule.patterns)[0];
688
+ const compiled = own === undefined ? null : own instanceof RegExp ? own : new RegExp(own);
689
+ cache.set(scope, compiled);
690
+ return compiled;
691
+ };
692
+ }
693
+ function customPatternFor(rule, global) {
694
+ const cache = new Map;
695
+ return (scope) => {
696
+ if (cache.has(scope))
697
+ return cache.get(scope) ?? null;
698
+ const source = rule.patterns?.[scope] ?? rule.pattern;
699
+ const compiled = source === undefined ? null : new RegExp(source, `${rule.flags ?? ""}${global ? "g" : ""}`);
700
+ cache.set(scope, compiled);
701
+ return compiled;
702
+ };
703
+ }
704
+ function resolveProseRules(config = undefined, options = {}) {
705
+ const rules = [];
706
+ const defaults = config?.defaults ?? {};
707
+ for (const rule of CONFIGURABLE_DEFAULT_RULES) {
708
+ const override = defaults[rule.id];
709
+ if (override === "off")
710
+ continue;
711
+ const group = rule.group;
712
+ const scopes = override?.scopes ?? rule.scopes;
713
+ const base = {};
714
+ for (const scope of scopes) {
715
+ base[scope] = scope === "source-comment" ? options.sourceCommentSeverity ?? rule.severity[scope] ?? "warning" : rule.severity[scope] ?? scopeDefaultSeverity(scope, options.sourceCommentSeverity);
716
+ }
717
+ rules.push({
718
+ id: rule.id,
719
+ group,
720
+ custom: false,
721
+ builtIn: rule.builtIn === true,
722
+ scopes,
723
+ message: rule.message,
724
+ severity: applySeverity(scopes, base, override?.severity),
725
+ exempt: override?.exempt ?? [],
726
+ substringExempt: rule.exemptions,
727
+ reportGroup: REPORT_GROUPS[rule.id],
728
+ patternFor: defaultPatternFor(rule)
729
+ });
730
+ }
731
+ for (const rule of config?.custom ?? []) {
732
+ const group = groupOfScope(rule.scopes[0] ?? "") ?? "reader-resolvable";
733
+ const base = {};
734
+ for (const scope of rule.scopes)
735
+ base[scope] = scopeDefaultSeverity(scope, options.sourceCommentSeverity);
736
+ rules.push({
737
+ id: rule.id,
738
+ group,
739
+ custom: true,
740
+ builtIn: false,
741
+ scopes: rule.scopes,
742
+ message: rule.means,
743
+ severity: applySeverity(rule.scopes, base, rule.severity),
744
+ exempt: rule.exempt ?? [],
745
+ substringExempt: [],
746
+ patternFor: customPatternFor(rule, group === "reader-resolvable")
747
+ });
748
+ }
749
+ if (options.decisionRecordsPath !== undefined)
750
+ rules.push(decisionRecordCitationRule(options.decisionRecordsPath));
751
+ const order = (rule) => {
752
+ const at = RESOLVABLE_RUN_ORDER.indexOf(rule.id);
753
+ return rule.custom || at === -1 ? RESOLVABLE_RUN_ORDER.length : at;
754
+ };
755
+ const resolvable = rules.filter((rule) => rule.group === "reader-resolvable");
756
+ const sorted = resolvable.map((rule, index) => ({ rule, index })).sort((a, b) => order(a.rule) - order(b.rule) || a.index - b.index).map(({ rule }) => rule);
757
+ return {
758
+ rules: [...sorted, ...rules.filter((rule) => rule.group === "retired-vocabulary")],
759
+ exempt: config?.exempt ?? [],
760
+ repoRoot: options.repoRoot
761
+ };
762
+ }
763
+ var DEFAULT_PROSE_RULE_SET = resolveProseRules();
764
+ var DECISION_RECORD_CITATION_ID = "decision-record-citation";
765
+ var DECISION_RECORD_CITATION_SCOPES = ["ships", "product", "spec", "source-comment"];
766
+ var DECISION_RECORD_CITATION_MESSAGE = "a decision-record number";
767
+ function escapeRegExp(text) {
768
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
769
+ }
770
+ function decisionRecordCitationPattern(decisionRecordsPath) {
771
+ const folder = escapeRegExp(normalizeRepoPath(decisionRecordsPath));
772
+ return new RegExp(String.raw`\bADR[- ]?[0-9]+\b|(?<![A-Za-z0-9_-])${folder}/[0-9]+[A-Za-z0-9._-]*`, "g");
773
+ }
774
+ function decisionRecordCitationRule(decisionRecordsPath) {
775
+ const folder = normalizeRepoPath(decisionRecordsPath);
776
+ const pattern = decisionRecordCitationPattern(folder);
777
+ const severity = {};
778
+ for (const scope of DECISION_RECORD_CITATION_SCOPES)
779
+ severity[scope] = "error";
780
+ return {
781
+ id: DECISION_RECORD_CITATION_ID,
782
+ group: "reader-resolvable",
783
+ custom: false,
784
+ builtIn: false,
785
+ scopes: DECISION_RECORD_CITATION_SCOPES,
786
+ message: DECISION_RECORD_CITATION_MESSAGE,
787
+ severity,
788
+ exempt: [folder],
789
+ substringExempt: [],
790
+ patternFor: () => pattern
791
+ };
792
+ }
793
+
574
794
  // ../../packages/aeg-core/src/reader-resolvable-prose.ts
795
+ function normalizeSpecPath(entry) {
796
+ return normalizeRepoPath(entry);
797
+ }
575
798
  var SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
799
+ var readerRules = rulesForGroup("reader-resolvable");
800
+ var readerPattern = (id, scope = "prose") => {
801
+ const pattern = readerRules.find((rule) => rule.id === id)?.patterns[scope];
802
+ if (!(pattern instanceof RegExp))
803
+ throw new Error(`default prose rule ${id} has no ${scope} pattern`);
804
+ return pattern;
805
+ };
806
+ var FORGE_NUMBER_PATTERN = readerPattern("forge-number");
807
+ var TRANCHE_SLUG_VN_PATTERN = readerPattern("tranche-slug");
808
+ var TASK_NUMBER_PATTERN = readerPattern("task-number");
809
+ var REFERENCE_CLASSES = new Set(["ships", "reader-facing", "product", "spec"]);
810
+ var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = readerPattern("source-comment-tranche-slug", "comment");
811
+ var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = readerPattern("source-comment-forge-number", "comment");
576
812
 
577
813
  // ../../packages/aeg-core/src/quoted-command.ts
578
814
  var QUOTED_COMMAND_SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
@@ -616,59 +852,9 @@ var R1_GRANDFATHERED_ISSUES = new Set([279, 280, 281, 282]);
616
852
  // ../../packages/aeg-core/src/diagram-model.ts
617
853
  import matter from "gray-matter";
618
854
  // ../../packages/aeg-core/src/retired-vocabulary.ts
619
- var PLAN_ON_DISK_PATTERNS = ["[Tt]opology files?", "aeg-root/tranches/", "aeg-project/"];
620
- var RETIRED_PATTERNS = [
621
- String.raw`\bD-[0-9]{3}\b`,
622
- "D-(###|NNN|nnn|xxx)",
623
- "decision (entry|logged)",
624
- "decision-log entry",
625
- "decision log entry",
626
- "decision log(s|ged|ging)?([^a-z]|$)",
627
- "decision-log",
628
- "decision entr",
629
- "decisions? (are |is )?logged",
630
- "log entries",
631
- String.raw`decisions\.md`,
632
- "decisions-legacy",
633
- "CONTRADICTION",
634
- "assumes Tier 3",
635
- "Lock: ?YES",
636
- "Lock: ?NO",
637
- "lock approvals?",
638
- "approves locks",
639
- "Conforms to lock",
640
- "Challenges lock",
641
- "checkDecisionNumbersFresh",
642
- String.raw`roles/team-leader\.md`,
643
- String.raw`\(,`,
644
- String.raw`,\)`,
645
- String.raw`\(\.\)`,
646
- ...PLAN_ON_DISK_PATTERNS
647
- ];
648
- var TRANCHE_MODEL_FILE = "/tranche-model.md";
649
- var PATTERN_EXEMPT = {
650
- [String.raw`\bD-[0-9]{3}\b`]: ["./CLAUDE.md"],
651
- [String.raw`decisions\.md`]: [
652
- "docs-index.md",
653
- "apps/vada-ai/specs/legacy/README.md",
654
- "apps/vada-ai/specs/vada-product-spec.md",
655
- "apps/vada-ai/web/CLAUDE.md",
656
- "apps/vada-ai/CLAUDE.md"
657
- ],
658
- "decisions-legacy": [
659
- "packages/aeg-core/src/file-classify.ts",
660
- "packages/aeg-core/src/file-classify.test.ts",
661
- "packages/aeg-core/src/pr-tier.test.ts",
662
- "docs-index.md",
663
- ".claude/skills/database/SKILL.md",
664
- ".claude/skills/vada-architecture/SKILL.md",
665
- "apps/vada-ai/specs/vada-byok-principles.md",
666
- "apps/vada-ai/web/CLAUDE.md",
667
- "apps/vada-ai/CLAUDE.md"
668
- ],
669
- CONTRADICTION: ["apps/vada-ai/specs/vada-reviewers-spec.md"],
670
- ...Object.fromEntries(PLAN_ON_DISK_PATTERNS.map((pattern) => [pattern, [TRANCHE_MODEL_FILE]]))
671
- };
855
+ var retiredRules = rulesForGroup("retired-vocabulary");
856
+ var RETIRED_PATTERNS = retiredRules.map((rule) => rule.patterns.repository);
857
+ var DEFAULT_PATTERN_OF = new Map(retiredRules.map((rule) => [rule.id, rule.patterns.repository]));
672
858
  // ../../packages/aeg-core/src/task-tools.ts
673
859
  import { z } from "zod";
674
860
  var TASK_TOOL_ERROR_KINDS = [
@@ -937,9 +1123,11 @@ var LineageSchema = z3.object({
937
1123
  parent: z3.string().nullable()
938
1124
  }).strict();
939
1125
  var InputVersionsSchema = z3.object({
1126
+ manifest_version: z3.literal(2).nullable().optional(),
940
1127
  objectives_version: z3.string().nullable(),
941
1128
  brief_hash: z3.string().nullable(),
942
1129
  ruling_ordinal: z3.number().int().nullable(),
1130
+ pause_bound_ruling: z3.object({ rulingId: z3.string().min(1), pauseId: z3.string().min(1), contentDigest: z3.string().min(1) }).strict().nullable().optional(),
943
1131
  policy_digest: z3.string().nullable()
944
1132
  }).strict();
945
1133
  var ProvenanceSchema = z3.enum(["parent_attributed", "env_correlated", "self_reported", "unavailable"]);
@@ -977,7 +1165,17 @@ var HeaderMetaV3Schema = z3.object({
977
1165
  runtime: z3.string().nullable(),
978
1166
  source: z3.string().nullable()
979
1167
  }).strict();
980
- var HeaderMetaSchema = z3.discriminatedUnion("schema", [HeaderMetaV1Schema, HeaderMetaV2Schema, HeaderMetaV3Schema]);
1168
+ var HeaderMetaV4Schema = HeaderMetaV3Schema.extend({
1169
+ schema: z3.literal(4),
1170
+ process: z3.object({ id: z3.string(), version: z3.string().nullable(), digest: z3.string().nullable() }).strict(),
1171
+ runner: z3.object({ id: z3.string(), version: z3.string().nullable() }).strict()
1172
+ }).strict();
1173
+ var HeaderMetaSchema = z3.discriminatedUnion("schema", [
1174
+ HeaderMetaV1Schema,
1175
+ HeaderMetaV2Schema,
1176
+ HeaderMetaV3Schema,
1177
+ HeaderMetaV4Schema
1178
+ ]);
981
1179
  var SubjectSchema = z3.object({
982
1180
  issue: z3.number().int().nullable(),
983
1181
  pr: z3.number().int().optional(),
@@ -1197,6 +1395,75 @@ var DevReviewLoopEventSchema = z3.discriminatedUnion("event", [
1197
1395
  round: z3.number().int(),
1198
1396
  phase: z3.string()
1199
1397
  }).strict(),
1398
+ z3.object({
1399
+ ...loopShared,
1400
+ event: z3.literal("conflict_reentry"),
1401
+ task: z3.number().int(),
1402
+ pr: z3.number().int().positive(),
1403
+ attempt: z3.number().int().positive(),
1404
+ bound: z3.number().int().positive()
1405
+ }).strict(),
1406
+ z3.object({
1407
+ ...loopShared,
1408
+ event: z3.literal("storage_push"),
1409
+ round: z3.number().int(),
1410
+ branch: z3.string(),
1411
+ head: z3.string()
1412
+ }).strict(),
1413
+ z3.object({
1414
+ ...loopShared,
1415
+ event: z3.literal("local_checks_run"),
1416
+ round: z3.number().int(),
1417
+ head: z3.string().nullable(),
1418
+ passed: z3.boolean(),
1419
+ wall_ms: z3.number().nonnegative()
1420
+ }).strict(),
1421
+ z3.object({
1422
+ ...loopShared,
1423
+ event: z3.literal("ready_push"),
1424
+ round: z3.number().int(),
1425
+ head: z3.string(),
1426
+ outcome: z3.enum(["passed", "refused"]),
1427
+ selected: z3.number().int().nonnegative(),
1428
+ failed: z3.number().int().nonnegative(),
1429
+ rerun: z3.boolean(),
1430
+ wall_ms: z3.number().nonnegative()
1431
+ }).strict(),
1432
+ z3.object({
1433
+ ...loopShared,
1434
+ event: z3.literal("failed_tests_rerun"),
1435
+ round: z3.number().int(),
1436
+ head: z3.string(),
1437
+ rerun_of: z3.string(),
1438
+ failed_files: z3.number().int().nonnegative(),
1439
+ affected_files: z3.number().int().nonnegative(),
1440
+ full_count: z3.number().int().nonnegative()
1441
+ }).strict(),
1442
+ z3.object({
1443
+ ...loopShared,
1444
+ event: z3.literal("pr_opened"),
1445
+ round: z3.number().int(),
1446
+ pr: z3.number().int().positive(),
1447
+ head: z3.string()
1448
+ }).strict(),
1449
+ z3.object({
1450
+ ...loopShared,
1451
+ event: z3.literal("ci_result_read"),
1452
+ round: z3.number().int(),
1453
+ pr: z3.number().int().positive(),
1454
+ head: z3.string(),
1455
+ conclusion: z3.enum(["green", "red", "pending", "skipped"]),
1456
+ failing_checks: z3.array(z3.string()),
1457
+ wait_ms: z3.number().nonnegative()
1458
+ }).strict(),
1459
+ z3.object({
1460
+ ...loopShared,
1461
+ event: z3.literal("phase_time"),
1462
+ round: z3.number().int(),
1463
+ phase: z3.enum(["developer", "local_checks", "review", "push", "ci", "other"]),
1464
+ step: z3.string(),
1465
+ wall_ms: z3.number().nonnegative()
1466
+ }).strict(),
1200
1467
  z3.object({
1201
1468
  ...loopShared,
1202
1469
  event: z3.literal("driver_exited"),
@@ -1384,7 +1651,7 @@ var EffectEventSchema = z3.discriminatedUnion("event", [
1384
1651
  ]);
1385
1652
  var CustomFieldValueSchema = z3.union([z3.string().max(CUSTOM_TEXT_MAX_LENGTH), z3.number().finite(), z3.boolean()]);
1386
1653
  var customShared = {
1387
- meta: HeaderMetaV3Schema,
1654
+ meta: HeaderMetaSchema,
1388
1655
  subject: SubjectSchema,
1389
1656
  kind: z3.literal("custom"),
1390
1657
  ...envelopeTail
@@ -1469,7 +1736,7 @@ function buildHeader(input) {
1469
1736
  const issue = subject.issue;
1470
1737
  return {
1471
1738
  meta: {
1472
- schema: 3,
1739
+ schema: 4,
1473
1740
  ts: input.now.toISOString(),
1474
1741
  run_id: input.runId,
1475
1742
  seq: input.seq,
@@ -1487,23 +1754,34 @@ function buildHeader(input) {
1487
1754
  parent: lineageFieldFromEnv(input.env.parent)
1488
1755
  },
1489
1756
  input_versions: {
1757
+ manifest_version: input.inputVersions?.manifestVersion ?? null,
1490
1758
  objectives_version: input.inputVersions?.objectivesVersion ?? null,
1491
1759
  brief_hash: input.inputVersions?.briefHash ?? null,
1492
1760
  ruling_ordinal: input.inputVersions?.rulingOrdinal ?? null,
1761
+ pause_bound_ruling: input.inputVersions?.pauseBoundRuling ?? null,
1493
1762
  policy_digest: input.inputVersions?.policyDigest ?? null
1494
1763
  },
1495
1764
  provenance: provenanceFor(input),
1496
1765
  work: {
1497
1766
  ref: lineageFieldFromEnv(input.env.workRef) ?? (issue === null ? null : String(issue)),
1498
1767
  repo: input.repo,
1499
- change: null,
1500
- revision: null
1768
+ change: pr === undefined ? null : String(pr),
1769
+ revision: input.revision ?? null
1501
1770
  },
1502
1771
  flow: {
1503
1772
  id: lineageFieldFromEnv(input.env.flow) ?? "vinaya",
1504
1773
  version: lineageFieldFromEnv(input.env.flowVersion)
1505
1774
  },
1506
1775
  runtime: lineageFieldFromEnv(input.env.runtime),
1776
+ process: {
1777
+ id: lineageFieldFromEnv(input.env.processId) ?? "vinaya",
1778
+ version: lineageFieldFromEnv(input.env.processVersion),
1779
+ digest: lineageFieldFromEnv(input.env.processDigest)
1780
+ },
1781
+ runner: {
1782
+ id: lineageFieldFromEnv(input.env.runnerId) ?? "standalone",
1783
+ version: lineageFieldFromEnv(input.env.runnerVersion)
1784
+ },
1507
1785
  source: lineageFieldFromEnv(input.env.source)
1508
1786
  },
1509
1787
  subject
@@ -1547,7 +1825,7 @@ function redact(value, home) {
1547
1825
  return value;
1548
1826
  }
1549
1827
  // ../../packages/aeg-core/src/log/store.ts
1550
- var KNOWN_SCHEMA_VERSIONS = [1, 2, 3];
1828
+ var KNOWN_SCHEMA_VERSIONS = [1, 2, 3, 4];
1551
1829
  function metaOf(obj) {
1552
1830
  if (obj === null || typeof obj !== "object")
1553
1831
  return null;
@@ -1685,6 +1963,12 @@ var ManifestRecordSchema = z4.object({
1685
1963
  briefHash: z4.string().min(1).nullable(),
1686
1964
  objectivesVersion: z4.string().min(1).nullable(),
1687
1965
  rulingOrdinal: epochNumber,
1966
+ manifestVersion: z4.literal(2).optional(),
1967
+ pauseBoundRuling: z4.object({
1968
+ rulingId: z4.string().min(1),
1969
+ pauseId: z4.string().min(1),
1970
+ contentDigest: z4.string().min(1)
1971
+ }).strict().nullable().optional(),
1688
1972
  policyDigest: z4.string().min(1),
1689
1973
  recordedAt: isoTimestamp
1690
1974
  }).strict();
@@ -1706,7 +1990,11 @@ var LoopStateRecordSchema = z4.object({
1706
1990
  deliveredFindings: roundHeadIdentity.nullable(),
1707
1991
  repeatMemory: z4.object({
1708
1992
  blockingFindings: z4.array(z4.string()),
1709
- lastFailure: z4.object({ signature: z4.string(), message: z4.string() }).nullable()
1993
+ lastFailure: z4.object({ signature: z4.string(), message: z4.string(), developerAttemptedSince: z4.boolean().optional() }).nullable()
1994
+ }).strict().optional(),
1995
+ developerHandoff: z4.object({
1996
+ findings: z4.array(z4.object({ id: z4.string().min(1), description: z4.string().min(1) }).strict()),
1997
+ failingChecks: z4.array(z4.string().min(1))
1710
1998
  }).strict().optional(),
1711
1999
  publicationExpectedBase: z4.string().regex(/^[0-9a-f]{40}$/).nullable().optional(),
1712
2000
  taskStartedAt: isoTimestamp.optional(),
@@ -1761,6 +2049,16 @@ var ResolutionRecordSchema = z4.object({
1761
2049
  authenticatedFrom: z4.string().min(1),
1762
2050
  consumedAt: isoTimestamp
1763
2051
  }).strict();
2052
+ var ExecutionRoundMirrorRecordSchema = z4.object({
2053
+ version: z4.literal(1),
2054
+ kind: z4.literal("execution_round"),
2055
+ task: taskId,
2056
+ repository: z4.string().min(1),
2057
+ threadId: z4.string().min(1),
2058
+ checkpointId: z4.string().min(1),
2059
+ round: z4.number().int().positive(),
2060
+ recordedAt: isoTimestamp
2061
+ }).strict();
1764
2062
  // ../../packages/aeg-core/src/control-store/local.ts
1765
2063
  import {
1766
2064
  closeSync as closeSync2,
@@ -1782,10 +2080,10 @@ import { dirname, join, resolve, sep } from "node:path";
1782
2080
  function isErrnoException(err, code) {
1783
2081
  return typeof err === "object" && err !== null && err.code === code;
1784
2082
  }
1785
- function isTrustedDirStat(stat, ownUid) {
2083
+ function isTrustedDirStat(stat, ownUid, trustedOverflowUid) {
1786
2084
  if (typeof ownUid !== "number")
1787
2085
  return true;
1788
- if (stat.uid !== ownUid && stat.uid !== 0)
2086
+ if (stat.uid !== ownUid && stat.uid !== 0 && stat.uid !== trustedOverflowUid)
1789
2087
  return false;
1790
2088
  const worldWritable = (stat.mode & 2) !== 0;
1791
2089
  const sticky = (stat.mode & 512) !== 0;
@@ -1794,15 +2092,54 @@ function isTrustedDirStat(stat, ownUid) {
1794
2092
  function currentUid() {
1795
2093
  return typeof process.getuid === "function" ? process.getuid() : undefined;
1796
2094
  }
2095
+ function uidMapLeavesRootUnmapped(uidMap) {
2096
+ const lines = uidMap.split(`
2097
+ `).map((line) => line.trim()).filter((line) => line.length > 0);
2098
+ if (lines.length === 0)
2099
+ return false;
2100
+ for (const line of lines) {
2101
+ const fields = line.split(/\s+/);
2102
+ if (fields.length !== 3 || !fields.every((field) => /^\d+$/.test(field)))
2103
+ return false;
2104
+ const inside = Number(fields[0]);
2105
+ const count = Number(fields[2]);
2106
+ if (inside === 0 && count > 0)
2107
+ return false;
2108
+ }
2109
+ return true;
2110
+ }
2111
+ function readTrustedOverflowUid(readFile) {
2112
+ try {
2113
+ if (!uidMapLeavesRootUnmapped(readFile("/proc/self/uid_map")))
2114
+ return;
2115
+ const overflow = readFile("/proc/sys/kernel/overflowuid").trim();
2116
+ return /^\d+$/.test(overflow) ? Number(overflow) : undefined;
2117
+ } catch {
2118
+ return;
2119
+ }
2120
+ }
2121
+ var cachedTrustedOverflowUid;
2122
+ function processTrustedOverflowUid() {
2123
+ cachedTrustedOverflowUid ??= { value: readTrustedOverflowUid((path) => readFileSync2(path, "utf8")) };
2124
+ return cachedTrustedOverflowUid.value;
2125
+ }
2126
+ function isAtOrBelowTrustedRoot(index, rootSegmentCount) {
2127
+ return index >= rootSegmentCount - 1;
2128
+ }
2129
+ function segmentTrustedOverflowUid(index, rootSegmentCount, trustedOverflowUid) {
2130
+ return isAtOrBelowTrustedRoot(index, rootSegmentCount) ? undefined : trustedOverflowUid;
2131
+ }
1797
2132
  function mkdirNoSymlinks(dir, mode, trustedRoot) {
1798
2133
  const absolute = resolve(dir);
1799
2134
  const rootSegments = resolve(trustedRoot).split(sep).filter((s) => s.length > 0);
1800
2135
  const segments = absolute.split(sep).filter((s) => s.length > 0);
1801
2136
  const ownUid = currentUid();
2137
+ const trustedOverflowUid = typeof ownUid === "number" ? processTrustedOverflowUid() : undefined;
1802
2138
  let current = absolute.startsWith(sep) ? sep : "";
1803
2139
  segments.forEach((segment, index) => {
1804
2140
  current = current === "" || current === sep ? `${current}${segment}` : `${current}${sep}${segment}`;
1805
- const atOrBelowTrustedRoot = index >= rootSegments.length - 1;
2141
+ const atOrBelowTrustedRoot = isAtOrBelowTrustedRoot(index, rootSegments.length);
2142
+ const overflowUid = segmentTrustedOverflowUid(index, rootSegments.length, trustedOverflowUid);
1806
2143
  try {
1807
2144
  mkdirSync(current, { mode });
1808
2145
  } catch (err) {
@@ -1823,7 +2160,7 @@ function mkdirNoSymlinks(dir, mode, trustedRoot) {
1823
2160
  if (!real.isDirectory()) {
1824
2161
  throw new Error(`control-store: refusing to create a run directory through ${current} — it is a symlink that does not resolve to a real directory`);
1825
2162
  }
1826
- if (!isTrustedDirStat(real, ownUid)) {
2163
+ if (!isTrustedDirStat(real, ownUid, overflowUid)) {
1827
2164
  throw new Error(`control-store: refusing to create a run directory through ${current} — its symlink target is owned by uid ${real.uid} with mode ${(real.mode & 4095).toString(8)}, neither this process's own user nor a safe shared mode`);
1828
2165
  }
1829
2166
  return;
@@ -1831,33 +2168,335 @@ function mkdirNoSymlinks(dir, mode, trustedRoot) {
1831
2168
  if (!stat.isDirectory()) {
1832
2169
  throw new Error(`control-store: refusing to create a run directory through ${current} — it already exists and is not a real directory (a symlink or a file)`);
1833
2170
  }
1834
- if (!isTrustedDirStat(stat, ownUid)) {
2171
+ if (!isTrustedDirStat(stat, ownUid, overflowUid)) {
1835
2172
  throw new Error(`control-store: refusing to create a run directory through ${current} — it already exists, owned by uid ${stat.uid} with mode ${(stat.mode & 4095).toString(8)}, neither this process's own user nor a safe shared mode`);
1836
2173
  }
1837
2174
  });
1838
2175
  }
1839
2176
  var CONTROL_AREA_DIRNAME = "control";
2177
+ // src/lib/pre-push-select-tests.ts
2178
+ import { existsSync as existsSync4 } from "node:fs";
2179
+
2180
+ // src/lib/config.ts
2181
+ import { execFile as execFile4, execFileSync as execFileSync2 } from "node:child_process";
2182
+ import { promisify as promisify4 } from "node:util";
2183
+ import { existsSync as existsSync2, lstatSync as lstatSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync3, realpathSync, writeFileSync } from "node:fs";
2184
+ import { homedir } from "node:os";
2185
+ import { basename, dirname as dirname2, isAbsolute, join as join2, resolve as resolve2 } from "node:path";
2186
+ import { z as z6 } from "zod";
2187
+
2188
+ // src/checks/contract.ts
2189
+ var CHECK_SCHEMA_VERSION = 1;
2190
+ function emitCheckError(error) {
2191
+ process.stderr.write(`${JSON.stringify(error)}
2192
+ `);
2193
+ }
2194
+
1840
2195
  // src/lib/agent-vendors.ts
1841
2196
  var AGENT_VENDORS = ["skills", "claude", "gemini"];
1842
2197
 
2198
+ // src/lib/prose-rules-config.ts
2199
+ import safeRegex from "safe-regex2";
2200
+ import { z as z5 } from "zod";
2201
+ var SEVERITIES = ["error", "warning"];
2202
+ var OVERRIDE_KEYS = ["scopes", "severity", "exempt"];
2203
+ var FIXED_DEFAULT_KEYS = ["pattern", "patterns", "flags", "means", "message", "id"];
2204
+ var CUSTOM_KEYS = ["id", "pattern", "patterns", "flags", "means", "scopes", "severity", "exempt"];
2205
+ var DEFAULT_IDS = new Set([...DEFAULT_PROSE_RULES.map((rule) => rule.id), DECISION_RECORD_CITATION_ID]);
2206
+ function isPlainObject(value) {
2207
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2208
+ }
2209
+ function outsideRepositoryReason(entry) {
2210
+ if (entry.startsWith("/") || /^[A-Za-z]:/.test(entry))
2211
+ return "must be a repository-relative path, not an absolute one";
2212
+ if (entry.split(/[\\/]/).includes(".."))
2213
+ return "must stay inside the repository — no `..` segment";
2214
+ return null;
2215
+ }
2216
+ var RepoRelativePathSchema = z5.string().min(1).superRefine((entry, ctx) => {
2217
+ const reason = outsideRepositoryReason(entry);
2218
+ if (reason)
2219
+ ctx.addIssue({ code: z5.ZodIssueCode.custom, message: reason });
2220
+ });
2221
+ function pathListIssues(value, path, issues) {
2222
+ if (!Array.isArray(value)) {
2223
+ issues.push({ path, message: "must be a list of repository-relative paths" });
2224
+ return;
2225
+ }
2226
+ value.forEach((entry, index) => {
2227
+ if (typeof entry !== "string" || entry.length === 0) {
2228
+ issues.push({ path: [...path, index], message: "must be a non-empty repository-relative path" });
2229
+ return;
2230
+ }
2231
+ const reason = outsideRepositoryReason(entry);
2232
+ if (reason)
2233
+ issues.push({ path: [...path, index], message: reason });
2234
+ });
2235
+ }
2236
+ function scopeListIssues(value, path, allowed, issues) {
2237
+ if (!Array.isArray(value) || value.length === 0) {
2238
+ issues.push({ path, message: "must name at least one scope" });
2239
+ return null;
2240
+ }
2241
+ const scopes = [];
2242
+ value.forEach((scope, index) => {
2243
+ if (typeof scope !== "string" || !CONFIGURABLE_PROSE_SCOPES.includes(scope)) {
2244
+ issues.push({
2245
+ path: [...path, index],
2246
+ 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(", ")}`
2247
+ });
2248
+ return;
2249
+ }
2250
+ if (!allowed.includes(scope)) {
2251
+ issues.push({
2252
+ path: [...path, index],
2253
+ message: `scope "${scope}" is not one this rule can run in — it can run in: ${allowed.join(", ")}`
2254
+ });
2255
+ return;
2256
+ }
2257
+ scopes.push(scope);
2258
+ });
2259
+ return scopes;
2260
+ }
2261
+ function severityIssues(value, path, scopes, issues) {
2262
+ if (typeof value === "string") {
2263
+ if (!SEVERITIES.includes(value)) {
2264
+ issues.push({ path, message: `unknown severity ${JSON.stringify(value)} — use "error" or "warning"` });
2265
+ }
2266
+ return;
2267
+ }
2268
+ if (!isPlainObject(value)) {
2269
+ issues.push({ path, message: 'must be "error", "warning", or a map from scope to one of them' });
2270
+ return;
2271
+ }
2272
+ for (const [scope, severity] of Object.entries(value)) {
2273
+ if (!scopes.includes(scope)) {
2274
+ issues.push({ path: [...path, scope], message: `names scope "${scope}", which this rule's scopes do not cover` });
2275
+ }
2276
+ if (typeof severity !== "string" || !SEVERITIES.includes(severity)) {
2277
+ issues.push({
2278
+ path: [...path, scope],
2279
+ message: `unknown severity ${JSON.stringify(severity)} — use "error" or "warning"`
2280
+ });
2281
+ }
2282
+ }
2283
+ }
2284
+ function patternIssues(source, flags, path, issues) {
2285
+ if (typeof source !== "string" || source.length === 0) {
2286
+ issues.push({ path, message: "must be a non-empty regular expression" });
2287
+ return;
2288
+ }
2289
+ if (source.length > CONFIGURED_PATTERN_MAX_LENGTH) {
2290
+ issues.push({
2291
+ path,
2292
+ message: `is ${source.length} characters, over the ${CONFIGURED_PATTERN_MAX_LENGTH}-character limit for a configured pattern`
2293
+ });
2294
+ return;
2295
+ }
2296
+ try {
2297
+ new RegExp(source, flags);
2298
+ } catch (err) {
2299
+ issues.push({ path, message: `does not compile: ${err.message}` });
2300
+ return;
2301
+ }
2302
+ if (!safeRegex(source, { limit: Number.MAX_SAFE_INTEGER })) {
2303
+ issues.push({
2304
+ path,
2305
+ 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."
2306
+ });
2307
+ }
2308
+ }
2309
+ function flagIssues(value, path, issues) {
2310
+ if (value === undefined)
2311
+ return "";
2312
+ if (typeof value !== "string") {
2313
+ issues.push({ path, message: 'must be a string of flags, e.g. "i"' });
2314
+ return "";
2315
+ }
2316
+ const seen = new Set;
2317
+ for (const flag of value) {
2318
+ if (!CONFIGURED_PROSE_FLAGS.includes(flag)) {
2319
+ issues.push({
2320
+ path,
2321
+ message: `unknown flag ${JSON.stringify(flag)} — only ${CONFIGURED_PROSE_FLAGS.map((f) => `"${f}"`).join(" and ")} are allowed`
2322
+ });
2323
+ return "";
2324
+ }
2325
+ if (seen.has(flag)) {
2326
+ issues.push({ path, message: `repeats the flag "${flag}"` });
2327
+ return "";
2328
+ }
2329
+ seen.add(flag);
2330
+ }
2331
+ return value;
2332
+ }
2333
+ function defaultsIssues(value, issues) {
2334
+ const base = ["defaults"];
2335
+ if (!isPlainObject(value)) {
2336
+ issues.push({ path: base, message: 'must map a default rule id to "off" or an override' });
2337
+ return;
2338
+ }
2339
+ for (const [id, override] of Object.entries(value)) {
2340
+ const path = [...base, id];
2341
+ const rule = CONFIGURABLE_DEFAULT_RULES.find((candidate) => candidate.id === id);
2342
+ if (!rule) {
2343
+ issues.push({
2344
+ path,
2345
+ message: `unknown default rule id "${id}" — \`vinaya check --plan\` lists the rules each prose check runs`
2346
+ });
2347
+ continue;
2348
+ }
2349
+ if (override === "off")
2350
+ continue;
2351
+ if (!isPlainObject(override)) {
2352
+ issues.push({ path, message: 'must be "off" or an object with any of scopes, severity, exempt' });
2353
+ continue;
2354
+ }
2355
+ for (const key of Object.keys(override)) {
2356
+ if (OVERRIDE_KEYS.includes(key))
2357
+ continue;
2358
+ issues.push({
2359
+ path: [...path, key],
2360
+ 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`
2361
+ });
2362
+ }
2363
+ const scopes = override.scopes === undefined ? [...rule.scopes] : scopeListIssues(override.scopes, [...path, "scopes"], allowedScopesFor(rule), issues);
2364
+ if (override.severity !== undefined && scopes)
2365
+ severityIssues(override.severity, [...path, "severity"], scopes, issues);
2366
+ if (override.exempt !== undefined)
2367
+ pathListIssues(override.exempt, [...path, "exempt"], issues);
2368
+ }
2369
+ }
2370
+ function customIssues(value, issues) {
2371
+ if (!Array.isArray(value)) {
2372
+ issues.push({ path: ["custom"], message: "must be a list of rules" });
2373
+ return;
2374
+ }
2375
+ const ids = new Set;
2376
+ value.forEach((rule, index) => {
2377
+ const path = ["custom", index];
2378
+ if (!isPlainObject(rule)) {
2379
+ issues.push({ path, message: "must be a rule object" });
2380
+ return;
2381
+ }
2382
+ for (const key of Object.keys(rule)) {
2383
+ if (!CUSTOM_KEYS.includes(key)) {
2384
+ issues.push({ path: [...path, key], message: `unknown key "${key}" — a rule takes ${CUSTOM_KEYS.join(", ")}` });
2385
+ }
2386
+ }
2387
+ if (typeof rule.id !== "string" || rule.id.length === 0) {
2388
+ issues.push({ path: [...path, "id"], message: "a custom rule needs an id" });
2389
+ } else if (DEFAULT_IDS.has(rule.id)) {
2390
+ issues.push({
2391
+ path: [...path, "id"],
2392
+ message: `"${rule.id}" is a default rule id — a custom rule needs its own id; retune the default under proseGates.rules.defaults instead`
2393
+ });
2394
+ } else if (ids.has(rule.id)) {
2395
+ issues.push({ path: [...path, "id"], message: `"${rule.id}" is used by an earlier custom rule` });
2396
+ } else {
2397
+ ids.add(rule.id);
2398
+ }
2399
+ if (typeof rule.means !== "string" || rule.means.trim().length === 0) {
2400
+ issues.push({ path: [...path, "means"], message: "a custom rule needs a message (`means`)" });
2401
+ }
2402
+ let scopes = null;
2403
+ if (rule.scopes === undefined) {
2404
+ issues.push({ path: [...path, "scopes"], message: "a custom rule needs at least one scope (`scopes`)" });
2405
+ } else {
2406
+ scopes = scopeListIssues(rule.scopes, [...path, "scopes"], CONFIGURABLE_PROSE_SCOPES, issues);
2407
+ }
2408
+ if (scopes && new Set(scopes.map(groupOfScope)).size > 1) {
2409
+ issues.push({
2410
+ path: [...path, "scopes"],
2411
+ 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'
2412
+ });
2413
+ }
2414
+ const flags = flagIssues(rule.flags, [...path, "flags"], issues);
2415
+ if (rule.pattern === undefined && rule.patterns === undefined) {
2416
+ issues.push({
2417
+ path: [...path, "pattern"],
2418
+ message: "a custom rule needs a `pattern` or a per-scope `patterns` map"
2419
+ });
2420
+ }
2421
+ if (rule.pattern !== undefined)
2422
+ patternIssues(rule.pattern, flags, [...path, "pattern"], issues);
2423
+ if (rule.patterns !== undefined) {
2424
+ if (!isPlainObject(rule.patterns)) {
2425
+ issues.push({ path: [...path, "patterns"], message: "must map a scope to a regular expression" });
2426
+ } else {
2427
+ for (const [scope, source] of Object.entries(rule.patterns)) {
2428
+ if (scopes && !scopes.includes(scope)) {
2429
+ issues.push({
2430
+ path: [...path, "patterns", scope],
2431
+ message: `names scope "${scope}", which this rule's scopes do not cover`
2432
+ });
2433
+ continue;
2434
+ }
2435
+ patternIssues(source, flags, [...path, "patterns", scope], issues);
2436
+ }
2437
+ if (rule.pattern === undefined && scopes) {
2438
+ for (const scope of scopes) {
2439
+ if (!(scope in rule.patterns)) {
2440
+ issues.push({
2441
+ path: [...path, "patterns"],
2442
+ message: `has no pattern for scope "${scope}" — add one, or a \`pattern\` every other scope uses`
2443
+ });
2444
+ }
2445
+ }
2446
+ }
2447
+ }
2448
+ }
2449
+ if (rule.severity !== undefined && scopes)
2450
+ severityIssues(rule.severity, [...path, "severity"], scopes, issues);
2451
+ if (rule.exempt !== undefined)
2452
+ pathListIssues(rule.exempt, [...path, "exempt"], issues);
2453
+ });
2454
+ }
2455
+ function proseRulesIssues(value) {
2456
+ const issues = [];
2457
+ if (!isPlainObject(value))
2458
+ return [{ path: [], message: "must be an object with any of exempt, defaults, custom" }];
2459
+ for (const key of Object.keys(value)) {
2460
+ if (!["exempt", "defaults", "custom"].includes(key)) {
2461
+ issues.push({ path: [key], message: `unknown key "${key}" — proseGates.rules takes exempt, defaults and custom` });
2462
+ }
2463
+ }
2464
+ if (value.exempt !== undefined)
2465
+ pathListIssues(value.exempt, ["exempt"], issues);
2466
+ if (value.defaults !== undefined)
2467
+ defaultsIssues(value.defaults, issues);
2468
+ if (value.custom !== undefined)
2469
+ customIssues(value.custom, issues);
2470
+ return issues;
2471
+ }
2472
+ var ProseRulesSchema = z5.unknown().superRefine((value, ctx) => {
2473
+ for (const issue of proseRulesIssues(value)) {
2474
+ ctx.addIssue({ code: z5.ZodIssueCode.custom, path: issue.path, message: issue.message });
2475
+ }
2476
+ }).transform((value) => value);
2477
+ var PublishedProseSchema = z5.object({
2478
+ allow: z5.array(z5.string().min(1)).optional()
2479
+ }).strict();
2480
+
1843
2481
  // src/lib/config.ts
1844
- var EnvEntrySchema = z5.union([
1845
- z5.literal(true),
1846
- z5.object({ optional: z5.literal(true) }),
1847
- z5.object({ anyOf: z5.array(z5.string()).min(2) }),
1848
- z5.string()
2482
+ var EnvEntrySchema = z6.union([
2483
+ z6.literal(true),
2484
+ z6.object({ optional: z6.literal(true) }),
2485
+ z6.object({ anyOf: z6.array(z6.string()).min(2) }),
2486
+ z6.string()
1849
2487
  ]);
1850
- var CheckEntrySchema = z5.object({
1851
- run: z5.string(),
1852
- scope: z5.enum(["diff", "full"]),
1853
- include: z5.array(z5.string()).optional(),
1854
- args: z5.array(z5.string()).optional(),
1855
- timeoutMs: z5.number().optional(),
1856
- env: z5.record(z5.string(), EnvEntrySchema).optional(),
1857
- requiresOpenPr: z5.boolean().optional(),
1858
- ownWorkflow: z5.boolean().optional(),
1859
- principalOwed: z5.literal(true).optional(),
1860
- validates: z5.enum(["body", "issue"]).optional()
2488
+ var CheckEntrySchema = z6.object({
2489
+ run: z6.string(),
2490
+ scope: z6.enum(["diff", "full"]),
2491
+ include: z6.array(z6.string()).optional(),
2492
+ args: z6.array(z6.string()).optional(),
2493
+ timeoutMs: z6.number().optional(),
2494
+ env: z6.record(z6.string(), EnvEntrySchema).optional(),
2495
+ requiresOpenPr: z6.boolean().optional(),
2496
+ ownWorkflow: z6.boolean().optional(),
2497
+ principalOwed: z6.literal(true).optional(),
2498
+ validates: z6.enum(["body", "issue"]).optional(),
2499
+ advisory: z6.literal(true).optional()
1861
2500
  }).superRefine((entry, ctx) => {
1862
2501
  if (!entry.env)
1863
2502
  return;
@@ -1867,22 +2506,22 @@ var CheckEntrySchema = z5.object({
1867
2506
  const members = value.anyOf;
1868
2507
  if (new Set(members).size !== members.length) {
1869
2508
  ctx.addIssue({
1870
- code: z5.ZodIssueCode.custom,
2509
+ code: z6.ZodIssueCode.custom,
1871
2510
  message: `env.${key}.anyOf has duplicate members`,
1872
2511
  path: ["env", key, "anyOf"]
1873
2512
  });
1874
2513
  }
1875
2514
  if (!members.includes(key)) {
1876
2515
  ctx.addIssue({
1877
- code: z5.ZodIssueCode.custom,
2516
+ code: z6.ZodIssueCode.custom,
1878
2517
  message: `env.${key}.anyOf must include "${key}" itself as a member`,
1879
2518
  path: ["env", key, "anyOf"]
1880
2519
  });
1881
2520
  }
1882
2521
  }
1883
2522
  });
1884
- var RoleEntrySchema = z5.object({
1885
- contract: z5.string().refine((p) => p.includes("/"), {
2523
+ var RoleEntrySchema = z6.object({
2524
+ contract: z6.string().refine((p) => p.includes("/"), {
1886
2525
  message: 'must be a path (contain at least one "/"), not a bare filename'
1887
2526
  })
1888
2527
  });
@@ -1906,17 +2545,17 @@ var BRIEF_BUILTINS = [
1906
2545
  "briefSections",
1907
2546
  "milestoneShape"
1908
2547
  ];
1909
- var BriefSectionSchema = z5.union([
1910
- z5.object({ builtin: z5.enum(BRIEF_BUILTINS) }),
1911
- z5.object({ heading: z5.string().min(1), name: z5.string().optional() }),
1912
- z5.object({ field: z5.string().min(1), name: z5.string().optional() }),
1913
- z5.object({ phrase: z5.string().min(1), name: z5.string().optional() })
2548
+ var BriefSectionSchema = z6.union([
2549
+ z6.object({ builtin: z6.enum(BRIEF_BUILTINS) }),
2550
+ z6.object({ heading: z6.string().min(1), name: z6.string().optional() }),
2551
+ z6.object({ field: z6.string().min(1), name: z6.string().optional() }),
2552
+ z6.object({ phrase: z6.string().min(1), name: z6.string().optional() })
1914
2553
  ]);
1915
- var BriefSchemaSchema = z5.object({
1916
- pr: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
1917
- issue: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
1918
- milestone: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
1919
- ack: z5.array(z5.enum(BRIEF_BUILTINS)).optional()
2554
+ var BriefSchemaSchema = z6.object({
2555
+ pr: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
2556
+ issue: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
2557
+ milestone: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
2558
+ ack: z6.array(z6.enum(BRIEF_BUILTINS)).optional()
1920
2559
  });
1921
2560
  function isSafeRepoRelPath(p) {
1922
2561
  if (p.length === 0)
@@ -1925,7 +2564,7 @@ function isSafeRepoRelPath(p) {
1925
2564
  return false;
1926
2565
  return p.split(/[\\/]/).every((seg) => seg !== ".." && seg !== "");
1927
2566
  }
1928
- var SafeRepoRelPath = z5.string().refine(isSafeRepoRelPath, {
2567
+ var SafeRepoRelPath = z6.string().refine(isSafeRepoRelPath, {
1929
2568
  message: "must be a repo-root-relative path with no `..` segment or absolute root"
1930
2569
  });
1931
2570
  var CANONICAL_HOOK_BLOCK_PREFIXES = [".git/", ".husky/", ".vinaya/hooks/", ".claude/hooks/"];
@@ -1935,22 +2574,22 @@ function isCanonicalHookBlockPath(p) {
1935
2574
  var ManagedHookBlockPath = SafeRepoRelPath.refine(isCanonicalHookBlockPath, {
1936
2575
  message: `must start with one of ${CANONICAL_HOOK_BLOCK_PREFIXES.join(", ")} (byte-exact, case-sensitive)`
1937
2576
  });
1938
- var ManagedBlockRecordSchema = z5.object({
2577
+ var ManagedBlockRecordSchema = z6.object({
1939
2578
  path: ManagedHookBlockPath,
1940
- marker: z5.string(),
1941
- comment: z5.enum(["hash", "html"])
2579
+ marker: z6.string(),
2580
+ comment: z6.enum(["hash", "html"])
1942
2581
  });
1943
- var ManagedManifestSchema = z5.object({
1944
- version: z5.number().int().positive(),
1945
- files: z5.array(SafeRepoRelPath),
1946
- blocks: z5.array(ManagedBlockRecordSchema),
1947
- labels: z5.array(z5.string()),
1948
- agents: z5.array(z5.enum(AGENT_VENDORS)).optional()
2582
+ var ManagedManifestSchema = z6.object({
2583
+ version: z6.number().int().positive(),
2584
+ files: z6.array(SafeRepoRelPath),
2585
+ blocks: z6.array(ManagedBlockRecordSchema),
2586
+ labels: z6.array(z6.string()),
2587
+ agents: z6.array(z6.enum(AGENT_VENDORS)).optional()
1949
2588
  });
1950
- var ProjectEntrySchema = z5.object({
1951
- name: z5.string().min(1),
1952
- description: z5.string().min(1).optional(),
1953
- path: z5.string().min(1).optional()
2589
+ var ProjectEntrySchema = z6.object({
2590
+ name: z6.string().min(1),
2591
+ description: z6.string().min(1).optional(),
2592
+ path: z6.string().min(1).optional()
1954
2593
  });
1955
2594
  function parseTokensCollectDeclaration(value) {
1956
2595
  const m = value.trim().match(/^(\S+)\s+(\S+)$/);
@@ -1961,90 +2600,101 @@ function parseTokensCollectDeclaration(value) {
1961
2600
  return null;
1962
2601
  return { interpreter, script };
1963
2602
  }
1964
- var VinayaConfigSchema = z5.object({
1965
- rings: z5.object({
1966
- ring1_forgeWriteInterception: z5.boolean(),
1967
- ring2_asyncAudits: z5.boolean()
2603
+ var VinayaConfigObjectSchema = z6.object({
2604
+ rings: z6.object({
2605
+ ring1_forgeWriteInterception: z6.boolean(),
2606
+ ring2_asyncAudits: z6.boolean()
1968
2607
  }).optional(),
1969
- checks: z5.record(z5.string(), CheckEntrySchema).optional(),
1970
- roles: z5.record(z5.string(), RoleEntrySchema).optional(),
2608
+ checks: z6.record(z6.string(), CheckEntrySchema).optional(),
2609
+ roles: z6.record(z6.string(), RoleEntrySchema).optional(),
1971
2610
  briefSchema: BriefSchemaSchema.optional(),
1972
2611
  managed: ManagedManifestSchema.optional(),
1973
- principals: z5.array(z5.string()).min(1).optional(),
1974
- releaseActor: z5.string().min(1).optional(),
1975
- ci: z5.object({ setup: z5.string().min(1) }).optional(),
1976
- tokens: z5.object({
1977
- collect: z5.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
2612
+ principals: z6.array(z6.string()).min(1).optional(),
2613
+ releaseActor: z6.string().min(1).optional(),
2614
+ ci: z6.object({ setup: z6.string().min(1) }).optional(),
2615
+ tokens: z6.object({
2616
+ collect: z6.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
1978
2617
  message: 'tokens.collect must be exactly "<interpreter> <repo-relative-script-path>" — two whitespace-separated tokens, no flags, no shell syntax, no quoting'
1979
2618
  })
1980
2619
  }).optional(),
1981
- blastRadius: z5.object({ extraDomains: z5.array(z5.string()).optional() }).optional(),
1982
- proseGates: z5.object({
1983
- doctrineRoot: z5.string().min(1).optional(),
1984
- readerFacingPrefix: z5.string().min(1).optional(),
1985
- readerFacingSuffix: z5.string().min(1).optional(),
1986
- legacySlugDir: z5.string().min(1).optional(),
1987
- sourceComments: z5.object({
1988
- globs: z5.array(z5.string().min(1)).optional(),
1989
- allowlist: z5.array(z5.string().min(1)).optional(),
1990
- severity: z5.enum(["warning", "error"]).optional()
2620
+ blastRadius: z6.object({ extraDomains: z6.array(z6.string()).optional() }).optional(),
2621
+ proseGates: z6.object({
2622
+ doctrineRoot: z6.string().min(1).optional(),
2623
+ readerFacingPrefix: z6.string().min(1).optional(),
2624
+ readerFacingSuffix: z6.string().min(1).optional(),
2625
+ legacySlugDir: z6.string().min(1).optional(),
2626
+ sourceComments: z6.object({
2627
+ globs: z6.array(z6.string().min(1)).optional(),
2628
+ allowlist: z6.array(z6.string().min(1)).optional(),
2629
+ severity: z6.enum(["warning", "error"]).optional()
1991
2630
  }).optional(),
1992
- specGrandfather: z5.union([z5.array(z5.string().min(1)), z5.record(z5.string().min(1), z5.number().int().min(0))]).optional(),
1993
- specPaths: z5.array(z5.string().min(1).refine((entry) => !entry.startsWith("/") && !/^[A-Za-z]:/.test(entry), {
1994
- message: "must be a repository-relative path, not an absolute one"
1995
- }).refine((entry) => !entry.split(/[\\/]/).includes(".."), {
1996
- message: "must stay inside the repository — no `..` segment"
1997
- })).optional()
2631
+ specGrandfather: z6.union([z6.array(z6.string().min(1)), z6.record(z6.string().min(1), z6.number().int().min(0))]).optional(),
2632
+ specPaths: z6.array(RepoRelativePathSchema).optional(),
2633
+ productPaths: z6.array(RepoRelativePathSchema).optional(),
2634
+ published: PublishedProseSchema.optional(),
2635
+ rules: ProseRulesSchema.optional()
1998
2636
  }).optional(),
1999
- projects: z5.array(ProjectEntrySchema).optional(),
2000
- dispatch: z5.object({
2001
- timeoutMs: z5.number().int().positive().optional(),
2002
- killGraceMs: z5.number().int().positive().optional(),
2003
- agent: z5.enum(["claude", "codex", "gemini"]).optional()
2637
+ projects: z6.array(ProjectEntrySchema).optional(),
2638
+ dispatch: z6.object({
2639
+ timeoutMs: z6.number().int().positive().optional(),
2640
+ reviewerTimeoutMs: z6.number().int().positive().optional(),
2641
+ killGraceMs: z6.number().int().positive().optional(),
2642
+ agent: z6.enum(["claude", "codex"]).optional()
2004
2643
  }).optional(),
2005
- reviewPolicy: z5.object({
2006
- codeReviewThreshold: z5.string().min(1).optional(),
2007
- securityThreshold: z5.string().min(1).optional(),
2008
- maxRounds: z5.number().optional(),
2009
- maxTaskMinutes: z5.number().optional()
2644
+ reviewPolicy: z6.object({
2645
+ codeReviewThreshold: z6.string().min(1).optional(),
2646
+ securityThreshold: z6.string().min(1).optional(),
2647
+ maxRounds: z6.number().optional(),
2648
+ maxTaskMinutes: z6.number().optional(),
2649
+ readyPushTimeoutMinutes: z6.number().optional()
2010
2650
  }).optional(),
2011
- securityScan: z5.object({
2012
- command: z5.array(z5.string().min(1)).min(1)
2651
+ securityScan: z6.object({
2652
+ command: z6.array(z6.string().min(1)).min(1)
2013
2653
  }).optional(),
2014
- gateCutovers: z5.object({
2015
- objectivesSinceIssue: z5.number().int().nonnegative().optional(),
2016
- briefSectionsSinceIssue: z5.number().int().nonnegative().optional(),
2017
- documentationSinceIssue: z5.number().int().nonnegative().optional(),
2018
- briefRulesSincePr: z5.number().int().nonnegative().optional(),
2019
- agentBoxesRefusedSincePr: z5.number().int().nonnegative().optional()
2654
+ gateCutovers: z6.object({
2655
+ objectivesSinceIssue: z6.number().int().nonnegative().optional(),
2656
+ briefSectionsSinceIssue: z6.number().int().nonnegative().optional(),
2657
+ documentationSinceIssue: z6.number().int().nonnegative().optional(),
2658
+ briefRulesSincePr: z6.number().int().nonnegative().optional(),
2659
+ agentBoxesRefusedSincePr: z6.number().int().nonnegative().optional()
2020
2660
  }).optional(),
2021
- planning: z5.object({
2022
- collisionThreshold: z5.number().int().nonnegative().optional()
2661
+ planning: z6.object({
2662
+ collisionThreshold: z6.number().int().nonnegative().optional()
2023
2663
  }).optional(),
2024
- prePush: z5.object({
2025
- alwaysRun: z5.array(z5.string()).optional()
2664
+ prePush: z6.object({
2665
+ alwaysRun: z6.array(z6.string()).optional(),
2666
+ readyTests: z6.object({
2667
+ mode: z6.literal("ci"),
2668
+ workflow: z6.literal(".github/workflows/ci.yml"),
2669
+ check: z6.literal("Vinaya CI")
2670
+ }).strict().optional(),
2671
+ requiredCi: z6.object({
2672
+ workflow: z6.literal(".github/workflows/ci.yml"),
2673
+ check: z6.literal("Vinaya CI")
2674
+ }).strict().optional()
2026
2675
  }).optional(),
2027
- report: z5.object({
2028
- commandTimeoutMs: z5.number().int().positive().optional()
2676
+ report: z6.object({
2677
+ commandTimeoutMs: z6.number().int().positive().optional()
2029
2678
  }).superRefine((report, ctx) => {
2030
2679
  const commandTimeoutMs = report.commandTimeoutMs;
2031
2680
  if (commandTimeoutMs !== undefined && commandTimeoutMs > MAX_REPORT_COMMAND_TIMEOUT_MS) {
2032
2681
  ctx.addIssue({
2033
- code: z5.ZodIssueCode.custom,
2682
+ code: z6.ZodIssueCode.custom,
2034
2683
  path: ["commandTimeoutMs"],
2035
2684
  message: "must be at most 3600000 (1 hour)"
2036
2685
  });
2037
2686
  }
2038
2687
  }).optional(),
2039
- logPublish: z5.unknown().refine((v) => v === undefined, {
2688
+ logPublish: z6.unknown().refine((v) => v === undefined, {
2040
2689
  message: "logPublish is removed — telemetry is never posted to a tracker or a code host; configure `logs` instead (a folder or a server destination)"
2041
2690
  }),
2042
- runtimeDir: z5.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
2043
- logs: z5.object({
2044
- folder: z5.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
2045
- url: z5.string().url().optional(),
2046
- headers: z5.record(z5.string()).optional(),
2047
- readHeaders: z5.record(z5.string()).optional(),
2691
+ runtimeDir: z6.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
2692
+ runner: z6.enum(["standalone", "atta-engine"]).optional(),
2693
+ logs: z6.object({
2694
+ folder: z6.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
2695
+ url: z6.string().url().optional(),
2696
+ headers: z6.record(z6.string()).optional(),
2697
+ readHeaders: z6.record(z6.string()).optional(),
2048
2698
  events: CustomEventDeclarationsSchema.optional()
2049
2699
  }).refine((v) => [v.folder, v.url].filter((x) => x !== undefined).length <= 1, {
2050
2700
  message: "logs: set at most one of folder/url"
@@ -2052,8 +2702,33 @@ var VinayaConfigSchema = z5.object({
2052
2702
  message: "logs: headers requires url"
2053
2703
  }).refine((v) => v.readHeaders === undefined || v.url !== undefined, {
2054
2704
  message: "logs: readHeaders requires url"
2055
- }).optional()
2705
+ }).or(z6.literal(false)).optional(),
2706
+ decisionRecords: z6.object({
2707
+ path: RepoRelativePathSchema
2708
+ }).strict().optional()
2709
+ });
2710
+ function decisionRecordsPathIssue(path, doctrineRoot) {
2711
+ const reason = outsideRepositoryReason(path);
2712
+ if (reason)
2713
+ return reason;
2714
+ const folder = normalizeSpecPath(path);
2715
+ if (folder === "" || folder === ".")
2716
+ return "must name a folder, not the repository root";
2717
+ const root = normalizeSpecPath(doctrineRoot ?? "aeg-root");
2718
+ if (folder === root || folder.startsWith(`${root}/`)) {
2719
+ return `must be outside the doctrine tree "${root}" — decision records belong to this repository, not to the doctrine it ships`;
2720
+ }
2721
+ return null;
2722
+ }
2723
+ var VinayaConfigSchema = VinayaConfigObjectSchema.superRefine((config, ctx) => {
2724
+ const path = config.decisionRecords?.path;
2725
+ if (path === undefined || outsideRepositoryReason(path))
2726
+ return;
2727
+ const issue = decisionRecordsPathIssue(path, config.proseGates?.doctrineRoot);
2728
+ if (issue)
2729
+ ctx.addIssue({ code: z6.ZodIssueCode.custom, path: ["decisionRecords", "path"], message: issue });
2056
2730
  });
2731
+ var VinayaConfigShape = VinayaConfigObjectSchema.shape;
2057
2732
  var GLOBAL_VINAYA_HOME = join2(homedir(), ".vinaya");
2058
2733
  var GLOBAL_CONFIG_PATH = join2(GLOBAL_VINAYA_HOME, "config.json");
2059
2734
  var LOCAL_CONFIG_FILENAME = "vinaya.config.json";
@@ -2134,6 +2809,7 @@ function stripGlobalOnlyKeys(config, path) {
2134
2809
  }
2135
2810
  return result;
2136
2811
  }
2812
+ var emittedLocalOverrideWarnings = new Set;
2137
2813
  function resolveRuntimeDirSetting(config) {
2138
2814
  return config?.runtimeDir ?? null;
2139
2815
  }
@@ -2227,13 +2903,14 @@ function readTrustAnchorConfigAtRef(ref) {
2227
2903
  });
2228
2904
  return Buffer.from(raw, "utf-8").toString("base64");
2229
2905
  }
2906
+ var NO_TRUST_ANCHOR_REPO_MESSAGE = "could not resolve repo identity for the trust-anchor read";
2230
2907
  function ghFetchTrustAnchorConfig() {
2231
2908
  const probeRef = resolveCiTrustAnchorProbeRef();
2232
2909
  if (probeRef)
2233
2910
  return readTrustAnchorConfigAtRef(probeRef);
2234
2911
  const repo = trustAnchorRepo();
2235
2912
  if (!repo)
2236
- throw new Error("could not resolve repo identity for the trust-anchor read");
2913
+ throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
2237
2914
  return execFileSync2("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], {
2238
2915
  encoding: "utf-8",
2239
2916
  stdio: ["ignore", "pipe", "pipe"]
@@ -2250,7 +2927,7 @@ async function ghFetchTrustAnchorConfigAsync() {
2250
2927
  }
2251
2928
  const repo = await trustAnchorRepoAsync();
2252
2929
  if (!repo)
2253
- throw new Error("could not resolve repo identity for the trust-anchor read");
2930
+ throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
2254
2931
  const { stdout } = await execFileAsync4("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], { encoding: "utf-8", timeout: 1e4, killSignal: "SIGKILL" });
2255
2932
  return stdout;
2256
2933
  }
@@ -2315,79 +2992,649 @@ function loadConfig() {
2315
2992
  const path = configPath();
2316
2993
  if (!path)
2317
2994
  return null;
2995
+ let text;
2318
2996
  try {
2319
- const raw = JSON.parse(readFileSync3(path, "utf-8"));
2320
- return stripGlobalOnlyKeys(VinayaConfigSchema.parse(raw), path);
2321
- } catch {
2997
+ text = readFileSync3(path, "utf-8");
2998
+ } catch (err) {
2999
+ reportInvalidConfigOnce(path, `unreadable: ${err.message}`);
3000
+ return null;
3001
+ }
3002
+ let raw;
3003
+ try {
3004
+ raw = JSON.parse(text);
3005
+ } catch (err) {
3006
+ reportInvalidConfigOnce(path, `invalid JSON: ${err.message}`);
3007
+ return null;
3008
+ }
3009
+ const parsed = VinayaConfigSchema.safeParse(raw);
3010
+ if (!parsed.success) {
3011
+ reportInvalidConfigOnce(path, schemaIssueDetail(parsed.error));
2322
3012
  return null;
2323
3013
  }
3014
+ return stripGlobalOnlyKeys(parsed.data, path);
3015
+ }
3016
+ function schemaIssueDetail(error) {
3017
+ return error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
3018
+ }
3019
+ var emittedInvalidConfigReports = new Set;
3020
+ function reportInvalidConfigOnce(path, detail) {
3021
+ const key = `${path}
3022
+ ${detail}`;
3023
+ if (emittedInvalidConfigReports.has(key))
3024
+ return;
3025
+ emittedInvalidConfigReports.add(key);
3026
+ const message = `${path} is not a valid Vinaya configuration (${detail}) — falling back to built-in defaults.`;
3027
+ const checkName = process.env.VINAYA_CHECK_NAME;
3028
+ if (checkName) {
3029
+ emitCheckError({
3030
+ schema: CHECK_SCHEMA_VERSION,
3031
+ check: checkName,
3032
+ severity: "warning",
3033
+ message,
3034
+ agent_recovery_prompt: `Fix the failing keys in ${path} (${detail}) so the file parses and satisfies the configuration schema, then re-run.`,
3035
+ file: path
3036
+ });
3037
+ return;
3038
+ }
3039
+ console.error(`⚠ ${message}`);
2324
3040
  }
2325
3041
  var TOKENS_COLLECT_TRUST_PATH = join2(GLOBAL_VINAYA_HOME, "tokens-collect-trust.json");
2326
3042
 
2327
- // src/lib/remote-base.ts
3043
+ // src/lib/pre-push-failed-tests.ts
2328
3044
  import { execFileSync as execFileSync3 } from "node:child_process";
2329
- import { join as join3 } from "node:path";
2330
- function cleanGitEnv() {
2331
- const env = { ...process.env };
2332
- for (const key of Object.keys(env)) {
2333
- if (key.startsWith("GIT_"))
2334
- delete env[key];
3045
+ import { createHash as createHash2 } from "node:crypto";
3046
+ import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync4, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
3047
+ import { dirname as dirname3, isAbsolute as isAbsolute2, join as join3 } from "node:path";
3048
+ var FAILED_TESTS_RECORD = "vinaya/pre-push-failed-tests.json";
3049
+ var LAST_PUSH_RESULT = "vinaya/pre-push-last-result.json";
3050
+ var SELECTION_NOTE = "vinaya/pre-push-selection.json";
3051
+ var TEST_SELECTION_COMPLETE = "vinaya-test-selection-complete ";
3052
+ function completedTestSelection(log, cwd, expected) {
3053
+ const completed = new Set;
3054
+ let batch = [];
3055
+ let markers = 0;
3056
+ const absolute = (path) => isAbsolute2(path) ? path : join3(cwd, path);
3057
+ for (const line of log.split(`
3058
+ `)) {
3059
+ if (!line.startsWith(TEST_SELECTION_COMPLETE)) {
3060
+ batch.push(line);
3061
+ continue;
3062
+ }
3063
+ try {
3064
+ const result = JSON.parse(line.slice(TEST_SELECTION_COMPLETE.length));
3065
+ if (![0, 1].includes(result.exitCode) || !Array.isArray(result.files) || !result.files.every((file) => typeof file === "string"))
3066
+ return false;
3067
+ const text = batch.join(`
3068
+ `);
3069
+ const summary = [...text.matchAll(/^Ran \d+ tests? across (\d+) files?\.(?:.*)$/gm)].at(-1);
3070
+ const headers = new Set([...text.matchAll(/^(\S.*\.test\.[a-zA-Z]+):$/gm)].map((match) => absolute(match[1])));
3071
+ const files = new Set(result.files.map(absolute));
3072
+ if (!summary || Number(summary[1]) !== files.size || headers.size !== files.size || [...files].some((file) => !headers.has(file)))
3073
+ return false;
3074
+ for (const file of files)
3075
+ completed.add(file);
3076
+ markers++;
3077
+ batch = [];
3078
+ } catch {
3079
+ return false;
3080
+ }
2335
3081
  }
2336
- return env;
3082
+ if (markers === 0 || batch.join(`
3083
+ `).trim() !== "")
3084
+ return false;
3085
+ return expected === undefined || new Set(expected.map(absolute)).size === completed.size && expected.every((file) => completed.has(absolute(file)));
2337
3086
  }
2338
- function git(repoRoot, args) {
2339
- try {
2340
- return execFileSync3("git", args, {
2341
- cwd: repoRoot,
2342
- encoding: "utf8",
2343
- stdio: ["ignore", "pipe", "ignore"],
2344
- env: cleanGitEnv()
2345
- }).trim();
2346
- } catch {
2347
- return "";
3087
+ function parseFailedTestFiles(log, cwd, exitedNonZero, selected) {
3088
+ if (exitedNonZero && !completedTestSelection(log, cwd, selected))
3089
+ return "all";
3090
+ const failed = new Set;
3091
+ let current = null;
3092
+ for (const raw of log.split(`
3093
+ `)) {
3094
+ const line = raw.trimEnd();
3095
+ if (/^\d+ tests? failed:/.test(line)) {
3096
+ current = null;
3097
+ continue;
3098
+ }
3099
+ const header = /^(\S.*\.test\.[a-zA-Z]+):$/.exec(line);
3100
+ if (header?.[1]) {
3101
+ current = isAbsolute2(header[1]) ? header[1] : join3(cwd, header[1]);
3102
+ continue;
3103
+ }
3104
+ if (current && (/^\(fail\) /.test(line) || line.startsWith("# Unhandled error")))
3105
+ failed.add(current);
2348
3106
  }
3107
+ if (failed.size === 0)
3108
+ return exitedNonZero ? "all" : [];
3109
+ return [...failed].sort();
2349
3110
  }
2350
- function resolveRemoteBase(repoRoot) {
2351
- const upstream = git(repoRoot, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]);
2352
- if (upstream)
2353
- return upstream;
2354
- const originMain = git(repoRoot, ["rev-parse", "--verify", "--quiet", "origin/main"]);
2355
- if (originMain)
2356
- return "origin/main";
2357
- return "HEAD~1";
2358
- }
2359
- function changedFilesSinceRemoteBase(repoRoot, base = resolveRemoteBase(repoRoot)) {
2360
- const out = git(repoRoot, ["diff", "--name-only", "--diff-filter=ACMR", `${base}...HEAD`]);
2361
- return out.split(`
2362
- `).map((s) => s.trim()).filter(Boolean);
3111
+ function chooseTests(inputs) {
3112
+ const { record, head, branch, fullSelection } = inputs;
3113
+ const full = {
3114
+ version: 1,
3115
+ mode: "full",
3116
+ head,
3117
+ fullCount: fullSelection.length,
3118
+ selected: fullSelection
3119
+ };
3120
+ if (!record || record.failed === "all" || record.selectionCompleted !== true)
3121
+ return full;
3122
+ if (record.branch !== branch || !inputs.recordIsAncestor)
3123
+ return full;
3124
+ if (!record.failed.every(inputs.exists))
3125
+ return full;
3126
+ const rerunFailed = [...record.failed];
3127
+ const affectedSince = inputs.affectedSince.filter(inputs.exists).sort();
3128
+ const selected = [...new Set([...rerunFailed, ...affectedSince])].sort();
3129
+ if (selected.length === 0)
3130
+ return full;
3131
+ return {
3132
+ version: 1,
3133
+ mode: "rerun",
3134
+ head,
3135
+ rerunOf: record.head,
3136
+ recordedHead: record.head,
3137
+ rerunFailed,
3138
+ affectedSince,
3139
+ fullCount: fullSelection.length,
3140
+ selected
3141
+ };
2363
3142
  }
2364
- function changedFilesSinceRemoteBaseAbsolute(repoRoot, base = resolveRemoteBase(repoRoot)) {
2365
- return changedFilesSinceRemoteBase(repoRoot, base).map((f) => join3(repoRoot, f));
3143
+ function recordFromRun(outcome, failed, head, branch, now) {
3144
+ if (outcome === "passed")
3145
+ return null;
3146
+ return { version: 1, head, branch, failed, recordedAt: now.toISOString(), selectionCompleted: failed !== "all" };
2366
3147
  }
2367
- function addedOrRenamedFilesSinceRemoteBase(repoRoot, base = resolveRemoteBase(repoRoot)) {
2368
- const out = git(repoRoot, ["diff", "--name-only", "--diff-filter=AR", `${base}...HEAD`]);
2369
- return out.split(`
2370
- `).map((s) => s.trim()).filter(Boolean);
3148
+ function parseRecord(text) {
3149
+ if (!text)
3150
+ return null;
3151
+ try {
3152
+ const value = JSON.parse(text);
3153
+ if (value.version !== 1 || typeof value.head !== "string" || typeof value.branch !== "string")
3154
+ return null;
3155
+ if (value.failed !== "all" && !Array.isArray(value.failed))
3156
+ return null;
3157
+ return value;
3158
+ } catch {
3159
+ return null;
3160
+ }
3161
+ }
3162
+ var PASSING_RECORD_VERSION = 2;
3163
+ var SELECTION_POLICY = {
3164
+ name: "pre-push-since-green",
3165
+ version: 1,
3166
+ depth: "one",
3167
+ testTimeoutMs: 30000,
3168
+ rootConfigFile: "vinaya.config.json"
3169
+ };
3170
+ var VERIFICATION_LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "yarn.lock", "pnpm-lock.yaml"];
3171
+ var VERIFICATION_INPUT_FILES = ["vinaya.config.json", "package.json", "bunfig.toml", ...VERIFICATION_LOCKFILES];
3172
+ var VERIFICATION_ENV_KEYS = ["BUN_ENV", "CI", "NODE_ENV", "NODE_OPTIONS", "TZ"];
3173
+ function parsePassingRecord(text) {
3174
+ if (!text)
3175
+ return null;
3176
+ try {
3177
+ const value = JSON.parse(text);
3178
+ if (value.version !== PASSING_RECORD_VERSION || value.kind !== "passed")
3179
+ return null;
3180
+ if (typeof value.head !== "string" || typeof value.branch !== "string" || typeof value.context !== "string")
3181
+ return null;
3182
+ if (!Array.isArray(value.selection) || !value.selection.every((file) => typeof file === "string"))
3183
+ return null;
3184
+ return value;
3185
+ } catch {
3186
+ return null;
3187
+ }
3188
+ }
3189
+ function parseSelectionNote(text, head) {
3190
+ if (!text)
3191
+ return null;
3192
+ try {
3193
+ const value = JSON.parse(text);
3194
+ if (value.head !== head || !Array.isArray(value.selected))
3195
+ return null;
3196
+ if (!value.selected.every((file) => typeof file === "string"))
3197
+ return null;
3198
+ return { mode: "full", ...value };
3199
+ } catch {
3200
+ return null;
3201
+ }
3202
+ }
3203
+ function passingRecordFromRun(inputs) {
3204
+ const { selection, head, branch } = inputs;
3205
+ if (inputs.outcome !== "passed" || !selection || selection.head !== head)
3206
+ return null;
3207
+ if (selection.selected.length === 0 || !head || !branch || branch === "HEAD")
3208
+ return null;
3209
+ if (!selection.context || inputs.context !== selection.context || inputs.inputsClean !== true)
3210
+ return null;
3211
+ if (!completedTestSelection(inputs.log, inputs.repoRoot, selection.selected))
3212
+ return null;
3213
+ return {
3214
+ version: PASSING_RECORD_VERSION,
3215
+ kind: "passed",
3216
+ head,
3217
+ branch,
3218
+ selection: [...selection.selected],
3219
+ selectionCompleted: true,
3220
+ context: selection.context,
3221
+ recordedAt: inputs.now.toISOString()
3222
+ };
3223
+ }
3224
+ function decideSelection(deps) {
3225
+ const context = deps.context !== null && deps.inputsClean === true ? deps.context : null;
3226
+ const withContext = (note) => context === null ? note : { ...note, context };
3227
+ const sinceGreen = deps.failed === null ? sinceGreenNote(deps, context) : null;
3228
+ if (sinceGreen)
3229
+ return { note: withContext(sinceGreen), full: null };
3230
+ const full = deps.full();
3231
+ const record = deps.failed;
3232
+ const recordIsAncestor = record ? deps.isAncestor(record.head) : false;
3233
+ let usable = record;
3234
+ let affectedSince = [];
3235
+ if (record && record.failed !== "all" && recordIsAncestor && record.branch === deps.branch) {
3236
+ const changed = deps.changedBetween(record.head);
3237
+ if (changed === null)
3238
+ usable = null;
3239
+ else
3240
+ affectedSince = deps.affectedSince(changed);
3241
+ }
3242
+ const note = chooseTests({
3243
+ record: usable,
3244
+ head: deps.head,
3245
+ branch: deps.branch,
3246
+ recordIsAncestor,
3247
+ fullSelection: full.selected,
3248
+ affectedSince,
3249
+ exists: deps.exists
3250
+ });
3251
+ return { note: withContext(note), full };
3252
+ }
3253
+ function sinceGreenNote(deps, context) {
3254
+ const passing = deps.passing;
3255
+ if (!passing || passing.selectionCompleted !== true || passing.selection.length === 0)
3256
+ return null;
3257
+ if (passing.branch !== deps.branch || context === null || passing.context !== context)
3258
+ return null;
3259
+ if (!deps.isAncestor(passing.head))
3260
+ return null;
3261
+ const changed = deps.changedBetween(passing.head);
3262
+ if (changed === null || changed.includes(join3(deps.repoRoot, SELECTION_POLICY.rootConfigFile)))
3263
+ return null;
3264
+ const read = deps.sinceGreen(passing.head);
3265
+ if (read.readFailed)
3266
+ return null;
3267
+ const selected = [...new Set(read.selected)].filter(deps.exists).sort();
3268
+ const affectedSince = selected.filter((file) => !deps.isAlwaysRun(file) || changed.includes(file));
3269
+ if (changed.length > 0 && affectedSince.length === 0)
3270
+ return null;
3271
+ return {
3272
+ version: 1,
3273
+ mode: "since-green",
3274
+ head: deps.head,
3275
+ recordedHead: passing.head,
3276
+ affectedSince,
3277
+ fullCount: null,
3278
+ selected
3279
+ };
3280
+ }
3281
+ function cleanGitEnv() {
3282
+ const env = { ...process.env };
3283
+ for (const key of Object.keys(env))
3284
+ if (key.startsWith("GIT_"))
3285
+ delete env[key];
3286
+ return env;
3287
+ }
3288
+ function git(repoRoot, args) {
3289
+ try {
3290
+ return execFileSync3("git", args, {
3291
+ cwd: repoRoot,
3292
+ encoding: "utf8",
3293
+ stdio: ["ignore", "pipe", "ignore"],
3294
+ env: cleanGitEnv()
3295
+ }).trim();
3296
+ } catch {
3297
+ return null;
3298
+ }
3299
+ }
3300
+ function gitPath(repoRoot, name) {
3301
+ const out = git(repoRoot, ["rev-parse", "--git-path", name]);
3302
+ if (!out)
3303
+ return null;
3304
+ return isAbsolute2(out) ? out : join3(repoRoot, out);
2371
3305
  }
2372
- function addedOrRenamedFilesSinceRemoteBaseAbsolute(repoRoot, base = resolveRemoteBase(repoRoot)) {
2373
- return addedOrRenamedFilesSinceRemoteBase(repoRoot, base).map((f) => join3(repoRoot, f));
3306
+ function currentHead(repoRoot) {
3307
+ return git(repoRoot, ["rev-parse", "HEAD"]) ?? "";
3308
+ }
3309
+ function currentBranch(repoRoot) {
3310
+ return git(repoRoot, ["rev-parse", "--abbrev-ref", "HEAD"]) ?? "";
3311
+ }
3312
+ function isAncestor(repoRoot, ancestor, head) {
3313
+ try {
3314
+ execFileSync3("git", ["merge-base", "--is-ancestor", ancestor, head], {
3315
+ cwd: repoRoot,
3316
+ stdio: "ignore",
3317
+ env: cleanGitEnv()
3318
+ });
3319
+ return true;
3320
+ } catch {
3321
+ return false;
3322
+ }
3323
+ }
3324
+ function changedBetween(repoRoot, from, to) {
3325
+ const read = git(repoRoot, ["diff", "--name-only", "--diff-filter=ACMRD", from, to]);
3326
+ if (read === null)
3327
+ return null;
3328
+ return read.split(`
3329
+ `).map((s) => s.trim()).filter(Boolean).map((f) => join3(repoRoot, f));
3330
+ }
3331
+ function readJsonUnderGit(repoRoot, name) {
3332
+ const path = gitPath(repoRoot, name);
3333
+ if (!path || !existsSync3(path))
3334
+ return null;
3335
+ try {
3336
+ return readFileSync4(path, "utf8");
3337
+ } catch {
3338
+ return null;
3339
+ }
3340
+ }
3341
+ function writeJsonUnderGit(repoRoot, name, value) {
3342
+ const path = gitPath(repoRoot, name);
3343
+ if (!path)
3344
+ return;
3345
+ mkdirSync3(dirname3(path), { recursive: true });
3346
+ writeFileSync2(path, `${JSON.stringify(value, null, 2)}
3347
+ `);
3348
+ }
3349
+ function removeUnderGit(repoRoot, name) {
3350
+ const path = gitPath(repoRoot, name);
3351
+ if (path)
3352
+ rmSync(path, { force: true });
3353
+ }
3354
+ function readFailedTestsRecord(repoRoot) {
3355
+ return parseRecord(readJsonUnderGit(repoRoot, FAILED_TESTS_RECORD));
3356
+ }
3357
+ function readPassingRecord(repoRoot) {
3358
+ return parsePassingRecord(readJsonUnderGit(repoRoot, FAILED_TESTS_RECORD));
3359
+ }
3360
+ function clearRecordOfKind(repoRoot, kind) {
3361
+ const text = readJsonUnderGit(repoRoot, FAILED_TESTS_RECORD);
3362
+ const other = kind === "failed" ? parsePassingRecord(text) : parseRecord(text);
3363
+ if (text !== null && other !== null)
3364
+ return;
3365
+ removeUnderGit(repoRoot, FAILED_TESTS_RECORD);
3366
+ }
3367
+ function computeVerificationContext(repoRoot, env = process.env) {
3368
+ try {
3369
+ const sha = (data) => createHash2("sha256").update(data).digest("hex");
3370
+ const read = (name) => {
3371
+ const path = join3(repoRoot, name);
3372
+ return existsSync3(path) ? readFileSync4(path) : null;
3373
+ };
3374
+ const json = (name) => {
3375
+ const bytes = read(name);
3376
+ return bytes === null ? null : JSON.parse(bytes.toString("utf8"));
3377
+ };
3378
+ const config = json("vinaya.config.json");
3379
+ const pkg = json("package.json");
3380
+ const scripts = pkg?.scripts;
3381
+ const bunfig = read("bunfig.toml");
3382
+ const parts = {
3383
+ policy: sha(JSON.stringify(SELECTION_POLICY)),
3384
+ inputs: sha(JSON.stringify({ prePush: config?.prePush ?? null, workspaces: pkg?.workspaces ?? null })),
3385
+ lockfile: sha(VERIFICATION_LOCKFILES.map((name) => {
3386
+ const bytes = read(name);
3387
+ return `${name}:${bytes === null ? "absent" : sha(bytes)}`;
3388
+ }).join(`
3389
+ `)),
3390
+ runner: sha(JSON.stringify({
3391
+ bunfig: bunfig === null ? null : sha(bunfig),
3392
+ testScript: scripts?.test ?? null,
3393
+ bun: process.versions.bun ?? null
3394
+ })),
3395
+ environment: sha(VERIFICATION_ENV_KEYS.map((key) => `${key}=${env[key] ?? "\x00unset"}`).join(`
3396
+ `))
3397
+ };
3398
+ return { digest: sha(JSON.stringify(parts)), parts };
3399
+ } catch {
3400
+ return null;
3401
+ }
3402
+ }
3403
+ function verificationInputsDirty(repoRoot) {
3404
+ const out = git(repoRoot, ["status", "--porcelain", "--", ...VERIFICATION_INPUT_FILES]);
3405
+ return out === null ? null : out !== "";
3406
+ }
3407
+
3408
+ // src/lib/verification/changed-names.ts
3409
+ var ALL_NAMES = "all";
3410
+ var PARSEABLE = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
3411
+ function namesForRanges(ts, fileName, source, ranges) {
3412
+ if (ranges.length === 0)
3413
+ return new Set;
3414
+ const sourceFile = ts.createSourceFile(fileName, source, ts.ScriptTarget.ES2022, true);
3415
+ const lineOf = (pos) => sourceFile.getLineAndCharacterOfPosition(pos).line + 1;
3416
+ const declarations = [];
3417
+ const declarationStart = (statement) => {
3418
+ const comments = ts.getLeadingCommentRanges(source, statement.getFullStart());
3419
+ return comments && comments.length > 0 ? comments[0].pos : statement.getStart(sourceFile);
3420
+ };
3421
+ for (const statement of sourceFile.statements) {
3422
+ const span = { start: lineOf(declarationStart(statement)), end: lineOf(statement.getEnd()) };
3423
+ if (ts.isVariableStatement(statement)) {
3424
+ for (const declaration of statement.declarationList.declarations) {
3425
+ declarations.push({
3426
+ name: ts.isIdentifier(declaration.name) ? declaration.name.text : null,
3427
+ ...span,
3428
+ node: statement
3429
+ });
3430
+ }
3431
+ continue;
3432
+ }
3433
+ if (ts.isExportDeclaration(statement) && statement.exportClause && ts.isNamedExports(statement.exportClause)) {
3434
+ const clause = statement.exportClause;
3435
+ const local = statement.moduleSpecifier === undefined;
3436
+ declarations.push({
3437
+ name: null,
3438
+ ...span,
3439
+ node: statement,
3440
+ exportList: {
3441
+ open: lineOf(clause.getStart(sourceFile)),
3442
+ close: lineOf(clause.getEnd()),
3443
+ specifiers: clause.elements.map((element) => ({
3444
+ exported: element.name.text,
3445
+ local: local ? (element.propertyName ?? element.name).text : null,
3446
+ start: lineOf(element.getStart(sourceFile)),
3447
+ end: lineOf(element.getEnd())
3448
+ }))
3449
+ }
3450
+ });
3451
+ continue;
3452
+ }
3453
+ const named = ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement) || ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) || ts.isEnumDeclaration(statement) || ts.isModuleDeclaration(statement);
3454
+ const name = named && statement.name && ts.isIdentifier(statement.name) ? statement.name.text : null;
3455
+ declarations.push({ name, ...span, node: statement });
3456
+ }
3457
+ const topLevelNames = new Set(declarations.map((d) => d.name).filter((n) => n !== null));
3458
+ const seeded = new Set;
3459
+ for (const range of ranges) {
3460
+ if (range.end < range.start)
3461
+ continue;
3462
+ const overlapping = declarations.filter((d) => d.start <= range.end && range.start <= d.end);
3463
+ if (overlapping.length === 0)
3464
+ return null;
3465
+ for (const d of overlapping) {
3466
+ if (d.exportList) {
3467
+ const list = d.exportList;
3468
+ for (let line = Math.max(range.start, d.start);line <= Math.min(range.end, d.end); line++) {
3469
+ if (line <= list.open || line >= list.close)
3470
+ return null;
3471
+ const onLine = list.specifiers.filter((s) => s.start <= line && line <= s.end);
3472
+ if (onLine.length === 0)
3473
+ return null;
3474
+ for (const s of onLine)
3475
+ seeded.add(s.exported);
3476
+ }
3477
+ continue;
3478
+ }
3479
+ if (d.name === null)
3480
+ return null;
3481
+ seeded.add(d.name);
3482
+ }
3483
+ }
3484
+ const references = new Map;
3485
+ for (const d of declarations) {
3486
+ if (d.name === null)
3487
+ continue;
3488
+ const used = references.get(d.name) ?? new Set;
3489
+ const visit = (node) => {
3490
+ if (ts.isIdentifier(node) && node.text !== d.name && topLevelNames.has(node.text))
3491
+ used.add(node.text);
3492
+ ts.forEachChild(node, visit);
3493
+ };
3494
+ ts.forEachChild(d.node, visit);
3495
+ references.set(d.name, used);
3496
+ }
3497
+ for (const d of declarations) {
3498
+ for (const s of d.exportList?.specifiers ?? []) {
3499
+ if (s.local === null || s.local === s.exported || !topLevelNames.has(s.local))
3500
+ continue;
3501
+ const used = references.get(s.exported) ?? new Set;
3502
+ used.add(s.local);
3503
+ references.set(s.exported, used);
3504
+ }
3505
+ }
3506
+ const affected = new Set(seeded);
3507
+ for (let grew = true;grew; ) {
3508
+ grew = false;
3509
+ for (const [name, used] of references) {
3510
+ if (affected.has(name))
3511
+ continue;
3512
+ for (const u of used) {
3513
+ if (!affected.has(u))
3514
+ continue;
3515
+ affected.add(name);
3516
+ grew = true;
3517
+ break;
3518
+ }
3519
+ }
3520
+ }
3521
+ return affected;
2374
3522
  }
2375
- function removedFilesSinceRemoteBase(repoRoot, base = resolveRemoteBase(repoRoot)) {
2376
- const out = git(repoRoot, ["diff", "--name-status", "--diff-filter=DR", `${base}...HEAD`]);
3523
+ function affectedNamesForFile(ts, diff) {
3524
+ if (!PARSEABLE.some((ext) => diff.file.endsWith(ext)))
3525
+ return ALL_NAMES;
3526
+ const names = new Set;
3527
+ for (const [source, ranges] of [
3528
+ [diff.after, diff.afterRanges],
3529
+ [diff.before, diff.beforeRanges]
3530
+ ]) {
3531
+ if (source === null) {
3532
+ if (ranges.some((r) => r.end >= r.start))
3533
+ return ALL_NAMES;
3534
+ continue;
3535
+ }
3536
+ let attributed;
3537
+ try {
3538
+ attributed = namesForRanges(ts, diff.file, source, ranges);
3539
+ } catch {
3540
+ attributed = null;
3541
+ }
3542
+ if (attributed === null)
3543
+ return ALL_NAMES;
3544
+ for (const n of attributed)
3545
+ names.add(n);
3546
+ }
3547
+ return names;
3548
+ }
3549
+ function affectedNames(ts, diffs) {
3550
+ const out = new Map;
3551
+ for (const diff of diffs)
3552
+ out.set(diff.file, affectedNamesForFile(ts, diff));
3553
+ return out;
3554
+ }
3555
+ function parseHunkRanges(patch) {
3556
+ const beforeRanges = [];
3557
+ const afterRanges = [];
3558
+ const header = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/gm;
3559
+ for (let m = header.exec(patch);m !== null; m = header.exec(patch)) {
3560
+ const oldStart = Number(m[1]);
3561
+ const oldCount = m[2] === undefined ? 1 : Number(m[2]);
3562
+ const newStart = Number(m[3]);
3563
+ const newCount = m[4] === undefined ? 1 : Number(m[4]);
3564
+ beforeRanges.push({ start: oldStart, end: oldStart + oldCount - 1 });
3565
+ afterRanges.push({ start: newStart, end: newStart + newCount - 1 });
3566
+ }
3567
+ return { beforeRanges, afterRanges };
3568
+ }
3569
+ // src/lib/remote-base.ts
3570
+ import { execFileSync as execFileSync4 } from "node:child_process";
3571
+ import { join as join4 } from "node:path";
3572
+ function cleanGitEnv2() {
3573
+ const env = { ...process.env };
3574
+ for (const key of Object.keys(env)) {
3575
+ if (key.startsWith("GIT_"))
3576
+ delete env[key];
3577
+ }
3578
+ return env;
3579
+ }
3580
+ function git2(repoRoot, args, failure) {
3581
+ try {
3582
+ return execFileSync4("git", args, {
3583
+ cwd: repoRoot,
3584
+ encoding: "utf8",
3585
+ stdio: ["ignore", "pipe", "ignore"],
3586
+ env: cleanGitEnv2()
3587
+ }).trim();
3588
+ } catch {
3589
+ if (failure)
3590
+ failure.failed = true;
3591
+ return "";
3592
+ }
3593
+ }
3594
+ function resolveRemoteBase(repoRoot) {
3595
+ const named = process.env.VINAYA_PUSH_MODE?.trim() === "ready" ? process.env.VINAYA_PUSH_BASE?.trim() : undefined;
3596
+ if (named)
3597
+ return named;
3598
+ const upstream = git2(repoRoot, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]);
3599
+ if (upstream)
3600
+ return upstream;
3601
+ const originMain = git2(repoRoot, ["rev-parse", "--verify", "--quiet", "origin/main"]);
3602
+ if (originMain)
3603
+ return "origin/main";
3604
+ return "HEAD~1";
3605
+ }
3606
+ function changedFilesSinceRemoteBase(repoRoot, base = resolveRemoteBase(repoRoot), failure) {
3607
+ const out = git2(repoRoot, ["diff", "--name-only", "--diff-filter=ACMR", `${base}...HEAD`], failure);
3608
+ return out.split(`
3609
+ `).map((s) => s.trim()).filter(Boolean);
3610
+ }
3611
+ function changedFilesSinceRemoteBaseAbsolute(repoRoot, base = resolveRemoteBase(repoRoot), failure) {
3612
+ return changedFilesSinceRemoteBase(repoRoot, base, failure).map((f) => join4(repoRoot, f));
3613
+ }
3614
+ function addedOrRenamedFilesSinceRemoteBase(repoRoot, base = resolveRemoteBase(repoRoot), failure) {
3615
+ const out = git2(repoRoot, ["diff", "--name-only", "--diff-filter=AR", `${base}...HEAD`], failure);
3616
+ return out.split(`
3617
+ `).map((s) => s.trim()).filter(Boolean);
3618
+ }
3619
+ function addedOrRenamedFilesSinceRemoteBaseAbsolute(repoRoot, base = resolveRemoteBase(repoRoot), failure) {
3620
+ return addedOrRenamedFilesSinceRemoteBase(repoRoot, base, failure).map((f) => join4(repoRoot, f));
3621
+ }
3622
+ function removedFilesSinceRemoteBase(repoRoot, base = resolveRemoteBase(repoRoot), failure) {
3623
+ const out = git2(repoRoot, ["diff", "--name-status", "--diff-filter=DR", `${base}...HEAD`], failure);
2377
3624
  return out.split(`
2378
3625
  `).map((line) => line.split("\t")).filter((fields) => fields.length >= 2).map((fields) => fields[1].trim()).filter(Boolean);
2379
3626
  }
2380
- function removedFilesSinceRemoteBaseAbsolute(repoRoot, base = resolveRemoteBase(repoRoot)) {
2381
- return removedFilesSinceRemoteBase(repoRoot, base).map((f) => join3(repoRoot, f));
3627
+ function removedFilesSinceRemoteBaseAbsolute(repoRoot, base = resolveRemoteBase(repoRoot), failure) {
3628
+ return removedFilesSinceRemoteBase(repoRoot, base, failure).map((f) => join4(repoRoot, f));
2382
3629
  }
2383
- function changedFileDiffsSinceRemoteBase(repoRoot, base = resolveRemoteBase(repoRoot)) {
2384
- const mergeBase = git(repoRoot, ["merge-base", base, "HEAD"]) || base;
3630
+ function changedFileDiffsSinceRemoteBase(repoRoot, base = resolveRemoteBase(repoRoot), failure) {
3631
+ const mergeBase = git2(repoRoot, ["merge-base", base, "HEAD"], failure) || base;
2385
3632
  const out = [];
2386
- for (const relative of changedFilesSinceRemoteBase(repoRoot, base)) {
2387
- const patch = git(repoRoot, ["diff", "-U0", `${mergeBase}..HEAD`, "--", relative]);
3633
+ for (const relative of changedFilesSinceRemoteBase(repoRoot, base, failure)) {
3634
+ const patch = git2(repoRoot, ["diff", "-U0", `${mergeBase}..HEAD`, "--", relative], failure);
2388
3635
  const { beforeRanges, afterRanges } = parseHunkRanges(patch);
2389
3636
  out.push({
2390
- file: join3(repoRoot, relative),
3637
+ file: join4(repoRoot, relative),
2391
3638
  after: showBlob(repoRoot, "HEAD", relative),
2392
3639
  before: showBlob(repoRoot, mergeBase, relative),
2393
3640
  beforeRanges,
@@ -2398,24 +3645,20 @@ function changedFileDiffsSinceRemoteBase(repoRoot, base = resolveRemoteBase(repo
2398
3645
  }
2399
3646
  function showBlob(repoRoot, ref, relative) {
2400
3647
  try {
2401
- return execFileSync3("git", ["show", `${ref}:${relative}`], {
3648
+ return execFileSync4("git", ["show", `${ref}:${relative}`], {
2402
3649
  cwd: repoRoot,
2403
3650
  encoding: "utf8",
2404
3651
  maxBuffer: 64 * 1024 * 1024,
2405
3652
  stdio: ["ignore", "pipe", "ignore"],
2406
- env: cleanGitEnv()
3653
+ env: cleanGitEnv2()
2407
3654
  });
2408
3655
  } catch {
2409
3656
  return null;
2410
3657
  }
2411
3658
  }
2412
3659
 
2413
- // src/lib/test-selector.ts
2414
- import { readdirSync as readdirSync2, readFileSync as readFileSync4, statSync as statSync2 } from "node:fs";
2415
- import { dirname as dirname6, extname, isAbsolute as isAbsolute4, join as join7, resolve as resolve6 } from "node:path";
2416
-
2417
- // src/lib/cli-spawn-tests.ts
2418
- import { dirname as dirname3, isAbsolute as isAbsolute2, join as join4, resolve as resolve3 } from "node:path";
3660
+ // src/lib/verification/spawn-inputs.ts
3661
+ import { dirname as dirname4, isAbsolute as isAbsolute3, join as join5, resolve as resolve3 } from "node:path";
2419
3662
  function evaluateExpression(ts, node, file, fileDir, repoRoot, bindings) {
2420
3663
  if (ts.isStringLiteral(node))
2421
3664
  return node.text;
@@ -2436,7 +3679,7 @@ function evaluateExpression(ts, node, file, fileDir, repoRoot, bindings) {
2436
3679
  if (callee === "dirname") {
2437
3680
  const arg = node.arguments[0];
2438
3681
  const inner = arg ? evaluateExpression(ts, arg, file, fileDir, repoRoot, bindings) : null;
2439
- return inner !== null ? dirname3(inner) : null;
3682
+ return inner !== null ? dirname4(inner) : null;
2440
3683
  }
2441
3684
  if (callee === "fileURLToPath") {
2442
3685
  const arg = node.arguments[0];
@@ -2453,9 +3696,9 @@ function evaluateExpression(ts, node, file, fileDir, repoRoot, bindings) {
2453
3696
  if (parts.length === 0)
2454
3697
  return null;
2455
3698
  const first = parts[0];
2456
- if (!isAbsolute2(first))
3699
+ if (!isAbsolute3(first))
2457
3700
  return null;
2458
- return callee === "join" ? join4(...parts) : resolve3(...parts);
3701
+ return callee === "join" ? join5(...parts) : resolve3(...parts);
2459
3702
  }
2460
3703
  return null;
2461
3704
  }
@@ -2466,7 +3709,7 @@ function evaluateExpression(ts, node, file, fileDir, repoRoot, bindings) {
2466
3709
  const relativeArg = node.arguments?.[0];
2467
3710
  if (!relativeArg || !ts.isStringLiteral(relativeArg))
2468
3711
  return null;
2469
- return join4(fileDir, relativeArg.text);
3712
+ return join5(fileDir, relativeArg.text);
2470
3713
  }
2471
3714
  return null;
2472
3715
  }
@@ -2485,8 +3728,8 @@ function collectTopLevelBindings(ts, sourceFile, file, fileDir, repoRoot) {
2485
3728
  }
2486
3729
  return bindings;
2487
3730
  }
2488
- function cliSpawnEdgeOf(ts, file, source, repoRoot, entrypoint) {
2489
- const fileDir = dirname3(file);
3731
+ function spawnEdgeOf(ts, file, source, repoRoot, program) {
3732
+ const fileDir = dirname4(file);
2490
3733
  let sourceFile;
2491
3734
  try {
2492
3735
  sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.ES2022, true);
@@ -2507,18 +3750,18 @@ function cliSpawnEdgeOf(ts, file, source, repoRoot, entrypoint) {
2507
3750
  }
2508
3751
  }
2509
3752
  }
2510
- let sawBun = false;
3753
+ let sawBinary = false;
2511
3754
  let sawEntrypoint = false;
2512
3755
  for (const candidate of candidates) {
2513
3756
  const value = evaluateExpression(ts, candidate, file, fileDir, repoRoot, bindings);
2514
- if (value === "bun")
2515
- sawBun = true;
2516
- else if (value === entrypoint)
3757
+ if (value === program.binary)
3758
+ sawBinary = true;
3759
+ else if (value === program.entrypoint)
2517
3760
  sawEntrypoint = true;
2518
3761
  }
2519
- if (sawBun && sawEntrypoint)
3762
+ if (sawBinary && sawEntrypoint)
2520
3763
  classification = "entrypoint";
2521
- else if ((sawBun || sawEntrypoint) && classification !== "entrypoint")
3764
+ else if ((sawBinary || sawEntrypoint) && classification !== "entrypoint")
2522
3765
  classification = "fallback";
2523
3766
  }
2524
3767
  ts.forEachChild(node, visit);
@@ -2526,9 +3769,116 @@ function cliSpawnEdgeOf(ts, file, source, repoRoot, entrypoint) {
2526
3769
  visit(sourceFile);
2527
3770
  return classification;
2528
3771
  }
3772
+ function startedScriptsOf(ts, file, source, repoRoot, program, isSourceFile, readSource) {
3773
+ if (spawnEdgeOf(ts, file, source, repoRoot, program) !== "fallback")
3774
+ return null;
3775
+ const fileDir = dirname4(file);
3776
+ let sourceFile;
3777
+ try {
3778
+ sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.ES2022, true);
3779
+ } catch {
3780
+ return null;
3781
+ }
3782
+ const bindings = collectTopLevelBindings(ts, sourceFile, file, fileDir, repoRoot);
3783
+ const evaluate = (node) => ts.isSpreadElement(node) ? null : evaluateExpression(ts, node, file, fileDir, repoRoot, bindings);
3784
+ const scriptOf = (argv) => {
3785
+ const first = argv[0];
3786
+ const element = first && evaluate(first) === "run" ? argv[1] : first;
3787
+ const value = element ? evaluate(element) : null;
3788
+ return value !== null && isAbsolute3(value) && isSourceFile(value) ? value : null;
3789
+ };
3790
+ const scripts = new Set;
3791
+ let readable = true;
3792
+ const visit = (node) => {
3793
+ if (!readable)
3794
+ return;
3795
+ if (ts.isCallExpression(node)) {
3796
+ const signal = node.arguments.some((arg) => (ts.isArrayLiteralExpression(arg) ? [...arg.elements] : [arg]).some((candidate) => {
3797
+ const value = evaluate(candidate);
3798
+ return value === program.binary || value === program.entrypoint;
3799
+ }));
3800
+ if (signal) {
3801
+ const [first, second] = node.arguments;
3802
+ let script = null;
3803
+ if (first && ts.isArrayLiteralExpression(first)) {
3804
+ const [binary, ...argv] = first.elements;
3805
+ if (binary && evaluate(binary) === program.binary)
3806
+ script = scriptOf(argv);
3807
+ } else if (first && evaluate(first) === program.binary && second && ts.isArrayLiteralExpression(second)) {
3808
+ script = scriptOf(second.elements);
3809
+ }
3810
+ if (script === null)
3811
+ readable = false;
3812
+ else
3813
+ scripts.add(script);
3814
+ }
3815
+ }
3816
+ ts.forEachChild(node, visit);
3817
+ };
3818
+ visit(sourceFile);
3819
+ if (!readable || scripts.size === 0)
3820
+ return null;
3821
+ for (const script of scripts)
3822
+ if (mayStartProgram(ts, script, readSource(script), repoRoot, program))
3823
+ return null;
3824
+ return [...scripts].sort();
3825
+ }
3826
+ function mayStartProgram(ts, script, text, repoRoot, program) {
3827
+ let sourceFile;
3828
+ try {
3829
+ sourceFile = ts.createSourceFile(script, text, ts.ScriptTarget.ES2022, true);
3830
+ } catch {
3831
+ return true;
3832
+ }
3833
+ let found = false;
3834
+ const visit = (node) => {
3835
+ if (found)
3836
+ return;
3837
+ if ((ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) && node.text === program.binary)
3838
+ found = true;
3839
+ else
3840
+ ts.forEachChild(node, visit);
3841
+ };
3842
+ visit(sourceFile);
3843
+ return found || spawnEdgeOf(ts, script, text, repoRoot, program) !== null;
3844
+ }
2529
3845
 
2530
- // src/lib/repo-scanner-tests.ts
2531
- import { dirname as dirname4, isAbsolute as isAbsolute3, join as join5, resolve as resolve4 } from "node:path";
3846
+ // src/lib/cli-spawn-tests.ts
3847
+ var CLI_SPAWN_BINARY = "bun";
3848
+
3849
+ // src/lib/verification/scanner-inputs.ts
3850
+ import { dirname as dirname5, isAbsolute as isAbsolute4, join as join6, resolve as resolve4 } from "node:path";
3851
+
3852
+ // src/lib/verification/path-pattern.ts
3853
+ function globToRegex2(pat) {
3854
+ let re = "^";
3855
+ let i = 0;
3856
+ while (i < pat.length) {
3857
+ const c = pat[i];
3858
+ if (c === "*") {
3859
+ if (pat[i + 1] === "*") {
3860
+ re += ".*";
3861
+ i += 2;
3862
+ } else {
3863
+ re += "[^/]*";
3864
+ i += 1;
3865
+ }
3866
+ } else if (/[.+^$|(){}[\]\\?]/.test(c)) {
3867
+ re += `\\${c}`;
3868
+ i += 1;
3869
+ } else {
3870
+ re += c;
3871
+ i += 1;
3872
+ }
3873
+ }
3874
+ re += "$";
3875
+ return new RegExp(re);
3876
+ }
3877
+ function underDeclaredRoot(path, root) {
3878
+ return root === "." || path.startsWith(root);
3879
+ }
3880
+
3881
+ // src/lib/verification/scanner-inputs.ts
2532
3882
  var TREE_READERS = new Set([
2533
3883
  "readdirSync",
2534
3884
  "readdir",
@@ -2568,9 +3918,9 @@ function evaluatePath(ts, node, fileDir, repoRoot, bindings) {
2568
3918
  if (parts.length === 0)
2569
3919
  return null;
2570
3920
  const first = parts[0];
2571
- if (!isAbsolute3(first))
3921
+ if (!isAbsolute4(first))
2572
3922
  return null;
2573
- return callee === "join" ? join5(...parts) : resolve4(...parts);
3923
+ return callee === "join" ? join6(...parts) : resolve4(...parts);
2574
3924
  }
2575
3925
  return null;
2576
3926
  }
@@ -2581,12 +3931,12 @@ function evaluatePath(ts, node, fileDir, repoRoot, bindings) {
2581
3931
  const relativeArg = node.arguments?.[0];
2582
3932
  if (!relativeArg || !ts.isStringLiteral(relativeArg))
2583
3933
  return null;
2584
- return join5(fileDir, relativeArg.text);
3934
+ return join6(fileDir, relativeArg.text);
2585
3935
  }
2586
3936
  return null;
2587
3937
  }
2588
3938
  function scannedRootsOf(ts, file, source, repoRoot) {
2589
- const fileDir = dirname4(file);
3939
+ const fileDir = dirname5(file);
2590
3940
  let sourceFile;
2591
3941
  try {
2592
3942
  sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.ES2022, true);
@@ -2627,13 +3977,63 @@ function scannedRootsOf(ts, file, source, repoRoot) {
2627
3977
  ts.forEachChild(node, visit);
2628
3978
  };
2629
3979
  ts.forEachChild(sourceFile, visit);
2630
- if (!readsTreeSomehow)
2631
- return [];
2632
- const roots = walked.size > 0 ? [...walked] : declaredRoots;
2633
- if (roots.length === 0)
2634
- return [];
2635
- return roots.filter((r) => !roots.some((other) => other !== r && r.startsWith(`${other}/`))).sort();
3980
+ if (!readsTreeSomehow)
3981
+ return [];
3982
+ const roots = walked.size > 0 ? [...walked] : declaredRoots;
3983
+ if (roots.length === 0)
3984
+ return [];
3985
+ return roots.filter((r) => !roots.some((other) => other !== r && r.startsWith(`${other}/`))).sort();
3986
+ }
3987
+ function scannerTriggered(declaration, change) {
3988
+ const under = (path) => declaration.roots.some((root) => underDeclaredRoot(path, root));
3989
+ if (declaration.trigger === "tree-shape")
3990
+ return [...change.added, ...change.removed].some(under);
3991
+ if (declaration.trigger === "listed-files")
3992
+ return [...change.changed, ...change.added, ...change.removed].some(under);
3993
+ if (declaration.trigger !== "process-start")
3994
+ return false;
3995
+ const added = new Set(change.added);
3996
+ return change.changed.some((path) => {
3997
+ if (!/\.tsx?$/.test(path) || !under(path))
3998
+ return false;
3999
+ if (!change.typescript)
4000
+ return true;
4001
+ return startsProcessIn(change.typescript, path, change.read(path) ?? "", added.has(path) ? undefined : change.ranges(path));
4002
+ });
4003
+ }
4004
+ var PROCESS_CALLS = new Set([...SPAWN_CALLS, "fork"]);
4005
+ function startsProcessIn(ts, file, source, ranges) {
4006
+ let sourceFile;
4007
+ try {
4008
+ sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.ES2022, true);
4009
+ } catch {
4010
+ return false;
4011
+ }
4012
+ const touched = (node) => {
4013
+ if (!ranges)
4014
+ return true;
4015
+ const first = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
4016
+ const last = sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line + 1;
4017
+ return ranges.some((r) => r.start <= last && r.end >= first);
4018
+ };
4019
+ let found = false;
4020
+ const visit = (node) => {
4021
+ if (found)
4022
+ return;
4023
+ if (ts.isCallExpression(node)) {
4024
+ const callee = ts.isIdentifier(node.expression) ? node.expression.text : ts.isPropertyAccessExpression(node.expression) && node.expression.name.text !== "exec" ? node.expression.name.text : "";
4025
+ if (PROCESS_CALLS.has(callee) && touched(node)) {
4026
+ found = true;
4027
+ return;
4028
+ }
4029
+ }
4030
+ ts.forEachChild(node, visit);
4031
+ };
4032
+ ts.forEachChild(sourceFile, visit);
4033
+ return found;
2636
4034
  }
4035
+
4036
+ // src/lib/repo-scanner-tests.ts
2637
4037
  var SCANNER_DECLARATIONS = [
2638
4038
  {
2639
4039
  test: "apps/cli/tests/conformance/dev-review-engine-architecture-exit.test.ts",
@@ -2648,6 +4048,17 @@ var SCANNER_DECLARATIONS = [
2648
4048
  ],
2649
4049
  trigger: "listed-files"
2650
4050
  },
4051
+ {
4052
+ test: "apps/cli/tests/conformance/adapter-contract.test.ts",
4053
+ roots: [
4054
+ "apps/cli/specs/dev-review-engine-capability-matrix.md",
4055
+ "apps/cli/tests/fixtures/dev-review-engine-capability-matrix.json",
4056
+ "apps/cli/tests/eval/registry/modules.json",
4057
+ "AGENTS.md",
4058
+ "CLAUDE.md"
4059
+ ],
4060
+ trigger: "listed-files"
4061
+ },
2651
4062
  { test: "apps/cli/tests/ci-shards.test.ts", roots: ["apps/cli/"], trigger: "tree-shape" },
2652
4063
  {
2653
4064
  test: "apps/cli/tests/conformance/dev-review-invariant-coverage.test.ts",
@@ -2661,9 +4072,16 @@ var SCANNER_DECLARATIONS = [
2661
4072
  ],
2662
4073
  trigger: "tree-shape"
2663
4074
  },
4075
+ {
4076
+ test: "apps/cli/tests/conformance/packed-runtime-not-shipped.test.ts",
4077
+ roots: ["apps/cli/src/"],
4078
+ trigger: "content"
4079
+ },
2664
4080
  { test: "apps/cli/tests/platform-independence.test.ts", roots: ["apps/cli/tests/"], trigger: "content" },
2665
4081
  { test: "apps/cli/tests/process-fixture-coverage.test.ts", roots: ["apps/cli/tests/"], trigger: "process-start" },
2666
4082
  { test: "apps/cli/scripts/bundle-doctrine.test.ts", roots: ["."], trigger: "content" },
4083
+ { test: "processes/vinaya/tests/run-engine.test.ts", roots: ["."], trigger: "content" },
4084
+ { test: "harness/dev-process/loader/load-process.test.ts", roots: ["processes/"], trigger: "content" },
2667
4085
  { test: "apps/cli/tests/checks/bin-permissions.test.ts", roots: ["."], trigger: "content" },
2668
4086
  {
2669
4087
  test: "apps/cli/tests/checks/registry-gates.test.ts",
@@ -2718,6 +4136,17 @@ var SCANNER_DECLARATIONS = [
2718
4136
  trigger: "content"
2719
4137
  },
2720
4138
  { test: "apps/cli/tests/lib/no-log-forge-writes.test.ts", roots: ["."], trigger: "content" },
4139
+ {
4140
+ test: "apps/cli/tests/lib/verification-library.test.ts",
4141
+ roots: [
4142
+ "apps/cli/src/lib/verification/",
4143
+ "apps/cli/LICENSE",
4144
+ "scripts/test-suites/inventory.json",
4145
+ "scripts/test-suites/inventory-check.ts",
4146
+ "scripts/test-suites/repository-selection.ts"
4147
+ ],
4148
+ trigger: "listed-files"
4149
+ },
2721
4150
  {
2722
4151
  test: "apps/cli/tests/log-destination-isolation.test.ts",
2723
4152
  roots: ["apps/cli/src/", "apps/cli/tests/"],
@@ -2727,6 +4156,16 @@ var SCANNER_DECLARATIONS = [
2727
4156
  { test: "apps/cli/tests/run-paths-only.test.ts", roots: ["."], trigger: "content" },
2728
4157
  { test: "apps/cli/tests/surface-index.test.ts", roots: ["apps/cli/src/commands/"], trigger: "content" },
2729
4158
  { test: "apps/cli/tests/surface-spec-exports.test.ts", roots: ["apps/cli/src/commands/"], trigger: "content" },
4159
+ {
4160
+ test: "apps/vinaya-portal/src/lib/docs/private-source-links.test.ts",
4161
+ roots: ["apps/vinaya-portal/src/app/(site)/docs/"],
4162
+ trigger: "content"
4163
+ },
4164
+ {
4165
+ test: "apps/vinaya-portal/src/lib/import-boundary.test.ts",
4166
+ roots: ["apps/vinaya-portal/src/"],
4167
+ trigger: "content"
4168
+ },
2730
4169
  { test: "packages/aeg-core/src/actions.test.ts", roots: ["aeg-root/roles/"], trigger: "content" },
2731
4170
  { test: "packages/aeg-core/src/diagram-model.test.ts", roots: ["."], trigger: "content" },
2732
4171
  {
@@ -2739,46 +4178,19 @@ var SCANNER_DECLARATIONS = [
2739
4178
  { test: "packages/aeg-core/src/no-binary-sources.test.ts", roots: ["."], trigger: "content" },
2740
4179
  { test: "packages/aeg-core/src/retired-vocabulary.test.ts", roots: ["."], trigger: "content" }
2741
4180
  ];
2742
- function underDeclaredRoot(path, root) {
2743
- return root === "." || path.startsWith(root);
2744
- }
2745
- var PROCESS_CALLS = new Set([...SPAWN_CALLS, "fork"]);
2746
- function startsProcessIn(ts, file, source, ranges) {
2747
- let sourceFile;
2748
- try {
2749
- sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.ES2022, true);
2750
- } catch {
2751
- return false;
2752
- }
2753
- const touched = (node) => {
2754
- if (!ranges)
2755
- return true;
2756
- const first = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
2757
- const last = sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line + 1;
2758
- return ranges.some((r) => r.start <= last && r.end >= first);
2759
- };
2760
- let found = false;
2761
- const visit = (node) => {
2762
- if (found)
2763
- return;
2764
- if (ts.isCallExpression(node)) {
2765
- const callee = ts.isIdentifier(node.expression) ? node.expression.text : ts.isPropertyAccessExpression(node.expression) && node.expression.name.text !== "exec" ? node.expression.name.text : "";
2766
- if (PROCESS_CALLS.has(callee) && touched(node)) {
2767
- found = true;
2768
- return;
2769
- }
2770
- }
2771
- ts.forEachChild(node, visit);
2772
- };
2773
- ts.forEachChild(sourceFile, visit);
2774
- return found;
2775
- }
2776
4181
 
2777
- // src/lib/ts-module-graph.ts
4182
+ // src/lib/verification/selector.ts
4183
+ import { readdirSync as readdirSync2, readFileSync as readFileSync5, statSync as statSync2 } from "node:fs";
4184
+ import { dirname as dirname7, extname, isAbsolute as isAbsolute5, join as join8, resolve as resolve6 } from "node:path";
4185
+
4186
+ // src/lib/verification/compiler-graph.ts
2778
4187
  import { createRequire } from "node:module";
2779
- import { dirname as dirname5, join as join6, resolve as resolve5 } from "node:path";
4188
+ import { dirname as dirname6, join as join7, resolve as resolve5 } from "node:path";
2780
4189
  function loadTypeScript(repoRoot) {
2781
- for (const from of [join6(repoRoot, "package.json"), import.meta.url]) {
4190
+ return loadTypeScriptFrom([join7(repoRoot, "package.json"), import.meta.url]);
4191
+ }
4192
+ function loadTypeScriptFrom(anchors) {
4193
+ for (const from of anchors) {
2782
4194
  try {
2783
4195
  const loaded = createRequire(from)("typescript");
2784
4196
  if (loaded && typeof loaded.createProgram === "function" && loaded.ScriptTarget)
@@ -2813,15 +4225,37 @@ function graphCompilerOptions(ts, input) {
2813
4225
  resolveJsonModule: true
2814
4226
  };
2815
4227
  }
4228
+ function viewCompilerHost(ts, options, root, view) {
4229
+ const base = ts.createCompilerHost(options);
4230
+ const libDir = dirname6(ts.getDefaultLibFilePath(options));
4231
+ const isLib = (path) => path.startsWith(`${libDir}/`);
4232
+ return {
4233
+ ...base,
4234
+ getCurrentDirectory: () => root,
4235
+ useCaseSensitiveFileNames: () => true,
4236
+ getCanonicalFileName: (name) => name,
4237
+ realpath: (path) => path,
4238
+ fileExists: (path) => isLib(path) ? base.fileExists(path) : view.fileExists(path),
4239
+ readFile: (path) => isLib(path) ? base.readFile(path) : view.readFile(path),
4240
+ directoryExists: (path) => isLib(path) ? true : view.directoryExists(path),
4241
+ getDirectories: (path) => isLib(path) ? [] : view.getDirectories(path),
4242
+ getSourceFile: (fileName, languageVersion) => {
4243
+ if (isLib(fileName))
4244
+ return base.getSourceFile(fileName, languageVersion);
4245
+ const text = view.readFile(fileName);
4246
+ return text === undefined ? undefined : ts.createSourceFile(fileName, text, languageVersion);
4247
+ }
4248
+ };
4249
+ }
2816
4250
  function buildCompilerGraph(ts, input) {
2817
4251
  const { files, packageOfFile, packageOfBareSpecifier } = input;
2818
4252
  const fileSet = new Set(files);
2819
4253
  const options = graphCompilerOptions(ts, input);
4254
+ const host = input.host ? viewCompilerHost(ts, options, input.repoRoot, input.host) : ts.createCompilerHost(options);
2820
4255
  const t0 = performance.now();
2821
- const program = ts.createProgram([...files], options);
4256
+ const program = input.host ? ts.createProgram([...files], options, host) : ts.createProgram([...files], options);
2822
4257
  const checker = program.getTypeChecker();
2823
4258
  const programMs = performance.now() - t0;
2824
- const host = ts.createCompilerHost(options);
2825
4259
  const resolutionCache = new Map;
2826
4260
  const resolveToWorkspaceFile = (specifier, containingFile) => {
2827
4261
  const key = `${containingFile}
@@ -2906,7 +4340,7 @@ ${specifier}`;
2906
4340
  const resolveWithLiteral = (specifier, into) => {
2907
4341
  const target = resolveToWorkspaceFile(specifier, file);
2908
4342
  if (specifier.startsWith(".")) {
2909
- const literal = resolve5(dirname5(file), specifier);
4343
+ const literal = resolve5(dirname6(file), specifier);
2910
4344
  if (literal !== target && fileSet.has(literal))
2911
4345
  into.push(`${ALL_PREFIX}${literal}`);
2912
4346
  }
@@ -3039,7 +4473,52 @@ ${specifier}`;
3039
4473
  return { edges, programMs };
3040
4474
  }
3041
4475
 
3042
- // src/lib/test-selector.ts
4476
+ // src/lib/verification/inventory.ts
4477
+ var READER_KINDS = new Set(["code", "raw-bytes", "semantic", "parsed-keys", "schema-policy"]);
4478
+ var EDGE_KINDS = new Set([
4479
+ "import",
4480
+ "preload",
4481
+ "runner-config",
4482
+ "lockfile",
4483
+ "fixture",
4484
+ "schema",
4485
+ "doc",
4486
+ "config",
4487
+ "spawn",
4488
+ "scan",
4489
+ "provider"
4490
+ ]);
4491
+ var POLICY_KINDS = new Set(["always-run", "mandatory", "security", "oracle"]);
4492
+ var RUNNERS = new Set(["bun", "vitest"]);
4493
+
4494
+ // src/lib/verification/selector.ts
4495
+ function diskTree(root) {
4496
+ return {
4497
+ root,
4498
+ readDir: (path) => {
4499
+ try {
4500
+ return readdirSync2(path);
4501
+ } catch {
4502
+ return null;
4503
+ }
4504
+ },
4505
+ kind: (path) => {
4506
+ try {
4507
+ return statSync2(path).isDirectory() ? "directory" : "file";
4508
+ } catch {
4509
+ return null;
4510
+ }
4511
+ },
4512
+ readFile: (path) => {
4513
+ try {
4514
+ return readFileSync5(path, "utf8");
4515
+ } catch {
4516
+ return null;
4517
+ }
4518
+ }
4519
+ };
4520
+ }
4521
+ var MAX_BATCH_BLOB_BYTES = 4 << 20;
3043
4522
  var SOURCE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
3044
4523
  var SKIP_DIRS = new Set(["node_modules", "dist", ".git", "build", "coverage"]);
3045
4524
  var OUTPUT_TO_SOURCE_EXTENSIONS = new Map([
@@ -3117,26 +4596,20 @@ function extractImportRecords(source) {
3117
4596
  function extractOwnImportRecords(source) {
3118
4597
  return collectRecords(source, false);
3119
4598
  }
3120
- function walkFiles(root) {
4599
+ function walkTree(tree, root) {
3121
4600
  const out = [];
3122
- let entries;
3123
- try {
3124
- entries = readdirSync2(root);
3125
- } catch {
4601
+ const entries = tree.readDir(root);
4602
+ if (entries === null)
3126
4603
  return out;
3127
- }
3128
4604
  for (const entry of entries) {
3129
4605
  if (SKIP_DIRS.has(entry))
3130
4606
  continue;
3131
- const abs = join7(root, entry);
3132
- let s;
3133
- try {
3134
- s = statSync2(abs);
3135
- } catch {
4607
+ const abs = join8(root, entry);
4608
+ const kind = tree.kind(abs);
4609
+ if (kind === null)
3136
4610
  continue;
3137
- }
3138
- if (s.isDirectory()) {
3139
- out.push(...walkFiles(abs));
4611
+ if (kind === "directory") {
4612
+ out.push(...walkTree(tree, abs));
3140
4613
  } else {
3141
4614
  out.push(abs);
3142
4615
  }
@@ -3157,7 +4630,7 @@ function resolveFileCandidate(base, knownFiles) {
3157
4630
  return base + ext;
3158
4631
  }
3159
4632
  for (const ext of SOURCE_EXTENSIONS) {
3160
- const indexed = join7(base, `index${ext}`);
4633
+ const indexed = join8(base, `index${ext}`);
3161
4634
  if (knownFiles.has(indexed))
3162
4635
  return indexed;
3163
4636
  }
@@ -3166,13 +4639,22 @@ function resolveFileCandidate(base, knownFiles) {
3166
4639
  function resolveRelativeImport(fromFile, specifier, knownFiles) {
3167
4640
  if (!specifier.startsWith("."))
3168
4641
  return null;
3169
- return resolveFileCandidate(resolve6(dirname6(fromFile), specifier), knownFiles);
4642
+ return resolveFileCandidate(resolve6(dirname7(fromFile), specifier), knownFiles);
3170
4643
  }
3171
4644
  function isBunTestScript(script) {
3172
4645
  if (!script)
3173
4646
  return true;
3174
4647
  return /(^|[\s;&|])bun\s+test\b/.test(script);
3175
4648
  }
4649
+ function testRunnerOf(script) {
4650
+ if (!script)
4651
+ return "none";
4652
+ if (isBunTestScript(script))
4653
+ return "bun";
4654
+ if (/(^|[\s;&|])vitest(\s|$)/.test(script))
4655
+ return "vitest";
4656
+ return "other";
4657
+ }
3176
4658
  var TYPE_ONLY_CONDITIONS = new Set(["types", "typings"]);
3177
4659
  function declaredTargets(value, out = []) {
3178
4660
  if (typeof value === "string") {
@@ -3214,48 +4696,104 @@ function deriveEntrypoints(dir, pkg, knownFiles) {
3214
4696
  add(".", pkg.main);
3215
4697
  return out;
3216
4698
  }
3217
- function discoverWorkspacePackages(repoRoot) {
3218
- const rootPkgPath = join7(repoRoot, "package.json");
3219
- let workspaces = [];
4699
+ function readWorkspacePatterns(tree) {
3220
4700
  try {
3221
- const rootPkg = JSON.parse(readFileSync4(rootPkgPath, "utf8"));
3222
- workspaces = rootPkg.workspaces ?? [];
4701
+ const rootPkg = JSON.parse(tree.readFile(join8(tree.root, "package.json")) ?? "");
4702
+ const declared = Array.isArray(rootPkg.workspaces) ? rootPkg.workspaces : rootPkg.workspaces?.packages ?? [];
4703
+ return declared.filter((entry) => typeof entry === "string");
3223
4704
  } catch {
3224
- return [];
4705
+ return null;
3225
4706
  }
4707
+ }
4708
+ function segmentMatcher(segment) {
4709
+ if (!segment.includes("*"))
4710
+ return (entry) => entry === segment;
4711
+ const re = new RegExp(`^${segment.split("*").map(escapeForRegex).join("[^/]*")}$`);
4712
+ return (entry) => re.test(entry);
4713
+ }
4714
+ function escapeForRegex(text) {
4715
+ return text.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
4716
+ }
4717
+ function expandWorkspacePatterns(tree, patterns) {
4718
+ const expand = (pattern) => {
4719
+ const segments = pattern.replace(/^\.\//, "").replace(/\/+$/, "").split("/").filter(Boolean);
4720
+ if (segments.length === 0 || segments.includes("**"))
4721
+ return [];
4722
+ let dirs = [""];
4723
+ for (const segment of segments) {
4724
+ const matches = segmentMatcher(segment);
4725
+ const next = [];
4726
+ for (const dir of dirs) {
4727
+ if (!segment.includes("*")) {
4728
+ next.push(dir ? `${dir}/${segment}` : segment);
4729
+ continue;
4730
+ }
4731
+ const entries = tree.readDir(join8(tree.root, dir));
4732
+ if (entries === null)
4733
+ continue;
4734
+ for (const entry of [...entries].sort()) {
4735
+ if (SKIP_DIRS.has(entry) || !matches(entry))
4736
+ continue;
4737
+ const child = dir ? `${dir}/${entry}` : entry;
4738
+ if (tree.kind(join8(tree.root, child)) === "directory")
4739
+ next.push(child);
4740
+ }
4741
+ }
4742
+ dirs = next;
4743
+ }
4744
+ return dirs;
4745
+ };
3226
4746
  const out = [];
3227
- for (const glob of workspaces) {
3228
- const m = /^([^*]+)\*$/.exec(glob);
3229
- if (!m)
4747
+ for (const pattern of patterns) {
4748
+ if (pattern.startsWith("!")) {
4749
+ const removed = new Set(expand(pattern.slice(1)));
4750
+ for (let i = out.length - 1;i >= 0; i--)
4751
+ if (removed.has(out[i]))
4752
+ out.splice(i, 1);
3230
4753
  continue;
3231
- const parentDir = join7(repoRoot, m[1].replace(/\/$/, ""));
3232
- let entries;
4754
+ }
4755
+ for (const dir of expand(pattern))
4756
+ if (!out.includes(dir))
4757
+ out.push(dir);
4758
+ }
4759
+ return out;
4760
+ }
4761
+ function discoverWorkspaceDirs(tree) {
4762
+ const patterns = readWorkspacePatterns(tree);
4763
+ if (!patterns)
4764
+ return [];
4765
+ return expandWorkspacePatterns(tree, patterns).filter((dir) => {
3233
4766
  try {
3234
- entries = readdirSync2(parentDir);
4767
+ const pkg = JSON.parse(tree.readFile(join8(tree.root, dir, "package.json")) ?? "");
4768
+ return typeof pkg.name === "string" && pkg.name.length > 0;
3235
4769
  } catch {
3236
- continue;
4770
+ return false;
3237
4771
  }
3238
- for (const entry of entries) {
3239
- const dir = join7(parentDir, entry);
3240
- const pkgPath = join7(dir, "package.json");
3241
- let pkg;
3242
- try {
3243
- pkg = JSON.parse(readFileSync4(pkgPath, "utf8"));
3244
- } catch {
3245
- continue;
3246
- }
3247
- if (!pkg.name)
3248
- continue;
3249
- const sourceFiles = walkFiles(dir).filter((f) => SOURCE_EXTENSIONS.includes(extname(f)));
3250
- const knownFiles = new Set(sourceFiles);
3251
- out.push({
3252
- dir,
3253
- name: pkg.name,
3254
- bunTestCompatible: isBunTestScript(pkg.scripts?.test),
3255
- entrypoints: deriveEntrypoints(dir, pkg, knownFiles),
3256
- sourceFiles
3257
- });
4772
+ });
4773
+ }
4774
+ function discoverWorkspacePackages(tree) {
4775
+ const dirs = discoverWorkspaceDirs(tree).map((dir) => join8(tree.root, dir));
4776
+ const out = [];
4777
+ for (const dir of dirs) {
4778
+ let pkg;
4779
+ try {
4780
+ pkg = JSON.parse(tree.readFile(join8(dir, "package.json")) ?? "");
4781
+ } catch {
4782
+ continue;
3258
4783
  }
4784
+ if (!pkg.name)
4785
+ continue;
4786
+ const nested = dirs.filter((other) => other !== dir && other.startsWith(`${dir}/`));
4787
+ const sourceFiles = walkTree(tree, dir).filter((f) => SOURCE_EXTENSIONS.includes(extname(f)) && !nested.some((other) => f.startsWith(`${other}/`)));
4788
+ const knownFiles = new Set(sourceFiles);
4789
+ out.push({
4790
+ dir,
4791
+ name: pkg.name,
4792
+ bunTestCompatible: isBunTestScript(pkg.scripts?.test),
4793
+ testRunner: testRunnerOf(pkg.scripts?.test),
4794
+ entrypoints: deriveEntrypoints(dir, pkg, knownFiles),
4795
+ sourceFiles
4796
+ });
3259
4797
  }
3260
4798
  return out;
3261
4799
  }
@@ -3333,16 +4871,12 @@ function parseExportTable(source) {
3333
4871
  return { directDefs, localReexports, namedReexports, starReexports, starAsNames, imports, ownImports };
3334
4872
  }
3335
4873
  var UNRESOLVED = { resolved: false };
3336
- function makeSourceReader() {
4874
+ function makeSourceReader(tree) {
3337
4875
  const cache = new Map;
3338
4876
  return (file) => {
3339
4877
  let cached = cache.get(file);
3340
4878
  if (cached === undefined) {
3341
- try {
3342
- cached = readFileSync4(file, "utf8");
3343
- } catch {
3344
- cached = "";
3345
- }
4879
+ cached = tree.readFile(file) ?? "";
3346
4880
  cache.set(file, cached);
3347
4881
  }
3348
4882
  return cached;
@@ -3472,14 +5006,10 @@ function resolveThroughTable(ctx, file, name, table, stack) {
3472
5006
  hopDeps: new Set([...ownHopDeps(), ...only.hopDeps])
3473
5007
  };
3474
5008
  }
3475
- var DEFAULT_CLI_ENTRYPOINT = "apps/cli/src/index.ts";
3476
- var ROOT_CONFIG_FILENAME = "vinaya.config.json";
3477
- function selectAffectedTestFiles(repoRoot, changedFiles, options = {}) {
3478
- const packages = discoverWorkspacePackages(repoRoot);
3479
- const absChanged = new Set(changedFiles.map((f) => isAbsolute4(f) ? f : join7(repoRoot, f)));
3480
- const alwaysRunRegexes = (options.alwaysRun ?? []).map(globToRegex);
3481
- const addedOrRenamed = new Set((options.addedOrRenamed ?? []).map((f) => isAbsolute4(f) ? f : join7(repoRoot, f)));
3482
- const readSource = makeSourceReader();
5009
+ function buildSelectionGraph(tree, options) {
5010
+ const repoRoot = tree.root;
5011
+ const packages = discoverWorkspacePackages(tree);
5012
+ const readSource = makeSourceReader(tree);
3483
5013
  const tableCache = new Map;
3484
5014
  const resultCache = new Map;
3485
5015
  const pkgFiles = new Map;
@@ -3495,16 +5025,14 @@ function selectAffectedTestFiles(repoRoot, changedFiles, options = {}) {
3495
5025
  allSourceFiles.add(f);
3496
5026
  }
3497
5027
  }
3498
- const changedPackageNames = new Set;
3499
- const nonSourceChangedPackages = new Set;
3500
- for (const pkg of packages) {
3501
- for (const f of absChanged) {
3502
- if (!f.startsWith(`${pkg.dir}/`))
3503
- continue;
3504
- changedPackageNames.add(pkg.name);
3505
- if (!allSourceFiles.has(f))
3506
- nonSourceChangedPackages.add(pkg.name);
3507
- }
5028
+ const unpackaged = [];
5029
+ if (options.includeUnpackaged) {
5030
+ const pkgDirs = packages.map((p) => p.dir);
5031
+ for (const f of walkTree(tree, repoRoot))
5032
+ if (SOURCE_EXTENSIONS.includes(extname(f)) && !pkgDirs.some((d) => f.startsWith(`${d}/`))) {
5033
+ unpackaged.push(f);
5034
+ allSourceFiles.add(f);
5035
+ }
3508
5036
  }
3509
5037
  const matchPackage = (specifier) => {
3510
5038
  let best = null;
@@ -3533,7 +5061,7 @@ function selectAffectedTestFiles(repoRoot, changedFiles, options = {}) {
3533
5061
  return m ? { name: m.pkg.name, entry: m.pkg.entrypoints.get(m.subpath) ?? null } : null;
3534
5062
  }
3535
5063
  };
3536
- const typescript = loadTypeScript(repoRoot);
5064
+ const typescript = options.typescript;
3537
5065
  const graphTypescript = options.resolver === "text-scan" ? null : typescript;
3538
5066
  const edges = new Map;
3539
5067
  let programMs = 0;
@@ -3549,107 +5077,91 @@ function selectAffectedTestFiles(repoRoot, changedFiles, options = {}) {
3549
5077
  files: [...allSourceFiles],
3550
5078
  packageOfFile: (f) => fileToPackage.get(f) ?? null,
3551
5079
  packageOfBareSpecifier: (specifier) => matchPackage(specifier)?.pkg.name ?? null,
3552
- entrypoints
5080
+ entrypoints,
5081
+ ...tree.host ? { host: tree.host } : {}
3553
5082
  });
3554
5083
  for (const [node, deps] of graph.edges)
3555
5084
  edges.set(node, deps);
3556
5085
  programMs = graph.programMs;
3557
5086
  } else {
3558
- buildTextScanGraph();
5087
+ for (const pkg of packages)
5088
+ textScanEdges(pkgFiles.get(pkg), pkgKnownFiles.get(pkg));
5089
+ if (unpackaged.length > 0)
5090
+ textScanEdges(unpackaged, allSourceFiles);
3559
5091
  }
3560
- function buildTextScanGraph() {
3561
- for (const pkg of packages) {
3562
- const knownFiles = pkgKnownFiles.get(pkg);
3563
- for (const file of pkgFiles.get(pkg)) {
3564
- const deps = [];
3565
- const coarsePackages = new Set;
3566
- const resolvedNamed = new Map;
3567
- for (const record of extractImportRecords(readSource(file))) {
3568
- const specifier = record.specifier;
3569
- if (specifier.startsWith(".")) {
3570
- const resolved = resolveRelativeImport(file, specifier, knownFiles);
3571
- if (resolved)
3572
- deps.push(resolved);
3573
- continue;
3574
- }
3575
- const match = matchPackage(specifier);
3576
- if (!match)
3577
- continue;
3578
- if (coarsePackages.has(match.pkg.name))
3579
- continue;
3580
- const entry = match.pkg.entrypoints.get(match.subpath);
3581
- if (record.kind !== "named" || !record.clean || !entry) {
5092
+ function textScanEdges(files, knownFiles) {
5093
+ for (const file of files) {
5094
+ const deps = [];
5095
+ const coarsePackages = new Set;
5096
+ const resolvedNamed = new Map;
5097
+ for (const record of extractImportRecords(readSource(file))) {
5098
+ const specifier = record.specifier;
5099
+ if (specifier.startsWith(".")) {
5100
+ const resolved = resolveRelativeImport(file, specifier, knownFiles);
5101
+ if (resolved)
5102
+ deps.push(resolved);
5103
+ continue;
5104
+ }
5105
+ const match = matchPackage(specifier);
5106
+ if (!match)
5107
+ continue;
5108
+ if (coarsePackages.has(match.pkg.name))
5109
+ continue;
5110
+ const entry = match.pkg.entrypoints.get(match.subpath);
5111
+ if (record.kind !== "named" || !record.clean || !entry) {
5112
+ coarsePackages.add(match.pkg.name);
5113
+ continue;
5114
+ }
5115
+ let acc = resolvedNamed.get(match.pkg.name);
5116
+ for (const name of record.names) {
5117
+ const resolution = resolveExportedName(ctx, entry, name, new Set);
5118
+ if (!resolution.resolved) {
3582
5119
  coarsePackages.add(match.pkg.name);
3583
- continue;
5120
+ acc = undefined;
5121
+ resolvedNamed.delete(match.pkg.name);
5122
+ break;
3584
5123
  }
3585
- let acc = resolvedNamed.get(match.pkg.name);
3586
- for (const name of record.names) {
3587
- const resolution = resolveExportedName(ctx, entry, name, new Set);
3588
- if (!resolution.resolved) {
3589
- coarsePackages.add(match.pkg.name);
3590
- acc = undefined;
3591
- resolvedNamed.delete(match.pkg.name);
3592
- break;
3593
- }
3594
- if (!acc) {
3595
- acc = { touched: new Set, definers: new Set, hopDeps: new Set };
3596
- resolvedNamed.set(match.pkg.name, acc);
3597
- }
3598
- for (const t of resolution.touched)
3599
- acc.touched.add(t);
3600
- for (const d of resolution.definers)
3601
- acc.definers.add(d);
3602
- for (const h of resolution.hopDeps)
3603
- acc.hopDeps.add(h);
5124
+ if (!acc) {
5125
+ acc = { touched: new Set, definers: new Set, hopDeps: new Set };
5126
+ resolvedNamed.set(match.pkg.name, acc);
3604
5127
  }
5128
+ for (const t of resolution.touched)
5129
+ acc.touched.add(t);
5130
+ for (const d of resolution.definers)
5131
+ acc.definers.add(d);
5132
+ for (const h of resolution.hopDeps)
5133
+ acc.hopDeps.add(h);
3605
5134
  }
3606
- for (const [name, acc] of resolvedNamed) {
3607
- if (coarsePackages.has(name))
3608
- continue;
3609
- const metaPackages = new Set([name]);
3610
- for (const f of [...acc.touched, ...acc.definers, ...acc.hopDeps]) {
3611
- const owner = fileToPackage.get(f);
3612
- if (owner)
3613
- metaPackages.add(owner);
3614
- }
3615
- for (const p of metaPackages)
3616
- deps.push(`${PKGMETA_PREFIX}${p}`);
3617
- for (const t of acc.touched)
3618
- if (t !== file)
3619
- deps.push(`${TOUCH_PREFIX}${t}`);
3620
- for (const d of acc.definers)
3621
- deps.push(d);
3622
- for (const h of acc.hopDeps)
3623
- deps.push(h);
5135
+ }
5136
+ for (const [name, acc] of resolvedNamed) {
5137
+ if (coarsePackages.has(name))
5138
+ continue;
5139
+ const metaPackages = new Set([name]);
5140
+ for (const f of [...acc.touched, ...acc.definers, ...acc.hopDeps]) {
5141
+ const owner = fileToPackage.get(f);
5142
+ if (owner)
5143
+ metaPackages.add(owner);
3624
5144
  }
3625
- for (const name of coarsePackages)
3626
- deps.push(`${EXTERNAL_PREFIX}${name}`);
3627
- const keys = deps.map((d) => /^(?:touch|external|pkgmeta):/.test(d) ? d : `${ALL_PREFIX}${d}`);
3628
- edges.set(`${ALL_PREFIX}${file}`, keys);
3629
- edges.set(`${OWN_PREFIX}${file}`, keys);
5145
+ for (const p of metaPackages)
5146
+ deps.push(`${PKGMETA_PREFIX}${p}`);
5147
+ for (const t of acc.touched)
5148
+ if (t !== file)
5149
+ deps.push(`${TOUCH_PREFIX}${t}`);
5150
+ for (const d of acc.definers)
5151
+ deps.push(d);
5152
+ for (const h of acc.hopDeps)
5153
+ deps.push(h);
3630
5154
  }
5155
+ for (const name of coarsePackages)
5156
+ deps.push(`${EXTERNAL_PREFIX}${name}`);
5157
+ const keys = deps.map((d) => /^(?:touch|external|pkgmeta):/.test(d) ? d : `${ALL_PREFIX}${d}`);
5158
+ edges.set(`${ALL_PREFIX}${file}`, keys);
5159
+ edges.set(`${OWN_PREFIX}${file}`, keys);
3631
5160
  }
3632
5161
  }
3633
- const affectedNames = options.affectedNames ?? new Map;
3634
- const changeFacts = {
3635
- files: absChanged,
3636
- packages: changedPackageNames,
3637
- nonSourcePackages: nonSourceChangedPackages,
3638
- packageOfFile: (f) => fileToPackage.get(f) ?? null,
3639
- affects: (file, name) => {
3640
- const affected = affectedNames.get(file) ?? affectedNames.get(file.startsWith(repoRoot) ? file.slice(repoRoot.length + 1) : file);
3641
- return affected === undefined || affected === "all" || affected.has(name);
3642
- }
3643
- };
3644
- const depthOneDefault = options.depth === "one" ? "ignore" : "select";
3645
- const repoTreeScanners = options.repoTreeScanners ?? depthOneDefault;
3646
- const cliSpawnDetection = options.cliSpawnDetection ?? depthOneDefault;
3647
- const cliEntrypoint = join7(repoRoot, options.cliEntrypoint ?? DEFAULT_CLI_ENTRYPOINT);
3648
- const rootConfigChanged = absChanged.has(join7(repoRoot, ROOT_CONFIG_FILENAME));
3649
- const cliPackage = packages.find((pkg) => cliEntrypoint.startsWith(`${pkg.dir}/`)) ?? null;
3650
- if (typescript && repoTreeScanners !== "ignore") {
5162
+ if (typescript && options.repoTreeScanners !== "ignore") {
3651
5163
  for (const file of allSourceFiles) {
3652
- if (!isTestFile(file))
5164
+ if (!options.isTest(file))
3653
5165
  continue;
3654
5166
  const roots = scannedRootsOf(typescript, file, readSource(file), repoRoot);
3655
5167
  if (roots.length === 0)
@@ -3658,57 +5170,183 @@ function selectAffectedTestFiles(repoRoot, changedFiles, options = {}) {
3658
5170
  edges.set(key, [...edges.get(key) ?? [], ...roots.map((r) => `${SCAN_PREFIX}${r}`)]);
3659
5171
  }
3660
5172
  }
3661
- if (typescript && cliSpawnDetection !== "ignore") {
3662
- const cliEntrypointSourceRoot = dirname6(cliEntrypoint);
3663
- for (const file of allSourceFiles) {
3664
- if (!isTestFile(file))
3665
- continue;
3666
- const classification = cliSpawnEdgeOf(typescript, file, readSource(file), repoRoot, cliEntrypoint);
3667
- if (!classification)
5173
+ if (typescript && options.spawnDetection !== "ignore") {
5174
+ for (const program of options.spawnPrograms) {
5175
+ const entrypoint = join8(repoRoot, program.entrypoint);
5176
+ const entrypointSourceRoot = dirname7(entrypoint);
5177
+ const spawnProgram = { binary: program.binary, entrypoint };
5178
+ for (const file of allSourceFiles) {
5179
+ if (!options.isTest(file))
5180
+ continue;
5181
+ const classification = spawnEdgeOf(typescript, file, readSource(file), repoRoot, spawnProgram);
5182
+ if (!classification)
5183
+ continue;
5184
+ const key = `${ALL_PREFIX}${file}`;
5185
+ const scripts = classification === "fallback" ? startedScriptsOf(typescript, file, readSource(file), repoRoot, spawnProgram, (path) => allSourceFiles.has(path), readSource) : null;
5186
+ const added = classification === "entrypoint" ? [`${ALL_PREFIX}${entrypoint}`] : scripts ? scripts.map((script) => `${ALL_PREFIX}${script}`) : [`${SCAN_PREFIX}${entrypointSourceRoot}`];
5187
+ edges.set(key, [...edges.get(key) ?? [], ...added]);
5188
+ }
5189
+ }
5190
+ }
5191
+ for (const [file, extra] of options.extraEdges ?? []) {
5192
+ const key = `${ALL_PREFIX}${file}`;
5193
+ edges.set(key, [...edges.get(key) ?? [], ...extra]);
5194
+ }
5195
+ return {
5196
+ tree,
5197
+ packages,
5198
+ pkgFiles,
5199
+ fileToPackage,
5200
+ allSourceFiles,
5201
+ edges,
5202
+ readSource,
5203
+ graphTypescript,
5204
+ programMs
5205
+ };
5206
+ }
5207
+ var PACKAGE_TEST_DATA_FOLDERS = new Set(["tests", "test", "__tests__", "specs", "fixtures"]);
5208
+ var PACKAGE_PROSE_FILE_NAMES = new Set(["README.md", "CHANGELOG.md", "LICENSE"]);
5209
+ function isPackageTestData(packageRelative) {
5210
+ const segments = packageRelative.split("/");
5211
+ if (PACKAGE_PROSE_FILE_NAMES.has(segments[segments.length - 1] ?? ""))
5212
+ return true;
5213
+ return segments.slice(0, -1).some((segment) => PACKAGE_TEST_DATA_FOLDERS.has(segment));
5214
+ }
5215
+ function changeFactsFor(graph, changed, affectedNames) {
5216
+ const repoRoot = graph.tree.root;
5217
+ const changedPackageNames = new Set;
5218
+ const nonSourceChangedPackages = new Set;
5219
+ for (const pkg of graph.packages) {
5220
+ for (const f of changed) {
5221
+ if (!f.startsWith(`${pkg.dir}/`))
3668
5222
  continue;
3669
- const key = `${ALL_PREFIX}${file}`;
3670
- const edge = classification === "entrypoint" ? `${ALL_PREFIX}${cliEntrypoint}` : `${SCAN_PREFIX}${cliEntrypointSourceRoot}`;
3671
- edges.set(key, [...edges.get(key) ?? [], edge]);
5223
+ changedPackageNames.add(pkg.name);
5224
+ if (!graph.allSourceFiles.has(f) && !isPackageTestData(f.slice(pkg.dir.length + 1)))
5225
+ nonSourceChangedPackages.add(pkg.name);
3672
5226
  }
3673
5227
  }
5228
+ return {
5229
+ files: changed,
5230
+ packages: changedPackageNames,
5231
+ nonSourcePackages: nonSourceChangedPackages,
5232
+ packageOfFile: (f) => graph.fileToPackage.get(f) ?? null,
5233
+ affects: (file, name) => {
5234
+ const affected = affectedNames.get(file) ?? affectedNames.get(file.startsWith(repoRoot) ? file.slice(repoRoot.length + 1) : file);
5235
+ return affected === undefined || affected === "all" || affected.has(name);
5236
+ }
5237
+ };
5238
+ }
5239
+ function selectAffectedFiles(tree, changedFiles, options = {}) {
5240
+ const repoRoot = tree.root;
5241
+ const absChanged = new Set(changedFiles.map((f) => isAbsolute5(f) ? f : join8(repoRoot, f)));
5242
+ const alwaysRunRegexes = (options.alwaysRun ?? []).map(globToRegex2);
5243
+ const addedOrRenamed = new Set((options.addedOrRenamed ?? []).map((f) => isAbsolute5(f) ? f : join8(repoRoot, f)));
5244
+ const depthOneDefault = options.depth === "one" ? "ignore" : "select";
5245
+ const typescript = options.typescript === undefined ? loadTypeScript(repoRoot) : options.typescript;
5246
+ const graph = buildSelectionGraph(tree, {
5247
+ typescript,
5248
+ ...options.resolver ? { resolver: options.resolver } : {},
5249
+ repoTreeScanners: options.repoTreeScanners ?? depthOneDefault,
5250
+ spawnDetection: options.spawnDetection ?? depthOneDefault,
5251
+ spawnPrograms: options.spawnPrograms ?? [],
5252
+ isTest: isTestFile
5253
+ });
5254
+ const { packages, pkgFiles, edges, readSource } = graph;
5255
+ const changeFacts = changeFactsFor(graph, absChanged, options.affectedNames ?? new Map);
5256
+ const configs = (options.configInputs ?? []).filter((config) => absChanged.has(join8(repoRoot, config.path))).map((config) => {
5257
+ const owner = join8(repoRoot, config.ownerFile);
5258
+ return {
5259
+ config,
5260
+ pkg: packages.find((pkg) => owner.startsWith(`${pkg.dir}/`)) ?? null,
5261
+ loaderFacts: {
5262
+ files: new Set([join8(repoRoot, config.loader)]),
5263
+ packages: new Set,
5264
+ nonSourcePackages: new Set,
5265
+ packageOfFile: changeFacts.packageOfFile,
5266
+ affects: () => true
5267
+ }
5268
+ };
5269
+ });
5270
+ const relative = (f) => isAbsolute5(f) ? f.slice(repoRoot.length + 1) : f;
5271
+ const changedRanges = new Map([...options.changedRanges ?? new Map].map(([f, ranges]) => [isAbsolute5(f) ? f : join8(repoRoot, f), ranges]));
3674
5272
  const triggeredScanners = new Set;
3675
- const relative = (f) => isAbsolute4(f) ? f.slice(repoRoot.length + 1) : f;
3676
- const reshaped = [...addedOrRenamed, ...options.removed ?? []].map(relative);
3677
- const changedRanges = new Map([...options.changedRanges ?? new Map].map(([f, ranges]) => [isAbsolute4(f) ? f : join7(repoRoot, f), ranges]));
3678
- for (const declaration of options.scannerDeclarations ?? SCANNER_DECLARATIONS) {
3679
- const under = (f) => declaration.roots.some((root) => underDeclaredRoot(f, root));
3680
- const triggered = declaration.trigger === "tree-shape" ? reshaped.some(under) : declaration.trigger === "process-start" ? [...absChanged].some((abs) => {
3681
- if (!/\.tsx?$/.test(abs) || !under(relative(abs)))
3682
- return false;
3683
- if (!typescript)
3684
- return true;
3685
- const ranges = addedOrRenamed.has(abs) ? undefined : changedRanges.get(abs);
3686
- return startsProcessIn(typescript, abs, readSource(abs), ranges);
3687
- }) : declaration.trigger === "listed-files" ? [...absChanged, ...addedOrRenamed, ...options.removed ?? []].map(relative).some(under) : false;
5273
+ for (const declaration of options.scannerDeclarations ?? []) {
5274
+ const triggered = scannerTriggered(declaration, {
5275
+ changed: [...absChanged].map(relative),
5276
+ added: [...addedOrRenamed].map(relative),
5277
+ removed: (options.removed ?? []).map(relative),
5278
+ read: (path) => readSource(join8(repoRoot, path)),
5279
+ ranges: (path) => changedRanges.get(join8(repoRoot, path)),
5280
+ typescript
5281
+ });
3688
5282
  if (triggered)
3689
- triggeredScanners.add(join7(repoRoot, declaration.test));
5283
+ triggeredScanners.add(join8(repoRoot, declaration.test));
3690
5284
  }
3691
- const anythingChanged = absChanged.size > 0 || changedPackageNames.size > 0;
5285
+ const anythingChanged = absChanged.size > 0 || changeFacts.packages.size > 0;
3692
5286
  const selected = [];
5287
+ const explanations = [];
5288
+ const native = [];
3693
5289
  let totalTestFiles = 0;
5290
+ const reasonFor = (pkg, test, maxDepth) => {
5291
+ const rel = test.slice(repoRoot.length + 1);
5292
+ const glob = (options.alwaysRun ?? []).find((_, i) => alwaysRunRegexes[i]?.test(rel));
5293
+ if (glob !== undefined)
5294
+ return { kind: "always-run", detail: "alwaysRun names this test", via: glob };
5295
+ if (addedOrRenamed.has(test))
5296
+ return { kind: "direct-dependency", detail: "the test file itself was added or renamed", via: rel };
5297
+ if (triggeredScanners.has(test))
5298
+ return { kind: "declared-input", detail: "the diff is this folder-scanning test's declared trigger", via: rel };
5299
+ for (const { config, pkg: owner, loaderFacts } of configs) {
5300
+ if (pkg !== owner)
5301
+ continue;
5302
+ if (options.depth !== "one")
5303
+ return { kind: "declared-input", detail: `${config.label} changed`, via: config.path };
5304
+ if (reaches(`${ALL_PREFIX}${test}`, edges, loaderFacts, 1))
5305
+ return {
5306
+ kind: "declared-input",
5307
+ detail: `${config.label} changed and this test reaches its loader`,
5308
+ via: config.path
5309
+ };
5310
+ }
5311
+ if (!anythingChanged)
5312
+ return null;
5313
+ const reach = reaches(`${ALL_PREFIX}${test}`, edges, changeFacts, maxDepth);
5314
+ return reach ? { ...reach, via: reach.via.startsWith(`${repoRoot}/`) ? reach.via.slice(repoRoot.length + 1) : reach.via } : null;
5315
+ };
3694
5316
  for (const pkg of packages) {
3695
5317
  const testFiles = pkgFiles.get(pkg).filter(isTestFile);
3696
5318
  totalTestFiles += testFiles.length;
3697
- if (!pkg.bunTestCompatible)
3698
- continue;
3699
5319
  const maxDepth = options.depth === "one" ? 1 : Number.POSITIVE_INFINITY;
5320
+ if (!pkg.bunTestCompatible) {
5321
+ if (options.nativeRunners !== "expose")
5322
+ continue;
5323
+ const runner = pkg.testRunner ?? "other";
5324
+ for (const test of testFiles)
5325
+ if (reasonFor(pkg, test, maxDepth))
5326
+ native.push({ test, runner });
5327
+ continue;
5328
+ }
3700
5329
  for (const test of testFiles) {
3701
- const forced = alwaysRunRegexes.some((re) => re.test(test.slice(repoRoot.length + 1))) || addedOrRenamed.has(test) || triggeredScanners.has(test) || rootConfigChanged && pkg === cliPackage;
3702
- if (forced || anythingChanged && reaches(`${ALL_PREFIX}${test}`, edges, changeFacts, maxDepth)) {
3703
- selected.push(test);
3704
- }
5330
+ const reason = reasonFor(pkg, test, maxDepth);
5331
+ if (!reason)
5332
+ continue;
5333
+ selected.push(test);
5334
+ explanations.push({ test: test.slice(repoRoot.length + 1), ...reason });
3705
5335
  }
3706
5336
  }
3707
- return { selected, totalTestFiles, resolver: graphTypescript ? "compiler" : "text-scan", programMs };
5337
+ return {
5338
+ selected,
5339
+ totalTestFiles,
5340
+ resolver: graph.graphTypescript ? "compiler" : "text-scan",
5341
+ programMs: graph.programMs,
5342
+ explanations,
5343
+ native
5344
+ };
3708
5345
  }
3709
5346
  function reaches(start, edges, changed, maxDepth = Number.POSITIVE_INFINITY) {
3710
5347
  const visited = new Set;
3711
5348
  const stack = [[start, 0]];
5349
+ const importKind = (depth) => depth === 0 ? "direct-dependency" : "transitive-dependency";
3712
5350
  while (stack.length > 0) {
3713
5351
  const [current, depth] = stack.pop();
3714
5352
  if (visited.has(current))
@@ -3716,7 +5354,11 @@ function reaches(start, edges, changed, maxDepth = Number.POSITIVE_INFINITY) {
3716
5354
  visited.add(current);
3717
5355
  const currentFile = current.startsWith(ALL_PREFIX) ? current.slice(ALL_PREFIX.length) : current.startsWith(OWN_PREFIX) ? current.slice(OWN_PREFIX.length) : null;
3718
5356
  if (current.startsWith(ALL_PREFIX) && currentFile && changed.files.has(currentFile))
3719
- return true;
5357
+ return {
5358
+ kind: importKind(Math.max(0, depth - 1)),
5359
+ detail: depth === 0 ? "the test file itself changed" : "imports the changed file",
5360
+ via: currentFile
5361
+ };
3720
5362
  if (depth >= maxDepth)
3721
5363
  continue;
3722
5364
  const ownPackage = currentFile ? changed.packageOfFile(currentFile) : null;
@@ -3726,48 +5368,85 @@ function reaches(start, edges, changed, maxDepth = Number.POSITIVE_INFINITY) {
3726
5368
  const cut = body.lastIndexOf(NAME_SEPARATOR);
3727
5369
  const file = body.slice(0, cut);
3728
5370
  if (changed.files.has(file) && changed.affects(file, body.slice(cut + 1)))
3729
- return true;
5371
+ return { kind: importKind(depth), detail: `uses the changed name ${body.slice(cut + 1)}`, via: file };
3730
5372
  continue;
3731
5373
  }
3732
5374
  if (dep.startsWith(TOUCH_PREFIX)) {
3733
- if (changed.files.has(dep.slice(TOUCH_PREFIX.length)))
3734
- return true;
5375
+ const file = dep.slice(TOUCH_PREFIX.length);
5376
+ if (changed.files.has(file))
5377
+ return { kind: importKind(depth), detail: "resolves through the changed file", via: file };
3735
5378
  continue;
3736
5379
  }
3737
5380
  if (dep.startsWith(SCAN_PREFIX)) {
3738
5381
  const root = dep.slice(SCAN_PREFIX.length);
3739
5382
  for (const f of changed.files)
3740
5383
  if (f === root || f.startsWith(`${root}/`))
3741
- return true;
5384
+ return { kind: "declared-input", detail: `reads the folder ${root} from disk`, via: f };
3742
5385
  continue;
3743
5386
  }
3744
5387
  if (dep.startsWith(EXTERNAL_PREFIX)) {
3745
5388
  const pkg = dep.slice(EXTERNAL_PREFIX.length);
3746
5389
  if (changed.packages.has(pkg) && pkg !== ownPackage)
3747
- return true;
5390
+ return {
5391
+ kind: "conservative-fallback",
5392
+ detail: "an import shape the graph cannot narrow keeps the whole-package edge",
5393
+ via: pkg
5394
+ };
3748
5395
  continue;
3749
5396
  }
3750
5397
  if (dep.startsWith(PKGMETA_PREFIX)) {
3751
5398
  const pkg = dep.slice(PKGMETA_PREFIX.length);
3752
5399
  if (changed.nonSourcePackages.has(pkg) && pkg !== ownPackage)
3753
- return true;
5400
+ return {
5401
+ kind: "declared-input",
5402
+ detail: "a non-source file of a package it resolves through changed",
5403
+ via: pkg
5404
+ };
3754
5405
  continue;
3755
5406
  }
3756
5407
  if (!visited.has(dep))
3757
5408
  stack.push([dep, depth + 1]);
3758
5409
  }
3759
5410
  }
3760
- return false;
5411
+ return null;
5412
+ }
5413
+ // src/lib/test-selector.ts
5414
+ var DEFAULT_CLI_ENTRYPOINT = "apps/cli/src/index.ts";
5415
+ var DEFAULT_CONFIG_LOADER = "apps/cli/src/lib/config.ts";
5416
+ var ROOT_CONFIG_FILENAME = "vinaya.config.json";
5417
+ function selectAffectedTestFiles(repoRoot, changedFiles, options = {}) {
5418
+ const cliEntrypoint = options.cliEntrypoint ?? DEFAULT_CLI_ENTRYPOINT;
5419
+ return selectAffectedFiles(diskTree(repoRoot), changedFiles, {
5420
+ ...options.alwaysRun ? { alwaysRun: options.alwaysRun } : {},
5421
+ ...options.addedOrRenamed ? { addedOrRenamed: options.addedOrRenamed } : {},
5422
+ ...options.removed ? { removed: options.removed } : {},
5423
+ ...options.changedRanges ? { changedRanges: options.changedRanges } : {},
5424
+ ...options.affectedNames ? { affectedNames: options.affectedNames } : {},
5425
+ ...options.repoTreeScanners ? { repoTreeScanners: options.repoTreeScanners } : {},
5426
+ ...options.resolver ? { resolver: options.resolver } : {},
5427
+ ...options.cliSpawnDetection ? { spawnDetection: options.cliSpawnDetection } : {},
5428
+ ...options.depth ? { depth: options.depth } : {},
5429
+ ...options.nativeRunners ? { nativeRunners: options.nativeRunners } : {},
5430
+ scannerDeclarations: options.scannerDeclarations ?? SCANNER_DECLARATIONS,
5431
+ spawnPrograms: [{ binary: CLI_SPAWN_BINARY, entrypoint: cliEntrypoint }],
5432
+ configInputs: [
5433
+ {
5434
+ path: ROOT_CONFIG_FILENAME,
5435
+ label: "the repository-root configuration file",
5436
+ ownerFile: cliEntrypoint,
5437
+ loader: options.configLoader ?? DEFAULT_CONFIG_LOADER
5438
+ }
5439
+ ]
5440
+ });
3761
5441
  }
3762
-
3763
5442
  // src/lib/pre-push-selection.ts
3764
- function prePushSelection(repoRoot, base = resolveRemoteBase(repoRoot)) {
3765
- const changed = changedFilesSinceRemoteBaseAbsolute(repoRoot, base);
3766
- const addedOrRenamed = addedOrRenamedFilesSinceRemoteBaseAbsolute(repoRoot, base);
3767
- const removed = removedFilesSinceRemoteBaseAbsolute(repoRoot, base);
5443
+ function prePushSelection(repoRoot, base = resolveRemoteBase(repoRoot), depth = "one", failure, nativeRunners = "exclude") {
5444
+ const changed = changedFilesSinceRemoteBaseAbsolute(repoRoot, base, failure);
5445
+ const addedOrRenamed = addedOrRenamedFilesSinceRemoteBaseAbsolute(repoRoot, base, failure);
5446
+ const removed = removedFilesSinceRemoteBaseAbsolute(repoRoot, base, failure);
3768
5447
  const alwaysRun = loadConfig()?.prePush?.alwaysRun ?? [];
3769
5448
  const typescript = loadTypeScript(repoRoot);
3770
- const diffs = typescript ? changedFileDiffsSinceRemoteBase(repoRoot, base) : undefined;
5449
+ const diffs = typescript ? changedFileDiffsSinceRemoteBase(repoRoot, base, failure) : undefined;
3771
5450
  const names = typescript && diffs ? affectedNames(typescript, diffs) : undefined;
3772
5451
  const changedRanges = diffs ? new Map(diffs.map((d) => [d.file, d.afterRanges])) : undefined;
3773
5452
  return selectAffectedTestFiles(repoRoot, changed, {
@@ -3776,7 +5455,8 @@ function prePushSelection(repoRoot, base = resolveRemoteBase(repoRoot)) {
3776
5455
  removed,
3777
5456
  changedRanges,
3778
5457
  affectedNames: names,
3779
- depth: "one"
5458
+ depth,
5459
+ nativeRunners
3780
5460
  });
3781
5461
  }
3782
5462
 
@@ -3784,12 +5464,53 @@ function prePushSelection(repoRoot, base = resolveRemoteBase(repoRoot)) {
3784
5464
  function main() {
3785
5465
  const repoRoot = process.cwd();
3786
5466
  const started = performance.now();
3787
- const { selected, totalTestFiles, resolver, programMs } = prePushSelection(repoRoot);
5467
+ const head = currentHead(repoRoot);
5468
+ const branch = currentBranch(repoRoot);
5469
+ const alwaysRun = (loadConfig()?.prePush?.alwaysRun ?? []).map(globToRegex);
5470
+ let sinceGreen = null;
5471
+ const { note, full } = decideSelection({
5472
+ repoRoot,
5473
+ head,
5474
+ branch,
5475
+ failed: readFailedTestsRecord(repoRoot),
5476
+ passing: readPassingRecord(repoRoot),
5477
+ context: computeVerificationContext(repoRoot)?.digest ?? null,
5478
+ inputsClean: verificationInputsDirty(repoRoot) === false,
5479
+ isAncestor: (ancestor) => isAncestor(repoRoot, ancestor, head),
5480
+ exists: existsSync4,
5481
+ changedBetween: (from) => changedBetween(repoRoot, from, head),
5482
+ isAlwaysRun: (path) => alwaysRun.some((re) => re.test(path.slice(repoRoot.length + 1))),
5483
+ sinceGreen: (from) => {
5484
+ const failure = { failed: false };
5485
+ const result = prePushSelection(repoRoot, from, "one", failure);
5486
+ sinceGreen = result;
5487
+ return { selected: result.selected, readFailed: failure.failed };
5488
+ },
5489
+ affectedSince: (changed) => selectAffectedTestFiles(repoRoot, changed, { depth: "one" }).selected,
5490
+ full: () => prePushSelection(repoRoot)
5491
+ });
5492
+ try {
5493
+ writeJsonUnderGit(repoRoot, SELECTION_NOTE, note);
5494
+ } catch {}
5495
+ const selected = note.selected;
3788
5496
  const elapsed = performance.now() - started;
3789
5497
  for (const file of selected)
3790
5498
  process.stdout.write(`${file}
3791
5499
  `);
3792
- process.stderr.write(`vinaya pre-push: selected ${selected.length} of ${totalTestFiles} test file(s) ` + `[${resolver}, ${elapsed.toFixed(0)} ms selector, ${programMs.toFixed(0)} ms program]
5500
+ if (full) {
5501
+ process.stderr.write(`vinaya pre-push: selected ${selected.length} of ${full.totalTestFiles} test file(s) ` + `[${full.resolver}, ${elapsed.toFixed(0)} ms selector, ${full.programMs.toFixed(0)} ms program]
5502
+ `);
5503
+ } else {
5504
+ const read = sinceGreen;
5505
+ process.stderr.write(`vinaya pre-push: selected ${selected.length} test file(s) since the last passing run ` + `[${read?.resolver ?? "none"}, ${elapsed.toFixed(0)} ms selector, ${(read?.programMs ?? 0).toFixed(0)} ms program]
5506
+ `);
5507
+ }
5508
+ if (note.mode === "rerun") {
5509
+ process.stderr.write(`vinaya pre-push: re-running only what failed at ${note.rerunOf?.slice(0, 12)} — ` + `${note.rerunFailed?.length ?? 0} failed file(s) + ${note.affectedSince?.length ?? 0} affected since, ` + `instead of the full ${note.fullCount}
5510
+ `);
5511
+ } else if (note.mode === "since-green") {
5512
+ process.stderr.write(`vinaya pre-push: running only what changed since the passing run at ${note.recordedHead.slice(0, 12)} — ` + `${note.affectedSince.length} affected file(s) plus the always-run files, instead of the full selection
3793
5513
  `);
5514
+ }
3794
5515
  }
3795
5516
  main();