@attalabs/vinaya 0.39.0 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/README.md +9 -9
  2. package/aeg-root/contracts/developer-reviewer.md +2 -2
  3. package/aeg-root/contracts/planner-developer.md +5 -5
  4. package/aeg-root/enforcement.md +22 -22
  5. package/aeg-root/process.md +4 -4
  6. package/aeg-root/roles/archivist.md +1 -1
  7. package/aeg-root/roles/developer/reference.md +7 -1
  8. package/aeg-root/roles/developer.md +1 -1
  9. package/aeg-root/roles/planner/reference.md +18 -5
  10. package/aeg-root/roles/principal.md +1 -1
  11. package/aeg-root/roles/reviewer.md +3 -3
  12. package/aeg-root/roles/security.md +4 -4
  13. package/aeg-root/roles/tranche-archivist.md +2 -2
  14. package/aeg-root/skills/aeg/SKILL.md +1 -1
  15. package/aeg-root/state-machine.md +10 -15
  16. package/aeg-root/templates/brief-template.md +5 -2
  17. package/aeg-root/templates/decision-record-template.md +38 -0
  18. package/aeg-root/templates/issue-rationale-template.md +1 -1
  19. package/aeg-root/tranche-model.md +1 -1
  20. package/dist/checks/bin/check-body-bare-digits.js +1974 -354
  21. package/dist/checks/bin/check-branch-topology.js +1296 -243
  22. package/dist/checks/bin/check-brief-shape.js +2038 -460
  23. package/dist/checks/bin/check-changeset-coverage.js +2411 -564
  24. package/dist/checks/bin/check-ci-shard-coverage.js +12391 -15
  25. package/dist/checks/bin/check-closes-n.js +1296 -243
  26. package/dist/checks/bin/check-coherence.js +1914 -1155
  27. package/dist/checks/bin/check-dead-branch-push.js +1242 -230
  28. package/dist/checks/bin/check-dispatch-readiness.js +2222 -460
  29. package/dist/checks/bin/check-doc-claims.js +2233 -260
  30. package/dist/checks/bin/check-doc-coverage-push.js +2436 -550
  31. package/dist/checks/bin/check-doc-coverage.js +2434 -552
  32. package/dist/checks/bin/check-doctrine-no-procedures.js +1776 -353
  33. package/dist/checks/bin/check-doctrine-portability.js +2408 -561
  34. package/dist/checks/bin/check-evidence-fresh.js +2370 -508
  35. package/dist/checks/bin/check-exec-bits.js +2407 -560
  36. package/dist/checks/bin/check-first-push-dispatch.js +1984 -380
  37. package/dist/checks/bin/check-issue-assignment.js +712 -170
  38. package/dist/checks/bin/check-issue-milestone-attach.js +1233 -230
  39. package/dist/checks/bin/check-issue-objectives-numbering.js +1769 -346
  40. package/dist/checks/bin/check-issue-parts-coverage.js +1233 -230
  41. package/dist/checks/bin/check-issue-surface-globs.js +1926 -378
  42. package/dist/checks/bin/check-issue-title-grammar.js +1233 -230
  43. package/dist/checks/bin/check-issue-tranche-label.js +702 -170
  44. package/dist/checks/bin/check-main-branch-refusal.js +1245 -232
  45. package/dist/checks/bin/check-no-disk-state.js +1233 -230
  46. package/dist/checks/bin/check-pr-premise-reassert.js +1769 -346
  47. package/dist/checks/bin/check-pr-report-density.js +1233 -230
  48. package/dist/checks/bin/check-principal-test-plan-wait.js +2489 -259
  49. package/dist/checks/bin/check-quoted-command.js +2391 -544
  50. package/dist/checks/bin/check-reader-resolvable-prose.js +2437 -564
  51. package/dist/checks/bin/check-registry-gates.js +1380 -296
  52. package/dist/checks/bin/check-retired-vocabulary.js +2416 -550
  53. package/dist/checks/bin/check-review-gate.js +2073 -371
  54. package/dist/checks/bin/check-single-plan-pr.js +1297 -235
  55. package/dist/checks/bin/check-surface-scope.js +1531 -252
  56. package/dist/checks/bin/check-test-plan.js +2487 -258
  57. package/dist/checks/bin/check-token-collection-wired.js +1233 -230
  58. package/dist/checks/bin/check-workspace-escape.js +2408 -561
  59. package/dist/checks/bin/verify-coherence.js +597 -97
  60. package/dist/checks/bin/verify-dispatch.js +632 -152
  61. package/dist/checks/bin/verify-docs.js +642 -132
  62. package/dist/index.js +25948 -16630
  63. package/dist/lib/pre-push-cache-test-run.js +1813 -297
  64. package/dist/lib/pre-push-changed-files.js +65 -19
  65. package/dist/lib/pre-push-mode.js +466 -0
  66. package/dist/lib/pre-push-progress-dir.js +4205 -0
  67. package/dist/lib/pre-push-record-tests.js +446 -0
  68. package/dist/lib/pre-push-select-tests.js +2353 -632
  69. package/dist/lib/push-progress-observer.js +4213 -0
  70. package/package.json +22 -5
  71. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/anchored-region.ts +17 -3
  72. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/brief-render.ts +73 -30
  73. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/brief-validation.ts +3 -3
  74. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/coherence-checks.ts +2 -2
  75. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/local.ts +88 -5
  76. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/records.ts +34 -2
  77. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/assess-round.ts +26 -4
  78. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/fakes.ts +7 -2
  79. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/index.ts +7 -1
  80. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/types.ts +29 -3
  81. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dispatch-gate.ts +35 -18
  82. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/docs/index.ts +1 -1
  83. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/docs/published-prose.ts +70 -45
  84. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/doctrine-portability.ts +6 -1
  85. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/entry-point.ts +27 -0
  86. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/gate-audience.ts +3 -5
  87. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/index.ts +96 -9
  88. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/issue-assignment.ts +24 -54
  89. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/issue-validation.ts +809 -106
  90. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/live-record.ts +179 -0
  91. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/envelope.ts +8 -2
  92. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/index.ts +1 -0
  93. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/narration.ts +2 -0
  94. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/schema-digest.ts +225 -0
  95. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/schema.ts +7 -1
  96. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/main-branch-refusal.ts +23 -1
  97. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/pr-report-density.ts +6 -4
  98. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/principals-config.ts +44 -0
  99. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/prose-rules.ts +532 -0
  100. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/protected-paths.ts +31 -0
  101. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/reader-resolvable-prose.ts +157 -80
  102. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/registry-checks.ts +8 -12
  103. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/retired-vocabulary.ts +53 -93
  104. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-gate.ts +46 -17
  105. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-input-manifest.ts +85 -1
  106. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-policy.ts +32 -13
  107. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/ruling-ordinal.ts +46 -0
  108. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/task-branch-identity.ts +2 -4
  109. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/test-plan-gate.ts +63 -8
  110. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/verdict-extraction.ts +24 -0
  111. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/waiver-label.ts +0 -1
  112. package/studio-standalone/apps/vinaya-studio/web/.next/BUILD_ID +1 -1
  113. package/studio-standalone/apps/vinaya-studio/web/.next/build-manifest.json +3 -3
  114. package/studio-standalone/apps/vinaya-studio/web/.next/prerender-manifest.json +3 -3
  115. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.html +1 -1
  116. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.rsc +1 -1
  117. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  118. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  119. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  120. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  121. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  122. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page/server-reference-manifest.json +2 -2
  123. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page.js.nft.json +1 -1
  124. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  125. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page/server-reference-manifest.json +2 -2
  126. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page.js.nft.json +1 -1
  127. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page_client-reference-manifest.js +1 -1
  128. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page/server-reference-manifest.json +2 -2
  129. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page.js +1 -1
  130. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page.js.nft.json +1 -1
  131. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page_client-reference-manifest.js +1 -1
  132. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page/server-reference-manifest.json +2 -2
  133. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page.js +1 -1
  134. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page.js.nft.json +1 -1
  135. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page_client-reference-manifest.js +1 -1
  136. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page/server-reference-manifest.json +2 -2
  137. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page.js +1 -1
  138. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page.js.nft.json +1 -1
  139. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page_client-reference-manifest.js +1 -1
  140. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page/server-reference-manifest.json +3 -3
  141. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page.js +1 -1
  142. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page.js.nft.json +1 -1
  143. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page_client-reference-manifest.js +1 -1
  144. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page/server-reference-manifest.json +2 -2
  145. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page.js +2 -2
  146. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page.js.nft.json +1 -1
  147. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page_client-reference-manifest.js +1 -1
  148. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page/server-reference-manifest.json +2 -2
  149. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page.js +1 -1
  150. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page.js.nft.json +1 -1
  151. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page_client-reference-manifest.js +1 -1
  152. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page/server-reference-manifest.json +2 -2
  153. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page.js +1 -1
  154. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page.js.nft.json +1 -1
  155. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page_client-reference-manifest.js +1 -1
  156. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/1q96_modules_@clerk_nextjs_dist_esm_app-router_client_keyless-creator-reader_0lom2js.js +1 -1
  157. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__08e39jo._.js +1 -1
  158. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0ls23oh._.js +1 -1
  159. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0sxadt2._.js +13 -0
  160. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1a3j3n1._.js +57 -0
  161. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{[root-of-the-server]__1ug9syi._.js → [root-of-the-server]__1d4eth3._.js} +1 -1
  162. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1gjqmhq._.js +1 -1
  163. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1snpgaw._.js +3 -3
  164. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1wc4-ip._.js +1 -1
  165. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_08onyya._.js +2 -2
  166. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_096f46i._.js +1 -1
  167. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0af2one._.js +1 -1
  168. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0e5tkdd._.js +1 -1
  169. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0kf2g72._.js +1 -1
  170. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0zf4d27._.js +3 -3
  171. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1-wo68i._.js +1 -1
  172. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1achbh9._.js +1 -1
  173. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/node_modules_@clerk_nextjs_dist_esm_app-router_server-actions_1x7vfhn.js +2 -2
  174. package/studio-standalone/apps/vinaya-studio/web/.next/server/middleware-build-manifest.js +3 -3
  175. package/studio-standalone/apps/vinaya-studio/web/.next/server/pages/500.html +1 -1
  176. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.js +1 -1
  177. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.json +4 -4
  178. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{33rszkngkuoko.js → 0x7u6si-ai179.js} +1 -1
  179. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{06_55xbp7rcbi.js → 2fu7mfsj4oima.js} +1 -1
  180. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{2brkwv169ygep.js → 34b4ruddunn3q.js} +1 -1
  181. package/studio-standalone/apps/vinaya-studio/web/package.json +2 -2
  182. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__04adkz-._.js +0 -57
  183. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__19jyp3m._.js +0 -13
  184. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{D3LiJNIq5FWZxen7CpOSJ → 2ZARxTwpuRew8-SvYsRdU}/_buildManifest.js +0 -0
  185. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{D3LiJNIq5FWZxen7CpOSJ → 2ZARxTwpuRew8-SvYsRdU}/_clientMiddlewareManifest.js +0 -0
  186. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{D3LiJNIq5FWZxen7CpOSJ → 2ZARxTwpuRew8-SvYsRdU}/_ssgManifest.js +0 -0
@@ -1,28 +1,28 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/lib/pre-push-cache-test-run.ts
4
- import { readFileSync as readFileSync9 } from "node:fs";
4
+ import { readFileSync as readFileSync11 } from "node:fs";
5
5
 
6
6
  // src/lib/pr-report-engine.ts
7
- import { execFile as execFile6 } from "node:child_process";
8
- import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
7
+ import { execFile as execFile7 } from "node:child_process";
8
+ import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
9
9
  import {
10
- closeSync as closeSync6,
10
+ closeSync as closeSync7,
11
11
  constants as fsConstants6,
12
- existsSync as existsSync8,
13
- fsyncSync as fsyncSync2,
14
- lstatSync as lstatSync4,
12
+ existsSync as existsSync9,
13
+ fsyncSync as fsyncSync3,
14
+ lstatSync as lstatSync5,
15
15
  mkdtempSync,
16
- openSync as openSync6,
17
- readFileSync as readFileSync8,
18
- renameSync as renameSync4,
19
- rmSync,
20
- writeFileSync as writeFileSync4,
21
- writeSync as writeSync5
16
+ openSync as openSync7,
17
+ readFileSync as readFileSync10,
18
+ renameSync as renameSync5,
19
+ rmSync as rmSync3,
20
+ writeFileSync as writeFileSync5,
21
+ writeSync as writeSync6
22
22
  } from "node:fs";
23
23
  import { hostname, tmpdir } from "node:os";
24
- import { dirname as dirname8, join as join9, resolve as resolvePath2 } from "node:path";
25
- import { promisify as promisify6 } from "node:util";
24
+ import { dirname as dirname9, join as join10, resolve as resolvePath2 } from "node:path";
25
+ import { promisify as promisify7 } from "node:util";
26
26
  // ../../packages/aeg-forge-state/src/gh.ts
27
27
  import { execFile, execFileSync } from "node:child_process";
28
28
  import { promisify } from "node:util";
@@ -467,8 +467,372 @@ var NON_PATH_TOP_SEGMENTS = new Set(["origin", "refs", "HEAD", "vinaya", "fix"])
467
467
 
468
468
  // ../../packages/aeg-core/src/doctrine-no-procedures.ts
469
469
  var SHELL_LANGS = new Set(["", "sh", "bash", "shell", "console"]);
