@attalabs/vinaya 0.40.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 (157) hide show
  1. package/aeg-root/contracts/developer-reviewer.md +2 -2
  2. package/aeg-root/contracts/planner-developer.md +4 -4
  3. package/aeg-root/process.md +3 -3
  4. package/aeg-root/roles/developer/reference.md +3 -0
  5. package/aeg-root/state-machine.md +2 -2
  6. package/aeg-root/templates/brief-template.md +1 -1
  7. package/dist/checks/bin/check-body-bare-digits.js +165 -65
  8. package/dist/checks/bin/check-branch-topology.js +169 -60
  9. package/dist/checks/bin/check-brief-shape.js +165 -65
  10. package/dist/checks/bin/check-changeset-coverage.js +342 -122
  11. package/dist/checks/bin/check-ci-shard-coverage.js +384 -130
  12. package/dist/checks/bin/check-closes-n.js +169 -60
  13. package/dist/checks/bin/check-coherence.js +165 -65
  14. package/dist/checks/bin/check-dead-branch-push.js +142 -59
  15. package/dist/checks/bin/check-dispatch-readiness.js +211 -81
  16. package/dist/checks/bin/check-doc-claims.js +165 -65
  17. package/dist/checks/bin/check-doc-coverage-push.js +342 -122
  18. package/dist/checks/bin/check-doc-coverage.js +344 -124
  19. package/dist/checks/bin/check-doctrine-no-procedures.js +165 -65
  20. package/dist/checks/bin/check-doctrine-portability.js +342 -122
  21. package/dist/checks/bin/check-evidence-fresh.js +376 -129
  22. package/dist/checks/bin/check-exec-bits.js +342 -122
  23. package/dist/checks/bin/check-first-push-dispatch.js +208 -78
  24. package/dist/checks/bin/check-issue-milestone-attach.js +142 -59
  25. package/dist/checks/bin/check-issue-objectives-numbering.js +165 -65
  26. package/dist/checks/bin/check-issue-parts-coverage.js +142 -59
  27. package/dist/checks/bin/check-issue-surface-globs.js +218 -88
  28. package/dist/checks/bin/check-issue-title-grammar.js +142 -59
  29. package/dist/checks/bin/check-main-branch-refusal.js +142 -59
  30. package/dist/checks/bin/check-no-disk-state.js +142 -59
  31. package/dist/checks/bin/check-pr-premise-reassert.js +165 -65
  32. package/dist/checks/bin/check-pr-report-density.js +142 -59
  33. package/dist/checks/bin/check-principal-test-plan-wait.js +165 -65
  34. package/dist/checks/bin/check-quoted-command.js +338 -118
  35. package/dist/checks/bin/check-reader-resolvable-prose.js +338 -118
  36. package/dist/checks/bin/check-registry-gates.js +206 -78
  37. package/dist/checks/bin/check-retired-vocabulary.js +338 -118
  38. package/dist/checks/bin/check-review-gate.js +203 -83
  39. package/dist/checks/bin/check-single-plan-pr.js +142 -59
  40. package/dist/checks/bin/check-surface-scope.js +169 -60
  41. package/dist/checks/bin/check-test-plan.js +165 -65
  42. package/dist/checks/bin/check-token-collection-wired.js +142 -59
  43. package/dist/checks/bin/check-workspace-escape.js +340 -120
  44. package/dist/checks/bin/verify-coherence.js +153 -60
  45. package/dist/checks/bin/verify-dispatch.js +169 -69
  46. package/dist/checks/bin/verify-docs.js +142 -57
  47. package/dist/index.js +16280 -11764
  48. package/dist/lib/pre-push-cache-test-run.js +791 -68
  49. package/dist/lib/pre-push-changed-files.js +65 -19
  50. package/dist/lib/pre-push-mode.js +466 -0
  51. package/dist/lib/pre-push-progress-dir.js +4205 -0
  52. package/dist/lib/pre-push-record-tests.js +446 -0
  53. package/dist/lib/pre-push-select-tests.js +1426 -454
  54. package/dist/lib/push-progress-observer.js +4213 -0
  55. package/package.json +11 -5
  56. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/anchored-region.ts +5 -2
  57. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/brief-render.ts +18 -4
  58. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/brief-validation.ts +3 -3
  59. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/coherence-checks.ts +2 -2
  60. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/local.ts +88 -5
  61. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/records.ts +34 -2
  62. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/assess-round.ts +26 -4
  63. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/fakes.ts +7 -2
  64. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/index.ts +7 -1
  65. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/types.ts +17 -2
  66. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dispatch-gate.ts +13 -17
  67. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/docs/index.ts +1 -1
  68. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/docs/published-prose.ts +70 -45
  69. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/gate-audience.ts +1 -4
  70. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/index.ts +77 -7
  71. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/issue-assignment.ts +24 -54
  72. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/issue-validation.ts +221 -56
  73. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/live-record.ts +179 -0
  74. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/envelope.ts +8 -2
  75. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/index.ts +1 -0
  76. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/narration.ts +1 -0
  77. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/schema-digest.ts +225 -0
  78. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/schema.ts +7 -1
  79. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/main-branch-refusal.ts +23 -1
  80. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/principals-config.ts +44 -0
  81. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/prose-rules.ts +532 -0
  82. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/protected-paths.ts +31 -0
  83. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/reader-resolvable-prose.ts +157 -80
  84. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/registry-checks.ts +8 -12
  85. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/retired-vocabulary.ts +52 -109
  86. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-gate.ts +46 -17
  87. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-input-manifest.ts +85 -1
  88. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/ruling-ordinal.ts +46 -0
  89. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/task-branch-identity.ts +2 -4
  90. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/test-plan-gate.ts +63 -8
  91. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/verdict-extraction.ts +24 -0
  92. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/waiver-label.ts +0 -1
  93. package/studio-standalone/apps/vinaya-studio/web/.next/BUILD_ID +1 -1
  94. package/studio-standalone/apps/vinaya-studio/web/.next/build-manifest.json +3 -3
  95. package/studio-standalone/apps/vinaya-studio/web/.next/prerender-manifest.json +3 -3
  96. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.html +1 -1
  97. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.rsc +1 -1
  98. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  99. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  100. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  101. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  102. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  103. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page/server-reference-manifest.json +2 -2
  104. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page.js.nft.json +1 -1
  105. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  106. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page/server-reference-manifest.json +2 -2
  107. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page.js.nft.json +1 -1
  108. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page_client-reference-manifest.js +1 -1
  109. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page/server-reference-manifest.json +2 -2
  110. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page.js.nft.json +1 -1
  111. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page_client-reference-manifest.js +1 -1
  112. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page/server-reference-manifest.json +2 -2
  113. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page.js.nft.json +1 -1
  114. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page_client-reference-manifest.js +1 -1
  115. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page/server-reference-manifest.json +2 -2
  116. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page.js.nft.json +1 -1
  117. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page_client-reference-manifest.js +1 -1
  118. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page/server-reference-manifest.json +3 -3
  119. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page.js.nft.json +1 -1
  120. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page_client-reference-manifest.js +1 -1
  121. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page/server-reference-manifest.json +2 -2
  122. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page.js.nft.json +1 -1
  123. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page_client-reference-manifest.js +1 -1
  124. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page/server-reference-manifest.json +2 -2
  125. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page.js.nft.json +1 -1
  126. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page_client-reference-manifest.js +1 -1
  127. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page/server-reference-manifest.json +2 -2
  128. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page.js.nft.json +1 -1
  129. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page_client-reference-manifest.js +1 -1
  130. 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
  131. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__08e39jo._.js +1 -1
  132. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0ls23oh._.js +1 -1
  133. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1a3j3n1._.js +1 -1
  134. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{[root-of-the-server]__1wzfiav._.js → [root-of-the-server]__1d4eth3._.js} +1 -1
  135. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1gjqmhq._.js +1 -1
  136. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1snpgaw._.js +3 -3
  137. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1wc4-ip._.js +1 -1
  138. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_08onyya._.js +2 -2
  139. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_096f46i._.js +1 -1
  140. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0af2one._.js +1 -1
  141. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0e5tkdd._.js +1 -1
  142. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0kf2g72._.js +1 -1
  143. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0zf4d27._.js +3 -3
  144. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1-wo68i._.js +1 -1
  145. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1achbh9._.js +1 -1
  146. 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
  147. package/studio-standalone/apps/vinaya-studio/web/.next/server/middleware-build-manifest.js +3 -3
  148. package/studio-standalone/apps/vinaya-studio/web/.next/server/pages/500.html +1 -1
  149. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.js +1 -1
  150. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.json +4 -4
  151. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{38kom-9c-oi65.js → 0x7u6si-ai179.js} +1 -1
  152. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{1p3vr9qts86_b.js → 2fu7mfsj4oima.js} +1 -1
  153. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{21tunzmxjvm2a.js → 34b4ruddunn3q.js} +1 -1
  154. package/studio-standalone/apps/vinaya-studio/web/package.json +2 -2
  155. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{Y3oaZSTSP9PivUuJvxK1W → 2ZARxTwpuRew8-SvYsRdU}/_buildManifest.js +0 -0
  156. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{Y3oaZSTSP9PivUuJvxK1W → 2ZARxTwpuRew8-SvYsRdU}/_clientMiddlewareManifest.js +0 -0
  157. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{Y3oaZSTSP9PivUuJvxK1W → 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 z6 } 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";