470
+ // ../../packages/aeg-core/src/prose-rules.ts
471
+ var RETIRED_GLOBAL_EXEMPTIONS = [
472
+ "docs/decisions-legacy.md",
473
+ "apps/herald-ai/docs/",
474
+ "apps/vada-ai/docs/",
475
+ "aeg-root/tranches/completed/",
476
+ "packages/aeg-core/src/docs/published-prose",
477
+ "packages/aeg-core/src/retired-vocabulary.test.ts",
478
+ "packages/aeg-core/src/retired-vocabulary.ts",
479
+ "/fixtures/",
480
+ "/node_modules/",
481
+ "/.next/",
482
+ "/.turbo/"
483
+ ];
484
+ var PLAN_ON_DISK_PATTERNS = ["[Tt]opology files?", "aeg-root/tranches/", "aeg-project/"];
485
+ var TRANCHE_MODEL_FILE = "/tranche-model.md";
486
+ var RETIRED_PATTERN_EXEMPTIONS = {
487
+ [String.raw`\bD-[0-9]{3}\b`]: ["./CLAUDE.md"],
488
+ [String.raw`(^|[^-_a-zA-Z0-9])decisions\.md`]: [
489
+ "docs-index.md",
490
+ "apps/vada-ai/specs/legacy/README.md",
491
+ "apps/vada-ai/specs/vada-product-spec.md",
492
+ "apps/vada-ai/web/CLAUDE.md",
493
+ "apps/vada-ai/CLAUDE.md"
494
+ ],
495
+ "decisions-legacy": [
496
+ "packages/aeg-core/src/file-classify.ts",
497
+ "packages/aeg-core/src/file-classify.test.ts",
498
+ "packages/aeg-core/src/pr-tier.test.ts",
499
+ "docs-index.md",
500
+ ".claude/skills/database/SKILL.md",
501
+ ".claude/skills/vada-architecture/SKILL.md",
502
+ "apps/vada-ai/specs/vada-byok-principles.md",
503
+ "apps/vada-ai/web/CLAUDE.md",
504
+ "apps/vada-ai/CLAUDE.md"
505
+ ],
506
+ CONTRADICTION: ["apps/vada-ai/specs/vada-reviewers-spec.md"],
507
+ ...Object.fromEntries(PLAN_ON_DISK_PATTERNS.map((pattern) => [pattern, [TRANCHE_MODEL_FILE]]))
508
+ };
509
+ var retiredPatterns = [
510
+ String.raw`\bD-[0-9]{3}\b`,
511
+ "D-(###|NNN|nnn|xxx)",
512
+ "decision (entry|logged)",
513
+ "decision-log entry",
514
+ "decision log entry",
515
+ "decision log(s|ged|ging)?([^a-z]|$)",
516
+ "decision-log",
517
+ "decision entr",
518
+ "decisions? (are |is )?logged",
519
+ "log entries",
520
+ String.raw`(^|[^-_a-zA-Z0-9])decisions\.md`,
521
+ "decisions-legacy",
522
+ "CONTRADICTION",
523
+ "assumes Tier 3",
524
+ "Lock: ?YES",
525
+ "Lock: ?NO",
526
+ "lock approvals?",
527
+ "approves locks",
528
+ "Conforms to lock",
529
+ "Challenges lock",
530
+ "checkDecisionNumbersFresh",
531
+ String.raw`roles/team-leader\.md`,
532
+ String.raw`\(,`,
533
+ String.raw`,\)`,
534
+ String.raw`\(\.\)`,
535
+ ...PLAN_ON_DISK_PATTERNS
536
+ ];
537
+ var published = [
538
+ ["decision-id", "a decision id", /\bD-\d{3,}\b/],
539
+ ["section-ref", "a section reference", /§/],
540
+ ["forge-number", "a forge number", /#\d+/],
541
+ ["retired-name", "the retired public name", /\bAEG\b/],
542
+ ["tranche-slug", "a tranche slug", /\b[a-z][a-z0-9]*(?:-[a-z0-9]+)+-v\d+\b/],
543
+ [
544
+ "label-vocabulary",
545
+ "forge label vocabulary",
546
+ /(?:vinaya\/)?\b(?:tranche|iteration|tier|needs|waiver|project|aeg):(?![/\s]|$)/
547
+ ],
548
+ ["internal-path", "a repo-internal path", /\b(?:packages|apps|aeg-root|tools|scripts)\//],
549
+ ["internal-path", "a repo-internal path", /\.(?:claude|husky|github)\//],
550
+ [
551
+ "internal-path",
552
+ "a repo-internal file",
553
+ /(?:^|[\s(`"'[])[\w.-]+(?:\/[\w.-]+)*\.(?:ts|tsx|js|jsx|mjs|cjs|sh|ya?ml|json|md)\b/
554
+ ]
555
+ ];
556
+ var DEFAULT_PROSE_RULES = [
557
+ {
558
+ id: "forge-number",
559
+ group: "reader-resolvable",
560
+ scopes: ["ships", "reader-facing", "spec"],
561
+ patterns: { prose: /#[0-9]{2,4}/g },
562
+ flags: ["global"],
563
+ message: "a forge number",
564
+ severity: { ships: "warning", "reader-facing": "warning", spec: "error" },
565
+ exemptions: []
566
+ },
567
+ {
568
+ id: "tranche-slug",
569
+ group: "reader-resolvable",
570
+ scopes: ["ships", "reader-facing", "product", "spec"],
571
+ patterns: { prose: /[a-z][a-z-]+-v[0-9]/g },
572
+ flags: ["global"],
573
+ message: "an internal tranche slug",
574
+ severity: { ships: "warning", "reader-facing": "warning", product: "error", spec: "error" },
575
+ exemptions: []
576
+ },
577
+ {
578
+ id: "task-number",
579
+ group: "reader-resolvable",
580
+ scopes: ["spec"],
581
+ patterns: { prose: /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi },
582
+ flags: ["global", "ignore-case"],
583
+ message: "a task number",
584
+ severity: { spec: "error" },
585
+ exemptions: []
586
+ },
587
+ {
588
+ id: "source-comment-tranche-slug",
589
+ group: "reader-resolvable",
590
+ scopes: ["source-comment"],
591
+ patterns: { comment: /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g },
592
+ flags: ["global"],
593
+ message: "a tranche-slug citation",
594
+ severity: { "source-comment": "warning" },
595
+ exemptions: []
596
+ },
597
+ {
598
+ id: "source-comment-forge-number",
599
+ group: "reader-resolvable",
600
+ scopes: ["source-comment"],
601
+ patterns: { comment: /#[0-9]{2,}/g },
602
+ flags: ["global"],
603
+ message: "a forge-number citation",
604
+ severity: { "source-comment": "warning" },
605
+ exemptions: []
606
+ },
607
+ {
608
+ id: "legacy-batch-name",
609
+ group: "reader-resolvable",
610
+ scopes: ["ships", "reader-facing", "spec"],
611
+ patterns: {},
612
+ flags: ["built-in"],
613
+ message: "an internal tranche slug",
614
+ severity: { ships: "warning", "reader-facing": "warning", spec: "error" },
615
+ exemptions: [],
616
+ builtIn: true
617
+ },
618
+ {
619
+ id: "coined-term",
620
+ group: "reader-resolvable",
621
+ scopes: ["ships", "reader-facing"],
622
+ patterns: {},
623
+ flags: ["built-in"],
624
+ message: "uses coined term without defining it inline or linking the glossary",
625
+ severity: { ships: "warning", "reader-facing": "warning" },
626
+ exemptions: [],
627
+ builtIn: true
628
+ },
629
+ ...retiredPatterns.map((pattern, index) => ({
630
+ id: `retired-vocabulary-${index + 1}`,
631
+ group: "retired-vocabulary",
632
+ scopes: ["repository"],
633
+ patterns: { repository: pattern },
634
+ flags: [],
635
+ message: "retired vocabulary",
636
+ severity: { repository: "error" },
637
+ exemptions: RETIRED_GLOBAL_EXEMPTIONS,
638
+ patternExemptions: RETIRED_PATTERN_EXEMPTIONS
639
+ })),
640
+ ...published.map(([id, message, pattern]) => ({
641
+ id,
642
+ group: "published-prose",
643
+ scopes: ["published"],
644
+ patterns: { published: pattern },
645
+ flags: [],
646
+ message,
647
+ severity: { published: "error" },
648
+ exemptions: [".worktrees/task/<tranche>/<n>", "task/<tranche>/<n>", ".worktrees/"]
649
+ }))
650
+ ];
651
+ var rulesForGroup = (group) => DEFAULT_PROSE_RULES.filter((rule) => rule.group === group);
652
+ var RESOLVABLE_SCOPES = ["ships", "reader-facing", "product", "spec", "source-comment"];
653
+ var RETIRED_SCOPES = ["repository"];
654
+ var CONFIGURABLE_PROSE_SCOPES = [...RESOLVABLE_SCOPES, ...RETIRED_SCOPES];
655
+ function groupOfScope(scope) {
656
+ if (RESOLVABLE_SCOPES.includes(scope))
657
+ return "reader-resolvable";
658
+ if (RETIRED_SCOPES.includes(scope))
659
+ return "retired-vocabulary";
660
+ return;
661
+ }
662
+ var CONFIGURED_PROSE_FLAGS = ["i", "u"];
663
+ var CONFIGURED_PATTERN_MAX_LENGTH = 200;
664
+ var CONFIGURABLE_DEFAULT_RULES = DEFAULT_PROSE_RULES.filter((rule) => rule.group !== "published-prose");
665
+ function allowedScopesFor(rule) {
666
+ if (rule.builtIn)
667
+ return rule.scopes;
668
+ return rule.group === "retired-vocabulary" ? RETIRED_SCOPES : RESOLVABLE_SCOPES;
669
+ }
670
+ function normalizeRepoPath(entry) {
671
+ let out = entry.replace(/\\/g, "/");
672
+ while (out.startsWith("./"))
673
+ out = out.slice(2);
674
+ out = out.replace(/\/{2,}/g, "/");
675
+ while (out.endsWith("/"))
676
+ out = out.slice(0, -1);
677
+ return out;
678
+ }
679
+ var RESOLVABLE_RUN_ORDER = [
680
+ "forge-number",
681
+ "tranche-slug",
682
+ "legacy-batch-name",
683
+ "task-number",
684
+ "source-comment-tranche-slug",
685
+ "source-comment-forge-number",
686
+ "coined-term"
687
+ ];
688
+ var REPORT_GROUPS = { "task-number": 2, "legacy-batch-name": 2 };
689
+ function scopeDefaultSeverity(scope, sourceCommentSeverity) {
690
+ if (scope === "source-comment")
691
+ return sourceCommentSeverity ?? "warning";
692
+ if (scope === "repository")
693
+ return "error";
694
+ return "warning";
695
+ }
696
+ function applySeverity(scopes, base, setting) {
697
+ const out = {};
698
+ for (const scope of scopes) {
699
+ const configured = typeof setting === "string" ? setting : setting?.[scope];
700
+ const value = configured ?? base[scope];
701
+ if (value !== undefined)
702
+ out[scope] = value;
703
+ }
704
+ return out;
705
+ }
706
+ function defaultPatternFor(rule) {
707
+ const cache = new Map;
708
+ return (scope) => {
709
+ if (cache.has(scope))
710
+ return cache.get(scope) ?? null;
711
+ const own = rule.patterns[scope] ?? (scope === "source-comment" ? rule.patterns.comment : rule.patterns.prose) ?? Object.values(rule.patterns)[0];
712
+ const compiled = own === undefined ? null : own instanceof RegExp ? own : new RegExp(own);
713
+ cache.set(scope, compiled);
714
+ return compiled;
715
+ };
716
+ }
717
+ function customPatternFor(rule, global) {
718
+ const cache = new Map;
719
+ return (scope) => {
720
+ if (cache.has(scope))
721
+ return cache.get(scope) ?? null;
722
+ const source = rule.patterns?.[scope] ?? rule.pattern;
723
+ const compiled = source === undefined ? null : new RegExp(source, `${rule.flags ?? ""}${global ? "g" : ""}`);
724
+ cache.set(scope, compiled);
725
+ return compiled;
726
+ };
727
+ }
728
+ function resolveProseRules(config = undefined, options = {}) {
729
+ const rules = [];
730
+ const defaults = config?.defaults ?? {};
731
+ for (const rule of CONFIGURABLE_DEFAULT_RULES) {
732
+ const override = defaults[rule.id];
733
+ if (override === "off")
734
+ continue;
735
+ const group = rule.group;
736
+ const scopes = override?.scopes ?? rule.scopes;
737
+ const base = {};
738
+ for (const scope of scopes) {
739
+ base[scope] = scope === "source-comment" ? options.sourceCommentSeverity ?? rule.severity[scope] ?? "warning" : rule.severity[scope] ?? scopeDefaultSeverity(scope, options.sourceCommentSeverity);
740
+ }
741
+ rules.push({
742
+ id: rule.id,
743
+ group,
744
+ custom: false,
745
+ builtIn: rule.builtIn === true,
746
+ scopes,
747
+ message: rule.message,
748
+ severity: applySeverity(scopes, base, override?.severity),
749
+ exempt: override?.exempt ?? [],
750
+ substringExempt: rule.exemptions,
751
+ reportGroup: REPORT_GROUPS[rule.id],
752
+ patternFor: defaultPatternFor(rule)
753
+ });
754
+ }
755
+ for (const rule of config?.custom ?? []) {
756
+ const group = groupOfScope(rule.scopes[0] ?? "") ?? "reader-resolvable";
757
+ const base = {};
758
+ for (const scope of rule.scopes)
759
+ base[scope] = scopeDefaultSeverity(scope, options.sourceCommentSeverity);
760
+ rules.push({
761
+ id: rule.id,
762
+ group,
763
+ custom: true,
764
+ builtIn: false,
765
+ scopes: rule.scopes,
766
+ message: rule.means,
767
+ severity: applySeverity(rule.scopes, base, rule.severity),
768
+ exempt: rule.exempt ?? [],
769
+ substringExempt: [],
770
+ patternFor: customPatternFor(rule, group === "reader-resolvable")
771
+ });
772
+ }
773
+ if (options.decisionRecordsPath !== undefined)
774
+ rules.push(decisionRecordCitationRule(options.decisionRecordsPath));
775
+ const order = (rule) => {
776
+ const at = RESOLVABLE_RUN_ORDER.indexOf(rule.id);
777
+ return rule.custom || at === -1 ? RESOLVABLE_RUN_ORDER.length : at;
778
+ };
779
+ const resolvable = rules.filter((rule) => rule.group === "reader-resolvable");
780
+ const sorted = resolvable.map((rule, index) => ({ rule, index })).sort((a, b) => order(a.rule) - order(b.rule) || a.index - b.index).map(({ rule }) => rule);
781
+ return {
782
+ rules: [...sorted, ...rules.filter((rule) => rule.group === "retired-vocabulary")],
783
+ exempt: config?.exempt ?? [],
784
+ repoRoot: options.repoRoot
785
+ };
786
+ }
787
+ var DEFAULT_PROSE_RULE_SET = resolveProseRules();
788
+ var DECISION_RECORD_CITATION_ID = "decision-record-citation";
789
+ var DECISION_RECORD_CITATION_SCOPES = ["ships", "product", "spec", "source-comment"];
790
+ var DECISION_RECORD_CITATION_MESSAGE = "a decision-record number";
791
+ function escapeRegExp(text) {
792
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
793
+ }
794
+ function decisionRecordCitationPattern(decisionRecordsPath) {
795
+ const folder = escapeRegExp(normalizeRepoPath(decisionRecordsPath));
796
+ return new RegExp(String.raw`\bADR[- ]?[0-9]+\b|(?<![A-Za-z0-9_-])${folder}/[0-9]+[A-Za-z0-9._-]*`, "g");
797
+ }
798
+ function decisionRecordCitationRule(decisionRecordsPath) {
799
+ const folder = normalizeRepoPath(decisionRecordsPath);
800
+ const pattern = decisionRecordCitationPattern(folder);
801
+ const severity = {};
802
+ for (const scope of DECISION_RECORD_CITATION_SCOPES)
803
+ severity[scope] = "error";
804
+ return {
805
+ id: DECISION_RECORD_CITATION_ID,
806
+ group: "reader-resolvable",
807
+ custom: false,
808
+ builtIn: false,
809
+ scopes: DECISION_RECORD_CITATION_SCOPES,
810
+ message: DECISION_RECORD_CITATION_MESSAGE,
811
+ severity,
812
+ exempt: [folder],
813
+ substringExempt: [],
814
+ patternFor: () => pattern
815
+ };
816
+ }
817
+
470
818
  // ../../packages/aeg-core/src/reader-resolvable-prose.ts
819
+ function normalizeSpecPath(entry) {
820
+ return normalizeRepoPath(entry);
821
+ }
471
822
  var SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
823
+ var readerRules = rulesForGroup("reader-resolvable");
824
+ var readerPattern = (id, scope = "prose") => {
825
+ const pattern = readerRules.find((rule) => rule.id === id)?.patterns[scope];
826
+ if (!(pattern instanceof RegExp))
827
+ throw new Error(`default prose rule ${id} has no ${scope} pattern`);
828
+ return pattern;
829
+ };
830
+ var FORGE_NUMBER_PATTERN = readerPattern("forge-number");
831
+ var TRANCHE_SLUG_VN_PATTERN = readerPattern("tranche-slug");
832
+ var TASK_NUMBER_PATTERN = readerPattern("task-number");
833
+ var REFERENCE_CLASSES = new Set(["ships", "reader-facing", "product", "spec"]);
834
+ var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = readerPattern("source-comment-tranche-slug", "comment");
835
+ var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = readerPattern("source-comment-forge-number", "comment");
472
836
 
473
837
  // ../../packages/aeg-core/src/quoted-command.ts
474
838
  var QUOTED_COMMAND_SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
@@ -512,59 +876,9 @@ var R1_GRANDFATHERED_ISSUES = new Set([279, 280, 281, 282]);
512
876
  // ../../packages/aeg-core/src/diagram-model.ts
513
877
  import matter from "gray-matter";
514
878
  // ../../packages/aeg-core/src/retired-vocabulary.ts
515
- var PLAN_ON_DISK_PATTERNS = ["[Tt]opology files?", "aeg-root/tranches/", "aeg-project/"];
516
- var RETIRED_PATTERNS = [
517
- String.raw`\bD-[0-9]{3}\b`,
518
- "D-(###|NNN|nnn|xxx)",
519
- "decision (entry|logged)",
520
- "decision-log entry",
521
- "decision log entry",
522
- "decision log(s|ged|ging)?([^a-z]|$)",
523
- "decision-log",
524
- "decision entr",
525
- "decisions? (are |is )?logged",
526
- "log entries",
527
- String.raw`decisions\.md`,
528
- "decisions-legacy",
529
- "CONTRADICTION",
530
- "assumes Tier 3",
531
- "Lock: ?YES",
532
- "Lock: ?NO",
533
- "lock approvals?",
534
- "approves locks",
535
- "Conforms to lock",
536
- "Challenges lock",
537
- "checkDecisionNumbersFresh",
538
- String.raw`roles/team-leader\.md`,
539
- String.raw`\(,`,
540
- String.raw`,\)`,
541
- String.raw`\(\.\)`,
542
- ...PLAN_ON_DISK_PATTERNS
543
- ];
544
- var TRANCHE_MODEL_FILE = "/tranche-model.md";
545
- var PATTERN_EXEMPT = {
546
- [String.raw`\bD-[0-9]{3}\b`]: ["./CLAUDE.md"],
547
- [String.raw`decisions\.md`]: [
548
- "docs-index.md",
549
- "apps/vada-ai/specs/legacy/README.md",
550
- "apps/vada-ai/specs/vada-product-spec.md",
551
- "apps/vada-ai/web/CLAUDE.md",
552
- "apps/vada-ai/CLAUDE.md"
553
- ],
554
- "decisions-legacy": [
555
- "packages/aeg-core/src/file-classify.ts",
556
- "packages/aeg-core/src/file-classify.test.ts",
557
- "packages/aeg-core/src/pr-tier.test.ts",
558
- "docs-index.md",
559
- ".claude/skills/database/SKILL.md",
560
- ".claude/skills/vada-architecture/SKILL.md",
561
- "apps/vada-ai/specs/vada-byok-principles.md",
562
- "apps/vada-ai/web/CLAUDE.md",
563
- "apps/vada-ai/CLAUDE.md"
564
- ],
565
- CONTRADICTION: ["apps/vada-ai/specs/vada-reviewers-spec.md"],
566
- ...Object.fromEntries(PLAN_ON_DISK_PATTERNS.map((pattern) => [pattern, [TRANCHE_MODEL_FILE]]))
567
- };
879
+ var retiredRules = rulesForGroup("retired-vocabulary");
880
+ var RETIRED_PATTERNS = retiredRules.map((rule) => rule.patterns.repository);
881
+ var DEFAULT_PATTERN_OF = new Map(retiredRules.map((rule) => [rule.id, rule.patterns.repository]));
568
882
  // ../../packages/aeg-core/src/task-tools.ts
569
883
  import { z } from "zod";
570
884
  var TASK_TOOL_ERROR_KINDS = [
@@ -833,9 +1147,11 @@ var LineageSchema = z3.object({
833
1147
  parent: z3.string().nullable()
834
1148
  }).strict();
835
1149
  var InputVersionsSchema = z3.object({
1150
+ manifest_version: z3.literal(2).nullable().optional(),
836
1151
  objectives_version: z3.string().nullable(),
837
1152
  brief_hash: z3.string().nullable(),
838
1153
  ruling_ordinal: z3.number().int().nullable(),
1154
+ pause_bound_ruling: z3.object({ rulingId: z3.string().min(1), pauseId: z3.string().min(1), contentDigest: z3.string().min(1) }).strict().nullable().optional(),
839
1155
  policy_digest: z3.string().nullable()
840
1156
  }).strict();
841
1157
  var ProvenanceSchema = z3.enum(["parent_attributed", "env_correlated", "self_reported", "unavailable"]);
@@ -873,7 +1189,17 @@ var HeaderMetaV3Schema = z3.object({
873
1189
  runtime: z3.string().nullable(),
874
1190
  source: z3.string().nullable()
875
1191
  }).strict();
876
- var HeaderMetaSchema = z3.discriminatedUnion("schema", [HeaderMetaV1Schema, HeaderMetaV2Schema, HeaderMetaV3Schema]);
1192
+ var HeaderMetaV4Schema = HeaderMetaV3Schema.extend({
1193
+ schema: z3.literal(4),
1194
+ process: z3.object({ id: z3.string(), version: z3.string().nullable(), digest: z3.string().nullable() }).strict(),
1195
+ runner: z3.object({ id: z3.string(), version: z3.string().nullable() }).strict()
1196
+ }).strict();
1197
+ var HeaderMetaSchema = z3.discriminatedUnion("schema", [
1198
+ HeaderMetaV1Schema,
1199
+ HeaderMetaV2Schema,
1200
+ HeaderMetaV3Schema,
1201
+ HeaderMetaV4Schema
1202
+ ]);
877
1203
  var SubjectSchema = z3.object({
878
1204
  issue: z3.number().int().nullable(),
879
1205
  pr: z3.number().int().optional(),
@@ -1093,6 +1419,75 @@ var DevReviewLoopEventSchema = z3.discriminatedUnion("event", [
1093
1419
  round: z3.number().int(),
1094
1420
  phase: z3.string()
1095
1421
  }).strict(),
1422
+ z3.object({
1423
+ ...loopShared,
1424
+ event: z3.literal("conflict_reentry"),
1425
+ task: z3.number().int(),
1426
+ pr: z3.number().int().positive(),
1427
+ attempt: z3.number().int().positive(),
1428
+ bound: z3.number().int().positive()
1429
+ }).strict(),
1430
+ z3.object({
1431
+ ...loopShared,
1432
+ event: z3.literal("storage_push"),
1433
+ round: z3.number().int(),
1434
+ branch: z3.string(),
1435
+ head: z3.string()
1436
+ }).strict(),
1437
+ z3.object({
1438
+ ...loopShared,
1439
+ event: z3.literal("local_checks_run"),
1440
+ round: z3.number().int(),
1441
+ head: z3.string().nullable(),
1442
+ passed: z3.boolean(),
1443
+ wall_ms: z3.number().nonnegative()
1444
+ }).strict(),
1445
+ z3.object({
1446
+ ...loopShared,
1447
+ event: z3.literal("ready_push"),
1448
+ round: z3.number().int(),
1449
+ head: z3.string(),
1450
+ outcome: z3.enum(["passed", "refused"]),
1451
+ selected: z3.number().int().nonnegative(),
1452
+ failed: z3.number().int().nonnegative(),
1453
+ rerun: z3.boolean(),
1454
+ wall_ms: z3.number().nonnegative()
1455
+ }).strict(),
1456
+ z3.object({
1457
+ ...loopShared,
1458
+ event: z3.literal("failed_tests_rerun"),
1459
+ round: z3.number().int(),
1460
+ head: z3.string(),
1461
+ rerun_of: z3.string(),
1462
+ failed_files: z3.number().int().nonnegative(),
1463
+ affected_files: z3.number().int().nonnegative(),
1464
+ full_count: z3.number().int().nonnegative()
1465
+ }).strict(),
1466
+ z3.object({
1467
+ ...loopShared,
1468
+ event: z3.literal("pr_opened"),
1469
+ round: z3.number().int(),
1470
+ pr: z3.number().int().positive(),
1471
+ head: z3.string()
1472
+ }).strict(),
1473
+ z3.object({
1474
+ ...loopShared,
1475
+ event: z3.literal("ci_result_read"),
1476
+ round: z3.number().int(),
1477
+ pr: z3.number().int().positive(),
1478
+ head: z3.string(),
1479
+ conclusion: z3.enum(["green", "red", "pending", "skipped"]),
1480
+ failing_checks: z3.array(z3.string()),
1481
+ wait_ms: z3.number().nonnegative()
1482
+ }).strict(),
1483
+ z3.object({
1484
+ ...loopShared,
1485
+ event: z3.literal("phase_time"),
1486
+ round: z3.number().int(),
1487
+ phase: z3.enum(["developer", "local_checks", "review", "push", "ci", "other"]),
1488
+ step: z3.string(),
1489
+ wall_ms: z3.number().nonnegative()
1490
+ }).strict(),
1096
1491
  z3.object({
1097
1492
  ...loopShared,
1098
1493
  event: z3.literal("driver_exited"),
@@ -1280,7 +1675,7 @@ var EffectEventSchema = z3.discriminatedUnion("event", [
1280
1675
  ]);
1281
1676
  var CustomFieldValueSchema = z3.union([z3.string().max(CUSTOM_TEXT_MAX_LENGTH), z3.number().finite(), z3.boolean()]);
1282
1677
  var customShared = {
1283
- meta: HeaderMetaV3Schema,
1678
+ meta: HeaderMetaSchema,
1284
1679
  subject: SubjectSchema,
1285
1680
  kind: z3.literal("custom"),
1286
1681
  ...envelopeTail
@@ -1365,7 +1760,7 @@ function buildHeader(input) {
1365
1760
  const issue = subject.issue;
1366
1761
  return {
1367
1762
  meta: {
1368
- schema: 3,
1763
+ schema: 4,
1369
1764
  ts: input.now.toISOString(),
1370
1765
  run_id: input.runId,
1371
1766
  seq: input.seq,
@@ -1383,23 +1778,34 @@ function buildHeader(input) {
1383
1778
  parent: lineageFieldFromEnv(input.env.parent)
1384
1779
  },
1385
1780
  input_versions: {
1781
+ manifest_version: input.inputVersions?.manifestVersion ?? null,
1386
1782
  objectives_version: input.inputVersions?.objectivesVersion ?? null,
1387
1783
  brief_hash: input.inputVersions?.briefHash ?? null,
1388
1784
  ruling_ordinal: input.inputVersions?.rulingOrdinal ?? null,
1785
+ pause_bound_ruling: input.inputVersions?.pauseBoundRuling ?? null,
1389
1786
  policy_digest: input.inputVersions?.policyDigest ?? null
1390
1787
  },
1391
1788
  provenance: provenanceFor(input),
1392
1789
  work: {
1393
1790
  ref: lineageFieldFromEnv(input.env.workRef) ?? (issue === null ? null : String(issue)),
1394
1791
  repo: input.repo,
1395
- change: null,
1396
- revision: null
1792
+ change: pr === undefined ? null : String(pr),
1793
+ revision: input.revision ?? null
1397
1794
  },
1398
1795
  flow: {
1399
1796
  id: lineageFieldFromEnv(input.env.flow) ?? "vinaya",
1400
1797
  version: lineageFieldFromEnv(input.env.flowVersion)
1401
1798
  },
1402
1799
  runtime: lineageFieldFromEnv(input.env.runtime),
1800
+ process: {
1801
+ id: lineageFieldFromEnv(input.env.processId) ?? "vinaya",
1802
+ version: lineageFieldFromEnv(input.env.processVersion),
1803
+ digest: lineageFieldFromEnv(input.env.processDigest)
1804
+ },
1805
+ runner: {
1806
+ id: lineageFieldFromEnv(input.env.runnerId) ?? "standalone",
1807
+ version: lineageFieldFromEnv(input.env.runnerVersion)
1808
+ },
1403
1809
  source: lineageFieldFromEnv(input.env.source)
1404
1810
  },
1405
1811
  subject
@@ -1443,7 +1849,7 @@ function redact(value, home) {
1443
1849
  return value;
1444
1850
  }
1445
1851
  // ../../packages/aeg-core/src/log/store.ts
1446
- var KNOWN_SCHEMA_VERSIONS = [1, 2, 3];
1852
+ var KNOWN_SCHEMA_VERSIONS = [1, 2, 3, 4];
1447
1853
  function metaOf(obj) {
1448
1854
  if (obj === null || typeof obj !== "object")
1449
1855
  return null;
@@ -1581,6 +1987,12 @@ var ManifestRecordSchema = z4.object({
1581
1987
  briefHash: z4.string().min(1).nullable(),
1582
1988
  objectivesVersion: z4.string().min(1).nullable(),
1583
1989
  rulingOrdinal: epochNumber,
1990
+ manifestVersion: z4.literal(2).optional(),
1991
+ pauseBoundRuling: z4.object({
1992
+ rulingId: z4.string().min(1),
1993
+ pauseId: z4.string().min(1),
1994
+ contentDigest: z4.string().min(1)
1995
+ }).strict().nullable().optional(),
1584
1996
  policyDigest: z4.string().min(1),
1585
1997
  recordedAt: isoTimestamp
1586
1998
  }).strict();
@@ -1602,7 +2014,11 @@ var LoopStateRecordSchema = z4.object({
1602
2014
  deliveredFindings: roundHeadIdentity.nullable(),
1603
2015
  repeatMemory: z4.object({
1604
2016
  blockingFindings: z4.array(z4.string()),
1605
- lastFailure: z4.object({ signature: z4.string(), message: z4.string() }).nullable()
2017
+ lastFailure: z4.object({ signature: z4.string(), message: z4.string(), developerAttemptedSince: z4.boolean().optional() }).nullable()
2018
+ }).strict().optional(),
2019
+ developerHandoff: z4.object({
2020
+ findings: z4.array(z4.object({ id: z4.string().min(1), description: z4.string().min(1) }).strict()),
2021
+ failingChecks: z4.array(z4.string().min(1))
1606
2022
  }).strict().optional(),
1607
2023
  publicationExpectedBase: z4.string().regex(/^[0-9a-f]{40}$/).nullable().optional(),
1608
2024
  taskStartedAt: isoTimestamp.optional(),
@@ -1657,6 +2073,16 @@ var ResolutionRecordSchema = z4.object({
1657
2073
  authenticatedFrom: z4.string().min(1),
1658
2074
  consumedAt: isoTimestamp
1659
2075
  }).strict();
2076
+ var ExecutionRoundMirrorRecordSchema = z4.object({
2077
+ version: z4.literal(1),
2078
+ kind: z4.literal("execution_round"),
2079
+ task: taskId,
2080
+ repository: z4.string().min(1),
2081
+ threadId: z4.string().min(1),
2082
+ checkpointId: z4.string().min(1),
2083
+ round: z4.number().int().positive(),
2084
+ recordedAt: isoTimestamp
2085
+ }).strict();
1660
2086
  // ../../packages/aeg-core/src/control-store/local.ts
1661
2087
  import {
1662
2088
  closeSync as closeSync2,
@@ -1678,10 +2104,10 @@ import { dirname, join, resolve, sep } from "node:path";
1678
2104
  function isErrnoException(err, code) {
1679
2105
  return typeof err === "object" && err !== null && err.code === code;
1680
2106
  }
1681
- function isTrustedDirStat(stat, ownUid) {
2107
+ function isTrustedDirStat(stat, ownUid, trustedOverflowUid) {
1682
2108
  if (typeof ownUid !== "number")
1683
2109
  return true;
1684
- if (stat.uid !== ownUid && stat.uid !== 0)
2110
+ if (stat.uid !== ownUid && stat.uid !== 0 && stat.uid !== trustedOverflowUid)
1685
2111
  return false;
1686
2112
  const worldWritable = (stat.mode & 2) !== 0;
1687
2113
  const sticky = (stat.mode & 512) !== 0;
@@ -1690,15 +2116,54 @@ function isTrustedDirStat(stat, ownUid) {
1690
2116
  function currentUid() {
1691
2117
  return typeof process.getuid === "function" ? process.getuid() : undefined;
1692
2118
  }
2119
+ function uidMapLeavesRootUnmapped(uidMap) {
2120
+ const lines = uidMap.split(`
2121
+ `).map((line) => line.trim()).filter((line) => line.length > 0);
2122
+ if (lines.length === 0)
2123
+ return false;
2124
+ for (const line of lines) {
2125
+ const fields = line.split(/\s+/);
2126
+ if (fields.length !== 3 || !fields.every((field) => /^\d+$/.test(field)))
2127
+ return false;
2128
+ const inside = Number(fields[0]);
2129
+ const count = Number(fields[2]);
2130
+ if (inside === 0 && count > 0)
2131
+ return false;
2132
+ }
2133
+ return true;
2134
+ }
2135
+ function readTrustedOverflowUid(readFile) {
2136
+ try {
2137
+ if (!uidMapLeavesRootUnmapped(readFile("/proc/self/uid_map")))
2138
+ return;
2139
+ const overflow = readFile("/proc/sys/kernel/overflowuid").trim();
2140
+ return /^\d+$/.test(overflow) ? Number(overflow) : undefined;
2141
+ } catch {
2142
+ return;
2143
+ }
2144
+ }
2145
+ var cachedTrustedOverflowUid;
2146
+ function processTrustedOverflowUid() {
2147
+ cachedTrustedOverflowUid ??= { value: readTrustedOverflowUid((path) => readFileSync2(path, "utf8")) };
2148
+ return cachedTrustedOverflowUid.value;
2149
+ }
2150
+ function isAtOrBelowTrustedRoot(index, rootSegmentCount) {
2151
+ return index >= rootSegmentCount - 1;
2152
+ }
2153
+ function segmentTrustedOverflowUid(index, rootSegmentCount, trustedOverflowUid) {
2154
+ return isAtOrBelowTrustedRoot(index, rootSegmentCount) ? undefined : trustedOverflowUid;
2155
+ }
1693
2156
  function mkdirNoSymlinks(dir, mode, trustedRoot) {
1694
2157
  const absolute = resolve(dir);
1695
2158
  const rootSegments = resolve(trustedRoot).split(sep).filter((s) => s.length > 0);
1696
2159
  const segments = absolute.split(sep).filter((s) => s.length > 0);
1697
2160
  const ownUid = currentUid();
2161
+ const trustedOverflowUid = typeof ownUid === "number" ? processTrustedOverflowUid() : undefined;
1698
2162
  let current = absolute.startsWith(sep) ? sep : "";
1699
2163
  segments.forEach((segment, index) => {
1700
2164
  current = current === "" || current === sep ? `${current}${segment}` : `${current}${sep}${segment}`;
1701
- const atOrBelowTrustedRoot = index >= rootSegments.length - 1;
2165
+ const atOrBelowTrustedRoot = isAtOrBelowTrustedRoot(index, rootSegments.length);
2166
+ const overflowUid = segmentTrustedOverflowUid(index, rootSegments.length, trustedOverflowUid);
1702
2167
  try {
1703
2168
  mkdirSync(current, { mode });
1704
2169
  } catch (err) {
@@ -1719,7 +2184,7 @@ function mkdirNoSymlinks(dir, mode, trustedRoot) {
1719
2184
  if (!real.isDirectory()) {
1720
2185
  throw new Error(`control-store: refusing to create a run directory through ${current} — it is a symlink that does not resolve to a real directory`);
1721
2186
  }
1722
- if (!isTrustedDirStat(real, ownUid)) {
2187
+ if (!isTrustedDirStat(real, ownUid, overflowUid)) {
1723
2188
  throw new Error(`control-store: refusing to create a run directory through ${current} — its symlink target is owned by uid ${real.uid} with mode ${(real.mode & 4095).toString(8)}, neither this process's own user nor a safe shared mode`);
1724
2189
  }
1725
2190
  return;
@@ -1727,7 +2192,7 @@ function mkdirNoSymlinks(dir, mode, trustedRoot) {
1727
2192
  if (!stat.isDirectory()) {
1728
2193
  throw new Error(`control-store: refusing to create a run directory through ${current} — it already exists and is not a real directory (a symlink or a file)`);
1729
2194
  }
1730
- if (!isTrustedDirStat(stat, ownUid)) {
2195
+ if (!isTrustedDirStat(stat, ownUid, overflowUid)) {
1731
2196
  throw new Error(`control-store: refusing to create a run directory through ${current} — it already exists, owned by uid ${stat.uid} with mode ${(stat.mode & 4095).toString(8)}, neither this process's own user nor a safe shared mode`);
1732
2197
  }
1733
2198
  });
@@ -1771,6 +2236,7 @@ var REGISTRY = [
1771
2236
  {
1772
2237
  name: "brief-shape",
1773
2238
  validates: "body",
2239
+ requiresOpenPr: true,
1774
2240
  run: bin("check-brief-shape"),
1775
2241
  scope: "diff",
1776
2242
  timeoutMs: 15000,
@@ -1779,7 +2245,9 @@ var REGISTRY = [
1779
2245
  BRANCH: { optional: true },
1780
2246
  PR_NUMBER: { optional: true },
1781
2247
  GITHUB_TOKEN: { optional: true },
1782
- GH_TOKEN: { optional: true }
2248
+ GH_TOKEN: { optional: true },
2249
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
2250
+ GITHUB_ACTIONS: { optional: true }
1783
2251
  }
1784
2252
  },
1785
2253
  0
@@ -1788,6 +2256,7 @@ var REGISTRY = [
1788
2256
  {
1789
2257
  name: "pr-report-density",
1790
2258
  validates: "body",
2259
+ requiresOpenPr: true,
1791
2260
  run: bin("check-pr-report-density"),
1792
2261
  scope: "diff",
1793
2262
  timeoutMs: 15000,
@@ -1813,7 +2282,9 @@ var REGISTRY = [
1813
2282
  PR_NUMBER: { optional: true },
1814
2283
  GITHUB_REPOSITORY: { optional: true },
1815
2284
  GITHUB_TOKEN: { optional: true },
1816
- GH_TOKEN: { optional: true }
2285
+ GH_TOKEN: { optional: true },
2286
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
2287
+ GITHUB_ACTIONS: { optional: true }
1817
2288
  }
1818
2289
  },
1819
2290
  0
@@ -1837,6 +2308,7 @@ var REGISTRY = [
1837
2308
  {
1838
2309
  name: "pr-premise-reassert",
1839
2310
  validates: "body",
2311
+ requiresOpenPr: true,
1840
2312
  run: bin("check-pr-premise-reassert"),
1841
2313
  scope: "diff",
1842
2314
  timeoutMs: 15000,
@@ -1857,7 +2329,9 @@ var REGISTRY = [
1857
2329
  BRANCH: { optional: true },
1858
2330
  GITHUB_TOKEN: { optional: true },
1859
2331
  GH_TOKEN: { optional: true },
1860
- PREMISE_FILE: { optional: true }
2332
+ PREMISE_FILE: { optional: true },
2333
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
2334
+ GITHUB_ACTIONS: { optional: true }
1861
2335
  }
1862
2336
  },
1863
2337
  0
@@ -1909,7 +2383,9 @@ var REGISTRY = [
1909
2383
  PR_BODY: { optional: true },
1910
2384
  PR_BODY_FILE: { optional: true },
1911
2385
  GITHUB_TOKEN: { optional: true },
1912
- GH_TOKEN: { optional: true }
2386
+ GH_TOKEN: { optional: true },
2387
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
2388
+ GITHUB_ACTIONS: { optional: true }
1913
2389
  }
1914
2390
  },
1915
2391
  1
@@ -1925,7 +2401,13 @@ var REGISTRY = [
1925
2401
  principalOwed: true,
1926
2402
  env: {
1927
2403
  PR_BODY: { optional: true },
1928
- BRANCH: { optional: true }
2404
+ BRANCH: { optional: true },
2405
+ PULL_REQUEST_HEAD_SHA: { optional: true },
2406
+ GITHUB_REPOSITORY: { optional: true },
2407
+ GITHUB_TOKEN: { optional: true },
2408
+ GH_TOKEN: { optional: true },
2409
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
2410
+ GITHUB_ACTIONS: { optional: true }
1929
2411
  }
1930
2412
  },
1931
2413
  1
@@ -1941,7 +2423,13 @@ var REGISTRY = [
1941
2423
  ownWorkflow: true,
1942
2424
  env: {
1943
2425
  PR_BODY: { optional: true },
1944
- BRANCH: { optional: true }
2426
+ BRANCH: { optional: true },
2427
+ PULL_REQUEST_HEAD_SHA: { optional: true },
2428
+ GITHUB_REPOSITORY: { optional: true },
2429
+ GITHUB_TOKEN: { optional: true },
2430
+ GH_TOKEN: { optional: true },
2431
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
2432
+ GITHUB_ACTIONS: { optional: true }
1945
2433
  }
1946
2434
  },
1947
2435
  1
@@ -1960,7 +2448,9 @@ var REGISTRY = [
1960
2448
  PR_NUMBER: { optional: true },
1961
2449
  GITHUB_REPOSITORY: { optional: true },
1962
2450
  GITHUB_TOKEN: { optional: true },
1963
- GH_TOKEN: { optional: true }
2451
+ GH_TOKEN: { optional: true },
2452
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
2453
+ GITHUB_ACTIONS: { optional: true }
1964
2454
  }
1965
2455
  },
1966
2456
  1
@@ -2000,7 +2490,9 @@ var REGISTRY = [
2000
2490
  PR_NUMBER: { optional: true },
2001
2491
  GITHUB_REPOSITORY: { optional: true },
2002
2492
  GITHUB_TOKEN: { optional: true },
2003
- GH_TOKEN: { optional: true }
2493
+ GH_TOKEN: { optional: true },
2494
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
2495
+ GITHUB_ACTIONS: { optional: true }
2004
2496
  }
2005
2497
  },
2006
2498
  1
@@ -2053,12 +2545,15 @@ var REGISTRY = [
2053
2545
  {
2054
2546
  name: "doc-coverage-push",
2055
2547
  validates: "body",
2548
+ advisory: true,
2056
2549
  run: bin("check-doc-coverage-push"),
2057
2550
  scope: "diff",
2058
2551
  timeoutMs: 15000,
2059
2552
  env: {
2060
2553
  OVERRIDE_DOCS: { optional: true },
2061
2554
  BASE_SHA: { optional: true },
2555
+ GIT_INDEX_FILE: { optional: true },
2556
+ VINAYA_COMMIT_HOOK: { optional: true },
2062
2557
  PR_BODY: { optional: true },
2063
2558
  PR_BODY_FILE: { optional: true },
2064
2559
  PR_LABELS: { optional: true },
@@ -2070,21 +2565,6 @@ var REGISTRY = [
2070
2565
  },
2071
2566
  0
2072
2567
  ],
2073
- [
2074
- {
2075
- name: "issue-assignment",
2076
- run: bin("check-issue-assignment"),
2077
- scope: "full",
2078
- timeoutMs: 30000,
2079
- env: {
2080
- AEG_REPO: { optional: true },
2081
- BRANCH: { optional: true },
2082
- GITHUB_TOKEN: { optional: true },
2083
- GH_TOKEN: { optional: true }
2084
- }
2085
- },
2086
- 0
2087
- ],
2088
2568
  [
2089
2569
  {
2090
2570
  name: "evidence-fresh",
@@ -2098,7 +2578,9 @@ var REGISTRY = [
2098
2578
  PR_BODY: { optional: true },
2099
2579
  BASE_SHA: { optional: true },
2100
2580
  GITHUB_TOKEN: { optional: true },
2101
- GH_TOKEN: { optional: true }
2581
+ GH_TOKEN: { optional: true },
2582
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
2583
+ GITHUB_ACTIONS: { optional: true }
2102
2584
  }
2103
2585
  },
2104
2586
  1
@@ -2109,7 +2591,11 @@ var REGISTRY = [
2109
2591
  run: bin("check-reader-resolvable-prose"),
2110
2592
  scope: "full",
2111
2593
  timeoutMs: 30000,
2112
- env: {},
2594
+ env: {
2595
+ BASE_SHA: { optional: true },
2596
+ GIT_INDEX_FILE: { optional: true },
2597
+ VINAYA_COMMIT_HOOK: { optional: true }
2598
+ },
2113
2599
  include: [
2114
2600
  "aeg-root/**/*.md",
2115
2601
  "apps/cli/src/**",
@@ -2127,7 +2613,11 @@ var REGISTRY = [
2127
2613
  run: bin("check-retired-vocabulary"),
2128
2614
  scope: "full",
2129
2615
  timeoutMs: 30000,
2130
- env: {},
2616
+ env: {
2617
+ BASE_SHA: { optional: true },
2618
+ GIT_INDEX_FILE: { optional: true },
2619
+ VINAYA_COMMIT_HOOK: { optional: true }
2620
+ },
2131
2621
  include: ["aeg-root/**/*.md"]
2132
2622
  },
2133
2623
  0
@@ -2135,10 +2625,15 @@ var REGISTRY = [
2135
2625
  [
2136
2626
  {
2137
2627
  name: "doctrine-portability",
2628
+ advisory: true,
2138
2629
  run: bin("check-doctrine-portability"),
2139
2630
  scope: "full",
2140
2631
  timeoutMs: 30000,
2141
- env: { BASE_SHA: { optional: true } },
2632
+ env: {
2633
+ BASE_SHA: { optional: true },
2634
+ GIT_INDEX_FILE: { optional: true },
2635
+ VINAYA_COMMIT_HOOK: { optional: true }
2636
+ },
2142
2637
  include: ["aeg-root/**/*.md"]
2143
2638
  },
2144
2639
  0
@@ -2171,7 +2666,11 @@ var REGISTRY = [
2171
2666
  run: bin("check-exec-bits"),
2172
2667
  scope: "diff",
2173
2668
  timeoutMs: 30000,
2174
- env: {}
2669
+ env: {
2670
+ BASE_SHA: { optional: true },
2671
+ GIT_INDEX_FILE: { optional: true },
2672
+ VINAYA_COMMIT_HOOK: { optional: true }
2673
+ }
2175
2674
  },
2176
2675
  0
2177
2676
  ],
@@ -2181,17 +2680,26 @@ var REGISTRY = [
2181
2680
  run: bin("check-ci-shard-coverage"),
2182
2681
  scope: "diff",
2183
2682
  timeoutMs: 15000,
2184
- env: {}
2683
+ env: {
2684
+ BASE_SHA: { optional: true },
2685
+ GIT_INDEX_FILE: { optional: true },
2686
+ VINAYA_COMMIT_HOOK: { optional: true }
2687
+ }
2185
2688
  },
2186
2689
  0
2187
2690
  ],
2188
2691
  [
2189
2692
  {
2190
2693
  name: "workspace-escape",
2694
+ advisory: true,
2191
2695
  run: bin("check-workspace-escape"),
2192
2696
  scope: "full",
2193
2697
  timeoutMs: 30000,
2194
- env: {},
2698
+ env: {
2699
+ BASE_SHA: { optional: true },
2700
+ GIT_INDEX_FILE: { optional: true },
2701
+ VINAYA_COMMIT_HOOK: { optional: true }
2702
+ },
2195
2703
  include: ["aeg-root/**/*.md"]
2196
2704
  },
2197
2705
  0
@@ -2202,17 +2710,23 @@ var REGISTRY = [
2202
2710
  run: bin("check-changeset-coverage"),
2203
2711
  scope: "diff",
2204
2712
  timeoutMs: 15000,
2205
- env: {}
2713
+ env: {
2714
+ BASE_SHA: { optional: true },
2715
+ GIT_INDEX_FILE: { optional: true },
2716
+ VINAYA_COMMIT_HOOK: { optional: true }
2717
+ }
2206
2718
  },
2207
2719
  0
2208
2720
  ],
2209
2721
  [
2210
2722
  {
2211
2723
  name: "quoted-command",
2724
+ advisory: true,
2212
2725
  run: bin("check-quoted-command"),
2213
- scope: "diff",
2726
+ scope: "full",
2214
2727
  timeoutMs: 15000,
2215
- env: {}
2728
+ env: {},
2729
+ include: ["aeg-root/**/*.md"]
2216
2730
  },
2217
2731
  0
2218
2732
  ],
@@ -2220,7 +2734,7 @@ var REGISTRY = [
2220
2734
  {
2221
2735
  name: "main-branch-refusal",
2222
2736
  run: bin("check-main-branch-refusal"),
2223
- scope: "full",
2737
+ scope: "diff",
2224
2738
  timeoutMs: 15000,
2225
2739
  env: { VINAYA_PUSH_REFS: { optional: true } }
2226
2740
  },
@@ -2287,18 +2801,6 @@ var REGISTRY = [
2287
2801
  },
2288
2802
  1
2289
2803
  ],
2290
- [
2291
- {
2292
- name: "issue-tranche-label",
2293
- run: bin("check-issue-tranche-label"),
2294
- validates: "issue",
2295
- scope: "full",
2296
- ownWorkflow: true,
2297
- timeoutMs: 15000,
2298
- env: { ISSUE_BODY: { optional: true }, ISSUE_LABELS: { optional: true } }
2299
- },
2300
- 1
2301
- ],
2302
2804
  [
2303
2805
  {
2304
2806
  name: "issue-milestone-attach",
@@ -2331,7 +2833,7 @@ import {
2331
2833
  existsSync as existsSync6,
2332
2834
  fstatSync as fstatSync3,
2333
2835
  mkdirSync as mkdirSync5,
2334
- lstatSync as lstatSync3,
2836
+ lstatSync as lstatSync4,
2335
2837
  openSync as openSync5,
2336
2838
  readFileSync as readFileSync6,
2337
2839
  renameSync as renameSync3,
@@ -2345,32 +2847,323 @@ import { promisify as promisify5 } from "node:util";
2345
2847
  // src/lib/config.ts
2346
2848
  import { execFile as execFile4, execFileSync as execFileSync2 } from "node:child_process";
2347
2849
  import { promisify as promisify4 } from "node:util";
2348
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, realpathSync, writeFileSync } from "node:fs";
2850
+ import { existsSync as existsSync3, lstatSync as lstatSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync3, realpathSync, writeFileSync } from "node:fs";
2349
2851
  import { homedir } from "node:os";
2350
- import { dirname as dirname3, isAbsolute, join as join4, resolve as resolve2 } from "node:path";
2351
- import { z as z5 } from "zod";
2852
+ import { basename, dirname as dirname3, isAbsolute, join as join4, resolve as resolve2 } from "node:path";
2853
+ import { z as z6 } from "zod";
2854
+
2855
+ // src/checks/contract.ts
2856
+ var CHECK_SCHEMA_VERSION = 1;
2857
+ function emitCheckError(error) {
2858
+ process.stderr.write(`${JSON.stringify(error)}
2859
+ `);
2860
+ }
2352
2861
 
2353
2862
  // src/lib/agent-vendors.ts
2354
2863
  var AGENT_VENDORS = ["skills", "claude", "gemini"];
2355
2864
 
2865
+ // src/lib/prose-rules-config.ts
2866
+ import safeRegex from "safe-regex2";
2867
+ import { z as z5 } from "zod";
2868
+ var SEVERITIES = ["error", "warning"];
2869
+ var OVERRIDE_KEYS = ["scopes", "severity", "exempt"];
2870
+ var FIXED_DEFAULT_KEYS = ["pattern", "patterns", "flags", "means", "message", "id"];
2871
+ var CUSTOM_KEYS = ["id", "pattern", "patterns", "flags", "means", "scopes", "severity", "exempt"];
2872
+ var DEFAULT_IDS = new Set([...DEFAULT_PROSE_RULES.map((rule) => rule.id), DECISION_RECORD_CITATION_ID]);
2873
+ function isPlainObject(value) {
2874
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2875
+ }
2876
+ function outsideRepositoryReason(entry) {
2877
+ if (entry.startsWith("/") || /^[A-Za-z]:/.test(entry))
2878
+ return "must be a repository-relative path, not an absolute one";
2879
+ if (entry.split(/[\\/]/).includes(".."))
2880
+ return "must stay inside the repository — no `..` segment";
2881
+ return null;
2882
+ }
2883
+ var RepoRelativePathSchema = z5.string().min(1).superRefine((entry, ctx) => {
2884
+ const reason = outsideRepositoryReason(entry);
2885
+ if (reason)
2886
+ ctx.addIssue({ code: z5.ZodIssueCode.custom, message: reason });
2887
+ });
2888
+ function pathListIssues(value, path, issues) {
2889
+ if (!Array.isArray(value)) {
2890
+ issues.push({ path, message: "must be a list of repository-relative paths" });
2891
+ return;
2892
+ }
2893
+ value.forEach((entry, index) => {
2894
+ if (typeof entry !== "string" || entry.length === 0) {
2895
+ issues.push({ path: [...path, index], message: "must be a non-empty repository-relative path" });
2896
+ return;
2897
+ }
2898
+ const reason = outsideRepositoryReason(entry);
2899
+ if (reason)
2900
+ issues.push({ path: [...path, index], message: reason });
2901
+ });
2902
+ }
2903
+ function scopeListIssues(value, path, allowed, issues) {
2904
+ if (!Array.isArray(value) || value.length === 0) {
2905
+ issues.push({ path, message: "must name at least one scope" });
2906
+ return null;
2907
+ }
2908
+ const scopes = [];
2909
+ value.forEach((scope, index) => {
2910
+ if (typeof scope !== "string" || !CONFIGURABLE_PROSE_SCOPES.includes(scope)) {
2911
+ issues.push({
2912
+ path: [...path, index],
2913
+ message: scope === "published" ? 'scope "published" is not configurable here — the published pass is configured by proseGates.published.allow' : `unknown scope ${JSON.stringify(scope)} — the scopes are: ${CONFIGURABLE_PROSE_SCOPES.join(", ")}`
2914
+ });
2915
+ return;
2916
+ }
2917
+ if (!allowed.includes(scope)) {
2918
+ issues.push({
2919
+ path: [...path, index],
2920
+ message: `scope "${scope}" is not one this rule can run in — it can run in: ${allowed.join(", ")}`
2921
+ });
2922
+ return;
2923
+ }
2924
+ scopes.push(scope);
2925
+ });
2926
+ return scopes;
2927
+ }
2928
+ function severityIssues(value, path, scopes, issues) {
2929
+ if (typeof value === "string") {
2930
+ if (!SEVERITIES.includes(value)) {
2931
+ issues.push({ path, message: `unknown severity ${JSON.stringify(value)} — use "error" or "warning"` });
2932
+ }
2933
+ return;
2934
+ }
2935
+ if (!isPlainObject(value)) {
2936
+ issues.push({ path, message: 'must be "error", "warning", or a map from scope to one of them' });
2937
+ return;
2938
+ }
2939
+ for (const [scope, severity] of Object.entries(value)) {
2940
+ if (!scopes.includes(scope)) {
2941
+ issues.push({ path: [...path, scope], message: `names scope "${scope}", which this rule's scopes do not cover` });
2942
+ }
2943
+ if (typeof severity !== "string" || !SEVERITIES.includes(severity)) {
2944
+ issues.push({
2945
+ path: [...path, scope],
2946
+ message: `unknown severity ${JSON.stringify(severity)} — use "error" or "warning"`
2947
+ });
2948
+ }
2949
+ }
2950
+ }
2951
+ function patternIssues(source, flags, path, issues) {
2952
+ if (typeof source !== "string" || source.length === 0) {
2953
+ issues.push({ path, message: "must be a non-empty regular expression" });
2954
+ return;
2955
+ }
2956
+ if (source.length > CONFIGURED_PATTERN_MAX_LENGTH) {
2957
+ issues.push({
2958
+ path,
2959
+ message: `is ${source.length} characters, over the ${CONFIGURED_PATTERN_MAX_LENGTH}-character limit for a configured pattern`
2960
+ });
2961
+ return;
2962
+ }
2963
+ try {
2964
+ new RegExp(source, flags);
2965
+ } catch (err) {
2966
+ issues.push({ path, message: `does not compile: ${err.message}` });
2967
+ return;
2968
+ }
2969
+ if (!safeRegex(source, { limit: Number.MAX_SAFE_INTEGER })) {
2970
+ issues.push({
2971
+ path,
2972
+ message: "has star height above one (a repeated group that itself repeats), which can take exponential time — " + "safe-regex2 refuses it. The shipped defaults are not held to this limit, so a pattern copied from one of " + "them can still be refused here; rewrite it without the nested repetition."
2973
+ });
2974
+ }
2975
+ }
2976
+ function flagIssues(value, path, issues) {
2977
+ if (value === undefined)
2978
+ return "";
2979
+ if (typeof value !== "string") {
2980
+ issues.push({ path, message: 'must be a string of flags, e.g. "i"' });
2981
+ return "";
2982
+ }
2983
+ const seen = new Set;
2984
+ for (const flag of value) {
2985
+ if (!CONFIGURED_PROSE_FLAGS.includes(flag)) {
2986
+ issues.push({
2987
+ path,
2988
+ message: `unknown flag ${JSON.stringify(flag)} — only ${CONFIGURED_PROSE_FLAGS.map((f) => `"${f}"`).join(" and ")} are allowed`
2989
+ });
2990
+ return "";
2991
+ }
2992
+ if (seen.has(flag)) {
2993
+ issues.push({ path, message: `repeats the flag "${flag}"` });
2994
+ return "";
2995
+ }
2996
+ seen.add(flag);
2997
+ }
2998
+ return value;
2999
+ }
3000
+ function defaultsIssues(value, issues) {
3001
+ const base = ["defaults"];
3002
+ if (!isPlainObject(value)) {
3003
+ issues.push({ path: base, message: 'must map a default rule id to "off" or an override' });
3004
+ return;
3005
+ }
3006
+ for (const [id, override] of Object.entries(value)) {
3007
+ const path = [...base, id];
3008
+ const rule = CONFIGURABLE_DEFAULT_RULES.find((candidate) => candidate.id === id);
3009
+ if (!rule) {
3010
+ issues.push({
3011
+ path,
3012
+ message: `unknown default rule id "${id}" — \`vinaya check --plan\` lists the rules each prose check runs`
3013
+ });
3014
+ continue;
3015
+ }
3016
+ if (override === "off")
3017
+ continue;
3018
+ if (!isPlainObject(override)) {
3019
+ issues.push({ path, message: 'must be "off" or an object with any of scopes, severity, exempt' });
3020
+ continue;
3021
+ }
3022
+ for (const key of Object.keys(override)) {
3023
+ if (OVERRIDE_KEYS.includes(key))
3024
+ continue;
3025
+ issues.push({
3026
+ path: [...path, key],
3027
+ message: FIXED_DEFAULT_KEYS.includes(key) ? `a default rule's ${key} is fixed — add a custom rule under proseGates.rules.custom instead` : `unknown key "${key}" — a default rule takes only scopes, severity and exempt`
3028
+ });
3029
+ }
3030
+ const scopes = override.scopes === undefined ? [...rule.scopes] : scopeListIssues(override.scopes, [...path, "scopes"], allowedScopesFor(rule), issues);
3031
+ if (override.severity !== undefined && scopes)
3032
+ severityIssues(override.severity, [...path, "severity"], scopes, issues);
3033
+ if (override.exempt !== undefined)
3034
+ pathListIssues(override.exempt, [...path, "exempt"], issues);
3035
+ }
3036
+ }
3037
+ function customIssues(value, issues) {
3038
+ if (!Array.isArray(value)) {
3039
+ issues.push({ path: ["custom"], message: "must be a list of rules" });
3040
+ return;
3041
+ }
3042
+ const ids = new Set;
3043
+ value.forEach((rule, index) => {
3044
+ const path = ["custom", index];
3045
+ if (!isPlainObject(rule)) {
3046
+ issues.push({ path, message: "must be a rule object" });
3047
+ return;
3048
+ }
3049
+ for (const key of Object.keys(rule)) {
3050
+ if (!CUSTOM_KEYS.includes(key)) {
3051
+ issues.push({ path: [...path, key], message: `unknown key "${key}" — a rule takes ${CUSTOM_KEYS.join(", ")}` });
3052
+ }
3053
+ }
3054
+ if (typeof rule.id !== "string" || rule.id.length === 0) {
3055
+ issues.push({ path: [...path, "id"], message: "a custom rule needs an id" });
3056
+ } else if (DEFAULT_IDS.has(rule.id)) {
3057
+ issues.push({
3058
+ path: [...path, "id"],
3059
+ message: `"${rule.id}" is a default rule id — a custom rule needs its own id; retune the default under proseGates.rules.defaults instead`
3060
+ });
3061
+ } else if (ids.has(rule.id)) {
3062
+ issues.push({ path: [...path, "id"], message: `"${rule.id}" is used by an earlier custom rule` });
3063
+ } else {
3064
+ ids.add(rule.id);
3065
+ }
3066
+ if (typeof rule.means !== "string" || rule.means.trim().length === 0) {
3067
+ issues.push({ path: [...path, "means"], message: "a custom rule needs a message (`means`)" });
3068
+ }
3069
+ let scopes = null;
3070
+ if (rule.scopes === undefined) {
3071
+ issues.push({ path: [...path, "scopes"], message: "a custom rule needs at least one scope (`scopes`)" });
3072
+ } else {
3073
+ scopes = scopeListIssues(rule.scopes, [...path, "scopes"], CONFIGURABLE_PROSE_SCOPES, issues);
3074
+ }
3075
+ if (scopes && new Set(scopes.map(groupOfScope)).size > 1) {
3076
+ issues.push({
3077
+ path: [...path, "scopes"],
3078
+ message: 'mixes scopes of both prose checks — "repository" belongs to retired-vocabulary and every other scope to reader-resolvable-prose; write one rule per check'
3079
+ });
3080
+ }
3081
+ const flags = flagIssues(rule.flags, [...path, "flags"], issues);
3082
+ if (rule.pattern === undefined && rule.patterns === undefined) {
3083
+ issues.push({
3084
+ path: [...path, "pattern"],
3085
+ message: "a custom rule needs a `pattern` or a per-scope `patterns` map"
3086
+ });
3087
+ }
3088
+ if (rule.pattern !== undefined)
3089
+ patternIssues(rule.pattern, flags, [...path, "pattern"], issues);
3090
+ if (rule.patterns !== undefined) {
3091
+ if (!isPlainObject(rule.patterns)) {
3092
+ issues.push({ path: [...path, "patterns"], message: "must map a scope to a regular expression" });
3093
+ } else {
3094
+ for (const [scope, source] of Object.entries(rule.patterns)) {
3095
+ if (scopes && !scopes.includes(scope)) {
3096
+ issues.push({
3097
+ path: [...path, "patterns", scope],
3098
+ message: `names scope "${scope}", which this rule's scopes do not cover`
3099
+ });
3100
+ continue;
3101
+ }
3102
+ patternIssues(source, flags, [...path, "patterns", scope], issues);
3103
+ }
3104
+ if (rule.pattern === undefined && scopes) {
3105
+ for (const scope of scopes) {
3106
+ if (!(scope in rule.patterns)) {
3107
+ issues.push({
3108
+ path: [...path, "patterns"],
3109
+ message: `has no pattern for scope "${scope}" — add one, or a \`pattern\` every other scope uses`
3110
+ });
3111
+ }
3112
+ }
3113
+ }
3114
+ }
3115
+ }
3116
+ if (rule.severity !== undefined && scopes)
3117
+ severityIssues(rule.severity, [...path, "severity"], scopes, issues);
3118
+ if (rule.exempt !== undefined)
3119
+ pathListIssues(rule.exempt, [...path, "exempt"], issues);
3120
+ });
3121
+ }
3122
+ function proseRulesIssues(value) {
3123
+ const issues = [];
3124
+ if (!isPlainObject(value))
3125
+ return [{ path: [], message: "must be an object with any of exempt, defaults, custom" }];
3126
+ for (const key of Object.keys(value)) {
3127
+ if (!["exempt", "defaults", "custom"].includes(key)) {
3128
+ issues.push({ path: [key], message: `unknown key "${key}" — proseGates.rules takes exempt, defaults and custom` });
3129
+ }
3130
+ }
3131
+ if (value.exempt !== undefined)
3132
+ pathListIssues(value.exempt, ["exempt"], issues);
3133
+ if (value.defaults !== undefined)
3134
+ defaultsIssues(value.defaults, issues);
3135
+ if (value.custom !== undefined)
3136
+ customIssues(value.custom, issues);
3137
+ return issues;
3138
+ }
3139
+ var ProseRulesSchema = z5.unknown().superRefine((value, ctx) => {
3140
+ for (const issue of proseRulesIssues(value)) {
3141
+ ctx.addIssue({ code: z5.ZodIssueCode.custom, path: issue.path, message: issue.message });
3142
+ }
3143
+ }).transform((value) => value);
3144
+ var PublishedProseSchema = z5.object({
3145
+ allow: z5.array(z5.string().min(1)).optional()
3146
+ }).strict();
3147
+
2356
3148
  // src/lib/config.ts
2357
- var EnvEntrySchema = z5.union([
2358
- z5.literal(true),
2359
- z5.object({ optional: z5.literal(true) }),
2360
- z5.object({ anyOf: z5.array(z5.string()).min(2) }),
2361
- z5.string()
3149
+ var EnvEntrySchema = z6.union([
3150
+ z6.literal(true),
3151
+ z6.object({ optional: z6.literal(true) }),
3152
+ z6.object({ anyOf: z6.array(z6.string()).min(2) }),
3153
+ z6.string()
2362
3154
  ]);
2363
- var CheckEntrySchema = z5.object({
2364
- run: z5.string(),
2365
- scope: z5.enum(["diff", "full"]),
2366
- include: z5.array(z5.string()).optional(),
2367
- args: z5.array(z5.string()).optional(),
2368
- timeoutMs: z5.number().optional(),
2369
- env: z5.record(z5.string(), EnvEntrySchema).optional(),
2370
- requiresOpenPr: z5.boolean().optional(),
2371
- ownWorkflow: z5.boolean().optional(),
2372
- principalOwed: z5.literal(true).optional(),
2373
- validates: z5.enum(["body", "issue"]).optional()
3155
+ var CheckEntrySchema = z6.object({
3156
+ run: z6.string(),
3157
+ scope: z6.enum(["diff", "full"]),
3158
+ include: z6.array(z6.string()).optional(),
3159
+ args: z6.array(z6.string()).optional(),
3160
+ timeoutMs: z6.number().optional(),
3161
+ env: z6.record(z6.string(), EnvEntrySchema).optional(),
3162
+ requiresOpenPr: z6.boolean().optional(),
3163
+ ownWorkflow: z6.boolean().optional(),
3164
+ principalOwed: z6.literal(true).optional(),
3165
+ validates: z6.enum(["body", "issue"]).optional(),
3166
+ advisory: z6.literal(true).optional()
2374
3167
  }).superRefine((entry, ctx) => {
2375
3168
  if (!entry.env)
2376
3169
  return;
@@ -2380,22 +3173,22 @@ var CheckEntrySchema = z5.object({
2380
3173
  const members = value.anyOf;
2381
3174
  if (new Set(members).size !== members.length) {
2382
3175
  ctx.addIssue({
2383
- code: z5.ZodIssueCode.custom,
3176
+ code: z6.ZodIssueCode.custom,
2384
3177
  message: `env.${key}.anyOf has duplicate members`,
2385
3178
  path: ["env", key, "anyOf"]
2386
3179
  });
2387
3180
  }
2388
3181
  if (!members.includes(key)) {
2389
3182
  ctx.addIssue({
2390
- code: z5.ZodIssueCode.custom,
3183
+ code: z6.ZodIssueCode.custom,
2391
3184
  message: `env.${key}.anyOf must include "${key}" itself as a member`,
2392
3185
  path: ["env", key, "anyOf"]
2393
3186
  });
2394
3187
  }
2395
3188
  }
2396
3189
  });
2397
- var RoleEntrySchema = z5.object({
2398
- contract: z5.string().refine((p) => p.includes("/"), {
3190
+ var RoleEntrySchema = z6.object({
3191
+ contract: z6.string().refine((p) => p.includes("/"), {
2399
3192
  message: 'must be a path (contain at least one "/"), not a bare filename'
2400
3193
  })
2401
3194
  });
@@ -2419,17 +3212,17 @@ var BRIEF_BUILTINS = [
2419
3212
  "briefSections",
2420
3213
  "milestoneShape"
2421
3214
  ];
2422
- var BriefSectionSchema = z5.union([
2423
- z5.object({ builtin: z5.enum(BRIEF_BUILTINS) }),
2424
- z5.object({ heading: z5.string().min(1), name: z5.string().optional() }),
2425
- z5.object({ field: z5.string().min(1), name: z5.string().optional() }),
2426
- z5.object({ phrase: z5.string().min(1), name: z5.string().optional() })
3215
+ var BriefSectionSchema = z6.union([
3216
+ z6.object({ builtin: z6.enum(BRIEF_BUILTINS) }),
3217
+ z6.object({ heading: z6.string().min(1), name: z6.string().optional() }),
3218
+ z6.object({ field: z6.string().min(1), name: z6.string().optional() }),
3219
+ z6.object({ phrase: z6.string().min(1), name: z6.string().optional() })
2427
3220
  ]);
2428
- var BriefSchemaSchema = z5.object({
2429
- pr: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
2430
- issue: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
2431
- milestone: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
2432
- ack: z5.array(z5.enum(BRIEF_BUILTINS)).optional()
3221
+ var BriefSchemaSchema = z6.object({
3222
+ pr: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
3223
+ issue: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
3224
+ milestone: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
3225
+ ack: z6.array(z6.enum(BRIEF_BUILTINS)).optional()
2433
3226
  });
2434
3227
  function isSafeRepoRelPath(p) {
2435
3228
  if (p.length === 0)
@@ -2438,7 +3231,7 @@ function isSafeRepoRelPath(p) {
2438
3231
  return false;
2439
3232
  return p.split(/[\\/]/).every((seg) => seg !== ".." && seg !== "");
2440
3233
  }
2441
- var SafeRepoRelPath = z5.string().refine(isSafeRepoRelPath, {
3234
+ var SafeRepoRelPath = z6.string().refine(isSafeRepoRelPath, {
2442
3235
  message: "must be a repo-root-relative path with no `..` segment or absolute root"
2443
3236
  });
2444
3237
  var CANONICAL_HOOK_BLOCK_PREFIXES = [".git/", ".husky/", ".vinaya/hooks/", ".claude/hooks/"];
@@ -2448,22 +3241,22 @@ function isCanonicalHookBlockPath(p) {
2448
3241
  var ManagedHookBlockPath = SafeRepoRelPath.refine(isCanonicalHookBlockPath, {
2449
3242
  message: `must start with one of ${CANONICAL_HOOK_BLOCK_PREFIXES.join(", ")} (byte-exact, case-sensitive)`
2450
3243
  });
2451
- var ManagedBlockRecordSchema = z5.object({
3244
+ var ManagedBlockRecordSchema = z6.object({
2452
3245
  path: ManagedHookBlockPath,
2453
- marker: z5.string(),
2454
- comment: z5.enum(["hash", "html"])
3246
+ marker: z6.string(),
3247
+ comment: z6.enum(["hash", "html"])
2455
3248
  });
2456
- var ManagedManifestSchema = z5.object({
2457
- version: z5.number().int().positive(),
2458
- files: z5.array(SafeRepoRelPath),
2459
- blocks: z5.array(ManagedBlockRecordSchema),
2460
- labels: z5.array(z5.string()),
2461
- agents: z5.array(z5.enum(AGENT_VENDORS)).optional()
3249
+ var ManagedManifestSchema = z6.object({
3250
+ version: z6.number().int().positive(),
3251
+ files: z6.array(SafeRepoRelPath),
3252
+ blocks: z6.array(ManagedBlockRecordSchema),
3253
+ labels: z6.array(z6.string()),
3254
+ agents: z6.array(z6.enum(AGENT_VENDORS)).optional()
2462
3255
  });
2463
- var ProjectEntrySchema = z5.object({
2464
- name: z5.string().min(1),
2465
- description: z5.string().min(1).optional(),
2466
- path: z5.string().min(1).optional()
3256
+ var ProjectEntrySchema = z6.object({
3257
+ name: z6.string().min(1),
3258
+ description: z6.string().min(1).optional(),
3259
+ path: z6.string().min(1).optional()
2467
3260
  });
2468
3261
  function parseTokensCollectDeclaration(value) {
2469
3262
  const m = value.trim().match(/^(\S+)\s+(\S+)$/);
@@ -2474,90 +3267,101 @@ function parseTokensCollectDeclaration(value) {
2474
3267
  return null;
2475
3268
  return { interpreter, script };
2476
3269
  }
2477
- var VinayaConfigSchema = z5.object({
2478
- rings: z5.object({
2479
- ring1_forgeWriteInterception: z5.boolean(),
2480
- ring2_asyncAudits: z5.boolean()
3270
+ var VinayaConfigObjectSchema = z6.object({
3271
+ rings: z6.object({
3272
+ ring1_forgeWriteInterception: z6.boolean(),
3273
+ ring2_asyncAudits: z6.boolean()
2481
3274
  }).optional(),
2482
- checks: z5.record(z5.string(), CheckEntrySchema).optional(),
2483
- roles: z5.record(z5.string(), RoleEntrySchema).optional(),
3275
+ checks: z6.record(z6.string(), CheckEntrySchema).optional(),
3276
+ roles: z6.record(z6.string(), RoleEntrySchema).optional(),
2484
3277
  briefSchema: BriefSchemaSchema.optional(),
2485
3278
  managed: ManagedManifestSchema.optional(),
2486
- principals: z5.array(z5.string()).min(1).optional(),
2487
- releaseActor: z5.string().min(1).optional(),
2488
- ci: z5.object({ setup: z5.string().min(1) }).optional(),
2489
- tokens: z5.object({
2490
- collect: z5.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
3279
+ principals: z6.array(z6.string()).min(1).optional(),
3280
+ releaseActor: z6.string().min(1).optional(),
3281
+ ci: z6.object({ setup: z6.string().min(1) }).optional(),
3282
+ tokens: z6.object({
3283
+ collect: z6.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
2491
3284
  message: 'tokens.collect must be exactly "<interpreter> <repo-relative-script-path>" — two whitespace-separated tokens, no flags, no shell syntax, no quoting'
2492
3285
  })
2493
3286
  }).optional(),
2494
- blastRadius: z5.object({ extraDomains: z5.array(z5.string()).optional() }).optional(),
2495
- proseGates: z5.object({
2496
- doctrineRoot: z5.string().min(1).optional(),
2497
- readerFacingPrefix: z5.string().min(1).optional(),
2498
- readerFacingSuffix: z5.string().min(1).optional(),
2499
- legacySlugDir: z5.string().min(1).optional(),
2500
- sourceComments: z5.object({
2501
- globs: z5.array(z5.string().min(1)).optional(),
2502
- allowlist: z5.array(z5.string().min(1)).optional(),
2503
- severity: z5.enum(["warning", "error"]).optional()
3287
+ blastRadius: z6.object({ extraDomains: z6.array(z6.string()).optional() }).optional(),
3288
+ proseGates: z6.object({
3289
+ doctrineRoot: z6.string().min(1).optional(),
3290
+ readerFacingPrefix: z6.string().min(1).optional(),
3291
+ readerFacingSuffix: z6.string().min(1).optional(),
3292
+ legacySlugDir: z6.string().min(1).optional(),
3293
+ sourceComments: z6.object({
3294
+ globs: z6.array(z6.string().min(1)).optional(),
3295
+ allowlist: z6.array(z6.string().min(1)).optional(),
3296
+ severity: z6.enum(["warning", "error"]).optional()
2504
3297
  }).optional(),
2505
- specGrandfather: z5.union([z5.array(z5.string().min(1)), z5.record(z5.string().min(1), z5.number().int().min(0))]).optional(),
2506
- specPaths: z5.array(z5.string().min(1).refine((entry) => !entry.startsWith("/") && !/^[A-Za-z]:/.test(entry), {
2507
- message: "must be a repository-relative path, not an absolute one"
2508
- }).refine((entry) => !entry.split(/[\\/]/).includes(".."), {
2509
- message: "must stay inside the repository — no `..` segment"
2510
- })).optional()
3298
+ specGrandfather: z6.union([z6.array(z6.string().min(1)), z6.record(z6.string().min(1), z6.number().int().min(0))]).optional(),
3299
+ specPaths: z6.array(RepoRelativePathSchema).optional(),
3300
+ productPaths: z6.array(RepoRelativePathSchema).optional(),
3301
+ published: PublishedProseSchema.optional(),
3302
+ rules: ProseRulesSchema.optional()
2511
3303
  }).optional(),
2512
- projects: z5.array(ProjectEntrySchema).optional(),
2513
- dispatch: z5.object({
2514
- timeoutMs: z5.number().int().positive().optional(),
2515
- killGraceMs: z5.number().int().positive().optional(),
2516
- agent: z5.enum(["claude", "codex", "gemini"]).optional()
3304
+ projects: z6.array(ProjectEntrySchema).optional(),
3305
+ dispatch: z6.object({
3306
+ timeoutMs: z6.number().int().positive().optional(),
3307
+ reviewerTimeoutMs: z6.number().int().positive().optional(),
3308
+ killGraceMs: z6.number().int().positive().optional(),
3309
+ agent: z6.enum(["claude", "codex"]).optional()
2517
3310
  }).optional(),
2518
- reviewPolicy: z5.object({
2519
- codeReviewThreshold: z5.string().min(1).optional(),
2520
- securityThreshold: z5.string().min(1).optional(),
2521
- maxRounds: z5.number().optional(),
2522
- maxTaskMinutes: z5.number().optional()
3311
+ reviewPolicy: z6.object({
3312
+ codeReviewThreshold: z6.string().min(1).optional(),
3313
+ securityThreshold: z6.string().min(1).optional(),
3314
+ maxRounds: z6.number().optional(),
3315
+ maxTaskMinutes: z6.number().optional(),
3316
+ readyPushTimeoutMinutes: z6.number().optional()
2523
3317
  }).optional(),
2524
- securityScan: z5.object({
2525
- command: z5.array(z5.string().min(1)).min(1)
3318
+ securityScan: z6.object({
3319
+ command: z6.array(z6.string().min(1)).min(1)
2526
3320
  }).optional(),
2527
- gateCutovers: z5.object({
2528
- objectivesSinceIssue: z5.number().int().nonnegative().optional(),
2529
- briefSectionsSinceIssue: z5.number().int().nonnegative().optional(),
2530
- documentationSinceIssue: z5.number().int().nonnegative().optional(),
2531
- briefRulesSincePr: z5.number().int().nonnegative().optional(),
2532
- agentBoxesRefusedSincePr: z5.number().int().nonnegative().optional()
3321
+ gateCutovers: z6.object({
3322
+ objectivesSinceIssue: z6.number().int().nonnegative().optional(),
3323
+ briefSectionsSinceIssue: z6.number().int().nonnegative().optional(),
3324
+ documentationSinceIssue: z6.number().int().nonnegative().optional(),
3325
+ briefRulesSincePr: z6.number().int().nonnegative().optional(),
3326
+ agentBoxesRefusedSincePr: z6.number().int().nonnegative().optional()
2533
3327
  }).optional(),
2534
- planning: z5.object({
2535
- collisionThreshold: z5.number().int().nonnegative().optional()
3328
+ planning: z6.object({
3329
+ collisionThreshold: z6.number().int().nonnegative().optional()
2536
3330
  }).optional(),
2537
- prePush: z5.object({
2538
- alwaysRun: z5.array(z5.string()).optional()
3331
+ prePush: z6.object({
3332
+ alwaysRun: z6.array(z6.string()).optional(),
3333
+ readyTests: z6.object({
3334
+ mode: z6.literal("ci"),
3335
+ workflow: z6.literal(".github/workflows/ci.yml"),
3336
+ check: z6.literal("Vinaya CI")
3337
+ }).strict().optional(),
3338
+ requiredCi: z6.object({
3339
+ workflow: z6.literal(".github/workflows/ci.yml"),
3340
+ check: z6.literal("Vinaya CI")
3341
+ }).strict().optional()
2539
3342
  }).optional(),
2540
- report: z5.object({
2541
- commandTimeoutMs: z5.number().int().positive().optional()
3343
+ report: z6.object({
3344
+ commandTimeoutMs: z6.number().int().positive().optional()
2542
3345
  }).superRefine((report, ctx) => {
2543
3346
  const commandTimeoutMs = report.commandTimeoutMs;
2544
3347
  if (commandTimeoutMs !== undefined && commandTimeoutMs > MAX_REPORT_COMMAND_TIMEOUT_MS) {
2545
3348
  ctx.addIssue({
2546
- code: z5.ZodIssueCode.custom,
3349
+ code: z6.ZodIssueCode.custom,
2547
3350
  path: ["commandTimeoutMs"],
2548
3351
  message: "must be at most 3600000 (1 hour)"
2549
3352
  });
2550
3353
  }
2551
3354
  }).optional(),
2552
- logPublish: z5.unknown().refine((v) => v === undefined, {
3355
+ logPublish: z6.unknown().refine((v) => v === undefined, {
2553
3356
  message: "logPublish is removed — telemetry is never posted to a tracker or a code host; configure `logs` instead (a folder or a server destination)"
2554
3357
  }),
2555
- runtimeDir: z5.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
2556
- logs: z5.object({
2557
- folder: z5.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
2558
- url: z5.string().url().optional(),
2559
- headers: z5.record(z5.string()).optional(),
2560
- readHeaders: z5.record(z5.string()).optional(),
3358
+ runtimeDir: z6.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
3359
+ runner: z6.enum(["standalone", "atta-engine"]).optional(),
3360
+ logs: z6.object({
3361
+ folder: z6.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
3362
+ url: z6.string().url().optional(),
3363
+ headers: z6.record(z6.string()).optional(),
3364
+ readHeaders: z6.record(z6.string()).optional(),
2561
3365
  events: CustomEventDeclarationsSchema.optional()
2562
3366
  }).refine((v) => [v.folder, v.url].filter((x) => x !== undefined).length <= 1, {
2563
3367
  message: "logs: set at most one of folder/url"
@@ -2565,8 +3369,33 @@ var VinayaConfigSchema = z5.object({
2565
3369
  message: "logs: headers requires url"
2566
3370
  }).refine((v) => v.readHeaders === undefined || v.url !== undefined, {
2567
3371
  message: "logs: readHeaders requires url"
2568
- }).optional()
3372
+ }).or(z6.literal(false)).optional(),
3373
+ decisionRecords: z6.object({
3374
+ path: RepoRelativePathSchema
3375
+ }).strict().optional()
3376
+ });
3377
+ function decisionRecordsPathIssue(path, doctrineRoot) {
3378
+ const reason = outsideRepositoryReason(path);
3379
+ if (reason)
3380
+ return reason;
3381
+ const folder = normalizeSpecPath(path);
3382
+ if (folder === "" || folder === ".")
3383
+ return "must name a folder, not the repository root";
3384
+ const root = normalizeSpecPath(doctrineRoot ?? "aeg-root");
3385
+ if (folder === root || folder.startsWith(`${root}/`)) {
3386
+ return `must be outside the doctrine tree "${root}" — decision records belong to this repository, not to the doctrine it ships`;
3387
+ }
3388
+ return null;
3389
+ }
3390
+ var VinayaConfigSchema = VinayaConfigObjectSchema.superRefine((config, ctx) => {
3391
+ const path = config.decisionRecords?.path;
3392
+ if (path === undefined || outsideRepositoryReason(path))
3393
+ return;
3394
+ const issue = decisionRecordsPathIssue(path, config.proseGates?.doctrineRoot);
3395
+ if (issue)
3396
+ ctx.addIssue({ code: z6.ZodIssueCode.custom, path: ["decisionRecords", "path"], message: issue });
2569
3397
  });
3398
+ var VinayaConfigShape = VinayaConfigObjectSchema.shape;
2570
3399
  var GLOBAL_VINAYA_HOME = join4(homedir(), ".vinaya");
2571
3400
  var GLOBAL_CONFIG_PATH = join4(GLOBAL_VINAYA_HOME, "config.json");
2572
3401
  var LOCAL_CONFIG_FILENAME = "vinaya.config.json";
@@ -2647,6 +3476,7 @@ function stripGlobalOnlyKeys(config, path) {
2647
3476
  }
2648
3477
  return result;
2649
3478
  }
3479
+ var emittedLocalOverrideWarnings = new Set;
2650
3480
  function resolveRuntimeDirSetting(config) {
2651
3481
  return config?.runtimeDir ?? null;
2652
3482
  }
@@ -2740,13 +3570,14 @@ function readTrustAnchorConfigAtRef(ref) {
2740
3570
  });
2741
3571
  return Buffer.from(raw, "utf-8").toString("base64");
2742
3572
  }
3573
+ var NO_TRUST_ANCHOR_REPO_MESSAGE = "could not resolve repo identity for the trust-anchor read";
2743
3574
  function ghFetchTrustAnchorConfig() {
2744
3575
  const probeRef = resolveCiTrustAnchorProbeRef();
2745
3576
  if (probeRef)
2746
3577
  return readTrustAnchorConfigAtRef(probeRef);
2747
3578
  const repo = trustAnchorRepo();
2748
3579
  if (!repo)
2749
- throw new Error("could not resolve repo identity for the trust-anchor read");
3580
+ throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
2750
3581
  return execFileSync2("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], {
2751
3582
  encoding: "utf-8",
2752
3583
  stdio: ["ignore", "pipe", "pipe"]
@@ -2763,7 +3594,7 @@ async function ghFetchTrustAnchorConfigAsync() {
2763
3594
  }
2764
3595
  const repo = await trustAnchorRepoAsync();
2765
3596
  if (!repo)
2766
- throw new Error("could not resolve repo identity for the trust-anchor read");
3597
+ throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
2767
3598
  const { stdout } = await execFileAsync4("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], { encoding: "utf-8", timeout: 1e4, killSignal: "SIGKILL" });
2768
3599
  return stdout;
2769
3600
  }
@@ -2828,12 +3659,51 @@ function loadConfig() {
2828
3659
  const path = configPath();
2829
3660
  if (!path)
2830
3661
  return null;
3662
+ let text;
2831
3663
  try {
2832
- const raw = JSON.parse(readFileSync3(path, "utf-8"));
2833
- return stripGlobalOnlyKeys(VinayaConfigSchema.parse(raw), path);
2834
- } catch {
3664
+ text = readFileSync3(path, "utf-8");
3665
+ } catch (err) {
3666
+ reportInvalidConfigOnce(path, `unreadable: ${err.message}`);
3667
+ return null;
3668
+ }
3669
+ let raw;
3670
+ try {
3671
+ raw = JSON.parse(text);
3672
+ } catch (err) {
3673
+ reportInvalidConfigOnce(path, `invalid JSON: ${err.message}`);
3674
+ return null;
3675
+ }
3676
+ const parsed = VinayaConfigSchema.safeParse(raw);
3677
+ if (!parsed.success) {
3678
+ reportInvalidConfigOnce(path, schemaIssueDetail(parsed.error));
2835
3679
  return null;
2836
3680
  }
3681
+ return stripGlobalOnlyKeys(parsed.data, path);
3682
+ }
3683
+ function schemaIssueDetail(error) {
3684
+ return error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
3685
+ }
3686
+ var emittedInvalidConfigReports = new Set;
3687
+ function reportInvalidConfigOnce(path, detail) {
3688
+ const key = `${path}
3689
+ ${detail}`;
3690
+ if (emittedInvalidConfigReports.has(key))
3691
+ return;
3692
+ emittedInvalidConfigReports.add(key);
3693
+ const message = `${path} is not a valid Vinaya configuration (${detail}) — falling back to built-in defaults.`;
3694
+ const checkName = process.env.VINAYA_CHECK_NAME;
3695
+ if (checkName) {
3696
+ emitCheckError({
3697
+ schema: CHECK_SCHEMA_VERSION,
3698
+ check: checkName,
3699
+ severity: "warning",
3700
+ message,
3701
+ agent_recovery_prompt: `Fix the failing keys in ${path} (${detail}) so the file parses and satisfies the configuration schema, then re-run.`,
3702
+ file: path
3703
+ });
3704
+ return;
3705
+ }
3706
+ console.error(`⚠ ${message}`);
2837
3707
  }
2838
3708
  var TOKENS_COLLECT_TRUST_PATH = join4(GLOBAL_VINAYA_HOME, "tokens-collect-trust.json");
2839
3709
 
@@ -3054,7 +3924,7 @@ function appendLoopLogLine(path, line) {
3054
3924
  import {
3055
3925
  closeSync as closeSync4,
3056
3926
  constants as fsConstants4,
3057
- lstatSync as lstatSync2,
3927
+ lstatSync as lstatSync3,
3058
3928
  mkdirSync as mkdirSync4,
3059
3929
  openSync as openSync4,
3060
3930
  linkSync as linkSync2,
@@ -3225,7 +4095,7 @@ function removeQueueHead(path, cut) {
3225
4095
  function queueBucketSize(path) {
3226
4096
  let lstat;
3227
4097
  try {
3228
- lstat = lstatSync2(path);
4098
+ lstat = lstatSync3(path);
3229
4099
  } catch (err) {
3230
4100
  if (!isEnoent(err))
3231
4101
  throw err;
@@ -3392,6 +4262,7 @@ async function drainOutboxToWebhook(outboxTask, webhookUrl, headers, fetchTimeou
3392
4262
 
3393
4263
  // src/lib/log-sink.ts
3394
4264
  var OUTBOX_MAX_BYTES = 8 * 1024 * 1024;
4265
+ var LOG_FOLDER_ONLY_ENV = "VINAYA_LOG_FOLDER_ONLY";
3395
4266
  function describeFolderFallback(reason) {
3396
4267
  if (reason.kind === "anchor-unreadable") {
3397
4268
  return `not delivering to the configured log server ${reason.intendedUrl} — the default branch's ` + "vinaya.config.json could not be read to confirm it (the trust-anchor read via `gh` was offline, " + "unauthenticated, or slower than its deadline); events are written to the local folder and can be " + "delivered later with `vinaya log send`";
@@ -3431,6 +4302,9 @@ function logsCredentialMissing(headers, env) {
3431
4302
  return false;
3432
4303
  }
3433
4304
  function resolveLogDestinationFrom(input) {
4305
+ if (input.localConfig?.logs === false || input.unattended && input.trustAnchorConfig?.logs === false) {
4306
+ return { kind: "none", reason: "logs: false disables Log recording" };
4307
+ }
3434
4308
  const spoolDir = input.env.VINAYA_LOG_SPOOL_DIR;
3435
4309
  if (spoolDir !== undefined && spoolDir.trim() !== "") {
3436
4310
  return { kind: "folder", folder: spoolDir };
@@ -3450,6 +4324,10 @@ function resolveLogDestinationFrom(input) {
3450
4324
  } else {
3451
4325
  effective = local;
3452
4326
  }
4327
+ if (input.folderOnly || input.env[LOG_FOLDER_ONLY_ENV] === "1") {
4328
+ const folder = effective && "folder" in effective && !isInsideRepo(effective.folder, input.repoRoot) ? effective.folder : input.defaultFolder;
4329
+ return { kind: "folder", folder };
4330
+ }
3453
4331
  if (hostFromEnv(input.env) === "ci") {
3454
4332
  if (effective && "url" in effective) {
3455
4333
  if (logsCredentialMissing(effective.headers, input.env)) {
@@ -3474,21 +4352,51 @@ function resolveLogDestinationFrom(input) {
3474
4352
  const folder = effective && "folder" in effective ? effective.folder : input.defaultFolder;
3475
4353
  return fallbackReason ? { kind: "folder", folder, fallbackReason } : { kind: "folder", folder };
3476
4354
  }
3477
- var processTrustAnchorByRepo = new Map;
4355
+ var LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS = 30000;
4356
+ var LOG_DESTINATION_ANCHOR_MAX_RETRIES = 5;
4357
+ function createTrustAnchorCache(read, now = Date.now, bounds = {
4358
+ retryIntervalMs: LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS,
4359
+ maxRetries: LOG_DESTINATION_ANCHOR_MAX_RETRIES
4360
+ }) {
4361
+ const slots = new Map;
4362
+ const start = (repoRoot, retries) => {
4363
+ const slot = {
4364
+ reading: Promise.resolve().then(read).catch(() => null),
4365
+ retries,
4366
+ missedAt: null
4367
+ };
4368
+ slots.set(repoRoot, slot);
4369
+ slot.reading.then((config) => {
4370
+ if (config === null)
4371
+ slot.missedAt = now();
4372
+ });
4373
+ return slot.reading;
4374
+ };
4375
+ return {
4376
+ get: (repoRoot) => {
4377
+ const slot = slots.get(repoRoot);
4378
+ if (slot === undefined)
4379
+ return start(repoRoot, 0);
4380
+ if (slot.missedAt === null)
4381
+ return slot.reading;
4382
+ if (slot.retries >= bounds.maxRetries || now() - slot.missedAt < bounds.retryIntervalMs)
4383
+ return slot.reading;
4384
+ return start(repoRoot, slot.retries + 1);
4385
+ },
4386
+ clear: () => slots.clear()
4387
+ };
4388
+ }
4389
+ var processTrustAnchorByRepo = createTrustAnchorCache(safeLoadTrustAnchorConfig);
3478
4390
  function processTrustAnchor(repoRoot) {
3479
- const cached = processTrustAnchorByRepo.get(repoRoot);
3480
- if (cached !== undefined)
3481
- return cached;
3482
- const reading = safeLoadTrustAnchorConfig();
3483
- processTrustAnchorByRepo.set(repoRoot, reading);
3484
- return reading;
4391
+ return processTrustAnchorByRepo.get(repoRoot);
3485
4392
  }
3486
- async function defaultResolveLogDestination(repo, env) {
4393
+ async function defaultResolveLogDestination(repo, env, folderOnly = false) {
3487
4394
  const localConfig = loadConfig();
3488
4395
  const unattended = isUnattendedProcess(process.env);
3489
4396
  const repoRoot = repoRootSync();
3490
4397
  return resolveLogDestinationFrom({
3491
4398
  localConfig,
4399
+ folderOnly,
3492
4400
  trustAnchorConfig: unattended ? await processTrustAnchor(repoRoot) : null,
3493
4401
  unattended,
3494
4402
  env,
@@ -3497,14 +4405,16 @@ async function defaultResolveLogDestination(repo, env) {
3497
4405
  });
3498
4406
  }
3499
4407
  function unresolvedLogDestination(env) {
4408
+ const loaded = loadConfig();
4409
+ if (loaded?.logs === false)
4410
+ return { kind: "none", reason: "logs: false disables Log recording" };
3500
4411
  if (hostFromEnv(env) === "ci") {
3501
4412
  return {
3502
4413
  kind: "none",
3503
4414
  reason: "the process ended before its log destination was resolved, and a CI job never records to a folder"
3504
4415
  };
3505
4416
  }
3506
- const loaded = loadConfig();
3507
- const localConfig = loaded?.logs?.url !== undefined ? { ...loaded, logs: undefined } : loaded;
4417
+ const localConfig = loaded?.logs && loaded.logs.url !== undefined ? { ...loaded, logs: undefined } : loaded;
3508
4418
  const unattended = isUnattendedProcess(process.env);
3509
4419
  const repoRoot = repoRootSync();
3510
4420
  const runtimeDir = process.env[RUNTIME_DIR_ENV_KEY] || resolveRuntimeDir({ repo: null, localConfig, trustAnchorConfig: null, unattended, repoRoot });
@@ -3726,6 +4636,7 @@ async function resolveHeadSha(cwd) {
3726
4636
  }
3727
4637
  function defaultDeps() {
3728
4638
  return {
4639
+ readConfig: loadConfig,
3729
4640
  outboxRoot: () => join7(GLOBAL_VINAYA_HOME, "outbox"),
3730
4641
  home: () => homedir3(),
3731
4642
  hostname: () => osHostname(),
@@ -3909,23 +4820,59 @@ function createLogSink(overrides = {}) {
3909
4820
  };
3910
4821
  let contextCache;
3911
4822
  let settledContext;
4823
+ let contextEnv = {};
4824
+ const resolveDestination = async (repo, env) => deps.readConfig()?.logs === false ? { kind: "none", reason: "logs: false disables Log recording" } : await deps.resolveLogDestination(repo, env, deps.folderOnly);
3912
4825
  const context = () => {
3913
4826
  if (contextCache === undefined) {
3914
4827
  const env = deps.env();
4828
+ contextEnv = env;
3915
4829
  contextCache = Promise.all([
3916
4830
  withDeadline(resolveRepoOnce(), LOG_CONTEXT_LOOKUP_DEADLINE_MS, null),
3917
4831
  doctrine()
3918
4832
  ]).then(async ([resolved, doctrineValue]) => {
3919
4833
  const repo = resolved && isSafeRepoSegment3(resolved.owner) && isSafeRepoSegment3(resolved.repo) ? resolved : null;
3920
- settledContext = { repo, doctrine: doctrineValue, destination: await deps.resolveLogDestination(repo, env) };
4834
+ settledContext = { repo, doctrine: doctrineValue, destination: await resolveDestination(repo, env) };
4835
+ destinationRetryDueAt = deps.now().getTime() + LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS;
3921
4836
  return settledContext;
3922
4837
  });
3923
4838
  }
3924
4839
  return contextCache;
3925
4840
  };
4841
+ let destinationRetries = 0;
4842
+ let destinationRetryDueAt = 0;
4843
+ let destinationRetryInFlight = false;
4844
+ const retryDestinationIfDue = (ctx) => {
4845
+ if (ctx.destination.kind !== "folder" || ctx.destination.fallbackReason?.kind !== "anchor-unreadable")
4846
+ return;
4847
+ if (destinationRetryInFlight || destinationRetries >= LOG_DESTINATION_ANCHOR_MAX_RETRIES)
4848
+ return;
4849
+ if (deps.now().getTime() < destinationRetryDueAt)
4850
+ return;
4851
+ destinationRetryInFlight = true;
4852
+ destinationRetries++;
4853
+ const generation = contextCache;
4854
+ Promise.resolve().then(() => resolveDestination(ctx.repo, contextEnv)).then((destination) => {
4855
+ if (contextCache !== generation)
4856
+ return;
4857
+ if (destination.kind === "server") {
4858
+ settledContext = { ...ctx, destination };
4859
+ contextCache = Promise.resolve(settledContext);
4860
+ return;
4861
+ }
4862
+ if (destination.kind !== "folder" || destination.fallbackReason?.kind !== "anchor-unreadable") {
4863
+ destinationRetries = LOG_DESTINATION_ANCHOR_MAX_RETRIES;
4864
+ }
4865
+ }, () => {
4866
+ return;
4867
+ }).finally(() => {
4868
+ destinationRetryInFlight = false;
4869
+ destinationRetryDueAt = deps.now().getTime() + LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS;
4870
+ });
4871
+ };
3926
4872
  const resetContext = () => {
3927
4873
  contextCache = undefined;
3928
4874
  settledContext = undefined;
4875
+ destinationRetries = 0;
3929
4876
  };
3930
4877
  let drainChain = Promise.resolve();
3931
4878
  const pendingWrites = new Set;
@@ -3938,24 +4885,30 @@ function createLogSink(overrides = {}) {
3938
4885
  `);
3939
4886
  });
3940
4887
  };
3941
- const snapshot = () => {
4888
+ const snapshot = (attribution) => {
3942
4889
  const env = deps.env();
3943
4890
  return {
4891
+ attributed: attribution !== undefined,
3944
4892
  host: hostFromEnv(env),
3945
4893
  now: deps.now(),
3946
4894
  seq: seq++,
3947
4895
  envFields: {
3948
- role: env.VINAYA_ROLE,
4896
+ role: attribution?.role ?? env.VINAYA_ROLE,
3949
4897
  task: env.VINAYA_TASK,
3950
- round: env.VINAYA_ROUND,
4898
+ round: attribution ? String(attribution.round) : env.VINAYA_ROUND,
3951
4899
  pr: env.VINAYA_PR,
3952
4900
  run: env.VINAYA_RUN || runId,
3953
- attempt: env.VINAYA_ATTEMPT,
4901
+ attempt: attribution ? String(attribution.attempt) : env.VINAYA_ATTEMPT,
3954
4902
  parent: env.VINAYA_PARENT_EVENT,
3955
4903
  workRef: env.VINAYA_WORK_REF,
3956
4904
  flow: env.VINAYA_FLOW,
3957
4905
  flowVersion: env.VINAYA_FLOW_VERSION,
3958
4906
  runtime: env.VINAYA_RUNTIME,
4907
+ processId: env.VINAYA_PROCESS_ID,
4908
+ processVersion: env.VINAYA_PROCESS_VERSION,
4909
+ processDigest: env.VINAYA_PROCESS_DIGEST,
4910
+ runnerId: env.VINAYA_RUNNER_ID,
4911
+ runnerVersion: env.VINAYA_RUNNER_VERSION,
3959
4912
  source: env.VINAYA_SOURCE
3960
4913
  }
3961
4914
  };
@@ -3984,6 +4937,8 @@ function createLogSink(overrides = {}) {
3984
4937
  branchIssue,
3985
4938
  eventId: randomUUID2(),
3986
4939
  processId,
4940
+ revision: headSha,
4941
+ provenance: call.attributed ? "parent_attributed" : deps.provenance,
3987
4942
  inputVersions: deps.inputVersions()
3988
4943
  });
3989
4944
  const header = headSha === null ? built : { ...built, subject: { ...built.subject, sha: headSha } };
@@ -4008,11 +4963,14 @@ function createLogSink(overrides = {}) {
4008
4963
  appendLine(outboxPathFor({ outboxRoot: () => destination.folder }, repo, header.subject.issue), line, warnOnce);
4009
4964
  }
4010
4965
  };
4011
- function log(e) {
4966
+ function log(e, attribution) {
4012
4967
  try {
4013
- const call = snapshot();
4968
+ const call = snapshot(attribution);
4014
4969
  const write = async () => {
4015
4970
  const ctx = await context();
4971
+ try {
4972
+ retryDestinationIfDue(ctx);
4973
+ } catch {}
4016
4974
  if (ctx.destination.kind === "none") {
4017
4975
  writeEvent(e, call, ctx, null, null, true);
4018
4976
  return;
@@ -4036,9 +4994,13 @@ function createLogSink(overrides = {}) {
4036
4994
  function logSync(e, opts = {}) {
4037
4995
  try {
4038
4996
  const call = snapshot();
4039
- let ctx = settledContext;
4997
+ let ctx = deps.readConfig()?.logs === false ? {
4998
+ repo: null,
4999
+ doctrine: "unknown",
5000
+ destination: { kind: "none", reason: "logs: false disables Log recording" }
5001
+ } : settledContext;
4040
5002
  if (ctx === undefined) {
4041
- const destination = deps.unresolvedLogDestination(deps.env());
5003
+ const destination = deps.readConfig()?.logs === false ? { kind: "none", reason: "logs: false disables Log recording" } : deps.unresolvedLogDestination(deps.env());
4042
5004
  if (destination.kind === "folder" && !opts.quiet) {
4043
5005
  warnOnce(`vinaya: the process ended before its log destination was resolved — the event is written to ${destination.folder}; \`vinaya log send\` delivers it to a configured server later
4044
5006
  `);
@@ -4198,6 +5160,16 @@ var COMMANDS = [
4198
5160
  ],
4199
5161
  status: "shipped"
4200
5162
  },
5163
+ {
5164
+ name: "new adr",
5165
+ needs: [],
5166
+ description: "Write the next numbered decision record into the folder decisionRecords.path names",
5167
+ details: [
5168
+ "`vinaya new adr <title>` writes `<decisionRecords.path>/NNNN-<kebab-title>.md` from the shipped decision-record template (`vinaya doctrine --template decision-record`), with status Proposed and today's date, and adds a row for it to the folder's `README.md` index page, creating that page on the first record. Numbers start at `0001` and are one past the highest number any file in the folder or any row of the index carries, so a number is never reused, even after its file is removed.",
5169
+ "Refuses, naming the key, while `decisionRecords.path` is unset: decision records are opt-in. The same key switches on the `decision-record-citation` writing rule — see `decisionRecords.path` in the configuration reference."
5170
+ ],
5171
+ status: "shipped"
5172
+ },
4201
5173
  {
4202
5174
  name: "brief render",
4203
5175
  needs: ["forge", "default-branch"],
@@ -4216,9 +5188,7 @@ var COMMANDS = [
4216
5188
  name: "task dispatch",
4217
5189
  needs: ["forge", "operator-seat"],
4218
5190
  description: "Deprecated — render, pin, and post the brief on the Issue as the frozen original; start the developer",
4219
- flags: [
4220
- { flag: "--agent <claude|codex|gemini>", description: "Start the developer through dispatchRole once posted" }
4221
- ],
5191
+ flags: [{ flag: "--agent <claude|codex>", description: "Start the developer through dispatchRole once posted" }],
4222
5192
  details: [
4223
5193
  "Renders the brief from the Issue and the tree (the same assembly `brief render` uses) and posts it once as an Issue comment whose first line is `<!-- aeg:brief:v1 -->` and whose second line is `Brief hash: <sha256>` — the hash covers only the body below those two lines, so any reader recomputes it. Refuses outright, naming the existing comment's URL, when a `v1` comment already exists on the Issue — the brief is frozen by design, never overwritten or silently reissued.",
4224
5194
  "With `--agent`, starts the Developer through `dispatchRole` when `apps/cli/src/lib/dispatch.ts` exports it; otherwise prints the rendered brief and the manual dispatch instruction and exits `0` — a soft dependency, never a hard block.",
@@ -4243,7 +5213,11 @@ var COMMANDS = [
4243
5213
  description: "One command from a planned Issue to a reviewed pull request — exactly one developer started",
4244
5214
  flags: [
4245
5215
  {
4246
- flag: "--agent <claude|codex|gemini>",
5216
+ flag: "--runner <standalone|atta-engine>",
5217
+ description: "Override runner config for this invocation; absent uses config, whose default is standalone"
5218
+ },
5219
+ {
5220
+ flag: "--agent <claude|codex>",
4247
5221
  description: "Vendor for the developer and both reviewers this run dispatches"
4248
5222
  },
4249
5223
  {
@@ -4253,17 +5227,39 @@ var COMMANDS = [
4253
5227
  {
4254
5228
  flag: "--widen-surface <glob,...> --reason <text>",
4255
5229
  description: "Continue a pre-pull-request escalation whose Developer asked for `widen_surface`: supersede the frozen brief with the globs added to `## Surface`, record that as the escalation's resolution, grade the widened Issue through the write gate, then start the run"
5230
+ },
5231
+ {
5232
+ flag: "--rollback",
5233
+ description: "Run the terminate-and-restart procedure for this task: cancel its in-flight Engine run, reconcile every prepared and uncertain effect by its identity, then start a fresh standalone run from the same frozen brief. Refuses a task whose recorded runner is not `atta-engine`"
4256
5234
  }
4257
5235
  ],
4258
5236
  details: [
5237
+ "The atta-engine runner starts the workspace Engine script with Bun, streams its output and returns its exit code. A published install without the script prints one notice and falls back to standalone. Engine Log events use the local folder only; logs: false disables all Log destinations for both runners.",
5238
+ "A run's runner is recorded when it starts and never changes: switching `runner` in config changes only the runner of new runs, and a run recorded on `atta-engine` keeps routing to the Engine for `task status`, `task_resume` and `task_cancel`. A start on a pause another runner holds is refused with a typed reason naming the recorded runner and the requested one, and so is a start on another runner's Engine run that is still in flight with no pause held — halted or stopped short of completed or cancelled.",
5239
+ "`--rollback` ends the Engine run first: a held pause through the shared cancel `task_cancel` uses, which needs a Principal ruling newer than the pause as any cancel does; a run halted with no pause held has its started effects fenced; a run that already completed or was cancelled is refused, as is a driver still running with no pause held, which is never signalled; and the standalone run never starts while the Engine driver lives, a cancelled run's driver given a bounded wait to release its lock. Every started and uncertain effect is then reconciled by its identity: one the forge carries is recorded verified, one it does not carry is left for the restarted run to complete, and one the forge read cannot settle refuses the restart. Each rehearsal appends a record — task, recorded runner, action, reconciled effect identities, the restarted run's runner and terminal state — to `backend-rollback-rehearsals.jsonl` in the task's runtime directory, whether it completed, was refused or failed at a later step, and nothing removes it.",
4259
5240
  "`--widen-surface` is the Planner's one command for a widen-surface escalation, and refuses before any write when the held pause is not one (no pause, a pause with a pull request — whose continuation is the ruling on that pull request — or a round whose Developer asked for no `widen_surface`), when a driver is still alive for the task, when the escalation's resolution is already consumed (a replay — the Surface is never widened twice), or when the widened body fails the write gate, whose findings name the field to edit first. The escalation packet's permitted next actions name this command with the globs the Developer asked for, and `task_resume` refuses such an escalation naming it.",
4260
- "Composes `task brief`'s own preparation (`prepareTask`) with the watching driver (`runDriverLoop`, `dev-review-loop.ts`) — nothing else. Preparation starts no agent; the loop's own round 1 reads the frozen brief off the Issue and is the only place a developer is ever dispatched from a fresh task, so exactly one developer is started by construction.",
5241
+ "Prepares the frozen brief and resolves the task, branch and model once. The standalone runner then starts the watching driver (`runDriverLoop`, `dev-review-loop.ts`). Preparation starts no agent; the loop's own round 1 reads the frozen brief off the Issue and is the only place a developer is ever dispatched from a fresh task, so exactly one developer is started by construction.",
4261
5242
  "A brief already frozen on the Issue is reused, never re-posted — the second `task dispatch`/`task brief` call this composes around does not fail the whole run, it just skips straight to running the loop. A task whose Issue refuses preparation (a missing brief section, an unmet dispatch gate) is refused before any agent starts, with nothing posted.",
4262
5243
  "Refuses when the frozen brief's developer branch already has an open pull request AND a driver is still live for it — a driver that crashed or was killed leaves its PR behind, and this command is the one that revives it, in any state, pause held or not.",
4263
5244
  "issue-711 O4: a pause never ends this process — it keeps running and watches the pull request, continuing on its own once a newer Principal ruling appears (or, for an `'infrastructure'`/`'stale_driver'` pause, after a bounded backoff), with no `--resume` command needed for the ordinary case. Exit and printed summary distinguish a published pull request OR a watched pause's own genuine end — merged, closed, or an operator's own `--cancel` (exit `0` either way, the PR URL) — from the one pause this process can never watch (no pull request exists yet — exit `1`, with the working `vinaya task run` command for this task's own branch to continue by hand — `<tranche> <n>` for a tranche task, `--issue <n>` for a backlog one — never a `dev-review-loop --resume` line naming a pull-request number this pause does not have), a usage/argv error (exit `2`), and any other failure (exit `3`)."
4264
5245
  ],
4265
5246
  status: "shipped"
4266
5247
  },
5248
+ {
5249
+ name: "task switch",
5250
+ needs: ["forge"],
5251
+ description: "Change a task's agent or model by setting its Engine checkpoint aside, so the next `task run` is accepted",
5252
+ flags: [
5253
+ { flag: "--issue <n>", description: "Address the task by its Issue number instead of `<tranche> <n>`" },
5254
+ { flag: "--agent <claude|codex>", description: "Vendor the next `task run` of the task continues on" },
5255
+ { flag: "--model <model>", description: "Model the next `task run` is meant to use; absent, the vendor default" }
5256
+ ],
5257
+ details: [
5258
+ "Refuses, changing nothing, while a driver for the task is alive, naming its pid. Otherwise moves the task's Engine checkpoint (`checkpoints.sqlite` with its `-wal` and `-shm` files) into a timestamped `switched-*` folder of the task's run directory and never deletes it; the branch, its commits and its pull request are untouched, so the next `task run` with the new agent continues the same branch on a fresh checkpoint.",
5259
+ "Writes one driver-log line naming the from and to agent, the from and to model and the folder the checkpoint went to. On the standalone runner it changes nothing on disk and says that runner already continues a task on a new `--agent` by itself. `task run` and `run-engine --resume` still refuse an agent other than the checkpoint's, and their refusal names this command."
5260
+ ],
5261
+ status: "shipped"
5262
+ },
4267
5263
  {
4268
5264
  name: "task status",
4269
5265
  needs: ["forge"],
@@ -4418,6 +5414,22 @@ var COMMANDS = [
4418
5414
  ],
4419
5415
  status: "shipped"
4420
5416
  },
5417
+ {
5418
+ name: "pr snapshot",
5419
+ needs: ["forge"],
5420
+ description: "CI plumbing: write a run's forge snapshot of the pull request and its task Issue, read over REST",
5421
+ flags: [
5422
+ {
5423
+ flag: "--dir",
5424
+ description: "The snapshot directory; its `raw/` holds the REST pull request and comment pages the read step wrote"
5425
+ }
5426
+ ],
5427
+ details: [
5428
+ "Run by the generated workflows' read step, never by hand. Maps the REST pull request and its comments to the shape `gh pr view --json` prints, resolves the task Issue from the body's `Closes #N`, and reads that Issue and its comments over REST — never GraphQL.",
5429
+ "A check reads the snapshot only when `GITHUB_ACTIONS` is `true` and the step running it sets `VINAYA_FORGE_SNAPSHOT_DIR`; anywhere else every read goes to the forge as before. Exits 1, naming what it could not read and both token budgets, on a failed read; 2 on a usage error."
5430
+ ],
5431
+ status: "shipped"
5432
+ },
4421
5433
  {
4422
5434
  name: "issue create",
4423
5435
  needs: ["forge"],
@@ -4538,14 +5550,14 @@ var COMMANDS = [
4538
5550
  {
4539
5551
  name: "milestone close",
4540
5552
  needs: ["forge"],
4541
- description: "Close a tranche's Milestone after verifying every labeled Issue is actually attached",
5553
+ description: "Close a tranche's Milestone after verifying every labeled Issue is attached and every tranche it declares is complete",
4542
5554
  flags: [
4543
5555
  { flag: "--slug", description: "The tranche whose Milestone is being closed" },
4544
5556
  { flag: "--validate-only", description: "Run every gate and report PASS without closing the Milestone" },
4545
5557
  { flag: "--json", description: "Enveloped JSON output (schema: 1)" }
4546
5558
  ],
4547
5559
  details: [
4548
- "Resolves the target Milestone the same legacy-or-intent-declared way Issue create auto-attach does, then refuses to close on any mismatch between the label's Issues and the Milestone's natively attached Issues — naming each unattached or foreign Issue and its repair path (`gh issue edit <n> --milestone <title>`, or `vinaya milestone adopt`) — before the PATCH ever reaches the forge."
5560
+ "Resolves the target Milestone the same legacy-or-intent-declared way Issue create auto-attach does, then refuses to close on any mismatch between the label's Issues and the Milestone's natively attached Issues — naming each unattached or foreign Issue and its repair path (`gh issue edit <n> --milestone <title>`, or `vinaya milestone adopt`) — before the PATCH ever reaches the forge. It also holds the Milestone open while a tranche its `### Tranche intents` section declares is not complete — naming each unfinished tranche and its lifecycle — or while that section carries no readable tranche line; a Milestone with no such section closes on attachment alone. `--validate-only` refuses with the same reasons."
4549
5561
  ],
4550
5562
  status: "shipped"
4551
5563
  },
@@ -4834,7 +5846,7 @@ var COMMANDS = [
4834
5846
  }
4835
5847
  ],
4836
5848
  details: [
4837
- "Refuses unless HEAD is the default branch, the working tree is clean, HEAD equals `origin/<default>` (after `git fetch origin`), HEAD's commit subject starts with `Chore(release): Version packages` (unless `--allow-any-commit`), and `npm whoami` exits `0` — each its own refusal naming the fix.",
5849
+ "Refuses unless HEAD is the default branch, the working tree is clean, HEAD equals `origin/<default>` (after `git fetch origin`), HEAD's commit subject starts with `Chore(release): Version packages` (unless `--allow-any-commit`), and `npm whoami` exits `0`. Before any plan step, including under `--dry-run`, every package in `.changeset/config.json` fixed groups must have an unpublished working-tree version. Exact-version registry queries refuse with every already-published package and version; workspace read failures and registry errors other than E404 also refuse with their reason. E404 for a missing package or version counts as unpublished.",
4838
5850
  "Then streams `bun install --frozen-lockfile`, `bun run build`, `bun run changeset:publish`, and `git push origin --tags` — a real push, so the repo's own generated pre-push hook sees it exactly as any other push would. After it, prints `npm view <pkg> version` for every tag now on HEAD, noting registry lag on `@attalabs/vinaya` (observed ~20 minutes) when it still shows the previous version.",
4839
5851
  'This is the one procedure named in `apps/cli/specs/self-hosting.md`, "How the published version is produced" — publishing itself stays manual and human-triggered; this command only removes the hand-typed four-step recipe.'
4840
5852
  ],
@@ -4843,11 +5855,11 @@ var COMMANDS = [
4843
5855
  {
4844
5856
  name: "dispatch",
4845
5857
  needs: ["operator-seat"],
4846
- description: "Start a role's headless agent session (claude/codex/gemini) with attribution set on its environment, recording the outcome through the Vinaya Log",
5858
+ description: "Start a role's headless agent session (claude/codex) with attribution set on its environment, recording the outcome through the Vinaya Log",
4847
5859
  flags: [
4848
5860
  {
4849
5861
  flag: "--agent",
4850
- description: "Vendor to start: `claude`, `codex`, or `gemini` (falls back to `dispatch.agent` in config)"
5862
+ description: "Vendor to start: `claude` or `codex` (falls back to `dispatch.agent` in config)"
4851
5863
  },
4852
5864
  { flag: "--prompt-file", description: "Path to the prompt text sent to the agent (never on argv)" },
4853
5865
  { flag: "--task", description: "This dispatch's task Issue number — mutually exclusive with `--pr`" },
@@ -4864,9 +5876,9 @@ var COMMANDS = [
4864
5876
  ],
4865
5877
  details: [
4866
5878
  "Sets `VINAYA_RUN_ID`/`VINAYA_ROLE`/`VINAYA_TASK`/`VINAYA_ROUND` on the child only — never on this process's own environment — and refuses by name, before any spawn attempt, when the named vendor binary is absent from `PATH` or present but not executable.",
4867
- "Records `dispatched` (with the prompt's sha256), `outcome_received` (duration, the vendor's own usage when its stdout prints a recognizable shape), or `dispatch_failed` (`timeout`, `crash`, or `refused`) through the Vinaya Log's one `dispatch` family writer, `dispatchRole`. A wall-time ceiling (`dispatch.timeoutMs` in config, default one hour) sends `SIGTERM` then, after a grace window, `SIGKILL`.",
5879
+ "Records `dispatched` (with the prompt's sha256), `outcome_received` (duration, the vendor's own usage when its stdout prints a recognizable shape), or `dispatch_failed` (`timeout`, `crash`, `refused`, or `usage_limit`) through the Vinaya Log's one `dispatch` family writer, `dispatchRole`. A wall-time ceiling (`dispatch.timeoutMs` in config, default one hour) sends `SIGTERM` then, after a grace window, `SIGKILL`.",
4868
5880
  "Runs no flush of its own after the dispatch returns: every log line `dispatchRole` emits reaches its configured `logs` destination live, as it is emitted, so there is nothing left to ship in a trailing step. `--task`/`--pr` are attribution only, and remain mutually exclusive.",
4869
- "A successful dispatch's `DispatchHandle` carries `resumeId` — the vendor's own session/thread identifier (claude/gemini: `session_id`; codex: `thread_id`), parsed from its stdout, `null` on any failure. Passing that value as `--resume <id>` on a later call swaps in that vendor's own resume invocation (`claude -p -r <id> ...`; `codex exec resume <id> ...`; `gemini ... --resume <id> ...`) in place of its first-dispatch args."
5881
+ "A successful dispatch's `DispatchHandle` carries `resumeId` — the vendor's own session/thread identifier (claude: `session_id`; codex: `thread_id`), parsed from its stdout, `null` on any failure. Passing that value as `--resume <id>` on a later call swaps in that vendor's own resume invocation (`claude -p -r <id> ...`; `codex exec resume <id> ...`) in place of its first-dispatch args."
4870
5882
  ],
4871
5883
  status: "shipped"
4872
5884
  },
@@ -4877,7 +5889,7 @@ var COMMANDS = [
4877
5889
  flags: [
4878
5890
  { flag: "--task <n>", description: "This task's Issue number — its frozen `aeg:brief:v1` comment is the brief" },
4879
5891
  {
4880
- flag: "--agent <claude|codex|gemini>",
5892
+ flag: "--agent <claude|codex>",
4881
5893
  description: "Vendor for every dispatch this loop makes (falls back to `dispatch.agent` in config)"
4882
5894
  },
4883
5895
  { flag: "--json", description: "Enveloped JSON output (schema: 1)" }
@@ -4948,13 +5960,16 @@ var COMMANDS = [
4948
5960
  }
4949
5961
  ];
4950
5962
  // ../../packages/sources/src/select-source.ts
4951
- import { z as z6 } from "zod";
4952
- var StateSourceConfigSchema = z6.discriminatedUnion("kind", [
4953
- z6.object({ kind: z6.literal("forge"), owner: z6.string(), repo: z6.string() }),
4954
- z6.object({ kind: z6.literal("file"), root: z6.string().optional() })
5963
+ import { z as z7 } from "zod";
5964
+ var StateSourceConfigSchema = z7.discriminatedUnion("kind", [
5965
+ z7.object({ kind: z7.literal("forge"), owner: z7.string(), repo: z7.string() }),
5966
+ z7.object({ kind: z7.literal("file"), root: z7.string().optional() })
4955
5967
  ]);
4956
5968
  // src/checks/edge-resolve.ts
5969
+ import { execFile as execFile6 } from "node:child_process";
5970
+ import { promisify as promisify6 } from "node:util";
4957
5971
  var issueCache = new Map;
5972
+ var execFileAsync6 = promisify6(execFile6);
4958
5973
  var siblingTrancheCache = new Map;
4959
5974
 
4960
5975
  // src/commands/doctrine.ts
@@ -4964,6 +5979,13 @@ import matter4 from "gray-matter";
4964
5979
  import matter2 from "gray-matter";
4965
5980
  // ../../packages/aeg-core/src/docs/surfaced-manifest.ts
4966
5981
  var NO_MODEL_BACKED_PATHS = new Set;
5982
+ // ../../packages/aeg-core/src/docs/published-prose.ts
5983
+ var ALLOWED_MECHANICS = rulesForGroup("published-prose")[0]?.exemptions ?? [];
5984
+ var PROSE_RULES = rulesForGroup("published-prose").map((rule) => ({
5985
+ id: rule.id,
5986
+ what: rule.message,
5987
+ pattern: rule.patterns.published
5988
+ }));
4967
5989
  // src/roles/contract.ts
4968
5990
  import matter3 from "gray-matter";
4969
5991
 
@@ -4981,8 +6003,480 @@ var INFORMATIONAL_DISPATCH_BLOCKER_CLASSES = new Set([
4981
6003
  "conflicts-with"
4982
6004
  ]);
4983
6005
 
6006
+ // src/lib/pre-push-failed-tests.ts
6007
+ import { execFileSync as execFileSync4 } from "node:child_process";
6008
+ import { createHash as createHash2 } from "node:crypto";
6009
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync8, rmSync, writeFileSync as writeFileSync4 } from "node:fs";
6010
+ import { dirname as dirname8, isAbsolute as isAbsolute2, join as join9 } from "node:path";
6011
+ var FAILED_TESTS_RECORD = "vinaya/pre-push-failed-tests.json";
6012
+ var LAST_PUSH_RESULT = "vinaya/pre-push-last-result.json";
6013
+ var SELECTION_NOTE = "vinaya/pre-push-selection.json";
6014
+ var TEST_SELECTION_COMPLETE = "vinaya-test-selection-complete ";
6015
+ function completedTestSelection(log, cwd, expected) {
6016
+ const completed = new Set;
6017
+ let batch = [];
6018
+ let markers = 0;
6019
+ const absolute = (path) => isAbsolute2(path) ? path : join9(cwd, path);
6020
+ for (const line of log.split(`
6021
+ `)) {
6022
+ if (!line.startsWith(TEST_SELECTION_COMPLETE)) {
6023
+ batch.push(line);
6024
+ continue;
6025
+ }
6026
+ try {
6027
+ const result = JSON.parse(line.slice(TEST_SELECTION_COMPLETE.length));
6028
+ if (![0, 1].includes(result.exitCode) || !Array.isArray(result.files) || !result.files.every((file) => typeof file === "string"))
6029
+ return false;
6030
+ const text = batch.join(`
6031
+ `);
6032
+ const summary = [...text.matchAll(/^Ran \d+ tests? across (\d+) files?\.(?:.*)$/gm)].at(-1);
6033
+ const headers = new Set([...text.matchAll(/^(\S.*\.test\.[a-zA-Z]+):$/gm)].map((match) => absolute(match[1])));
6034
+ const files = new Set(result.files.map(absolute));
6035
+ if (!summary || Number(summary[1]) !== files.size || headers.size !== files.size || [...files].some((file) => !headers.has(file)))
6036
+ return false;
6037
+ for (const file of files)
6038
+ completed.add(file);
6039
+ markers++;
6040
+ batch = [];
6041
+ } catch {
6042
+ return false;
6043
+ }
6044
+ }
6045
+ if (markers === 0 || batch.join(`
6046
+ `).trim() !== "")
6047
+ return false;
6048
+ return expected === undefined || new Set(expected.map(absolute)).size === completed.size && expected.every((file) => completed.has(absolute(file)));
6049
+ }
6050
+ function parseFailedTestFiles(log, cwd, exitedNonZero, selected) {
6051
+ if (exitedNonZero && !completedTestSelection(log, cwd, selected))
6052
+ return "all";
6053
+ const failed = new Set;
6054
+ let current = null;
6055
+ for (const raw of log.split(`
6056
+ `)) {
6057
+ const line = raw.trimEnd();
6058
+ if (/^\d+ tests? failed:/.test(line)) {
6059
+ current = null;
6060
+ continue;
6061
+ }
6062
+ const header = /^(\S.*\.test\.[a-zA-Z]+):$/.exec(line);
6063
+ if (header?.[1]) {
6064
+ current = isAbsolute2(header[1]) ? header[1] : join9(cwd, header[1]);
6065
+ continue;
6066
+ }
6067
+ if (current && (/^\(fail\) /.test(line) || line.startsWith("# Unhandled error")))
6068
+ failed.add(current);
6069
+ }
6070
+ if (failed.size === 0)
6071
+ return exitedNonZero ? "all" : [];
6072
+ return [...failed].sort();
6073
+ }
6074
+ function chooseTests(inputs) {
6075
+ const { record, head, branch, fullSelection } = inputs;
6076
+ const full = {
6077
+ version: 1,
6078
+ mode: "full",
6079
+ head,
6080
+ fullCount: fullSelection.length,
6081
+ selected: fullSelection
6082
+ };
6083
+ if (!record || record.failed === "all" || record.selectionCompleted !== true)
6084
+ return full;
6085
+ if (record.branch !== branch || !inputs.recordIsAncestor)
6086
+ return full;
6087
+ if (!record.failed.every(inputs.exists))
6088
+ return full;
6089
+ const rerunFailed = [...record.failed];
6090
+ const affectedSince = inputs.affectedSince.filter(inputs.exists).sort();
6091
+ const selected = [...new Set([...rerunFailed, ...affectedSince])].sort();
6092
+ if (selected.length === 0)
6093
+ return full;
6094
+ return {
6095
+ version: 1,
6096
+ mode: "rerun",
6097
+ head,
6098
+ rerunOf: record.head,
6099
+ recordedHead: record.head,
6100
+ rerunFailed,
6101
+ affectedSince,
6102
+ fullCount: fullSelection.length,
6103
+ selected
6104
+ };
6105
+ }
6106
+ function recordFromRun(outcome, failed, head, branch, now) {
6107
+ if (outcome === "passed")
6108
+ return null;
6109
+ return { version: 1, head, branch, failed, recordedAt: now.toISOString(), selectionCompleted: failed !== "all" };
6110
+ }
6111
+ function parseRecord(text) {
6112
+ if (!text)
6113
+ return null;
6114
+ try {
6115
+ const value = JSON.parse(text);
6116
+ if (value.version !== 1 || typeof value.head !== "string" || typeof value.branch !== "string")
6117
+ return null;
6118
+ if (value.failed !== "all" && !Array.isArray(value.failed))
6119
+ return null;
6120
+ return value;
6121
+ } catch {
6122
+ return null;
6123
+ }
6124
+ }
6125
+ var PASSING_RECORD_VERSION = 2;
6126
+ var SELECTION_POLICY = {
6127
+ name: "pre-push-since-green",
6128
+ version: 1,
6129
+ depth: "one",
6130
+ testTimeoutMs: 30000,
6131
+ rootConfigFile: "vinaya.config.json"
6132
+ };
6133
+ var VERIFICATION_LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "yarn.lock", "pnpm-lock.yaml"];
6134
+ var VERIFICATION_INPUT_FILES = ["vinaya.config.json", "package.json", "bunfig.toml", ...VERIFICATION_LOCKFILES];
6135
+ var VERIFICATION_ENV_KEYS = ["BUN_ENV", "CI", "NODE_ENV", "NODE_OPTIONS", "TZ"];
6136
+ function parsePassingRecord(text) {
6137
+ if (!text)
6138
+ return null;
6139
+ try {
6140
+ const value = JSON.parse(text);
6141
+ if (value.version !== PASSING_RECORD_VERSION || value.kind !== "passed")
6142
+ return null;
6143
+ if (typeof value.head !== "string" || typeof value.branch !== "string" || typeof value.context !== "string")
6144
+ return null;
6145
+ if (!Array.isArray(value.selection) || !value.selection.every((file) => typeof file === "string"))
6146
+ return null;
6147
+ return value;
6148
+ } catch {
6149
+ return null;
6150
+ }
6151
+ }
6152
+ function parseSelectionNote(text, head) {
6153
+ if (!text)
6154
+ return null;
6155
+ try {
6156
+ const value = JSON.parse(text);
6157
+ if (value.head !== head || !Array.isArray(value.selected))
6158
+ return null;
6159
+ if (!value.selected.every((file) => typeof file === "string"))
6160
+ return null;
6161
+ return { mode: "full", ...value };
6162
+ } catch {
6163
+ return null;
6164
+ }
6165
+ }
6166
+ function passingRecordFromRun(inputs) {
6167
+ const { selection, head, branch } = inputs;
6168
+ if (inputs.outcome !== "passed" || !selection || selection.head !== head)
6169
+ return null;
6170
+ if (selection.selected.length === 0 || !head || !branch || branch === "HEAD")
6171
+ return null;
6172
+ if (!selection.context || inputs.context !== selection.context || inputs.inputsClean !== true)
6173
+ return null;
6174
+ if (!completedTestSelection(inputs.log, inputs.repoRoot, selection.selected))
6175
+ return null;
6176
+ return {
6177
+ version: PASSING_RECORD_VERSION,
6178
+ kind: "passed",
6179
+ head,
6180
+ branch,
6181
+ selection: [...selection.selected],
6182
+ selectionCompleted: true,
6183
+ context: selection.context,
6184
+ recordedAt: inputs.now.toISOString()
6185
+ };
6186
+ }
6187
+ function decideSelection(deps) {
6188
+ const context = deps.context !== null && deps.inputsClean === true ? deps.context : null;
6189
+ const withContext = (note) => context === null ? note : { ...note, context };
6190
+ const sinceGreen = deps.failed === null ? sinceGreenNote(deps, context) : null;
6191
+ if (sinceGreen)
6192
+ return { note: withContext(sinceGreen), full: null };
6193
+ const full = deps.full();
6194
+ const record = deps.failed;
6195
+ const recordIsAncestor = record ? deps.isAncestor(record.head) : false;
6196
+ let usable = record;
6197
+ let affectedSince = [];
6198
+ if (record && record.failed !== "all" && recordIsAncestor && record.branch === deps.branch) {
6199
+ const changed = deps.changedBetween(record.head);
6200
+ if (changed === null)
6201
+ usable = null;
6202
+ else
6203
+ affectedSince = deps.affectedSince(changed);
6204
+ }
6205
+ const note = chooseTests({
6206
+ record: usable,
6207
+ head: deps.head,
6208
+ branch: deps.branch,
6209
+ recordIsAncestor,
6210
+ fullSelection: full.selected,
6211
+ affectedSince,
6212
+ exists: deps.exists
6213
+ });
6214
+ return { note: withContext(note), full };
6215
+ }
6216
+ function sinceGreenNote(deps, context) {
6217
+ const passing = deps.passing;
6218
+ if (!passing || passing.selectionCompleted !== true || passing.selection.length === 0)
6219
+ return null;
6220
+ if (passing.branch !== deps.branch || context === null || passing.context !== context)
6221
+ return null;
6222
+ if (!deps.isAncestor(passing.head))
6223
+ return null;
6224
+ const changed = deps.changedBetween(passing.head);
6225
+ if (changed === null || changed.includes(join9(deps.repoRoot, SELECTION_POLICY.rootConfigFile)))
6226
+ return null;
6227
+ const read = deps.sinceGreen(passing.head);
6228
+ if (read.readFailed)
6229
+ return null;
6230
+ const selected = [...new Set(read.selected)].filter(deps.exists).sort();
6231
+ const affectedSince = selected.filter((file) => !deps.isAlwaysRun(file) || changed.includes(file));
6232
+ if (changed.length > 0 && affectedSince.length === 0)
6233
+ return null;
6234
+ return {
6235
+ version: 1,
6236
+ mode: "since-green",
6237
+ head: deps.head,
6238
+ recordedHead: passing.head,
6239
+ affectedSince,
6240
+ fullCount: null,
6241
+ selected
6242
+ };
6243
+ }
6244
+ function cleanGitEnv() {
6245
+ const env = { ...process.env };
6246
+ for (const key of Object.keys(env))
6247
+ if (key.startsWith("GIT_"))
6248
+ delete env[key];
6249
+ return env;
6250
+ }
6251
+ function git(repoRoot, args) {
6252
+ try {
6253
+ return execFileSync4("git", args, {
6254
+ cwd: repoRoot,
6255
+ encoding: "utf8",
6256
+ stdio: ["ignore", "pipe", "ignore"],
6257
+ env: cleanGitEnv()
6258
+ }).trim();
6259
+ } catch {
6260
+ return null;
6261
+ }
6262
+ }
6263
+ function gitPath(repoRoot, name) {
6264
+ const out = git(repoRoot, ["rev-parse", "--git-path", name]);
6265
+ if (!out)
6266
+ return null;
6267
+ return isAbsolute2(out) ? out : join9(repoRoot, out);
6268
+ }
6269
+ function currentHead(repoRoot) {
6270
+ return git(repoRoot, ["rev-parse", "HEAD"]) ?? "";
6271
+ }
6272
+ function currentBranch(repoRoot) {
6273
+ return git(repoRoot, ["rev-parse", "--abbrev-ref", "HEAD"]) ?? "";
6274
+ }
6275
+ function isAncestor(repoRoot, ancestor, head) {
6276
+ try {
6277
+ execFileSync4("git", ["merge-base", "--is-ancestor", ancestor, head], {
6278
+ cwd: repoRoot,
6279
+ stdio: "ignore",
6280
+ env: cleanGitEnv()
6281
+ });
6282
+ return true;
6283
+ } catch {
6284
+ return false;
6285
+ }
6286
+ }
6287
+ function changedBetween(repoRoot, from, to) {
6288
+ const read = git(repoRoot, ["diff", "--name-only", "--diff-filter=ACMRD", from, to]);
6289
+ if (read === null)
6290
+ return null;
6291
+ return read.split(`
6292
+ `).map((s) => s.trim()).filter(Boolean).map((f) => join9(repoRoot, f));
6293
+ }
6294
+ function readJsonUnderGit(repoRoot, name) {
6295
+ const path = gitPath(repoRoot, name);
6296
+ if (!path || !existsSync8(path))
6297
+ return null;
6298
+ try {
6299
+ return readFileSync8(path, "utf8");
6300
+ } catch {
6301
+ return null;
6302
+ }
6303
+ }
6304
+ function writeJsonUnderGit(repoRoot, name, value) {
6305
+ const path = gitPath(repoRoot, name);
6306
+ if (!path)
6307
+ return;
6308
+ mkdirSync6(dirname8(path), { recursive: true });
6309
+ writeFileSync4(path, `${JSON.stringify(value, null, 2)}
6310
+ `);
6311
+ }
6312
+ function removeUnderGit(repoRoot, name) {
6313
+ const path = gitPath(repoRoot, name);
6314
+ if (path)
6315
+ rmSync(path, { force: true });
6316
+ }
6317
+ function readFailedTestsRecord(repoRoot) {
6318
+ return parseRecord(readJsonUnderGit(repoRoot, FAILED_TESTS_RECORD));
6319
+ }
6320
+ function readPassingRecord(repoRoot) {
6321
+ return parsePassingRecord(readJsonUnderGit(repoRoot, FAILED_TESTS_RECORD));
6322
+ }
6323
+ function clearRecordOfKind(repoRoot, kind) {
6324
+ const text = readJsonUnderGit(repoRoot, FAILED_TESTS_RECORD);
6325
+ const other = kind === "failed" ? parsePassingRecord(text) : parseRecord(text);
6326
+ if (text !== null && other !== null)
6327
+ return;
6328
+ removeUnderGit(repoRoot, FAILED_TESTS_RECORD);
6329
+ }
6330
+ function computeVerificationContext(repoRoot, env = process.env) {
6331
+ try {
6332
+ const sha = (data) => createHash2("sha256").update(data).digest("hex");
6333
+ const read = (name) => {
6334
+ const path = join9(repoRoot, name);
6335
+ return existsSync8(path) ? readFileSync8(path) : null;
6336
+ };
6337
+ const json = (name) => {
6338
+ const bytes = read(name);
6339
+ return bytes === null ? null : JSON.parse(bytes.toString("utf8"));
6340
+ };
6341
+ const config = json("vinaya.config.json");
6342
+ const pkg = json("package.json");
6343
+ const scripts = pkg?.scripts;
6344
+ const bunfig = read("bunfig.toml");
6345
+ const parts = {
6346
+ policy: sha(JSON.stringify(SELECTION_POLICY)),
6347
+ inputs: sha(JSON.stringify({ prePush: config?.prePush ?? null, workspaces: pkg?.workspaces ?? null })),
6348
+ lockfile: sha(VERIFICATION_LOCKFILES.map((name) => {
6349
+ const bytes = read(name);
6350
+ return `${name}:${bytes === null ? "absent" : sha(bytes)}`;
6351
+ }).join(`
6352
+ `)),
6353
+ runner: sha(JSON.stringify({
6354
+ bunfig: bunfig === null ? null : sha(bunfig),
6355
+ testScript: scripts?.test ?? null,
6356
+ bun: process.versions.bun ?? null
6357
+ })),
6358
+ environment: sha(VERIFICATION_ENV_KEYS.map((key) => `${key}=${env[key] ?? "\x00unset"}`).join(`
6359
+ `))
6360
+ };
6361
+ return { digest: sha(JSON.stringify(parts)), parts };
6362
+ } catch {
6363
+ return null;
6364
+ }
6365
+ }
6366
+ function verificationInputsDirty(repoRoot) {
6367
+ const out = git(repoRoot, ["status", "--porcelain", "--", ...VERIFICATION_INPUT_FILES]);
6368
+ return out === null ? null : out !== "";
6369
+ }
6370
+
6371
+ // src/lib/pre-push-mode-logic.ts
6372
+ var PUSH_MODE_MARKER = "vinaya/push-mode";
6373
+ function parseStorageMarker(text) {
6374
+ if (!text)
6375
+ return null;
6376
+ try {
6377
+ const value = JSON.parse(text);
6378
+ if (value.version !== 1 || value.mode !== "storage")
6379
+ return null;
6380
+ if (typeof value.runId !== "string" || value.runId === "")
6381
+ return null;
6382
+ if (typeof value.branch !== "string" || value.branch === "")
6383
+ return null;
6384
+ if (typeof value.pid !== "number" || !Number.isInteger(value.pid) || value.pid <= 0)
6385
+ return null;
6386
+ return value;
6387
+ } catch {
6388
+ return null;
6389
+ }
6390
+ }
6391
+ var isTaskBranch2 = (branch) => branch.startsWith("task/");
6392
+ function resolvePushMode(input) {
6393
+ const env = input.envMode?.trim();
6394
+ if (env === "ready" || env === "default")
6395
+ return { ok: true, mode: env };
6396
+ const marker = parseStorageMarker(input.marker);
6397
+ const live = marker !== null && isTaskBranch2(input.branch) && marker.branch === input.branch && input.isPidAlive(marker.pid);
6398
+ if (!live)
6399
+ return { ok: true, mode: "default" };
6400
+ let open;
6401
+ try {
6402
+ open = input.openPullRequests();
6403
+ } catch (error) {
6404
+ return {
6405
+ ok: false,
6406
+ reason: `a storage push runs no tests, so it must first confirm that no pull request is open for ${input.branch}, and that read failed: ${error instanceof Error ? error.message : String(error)}`
6407
+ };
6408
+ }
6409
+ if (open > 0) {
6410
+ return {
6411
+ ok: false,
6412
+ reason: `a pull request is open for ${input.branch}: storage pushes (no tests) are allowed only while none is open — push without the storage mode so the selected tests run`
6413
+ };
6414
+ }
6415
+ return { ok: true, mode: "storage" };
6416
+ }
6417
+
6418
+ // src/lib/process-registry.ts
6419
+ import { execFileSync as execFileSync5 } from "node:child_process";
6420
+ import {
6421
+ closeSync as closeSync6,
6422
+ fsyncSync as fsyncSync2,
6423
+ mkdirSync as mkdirSync7,
6424
+ openSync as openSync6,
6425
+ readdirSync as readdirSync3,
6426
+ readFileSync as readFileSync9,
6427
+ renameSync as renameSync4,
6428
+ rmSync as rmSync2,
6429
+ writeSync as writeSync5
6430
+ } from "node:fs";
6431
+ function linuxStartTime(pid) {
6432
+ try {
6433
+ const stat = readFileSync9(`/proc/${pid}/stat`, "utf8");
6434
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
6435
+ return fields[19] ?? null;
6436
+ } catch {
6437
+ return null;
6438
+ }
6439
+ }
6440
+ function psStartTime(pid) {
6441
+ try {
6442
+ const out = execFileSync5("ps", ["-o", "lstart=", "-p", String(pid)], {
6443
+ encoding: "utf8",
6444
+ stdio: ["ignore", "pipe", "ignore"]
6445
+ }).trim();
6446
+ return out === "" ? null : out;
6447
+ } catch {
6448
+ return null;
6449
+ }
6450
+ }
6451
+ function identityOf(pid) {
6452
+ if (!Number.isInteger(pid) || pid <= 0)
6453
+ return null;
6454
+ const startTime = process.platform === "linux" ? linuxStartTime(pid) : psStartTime(pid);
6455
+ return startTime === null ? null : { pid, startTime };
6456
+ }
6457
+
6458
+ // src/lib/pre-push-ready-policy.ts
6459
+ var DEFERRAL_MARKER_TTL_MS = 30 * 60 * 1000;
6460
+ if (false)
6461
+ ;
6462
+
6463
+ // src/lib/pre-push-test-runner.ts
6464
+ var REPOSITORY_LOCAL_RUN = "scripts/test-suites/local-run.ts";
6465
+ var NATIVE_EXACT = "exact";
6466
+ function parseNativeRunCommand(command) {
6467
+ const tokens = command.trim().split(/\s+/);
6468
+ if (tokens[0] !== "bun" || tokens[1] !== REPOSITORY_LOCAL_RUN || tokens[2] !== NATIVE_EXACT)
6469
+ return null;
6470
+ if (tokens[3] !== "--context" || !/^[0-9a-f]{64}$/.test(tokens[4] ?? "") || tokens[5] !== "--")
6471
+ return null;
6472
+ const identities = tokens.slice(6);
6473
+ if (identities.length === 0 || identities.some((identity) => identity.lastIndexOf("@") <= 0))
6474
+ return null;
6475
+ return { context: tokens[4], identities };
6476
+ }
6477
+
4984
6478
  // src/lib/pr-report-engine.ts
4985
- var execFileAsync6 = promisify6(execFile6);
6479
+ var execFileAsync7 = promisify7(execFile7);
4986
6480
  var BODY_READING_CHECK_NAMES = new Set(coreCheckRegistry().filter((spec) => {
4987
6481
  const decl = spec.env?.PR_BODY;
4988
6482
  return decl === true || typeof decl === "object" && decl !== null && "optional" in decl;
@@ -4990,23 +6484,23 @@ var BODY_READING_CHECK_NAMES = new Set(coreCheckRegistry().filter((spec) => {
4990
6484
  var FAILING_STATUSES = new Set(["fail", "error", "timeout"]);
4991
6485
  function readTestRunCacheFile(path) {
4992
6486
  try {
4993
- if (!lstatSync4(path).isFile())
6487
+ if (!lstatSync5(path).isFile())
4994
6488
  return {};
4995
- return JSON.parse(readFileSync8(path, "utf8"));
6489
+ return JSON.parse(readFileSync10(path, "utf8"));
4996
6490
  } catch {
4997
6491
  return {};
4998
6492
  }
4999
6493
  }
5000
6494
  function writeTestRunCacheFile(path, all) {
5001
6495
  const tmp = `${path}.tmp-${process.pid}-${randomUUID3()}`;
5002
- const fd = openSync6(tmp, fsConstants6.O_WRONLY | fsConstants6.O_CREAT | fsConstants6.O_EXCL, 384);
6496
+ const fd = openSync7(tmp, fsConstants6.O_WRONLY | fsConstants6.O_CREAT | fsConstants6.O_EXCL, 384);
5003
6497
  try {
5004
- writeSync5(fd, JSON.stringify(all, null, 2), null, "utf8");
5005
- fsyncSync2(fd);
6498
+ writeSync6(fd, JSON.stringify(all, null, 2), null, "utf8");
6499
+ fsyncSync3(fd);
5006
6500
  } finally {
5007
- closeSync6(fd);
6501
+ closeSync7(fd);
5008
6502
  }
5009
- renameSync4(tmp, path);
6503
+ renameSync5(tmp, path);
5010
6504
  }
5011
6505
  function fileBackedTestRunCache(path, runtimeDir) {
5012
6506
  return {
@@ -5014,7 +6508,7 @@ function fileBackedTestRunCache(path, runtimeDir) {
5014
6508
  set: (key, record) => {
5015
6509
  const all = readTestRunCacheFile(path);
5016
6510
  all[key] = record;
5017
- ensureRunDir(dirname8(path), runtimeDir);
6511
+ ensureRunDir(dirname9(path), runtimeDir);
5018
6512
  writeTestRunCacheFile(path, all);
5019
6513
  }
5020
6514
  };
@@ -5024,10 +6518,16 @@ function defaultTestRunCache() {
5024
6518
  const path = runPath(runtimeDir, "unscoped", { area: "output", file: "test-run-cache.json" });
5025
6519
  return fileBackedTestRunCache(path, runtimeDir);
5026
6520
  }
5027
- async function gitOrNull(args, cwd) {
6521
+ var GIT_MAX_BUFFER = 16 * 1024 * 1024;
6522
+ async function gitOrNull(args, cwd, trim = true) {
5028
6523
  try {
5029
- const { stdout } = await execFileAsync6("git", args, { encoding: "utf8", env: process.env, cwd });
5030
- return stdout.trim();
6524
+ const { stdout } = await execFileAsync7("git", args, {
6525
+ encoding: "utf8",
6526
+ env: process.env,
6527
+ cwd,
6528
+ maxBuffer: GIT_MAX_BUFFER
6529
+ });
6530
+ return trim ? stdout.trim() : stdout;
5031
6531
  } catch {
5032
6532
  return null;
5033
6533
  }
@@ -5044,19 +6544,24 @@ async function collectStateFields(cwd) {
5044
6544
  const head = await gitOrNull(["rev-parse", "HEAD"], cwd);
5045
6545
  if (!head)
5046
6546
  return null;
5047
- const status = await gitOrNull(["status", "--porcelain=v1", "-uall", "--ignored", "-z"], cwd);
6547
+ const status = await gitOrNull(["status", "--porcelain=v1", "-uall", "-z"], cwd);
5048
6548
  if (status === null)
5049
6549
  return null;
6550
+ const ignored = await gitOrNull(["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"], cwd, false);
6551
+ if (ignored === null)
6552
+ return null;
5050
6553
  const diff = await gitOrNull(["diff", "HEAD"], cwd);
5051
6554
  if (diff === null)
5052
6555
  return null;
5053
- const fields = [hostname(), head, status, diff];
5054
- const uncommitted = status.split(NUL).filter((entry) => entry.startsWith("?? ") || entry.startsWith("!! ")).map((entry) => entry.slice(3)).sort();
6556
+ const fields = [hostname(), head, status, ignored, diff];
6557
+ const untracked = status.split(NUL).filter((entry) => entry.startsWith("?? ")).map((entry) => entry.slice(3));
6558
+ const ignoredPaths = ignored.split(NUL).filter(Boolean);
6559
+ const uncommitted = [...untracked, ...ignoredPaths].sort();
5055
6560
  const base = cwd ?? process.cwd();
5056
6561
  for (const f of uncommitted) {
5057
6562
  fields.push(f);
5058
6563
  try {
5059
- fields.push(readFileSync8(join9(base, f)));
6564
+ fields.push(readFileSync10(join10(base, f)));
5060
6565
  } catch {
5061
6566
  fields.push("MISSING");
5062
6567
  }
@@ -5064,7 +6569,7 @@ async function collectStateFields(cwd) {
5064
6569
  return fields;
5065
6570
  }
5066
6571
  function digestFields(fields) {
5067
- const hash = createHash2("sha256");
6572
+ const hash = createHash3("sha256");
5068
6573
  for (const f of fields)
5069
6574
  hashField(hash, f);
5070
6575
  return hash.digest("hex");
@@ -5131,13 +6636,24 @@ function truncateAgentOutput(output) {
5131
6636
  ${output.slice(-AGENT_COMMAND_OUTPUT_MAX_CHARS)}`;
5132
6637
  }
5133
6638
  var AGENT_COMMAND_MAX_BUFFER_BYTES = 32 * 1024 * 1024;
5134
- async function recordGreenTestRun(command, output, cwd, source, cache = defaultTestRunCache()) {
6639
+ async function recordGreenTestRun(command, output, cwd, source, cache = defaultTestRunCache(), options = {}) {
6640
+ const native = parseNativeRunCommand(command);
6641
+ if (native && options.context !== native.context)
6642
+ return false;
5135
6643
  const key = await testRunCacheKey(command, cwd);
5136
6644
  if (!key)
5137
6645
  return false;
5138
6646
  const truncated = truncateAgentOutput(output);
5139
6647
  const recordedAt = new Date().toISOString();
5140
- cache.set(key, { output: truncated, exitCode: 0, timedOut: false, overflowed: false, recordedAt, source });
6648
+ cache.set(key, {
6649
+ output: truncated,
6650
+ exitCode: 0,
6651
+ timedOut: false,
6652
+ overflowed: false,
6653
+ recordedAt,
6654
+ source,
6655
+ ...options.context ? { context: options.context } : {}
6656
+ });
5141
6657
  const files = bunTestFileArgs(command);
5142
6658
  if (files) {
5143
6659
  const stateKey = await testRunStateKey(cwd);
@@ -5166,7 +6682,7 @@ async function main() {
5166
6682
  }
5167
6683
  let output;
5168
6684
  try {
5169
- output = readFileSync9(logPath, "utf8");
6685
+ output = readFileSync11(logPath, "utf8");
5170
6686
  } catch (err) {
5171
6687
  process.stderr.write(`vinaya pre-push: could not read ${logPath} to cache this run — nothing recorded (${err instanceof Error ? err.message : String(err)}).
5172
6688
  `);