@@ -1293,7 +1165,17 @@ var HeaderMetaV3Schema = z3.object({
1293
1165
  runtime: z3.string().nullable(),
1294
1166
  source: z3.string().nullable()
1295
1167
  }).strict();
1296
- 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
+ ]);
1297
1179
  var SubjectSchema = z3.object({
1298
1180
  issue: z3.number().int().nullable(),
1299
1181
  pr: z3.number().int().optional(),
@@ -1513,6 +1395,75 @@ var DevReviewLoopEventSchema = z3.discriminatedUnion("event", [
1513
1395
  round: z3.number().int(),
1514
1396
  phase: z3.string()
1515
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(),
1516
1467
  z3.object({
1517
1468
  ...loopShared,
1518
1469
  event: z3.literal("driver_exited"),
@@ -1700,7 +1651,7 @@ var EffectEventSchema = z3.discriminatedUnion("event", [
1700
1651
  ]);
1701
1652
  var CustomFieldValueSchema = z3.union([z3.string().max(CUSTOM_TEXT_MAX_LENGTH), z3.number().finite(), z3.boolean()]);
1702
1653
  var customShared = {
1703
- meta: HeaderMetaV3Schema,
1654
+ meta: HeaderMetaSchema,
1704
1655
  subject: SubjectSchema,
1705
1656
  kind: z3.literal("custom"),
1706
1657
  ...envelopeTail
@@ -1785,7 +1736,7 @@ function buildHeader(input) {
1785
1736
  const issue = subject.issue;
1786
1737
  return {
1787
1738
  meta: {
1788
- schema: 3,
1739
+ schema: 4,
1789
1740
  ts: input.now.toISOString(),
1790
1741
  run_id: input.runId,
1791
1742
  seq: input.seq,
@@ -1822,6 +1773,15 @@ function buildHeader(input) {
1822
1773
  version: lineageFieldFromEnv(input.env.flowVersion)
1823
1774
  },
1824
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
+ },
1825
1785
  source: lineageFieldFromEnv(input.env.source)
1826
1786
  },
1827
1787
  subject
@@ -1865,7 +1825,7 @@ function redact(value, home) {
1865
1825
  return value;
1866
1826
  }
1867
1827
  // ../../packages/aeg-core/src/log/store.ts
1868
- var KNOWN_SCHEMA_VERSIONS = [1, 2, 3];
1828
+ var KNOWN_SCHEMA_VERSIONS = [1, 2, 3, 4];
1869
1829
  function metaOf(obj) {
1870
1830
  if (obj === null || typeof obj !== "object")
1871
1831
  return null;
@@ -2089,6 +2049,16 @@ var ResolutionRecordSchema = z4.object({
2089
2049
  authenticatedFrom: z4.string().min(1),
2090
2050
  consumedAt: isoTimestamp
2091
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();
2092
2062
  // ../../packages/aeg-core/src/control-store/local.ts
2093
2063
  import {
2094
2064
  closeSync as closeSync2,
@@ -2204,6 +2174,17 @@ function mkdirNoSymlinks(dir, mode, trustedRoot) {
2204
2174
  });
2205
2175
  }
2206
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
+
2207
2188
  // src/checks/contract.ts
2208
2189
  var CHECK_SCHEMA_VERSION = 1;
2209
2190
  function emitCheckError(error) {
@@ -2664,7 +2645,8 @@ var VinayaConfigObjectSchema = z6.object({
2664
2645
  codeReviewThreshold: z6.string().min(1).optional(),
2665
2646
  securityThreshold: z6.string().min(1).optional(),
2666
2647
  maxRounds: z6.number().optional(),
2667
- maxTaskMinutes: z6.number().optional()
2648
+ maxTaskMinutes: z6.number().optional(),
2649
+ readyPushTimeoutMinutes: z6.number().optional()
2668
2650
  }).optional(),
2669
2651
  securityScan: z6.object({
2670
2652
  command: z6.array(z6.string().min(1)).min(1)
@@ -2680,7 +2662,16 @@ var VinayaConfigObjectSchema = z6.object({
2680
2662
  collisionThreshold: z6.number().int().nonnegative().optional()
2681
2663
  }).optional(),
2682
2664
  prePush: z6.object({
2683
- alwaysRun: z6.array(z6.string()).optional()
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()
2684
2675
  }).optional(),
2685
2676
  report: z6.object({
2686
2677
  commandTimeoutMs: z6.number().int().positive().optional()
@@ -2698,6 +2689,7 @@ var VinayaConfigObjectSchema = z6.object({
2698
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)"
2699
2690
  }),
2700
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(),
2701
2693
  logs: z6.object({
2702
2694
  folder: z6.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
2703
2695
  url: z6.string().url().optional(),
@@ -2710,7 +2702,7 @@ var VinayaConfigObjectSchema = z6.object({
2710
2702
  message: "logs: headers requires url"
2711
2703
  }).refine((v) => v.readHeaders === undefined || v.url !== undefined, {
2712
2704
  message: "logs: readHeaders requires url"
2713
- }).optional(),
2705
+ }).or(z6.literal(false)).optional(),
2714
2706
  decisionRecords: z6.object({
2715
2707
  path: RepoRelativePathSchema
2716
2708
  }).strict().optional()
@@ -2817,6 +2809,7 @@ function stripGlobalOnlyKeys(config, path) {
2817
2809
  }
2818
2810
  return result;
2819
2811
  }
2812
+ var emittedLocalOverrideWarnings = new Set;
2820
2813
  function resolveRuntimeDirSetting(config) {
2821
2814
  return config?.runtimeDir ?? null;
2822
2815
  }
@@ -3047,15 +3040,249 @@ ${detail}`;
3047
3040
  }
3048
3041
  var TOKENS_COLLECT_TRUST_PATH = join2(GLOBAL_VINAYA_HOME, "tokens-collect-trust.json");
3049
3042
 
3050
- // src/lib/remote-base.ts
3043
+ // src/lib/pre-push-failed-tests.ts
3051
3044
  import { execFileSync as execFileSync3 } from "node:child_process";
3052
- import { join as join3 } from "node:path";
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
+ }
3081
+ }
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)));
3086
+ }
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);
3106
+ }
3107
+ if (failed.size === 0)
3108
+ return exitedNonZero ? "all" : [];
3109
+ return [...failed].sort();
3110
+ }
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
+ };
3142
+ }
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" };
3147
+ }
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
+ }
3053
3281
  function cleanGitEnv() {
3054
3282
  const env = { ...process.env };
3055
- for (const key of Object.keys(env)) {
3283
+ for (const key of Object.keys(env))
3056
3284
  if (key.startsWith("GIT_"))
3057
3285
  delete env[key];
3058
- }
3059
3286
  return env;
3060
3287
  }
3061
3288
  function git(repoRoot, args) {
@@ -3067,50 +3294,347 @@ function git(repoRoot, args) {
3067
3294
  env: cleanGitEnv()
3068
3295
  }).trim();
3069
3296
  } catch {
3070
- return "";
3297
+ return null;
3071
3298
  }
3072
3299
  }
3073
- function resolveRemoteBase(repoRoot) {
3074
- const upstream = git(repoRoot, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]);
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);
3305
+ }
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;
3522
+ }
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}"]);
3075
3599
  if (upstream)
3076
3600
  return upstream;
3077
- const originMain = git(repoRoot, ["rev-parse", "--verify", "--quiet", "origin/main"]);
3601
+ const originMain = git2(repoRoot, ["rev-parse", "--verify", "--quiet", "origin/main"]);
3078
3602
  if (originMain)
3079
3603
  return "origin/main";
3080
3604
  return "HEAD~1";
3081
3605
  }
3082
- function changedFilesSinceRemoteBase(repoRoot, base = resolveRemoteBase(repoRoot)) {
3083
- const out = git(repoRoot, ["diff", "--name-only", "--diff-filter=ACMR", `${base}...HEAD`]);
3606
+ function changedFilesSinceRemoteBase(repoRoot, base = resolveRemoteBase(repoRoot), failure) {
3607
+ const out = git2(repoRoot, ["diff", "--name-only", "--diff-filter=ACMR", `${base}...HEAD`], failure);
3084
3608
  return out.split(`
3085
3609
  `).map((s) => s.trim()).filter(Boolean);
3086
3610
  }
3087
- function changedFilesSinceRemoteBaseAbsolute(repoRoot, base = resolveRemoteBase(repoRoot)) {
3088
- return changedFilesSinceRemoteBase(repoRoot, base).map((f) => join3(repoRoot, f));
3611
+ function changedFilesSinceRemoteBaseAbsolute(repoRoot, base = resolveRemoteBase(repoRoot), failure) {
3612
+ return changedFilesSinceRemoteBase(repoRoot, base, failure).map((f) => join4(repoRoot, f));
3089
3613
  }
3090
- function addedOrRenamedFilesSinceRemoteBase(repoRoot, base = resolveRemoteBase(repoRoot)) {
3091
- const out = git(repoRoot, ["diff", "--name-only", "--diff-filter=AR", `${base}...HEAD`]);
3614
+ function addedOrRenamedFilesSinceRemoteBase(repoRoot, base = resolveRemoteBase(repoRoot), failure) {
3615
+ const out = git2(repoRoot, ["diff", "--name-only", "--diff-filter=AR", `${base}...HEAD`], failure);
3092
3616
  return out.split(`
3093
3617
  `).map((s) => s.trim()).filter(Boolean);
3094
3618
  }
3095
- function addedOrRenamedFilesSinceRemoteBaseAbsolute(repoRoot, base = resolveRemoteBase(repoRoot)) {
3096
- return addedOrRenamedFilesSinceRemoteBase(repoRoot, base).map((f) => join3(repoRoot, f));
3619
+ function addedOrRenamedFilesSinceRemoteBaseAbsolute(repoRoot, base = resolveRemoteBase(repoRoot), failure) {
3620
+ return addedOrRenamedFilesSinceRemoteBase(repoRoot, base, failure).map((f) => join4(repoRoot, f));
3097
3621
  }
3098
- function removedFilesSinceRemoteBase(repoRoot, base = resolveRemoteBase(repoRoot)) {
3099
- const out = git(repoRoot, ["diff", "--name-status", "--diff-filter=DR", `${base}...HEAD`]);
3622
+ function removedFilesSinceRemoteBase(repoRoot, base = resolveRemoteBase(repoRoot), failure) {
3623
+ const out = git2(repoRoot, ["diff", "--name-status", "--diff-filter=DR", `${base}...HEAD`], failure);
3100
3624
  return out.split(`
3101
3625
  `).map((line) => line.split("\t")).filter((fields) => fields.length >= 2).map((fields) => fields[1].trim()).filter(Boolean);
3102
3626
  }
3103
- function removedFilesSinceRemoteBaseAbsolute(repoRoot, base = resolveRemoteBase(repoRoot)) {
3104
- 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));
3105
3629
  }
3106
- function changedFileDiffsSinceRemoteBase(repoRoot, base = resolveRemoteBase(repoRoot)) {
3107
- 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;
3108
3632
  const out = [];
3109
- for (const relative of changedFilesSinceRemoteBase(repoRoot, base)) {
3110
- 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);
3111
3635
  const { beforeRanges, afterRanges } = parseHunkRanges(patch);
3112
3636
  out.push({
3113
- file: join3(repoRoot, relative),
3637
+ file: join4(repoRoot, relative),
3114
3638
  after: showBlob(repoRoot, "HEAD", relative),
3115
3639
  before: showBlob(repoRoot, mergeBase, relative),
3116
3640
  beforeRanges,
@@ -3121,24 +3645,20 @@ function changedFileDiffsSinceRemoteBase(repoRoot, base = resolveRemoteBase(repo
3121
3645
  }
3122
3646
  function showBlob(repoRoot, ref, relative) {
3123
3647
  try {
3124
- return execFileSync3("git", ["show", `${ref}:${relative}`], {
3648
+ return execFileSync4("git", ["show", `${ref}:${relative}`], {
3125
3649
  cwd: repoRoot,
3126
3650
  encoding: "utf8",
3127
3651
  maxBuffer: 64 * 1024 * 1024,
3128
3652
  stdio: ["ignore", "pipe", "ignore"],
3129
- env: cleanGitEnv()
3653
+ env: cleanGitEnv2()
3130
3654
  });
3131
3655
  } catch {
3132
3656
  return null;
3133
3657
  }
3134
3658
  }
3135
3659
 
3136
- // src/lib/test-selector.ts
3137
- import { readdirSync as readdirSync2, readFileSync as readFileSync4, statSync as statSync2 } from "node:fs";
3138
- import { dirname as dirname6, extname, isAbsolute as isAbsolute4, join as join7, resolve as resolve6 } from "node:path";
3139
-
3140
- // src/lib/cli-spawn-tests.ts
3141
- 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";
3142
3662
  function evaluateExpression(ts, node, file, fileDir, repoRoot, bindings) {
3143
3663
  if (ts.isStringLiteral(node))
3144
3664
  return node.text;
@@ -3159,7 +3679,7 @@ function evaluateExpression(ts, node, file, fileDir, repoRoot, bindings) {
3159
3679
  if (callee === "dirname") {
3160
3680
  const arg = node.arguments[0];
3161
3681
  const inner = arg ? evaluateExpression(ts, arg, file, fileDir, repoRoot, bindings) : null;
3162
- return inner !== null ? dirname3(inner) : null;
3682
+ return inner !== null ? dirname4(inner) : null;
3163
3683
  }
3164
3684
  if (callee === "fileURLToPath") {
3165
3685
  const arg = node.arguments[0];
@@ -3176,9 +3696,9 @@ function evaluateExpression(ts, node, file, fileDir, repoRoot, bindings) {
3176
3696
  if (parts.length === 0)
3177
3697
  return null;
3178
3698
  const first = parts[0];
3179
- if (!isAbsolute2(first))
3699
+ if (!isAbsolute3(first))
3180
3700
  return null;
3181
- return callee === "join" ? join4(...parts) : resolve3(...parts);
3701
+ return callee === "join" ? join5(...parts) : resolve3(...parts);
3182
3702
  }
3183
3703
  return null;
3184
3704
  }
@@ -3189,7 +3709,7 @@ function evaluateExpression(ts, node, file, fileDir, repoRoot, bindings) {
3189
3709
  const relativeArg = node.arguments?.[0];
3190
3710
  if (!relativeArg || !ts.isStringLiteral(relativeArg))
3191
3711
  return null;
3192
- return join4(fileDir, relativeArg.text);
3712
+ return join5(fileDir, relativeArg.text);
3193
3713
  }
3194
3714
  return null;
3195
3715
  }
@@ -3208,8 +3728,8 @@ function collectTopLevelBindings(ts, sourceFile, file, fileDir, repoRoot) {
3208
3728
  }
3209
3729
  return bindings;
3210
3730
  }
3211
- function cliSpawnEdgeOf(ts, file, source, repoRoot, entrypoint) {
3212
- const fileDir = dirname3(file);
3731
+ function spawnEdgeOf(ts, file, source, repoRoot, program) {
3732
+ const fileDir = dirname4(file);
3213
3733
  let sourceFile;
3214
3734
  try {
3215
3735
  sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.ES2022, true);
@@ -3230,18 +3750,18 @@ function cliSpawnEdgeOf(ts, file, source, repoRoot, entrypoint) {
3230
3750
  }
3231
3751
  }
3232
3752
  }
3233
- let sawBun = false;
3753
+ let sawBinary = false;
3234
3754
  let sawEntrypoint = false;
3235
3755
  for (const candidate of candidates) {
3236
3756
  const value = evaluateExpression(ts, candidate, file, fileDir, repoRoot, bindings);
3237
- if (value === "bun")
3238
- sawBun = true;
3239
- else if (value === entrypoint)
3757
+ if (value === program.binary)
3758
+ sawBinary = true;
3759
+ else if (value === program.entrypoint)
3240
3760
  sawEntrypoint = true;
3241
3761
  }
3242
- if (sawBun && sawEntrypoint)
3762
+ if (sawBinary && sawEntrypoint)
3243
3763
  classification = "entrypoint";
3244
- else if ((sawBun || sawEntrypoint) && classification !== "entrypoint")
3764
+ else if ((sawBinary || sawEntrypoint) && classification !== "entrypoint")
3245
3765
  classification = "fallback";
3246
3766
  }
3247
3767
  ts.forEachChild(node, visit);
@@ -3249,9 +3769,116 @@ function cliSpawnEdgeOf(ts, file, source, repoRoot, entrypoint) {
3249
3769
  visit(sourceFile);
3250
3770
  return classification;
3251
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
+ }
3252
3845
 
3253
- // src/lib/repo-scanner-tests.ts
3254
- 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
3255
3882
  var TREE_READERS = new Set([
3256
3883
  "readdirSync",
3257
3884
  "readdir",
@@ -3291,9 +3918,9 @@ function evaluatePath(ts, node, fileDir, repoRoot, bindings) {
3291
3918
  if (parts.length === 0)
3292
3919
  return null;
3293
3920
  const first = parts[0];
3294
- if (!isAbsolute3(first))
3921
+ if (!isAbsolute4(first))
3295
3922
  return null;
3296
- return callee === "join" ? join5(...parts) : resolve4(...parts);
3923
+ return callee === "join" ? join6(...parts) : resolve4(...parts);
3297
3924
  }
3298
3925
  return null;
3299
3926
  }
@@ -3304,12 +3931,12 @@ function evaluatePath(ts, node, fileDir, repoRoot, bindings) {
3304
3931
  const relativeArg = node.arguments?.[0];
3305
3932
  if (!relativeArg || !ts.isStringLiteral(relativeArg))
3306
3933
  return null;
3307
- return join5(fileDir, relativeArg.text);
3934
+ return join6(fileDir, relativeArg.text);
3308
3935
  }
3309
3936
  return null;
3310
3937
  }
3311
3938
  function scannedRootsOf(ts, file, source, repoRoot) {
3312
- const fileDir = dirname4(file);
3939
+ const fileDir = dirname5(file);
3313
3940
  let sourceFile;
3314
3941
  try {
3315
3942
  sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.ES2022, true);
@@ -3333,30 +3960,80 @@ function scannedRootsOf(ts, file, source, repoRoot) {
3333
3960
  let readsTreeSomehow = false;
3334
3961
  const visit = (node) => {
3335
3962
  if (ts.isCallExpression(node)) {
3336
- const callee = ts.isIdentifier(node.expression) ? node.expression.text : ts.isPropertyAccessExpression(node.expression) ? node.expression.name.text : "";
3337
- if (TREE_READERS.has(callee)) {
3338
- readsTreeSomehow = true;
3339
- const arg = node.arguments[0];
3340
- const target = arg ? evaluatePath(ts, arg, fileDir, repoRoot, bindings) : null;
3341
- if (target && (target === repoRoot || target.startsWith(`${repoRoot}/`)))
3342
- walked.add(target);
3343
- } else if (SPAWN_CALLS.has(callee)) {
3344
- if (node.arguments.some((a) => a.getText().includes(GIT_TREE_SUBCOMMAND))) {
3345
- readsTreeSomehow = true;
3346
- walked.add(repoRoot);
3347
- }
3963
+ const callee = ts.isIdentifier(node.expression) ? node.expression.text : ts.isPropertyAccessExpression(node.expression) ? node.expression.name.text : "";
3964
+ if (TREE_READERS.has(callee)) {
3965
+ readsTreeSomehow = true;
3966
+ const arg = node.arguments[0];
3967
+ const target = arg ? evaluatePath(ts, arg, fileDir, repoRoot, bindings) : null;
3968
+ if (target && (target === repoRoot || target.startsWith(`${repoRoot}/`)))
3969
+ walked.add(target);
3970
+ } else if (SPAWN_CALLS.has(callee)) {
3971
+ if (node.arguments.some((a) => a.getText().includes(GIT_TREE_SUBCOMMAND))) {
3972
+ readsTreeSomehow = true;
3973
+ walked.add(repoRoot);
3974
+ }
3975
+ }
3976
+ }
3977
+ ts.forEachChild(node, visit);
3978
+ };
3979
+ ts.forEachChild(sourceFile, visit);
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;
3348
4028
  }
3349
4029
  }
3350
4030
  ts.forEachChild(node, visit);
3351
4031
  };
3352
4032
  ts.forEachChild(sourceFile, visit);
3353
- if (!readsTreeSomehow)
3354
- return [];
3355
- const roots = walked.size > 0 ? [...walked] : declaredRoots;
3356
- if (roots.length === 0)
3357
- return [];
3358
- return roots.filter((r) => !roots.some((other) => other !== r && r.startsWith(`${other}/`))).sort();
4033
+ return found;
3359
4034
  }
4035
+
4036
+ // src/lib/repo-scanner-tests.ts
3360
4037
  var SCANNER_DECLARATIONS = [
3361
4038
  {
3362
4039
  test: "apps/cli/tests/conformance/dev-review-engine-architecture-exit.test.ts",
@@ -3403,6 +4080,8 @@ var SCANNER_DECLARATIONS = [
3403
4080
  { test: "apps/cli/tests/platform-independence.test.ts", roots: ["apps/cli/tests/"], trigger: "content" },
3404
4081
  { test: "apps/cli/tests/process-fixture-coverage.test.ts", roots: ["apps/cli/tests/"], trigger: "process-start" },
3405
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" },
3406
4085
  { test: "apps/cli/tests/checks/bin-permissions.test.ts", roots: ["."], trigger: "content" },
3407
4086
  {
3408
4087
  test: "apps/cli/tests/checks/registry-gates.test.ts",
@@ -3457,6 +4136,17 @@ var SCANNER_DECLARATIONS = [
3457
4136
  trigger: "content"
3458
4137
  },
3459
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
+ },
3460
4150
  {
3461
4151
  test: "apps/cli/tests/log-destination-isolation.test.ts",
3462
4152
  roots: ["apps/cli/src/", "apps/cli/tests/"],
@@ -3488,46 +4178,19 @@ var SCANNER_DECLARATIONS = [
3488
4178
  { test: "packages/aeg-core/src/no-binary-sources.test.ts", roots: ["."], trigger: "content" },
3489
4179
  { test: "packages/aeg-core/src/retired-vocabulary.test.ts", roots: ["."], trigger: "content" }
3490
4180
  ];
3491
- function underDeclaredRoot(path, root) {
3492
- return root === "." || path.startsWith(root);
3493
- }
3494
- var PROCESS_CALLS = new Set([...SPAWN_CALLS, "fork"]);
3495
- function startsProcessIn(ts, file, source, ranges) {
3496
- let sourceFile;
3497
- try {
3498
- sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.ES2022, true);
3499
- } catch {
3500
- return false;
3501
- }
3502
- const touched = (node) => {
3503
- if (!ranges)
3504
- return true;
3505
- const first = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
3506
- const last = sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line + 1;
3507
- return ranges.some((r) => r.start <= last && r.end >= first);
3508
- };
3509
- let found = false;
3510
- const visit = (node) => {
3511
- if (found)
3512
- return;
3513
- if (ts.isCallExpression(node)) {
3514
- const callee = ts.isIdentifier(node.expression) ? node.expression.text : ts.isPropertyAccessExpression(node.expression) && node.expression.name.text !== "exec" ? node.expression.name.text : "";
3515
- if (PROCESS_CALLS.has(callee) && touched(node)) {
3516
- found = true;
3517
- return;
3518
- }
3519
- }
3520
- ts.forEachChild(node, visit);
3521
- };
3522
- ts.forEachChild(sourceFile, visit);
3523
- return found;
3524
- }
3525
4181
 
3526
- // 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
3527
4187
  import { createRequire } from "node:module";
3528
- 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";
3529
4189
  function loadTypeScript(repoRoot) {
3530
- 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) {
3531
4194
  try {
3532
4195
  const loaded = createRequire(from)("typescript");
3533
4196
  if (loaded && typeof loaded.createProgram === "function" && loaded.ScriptTarget)
@@ -3562,15 +4225,37 @@ function graphCompilerOptions(ts, input) {
3562
4225
  resolveJsonModule: true
3563
4226
  };
3564
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
+ }
3565
4250
  function buildCompilerGraph(ts, input) {
3566
4251
  const { files, packageOfFile, packageOfBareSpecifier } = input;
3567
4252
  const fileSet = new Set(files);
3568
4253
  const options = graphCompilerOptions(ts, input);
4254
+ const host = input.host ? viewCompilerHost(ts, options, input.repoRoot, input.host) : ts.createCompilerHost(options);
3569
4255
  const t0 = performance.now();
3570
- const program = ts.createProgram([...files], options);
4256
+ const program = input.host ? ts.createProgram([...files], options, host) : ts.createProgram([...files], options);
3571
4257
  const checker = program.getTypeChecker();
3572
4258
  const programMs = performance.now() - t0;
3573
- const host = ts.createCompilerHost(options);
3574
4259
  const resolutionCache = new Map;
3575
4260
  const resolveToWorkspaceFile = (specifier, containingFile) => {
3576
4261
  const key = `${containingFile}
@@ -3655,7 +4340,7 @@ ${specifier}`;
3655
4340
  const resolveWithLiteral = (specifier, into) => {
3656
4341
  const target = resolveToWorkspaceFile(specifier, file);
3657
4342
  if (specifier.startsWith(".")) {
3658
- const literal = resolve5(dirname5(file), specifier);
4343
+ const literal = resolve5(dirname6(file), specifier);
3659
4344
  if (literal !== target && fileSet.has(literal))
3660
4345
  into.push(`${ALL_PREFIX}${literal}`);
3661
4346
  }
@@ -3788,7 +4473,52 @@ ${specifier}`;
3788
4473
  return { edges, programMs };
3789
4474
  }
3790
4475
 
3791
- // 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;
3792
4522
  var SOURCE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
3793
4523
  var SKIP_DIRS = new Set(["node_modules", "dist", ".git", "build", "coverage"]);
3794
4524
  var OUTPUT_TO_SOURCE_EXTENSIONS = new Map([
@@ -3866,26 +4596,20 @@ function extractImportRecords(source) {
3866
4596
  function extractOwnImportRecords(source) {
3867
4597
  return collectRecords(source, false);
3868
4598
  }
3869
- function walkFiles(root) {
4599
+ function walkTree(tree, root) {
3870
4600
  const out = [];
3871
- let entries;
3872
- try {
3873
- entries = readdirSync2(root);
3874
- } catch {
4601
+ const entries = tree.readDir(root);
4602
+ if (entries === null)
3875
4603
  return out;
3876
- }
3877
4604
  for (const entry of entries) {
3878
4605
  if (SKIP_DIRS.has(entry))
3879
4606
  continue;
3880
- const abs = join7(root, entry);
3881
- let s;
3882
- try {
3883
- s = statSync2(abs);
3884
- } catch {
4607
+ const abs = join8(root, entry);
4608
+ const kind = tree.kind(abs);
4609
+ if (kind === null)
3885
4610
  continue;
3886
- }
3887
- if (s.isDirectory()) {
3888
- out.push(...walkFiles(abs));
4611
+ if (kind === "directory") {
4612
+ out.push(...walkTree(tree, abs));
3889
4613
  } else {
3890
4614
  out.push(abs);
3891
4615
  }
@@ -3906,7 +4630,7 @@ function resolveFileCandidate(base, knownFiles) {
3906
4630
  return base + ext;
3907
4631
  }
3908
4632
  for (const ext of SOURCE_EXTENSIONS) {
3909
- const indexed = join7(base, `index${ext}`);
4633
+ const indexed = join8(base, `index${ext}`);
3910
4634
  if (knownFiles.has(indexed))
3911
4635
  return indexed;
3912
4636
  }
@@ -3915,13 +4639,22 @@ function resolveFileCandidate(base, knownFiles) {
3915
4639
  function resolveRelativeImport(fromFile, specifier, knownFiles) {
3916
4640
  if (!specifier.startsWith("."))
3917
4641
  return null;
3918
- return resolveFileCandidate(resolve6(dirname6(fromFile), specifier), knownFiles);
4642
+ return resolveFileCandidate(resolve6(dirname7(fromFile), specifier), knownFiles);
3919
4643
  }
3920
4644
  function isBunTestScript(script) {
3921
4645
  if (!script)
3922
4646
  return true;
3923
4647
  return /(^|[\s;&|])bun\s+test\b/.test(script);
3924
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
+ }
3925
4658
  var TYPE_ONLY_CONDITIONS = new Set(["types", "typings"]);
3926
4659
  function declaredTargets(value, out = []) {
3927
4660
  if (typeof value === "string") {
@@ -3963,48 +4696,104 @@ function deriveEntrypoints(dir, pkg, knownFiles) {
3963
4696
  add(".", pkg.main);
3964
4697
  return out;
3965
4698
  }
3966
- function discoverWorkspacePackages(repoRoot) {
3967
- const rootPkgPath = join7(repoRoot, "package.json");
3968
- let workspaces = [];
4699
+ function readWorkspacePatterns(tree) {
3969
4700
  try {
3970
- const rootPkg = JSON.parse(readFileSync4(rootPkgPath, "utf8"));
3971
- 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");
3972
4704
  } catch {
3973
- return [];
4705
+ return null;
3974
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
+ };
3975
4746
  const out = [];
3976
- for (const glob of workspaces) {
3977
- const m = /^([^*]+)\*$/.exec(glob);
3978
- 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);
3979
4753
  continue;
3980
- const parentDir = join7(repoRoot, m[1].replace(/\/$/, ""));
3981
- 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) => {
3982
4766
  try {
3983
- 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;
3984
4769
  } catch {
3985
- continue;
4770
+ return false;
3986
4771
  }
3987
- for (const entry of entries) {
3988
- const dir = join7(parentDir, entry);
3989
- const pkgPath = join7(dir, "package.json");
3990
- let pkg;
3991
- try {
3992
- pkg = JSON.parse(readFileSync4(pkgPath, "utf8"));
3993
- } catch {
3994
- continue;
3995
- }
3996
- if (!pkg.name)
3997
- continue;
3998
- const sourceFiles = walkFiles(dir).filter((f) => SOURCE_EXTENSIONS.includes(extname(f)));
3999
- const knownFiles = new Set(sourceFiles);
4000
- out.push({
4001
- dir,
4002
- name: pkg.name,
4003
- bunTestCompatible: isBunTestScript(pkg.scripts?.test),
4004
- entrypoints: deriveEntrypoints(dir, pkg, knownFiles),
4005
- sourceFiles
4006
- });
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;
4007
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
+ });
4008
4797
  }
4009
4798
  return out;
4010
4799
  }
@@ -4082,16 +4871,12 @@ function parseExportTable(source) {
4082
4871
  return { directDefs, localReexports, namedReexports, starReexports, starAsNames, imports, ownImports };
4083
4872
  }
4084
4873
  var UNRESOLVED = { resolved: false };
4085
- function makeSourceReader() {
4874
+ function makeSourceReader(tree) {
4086
4875
  const cache = new Map;
4087
4876
  return (file) => {
4088
4877
  let cached = cache.get(file);
4089
4878
  if (cached === undefined) {
4090
- try {
4091
- cached = readFileSync4(file, "utf8");
4092
- } catch {
4093
- cached = "";
4094
- }
4879
+ cached = tree.readFile(file) ?? "";
4095
4880
  cache.set(file, cached);
4096
4881
  }
4097
4882
  return cached;
@@ -4221,14 +5006,10 @@ function resolveThroughTable(ctx, file, name, table, stack) {
4221
5006
  hopDeps: new Set([...ownHopDeps(), ...only.hopDeps])
4222
5007
  };
4223
5008
  }
4224
- var DEFAULT_CLI_ENTRYPOINT = "apps/cli/src/index.ts";
4225
- var ROOT_CONFIG_FILENAME = "vinaya.config.json";
4226
- function selectAffectedTestFiles(repoRoot, changedFiles, options = {}) {
4227
- const packages = discoverWorkspacePackages(repoRoot);
4228
- const absChanged = new Set(changedFiles.map((f) => isAbsolute4(f) ? f : join7(repoRoot, f)));
4229
- const alwaysRunRegexes = (options.alwaysRun ?? []).map(globToRegex);
4230
- const addedOrRenamed = new Set((options.addedOrRenamed ?? []).map((f) => isAbsolute4(f) ? f : join7(repoRoot, f)));
4231
- const readSource = makeSourceReader();
5009
+ function buildSelectionGraph(tree, options) {
5010
+ const repoRoot = tree.root;
5011
+ const packages = discoverWorkspacePackages(tree);
5012
+ const readSource = makeSourceReader(tree);
4232
5013
  const tableCache = new Map;
4233
5014
  const resultCache = new Map;
4234
5015
  const pkgFiles = new Map;
@@ -4244,16 +5025,14 @@ function selectAffectedTestFiles(repoRoot, changedFiles, options = {}) {
4244
5025
  allSourceFiles.add(f);
4245
5026
  }
4246
5027
  }
4247
- const changedPackageNames = new Set;
4248
- const nonSourceChangedPackages = new Set;
4249
- for (const pkg of packages) {
4250
- for (const f of absChanged) {
4251
- if (!f.startsWith(`${pkg.dir}/`))
4252
- continue;
4253
- changedPackageNames.add(pkg.name);
4254
- if (!allSourceFiles.has(f))
4255
- nonSourceChangedPackages.add(pkg.name);
4256
- }
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
+ }
4257
5036
  }
4258
5037
  const matchPackage = (specifier) => {
4259
5038
  let best = null;
@@ -4282,7 +5061,7 @@ function selectAffectedTestFiles(repoRoot, changedFiles, options = {}) {
4282
5061
  return m ? { name: m.pkg.name, entry: m.pkg.entrypoints.get(m.subpath) ?? null } : null;
4283
5062
  }
4284
5063
  };
4285
- const typescript = loadTypeScript(repoRoot);
5064
+ const typescript = options.typescript;
4286
5065
  const graphTypescript = options.resolver === "text-scan" ? null : typescript;
4287
5066
  const edges = new Map;
4288
5067
  let programMs = 0;
@@ -4298,107 +5077,91 @@ function selectAffectedTestFiles(repoRoot, changedFiles, options = {}) {
4298
5077
  files: [...allSourceFiles],
4299
5078
  packageOfFile: (f) => fileToPackage.get(f) ?? null,
4300
5079
  packageOfBareSpecifier: (specifier) => matchPackage(specifier)?.pkg.name ?? null,
4301
- entrypoints
5080
+ entrypoints,
5081
+ ...tree.host ? { host: tree.host } : {}
4302
5082
  });
4303
5083
  for (const [node, deps] of graph.edges)
4304
5084
  edges.set(node, deps);
4305
5085
  programMs = graph.programMs;
4306
5086
  } else {
4307
- buildTextScanGraph();
5087
+ for (const pkg of packages)
5088
+ textScanEdges(pkgFiles.get(pkg), pkgKnownFiles.get(pkg));
5089
+ if (unpackaged.length > 0)
5090
+ textScanEdges(unpackaged, allSourceFiles);
4308
5091
  }
4309
- function buildTextScanGraph() {
4310
- for (const pkg of packages) {
4311
- const knownFiles = pkgKnownFiles.get(pkg);
4312
- for (const file of pkgFiles.get(pkg)) {
4313
- const deps = [];
4314
- const coarsePackages = new Set;
4315
- const resolvedNamed = new Map;
4316
- for (const record of extractImportRecords(readSource(file))) {
4317
- const specifier = record.specifier;
4318
- if (specifier.startsWith(".")) {
4319
- const resolved = resolveRelativeImport(file, specifier, knownFiles);
4320
- if (resolved)
4321
- deps.push(resolved);
4322
- continue;
4323
- }
4324
- const match = matchPackage(specifier);
4325
- if (!match)
4326
- continue;
4327
- if (coarsePackages.has(match.pkg.name))
4328
- continue;
4329
- const entry = match.pkg.entrypoints.get(match.subpath);
4330
- 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) {
4331
5119
  coarsePackages.add(match.pkg.name);
4332
- continue;
5120
+ acc = undefined;
5121
+ resolvedNamed.delete(match.pkg.name);
5122
+ break;
4333
5123
  }
4334
- let acc = resolvedNamed.get(match.pkg.name);
4335
- for (const name of record.names) {
4336
- const resolution = resolveExportedName(ctx, entry, name, new Set);
4337
- if (!resolution.resolved) {
4338
- coarsePackages.add(match.pkg.name);
4339
- acc = undefined;
4340
- resolvedNamed.delete(match.pkg.name);
4341
- break;
4342
- }
4343
- if (!acc) {
4344
- acc = { touched: new Set, definers: new Set, hopDeps: new Set };
4345
- resolvedNamed.set(match.pkg.name, acc);
4346
- }
4347
- for (const t of resolution.touched)
4348
- acc.touched.add(t);
4349
- for (const d of resolution.definers)
4350
- acc.definers.add(d);
4351
- for (const h of resolution.hopDeps)
4352
- 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);
4353
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);
4354
5134
  }
4355
- for (const [name, acc] of resolvedNamed) {
4356
- if (coarsePackages.has(name))
4357
- continue;
4358
- const metaPackages = new Set([name]);
4359
- for (const f of [...acc.touched, ...acc.definers, ...acc.hopDeps]) {
4360
- const owner = fileToPackage.get(f);
4361
- if (owner)
4362
- metaPackages.add(owner);
4363
- }
4364
- for (const p of metaPackages)
4365
- deps.push(`${PKGMETA_PREFIX}${p}`);
4366
- for (const t of acc.touched)
4367
- if (t !== file)
4368
- deps.push(`${TOUCH_PREFIX}${t}`);
4369
- for (const d of acc.definers)
4370
- deps.push(d);
4371
- for (const h of acc.hopDeps)
4372
- 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);
4373
5144
  }
4374
- for (const name of coarsePackages)
4375
- deps.push(`${EXTERNAL_PREFIX}${name}`);
4376
- const keys = deps.map((d) => /^(?:touch|external|pkgmeta):/.test(d) ? d : `${ALL_PREFIX}${d}`);
4377
- edges.set(`${ALL_PREFIX}${file}`, keys);
4378
- 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);
4379
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);
4380
5160
  }
4381
5161
  }
4382
- const affectedNames = options.affectedNames ?? new Map;
4383
- const changeFacts = {
4384
- files: absChanged,
4385
- packages: changedPackageNames,
4386
- nonSourcePackages: nonSourceChangedPackages,
4387
- packageOfFile: (f) => fileToPackage.get(f) ?? null,
4388
- affects: (file, name) => {
4389
- const affected = affectedNames.get(file) ?? affectedNames.get(file.startsWith(repoRoot) ? file.slice(repoRoot.length + 1) : file);
4390
- return affected === undefined || affected === "all" || affected.has(name);
4391
- }
4392
- };
4393
- const depthOneDefault = options.depth === "one" ? "ignore" : "select";
4394
- const repoTreeScanners = options.repoTreeScanners ?? depthOneDefault;
4395
- const cliSpawnDetection = options.cliSpawnDetection ?? depthOneDefault;
4396
- const cliEntrypoint = join7(repoRoot, options.cliEntrypoint ?? DEFAULT_CLI_ENTRYPOINT);
4397
- const rootConfigChanged = absChanged.has(join7(repoRoot, ROOT_CONFIG_FILENAME));
4398
- const cliPackage = packages.find((pkg) => cliEntrypoint.startsWith(`${pkg.dir}/`)) ?? null;
4399
- if (typescript && repoTreeScanners !== "ignore") {
5162
+ if (typescript && options.repoTreeScanners !== "ignore") {
4400
5163
  for (const file of allSourceFiles) {
4401
- if (!isTestFile(file))
5164
+ if (!options.isTest(file))
4402
5165
  continue;
4403
5166
  const roots = scannedRootsOf(typescript, file, readSource(file), repoRoot);
4404
5167
  if (roots.length === 0)
@@ -4407,57 +5170,183 @@ function selectAffectedTestFiles(repoRoot, changedFiles, options = {}) {
4407
5170
  edges.set(key, [...edges.get(key) ?? [], ...roots.map((r) => `${SCAN_PREFIX}${r}`)]);
4408
5171
  }
4409
5172
  }
4410
- if (typescript && cliSpawnDetection !== "ignore") {
4411
- const cliEntrypointSourceRoot = dirname6(cliEntrypoint);
4412
- for (const file of allSourceFiles) {
4413
- if (!isTestFile(file))
4414
- continue;
4415
- const classification = cliSpawnEdgeOf(typescript, file, readSource(file), repoRoot, cliEntrypoint);
4416
- 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}/`))
4417
5222
  continue;
4418
- const key = `${ALL_PREFIX}${file}`;
4419
- const edge = classification === "entrypoint" ? `${ALL_PREFIX}${cliEntrypoint}` : `${SCAN_PREFIX}${cliEntrypointSourceRoot}`;
4420
- 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);
4421
5226
  }
4422
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]));
4423
5272
  const triggeredScanners = new Set;
4424
- const relative = (f) => isAbsolute4(f) ? f.slice(repoRoot.length + 1) : f;
4425
- const reshaped = [...addedOrRenamed, ...options.removed ?? []].map(relative);
4426
- const changedRanges = new Map([...options.changedRanges ?? new Map].map(([f, ranges]) => [isAbsolute4(f) ? f : join7(repoRoot, f), ranges]));
4427
- for (const declaration of options.scannerDeclarations ?? SCANNER_DECLARATIONS) {
4428
- const under = (f) => declaration.roots.some((root) => underDeclaredRoot(f, root));
4429
- const triggered = declaration.trigger === "tree-shape" ? reshaped.some(under) : declaration.trigger === "process-start" ? [...absChanged].some((abs) => {
4430
- if (!/\.tsx?$/.test(abs) || !under(relative(abs)))
4431
- return false;
4432
- if (!typescript)
4433
- return true;
4434
- const ranges = addedOrRenamed.has(abs) ? undefined : changedRanges.get(abs);
4435
- return startsProcessIn(typescript, abs, readSource(abs), ranges);
4436
- }) : 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
+ });
4437
5282
  if (triggered)
4438
- triggeredScanners.add(join7(repoRoot, declaration.test));
5283
+ triggeredScanners.add(join8(repoRoot, declaration.test));
4439
5284
  }
4440
- const anythingChanged = absChanged.size > 0 || changedPackageNames.size > 0;
5285
+ const anythingChanged = absChanged.size > 0 || changeFacts.packages.size > 0;
4441
5286
  const selected = [];
5287
+ const explanations = [];
5288
+ const native = [];
4442
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
+ };
4443
5316
  for (const pkg of packages) {
4444
5317
  const testFiles = pkgFiles.get(pkg).filter(isTestFile);
4445
5318
  totalTestFiles += testFiles.length;
4446
- if (!pkg.bunTestCompatible)
4447
- continue;
4448
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
+ }
4449
5329
  for (const test of testFiles) {
4450
- const forced = alwaysRunRegexes.some((re) => re.test(test.slice(repoRoot.length + 1))) || addedOrRenamed.has(test) || triggeredScanners.has(test) || rootConfigChanged && pkg === cliPackage;
4451
- if (forced || anythingChanged && reaches(`${ALL_PREFIX}${test}`, edges, changeFacts, maxDepth)) {
4452
- selected.push(test);
4453
- }
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 });
4454
5335
  }
4455
5336
  }
4456
- 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
+ };
4457
5345
  }
4458
5346
  function reaches(start, edges, changed, maxDepth = Number.POSITIVE_INFINITY) {
4459
5347
  const visited = new Set;
4460
5348
  const stack = [[start, 0]];
5349
+ const importKind = (depth) => depth === 0 ? "direct-dependency" : "transitive-dependency";
4461
5350
  while (stack.length > 0) {
4462
5351
  const [current, depth] = stack.pop();
4463
5352
  if (visited.has(current))
@@ -4465,7 +5354,11 @@ function reaches(start, edges, changed, maxDepth = Number.POSITIVE_INFINITY) {
4465
5354
  visited.add(current);
4466
5355
  const currentFile = current.startsWith(ALL_PREFIX) ? current.slice(ALL_PREFIX.length) : current.startsWith(OWN_PREFIX) ? current.slice(OWN_PREFIX.length) : null;
4467
5356
  if (current.startsWith(ALL_PREFIX) && currentFile && changed.files.has(currentFile))
4468
- 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
+ };
4469
5362
  if (depth >= maxDepth)
4470
5363
  continue;
4471
5364
  const ownPackage = currentFile ? changed.packageOfFile(currentFile) : null;
@@ -4475,48 +5368,85 @@ function reaches(start, edges, changed, maxDepth = Number.POSITIVE_INFINITY) {
4475
5368
  const cut = body.lastIndexOf(NAME_SEPARATOR);
4476
5369
  const file = body.slice(0, cut);
4477
5370
  if (changed.files.has(file) && changed.affects(file, body.slice(cut + 1)))
4478
- return true;
5371
+ return { kind: importKind(depth), detail: `uses the changed name ${body.slice(cut + 1)}`, via: file };
4479
5372
  continue;
4480
5373
  }
4481
5374
  if (dep.startsWith(TOUCH_PREFIX)) {
4482
- if (changed.files.has(dep.slice(TOUCH_PREFIX.length)))
4483
- 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 };
4484
5378
  continue;
4485
5379
  }
4486
5380
  if (dep.startsWith(SCAN_PREFIX)) {
4487
5381
  const root = dep.slice(SCAN_PREFIX.length);
4488
5382
  for (const f of changed.files)
4489
5383
  if (f === root || f.startsWith(`${root}/`))
4490
- return true;
5384
+ return { kind: "declared-input", detail: `reads the folder ${root} from disk`, via: f };
4491
5385
  continue;
4492
5386
  }
4493
5387
  if (dep.startsWith(EXTERNAL_PREFIX)) {
4494
5388
  const pkg = dep.slice(EXTERNAL_PREFIX.length);
4495
5389
  if (changed.packages.has(pkg) && pkg !== ownPackage)
4496
- 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
+ };
4497
5395
  continue;
4498
5396
  }
4499
5397
  if (dep.startsWith(PKGMETA_PREFIX)) {
4500
5398
  const pkg = dep.slice(PKGMETA_PREFIX.length);
4501
5399
  if (changed.nonSourcePackages.has(pkg) && pkg !== ownPackage)
4502
- 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
+ };
4503
5405
  continue;
4504
5406
  }
4505
5407
  if (!visited.has(dep))
4506
5408
  stack.push([dep, depth + 1]);
4507
5409
  }
4508
5410
  }
4509
- 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
+ });
4510
5441
  }
4511
-
4512
5442
  // src/lib/pre-push-selection.ts
4513
- function prePushSelection(repoRoot, base = resolveRemoteBase(repoRoot), depth = "one") {
4514
- const changed = changedFilesSinceRemoteBaseAbsolute(repoRoot, base);
4515
- const addedOrRenamed = addedOrRenamedFilesSinceRemoteBaseAbsolute(repoRoot, base);
4516
- 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);
4517
5447
  const alwaysRun = loadConfig()?.prePush?.alwaysRun ?? [];
4518
5448
  const typescript = loadTypeScript(repoRoot);
4519
- const diffs = typescript ? changedFileDiffsSinceRemoteBase(repoRoot, base) : undefined;
5449
+ const diffs = typescript ? changedFileDiffsSinceRemoteBase(repoRoot, base, failure) : undefined;
4520
5450
  const names = typescript && diffs ? affectedNames(typescript, diffs) : undefined;
4521
5451
  const changedRanges = diffs ? new Map(diffs.map((d) => [d.file, d.afterRanges])) : undefined;
4522
5452
  return selectAffectedTestFiles(repoRoot, changed, {
@@ -4525,7 +5455,8 @@ function prePushSelection(repoRoot, base = resolveRemoteBase(repoRoot), depth =
4525
5455
  removed,
4526
5456
  changedRanges,
4527
5457
  affectedNames: names,
4528
- depth
5458
+ depth,
5459
+ nativeRunners
4529
5460
  });
4530
5461
  }
4531
5462
 
@@ -4533,12 +5464,53 @@ function prePushSelection(repoRoot, base = resolveRemoteBase(repoRoot), depth =
4533
5464
  function main() {
4534
5465
  const repoRoot = process.cwd();
4535
5466
  const started = performance.now();
4536
- 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;
4537
5496
  const elapsed = performance.now() - started;
4538
5497
  for (const file of selected)
4539
5498
  process.stdout.write(`${file}
4540
5499
  `);
4541
- 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
4542
5513
  `);
5514
+ }
4543
5515
  }
4544
5516
  main();