@attalabs/vinaya 0.34.0 → 0.36.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 (131) hide show
  1. package/LICENSE +104 -201
  2. package/README.md +1 -1
  3. package/aeg-root/roles/planner/reference.md +21 -6
  4. package/aeg-root/roles/planner.md +2 -0
  5. package/aeg-root/roles/reviewer.md +3 -1
  6. package/aeg-root/templates/brief-template.md +4 -0
  7. package/dist/checks/bin/check-body-bare-digits.js +1450 -1350
  8. package/dist/checks/bin/check-branch-topology.js +1432 -1342
  9. package/dist/checks/bin/check-brief-shape.js +1451 -1351
  10. package/dist/checks/bin/check-changeset-coverage.js +1502 -1360
  11. package/dist/checks/bin/check-closes-n.js +1432 -1342
  12. package/dist/checks/bin/check-coherence.js +1472 -1351
  13. package/dist/checks/bin/check-dead-branch-push.js +1408 -1339
  14. package/dist/checks/bin/check-dispatch-readiness.js +1475 -1354
  15. package/dist/checks/bin/check-doc-coverage-push.js +1502 -1360
  16. package/dist/checks/bin/check-doc-coverage.js +1504 -1362
  17. package/dist/checks/bin/check-doctrine-no-procedures.js +1449 -1349
  18. package/dist/checks/bin/check-doctrine-portability.js +1502 -1360
  19. package/dist/checks/bin/check-evidence-fresh.js +1508 -1366
  20. package/dist/checks/bin/check-exec-bits.js +1502 -1360
  21. package/dist/checks/bin/check-first-push-dispatch.js +1476 -1355
  22. package/dist/checks/bin/check-issue-assignment.js +1432 -1342
  23. package/dist/checks/bin/check-issue-milestone-attach.js +1408 -1339
  24. package/dist/checks/bin/check-issue-objectives-numbering.js +1449 -1349
  25. package/dist/checks/bin/check-issue-parts-coverage.js +1408 -1339
  26. package/dist/checks/bin/check-issue-surface-globs.js +1475 -1354
  27. package/dist/checks/bin/check-issue-title-grammar.js +1408 -1339
  28. package/dist/checks/bin/check-issue-tranche-label.js +1408 -1339
  29. package/dist/checks/bin/check-main-branch-refusal.js +1410 -1341
  30. package/dist/checks/bin/check-no-disk-state.js +1410 -1341
  31. package/dist/checks/bin/check-pr-premise-reassert.js +1449 -1349
  32. package/dist/checks/bin/check-pr-report-density.js +1410 -1341
  33. package/dist/checks/bin/check-principal-test-plan-wait.js +1410 -1341
  34. package/dist/checks/bin/check-quoted-command.js +1500 -1358
  35. package/dist/checks/bin/check-reader-resolvable-prose.js +1500 -1358
  36. package/dist/checks/bin/check-registry-gates.js +1410 -1341
  37. package/dist/checks/bin/check-retired-vocabulary.js +1500 -1358
  38. package/dist/checks/bin/check-review-gate.js +1463 -1363
  39. package/dist/checks/bin/check-single-plan-pr.js +1408 -1339
  40. package/dist/checks/bin/check-surface-scope.js +1432 -1342
  41. package/dist/checks/bin/check-test-plan.js +1408 -1339
  42. package/dist/checks/bin/check-token-collection-wired.js +1410 -1341
  43. package/dist/checks/bin/check-token-report.js +1410 -1341
  44. package/dist/checks/bin/check-workspace-escape.js +1501 -1359
  45. package/dist/index.js +4261 -1917
  46. package/dist/lib/pre-push-cache-test-run.js +130 -19
  47. package/dist/lib/pre-push-select-tests.js +86 -17
  48. package/package.json +2 -2
  49. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/brief-render.ts +153 -37
  50. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/brief-validation.ts +87 -24
  51. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/coherence-checks.ts +9 -2
  52. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/assess-round.ts +31 -2
  53. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/index.ts +1 -0
  54. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/render-summary.ts +52 -3
  55. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/types.ts +28 -0
  56. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/gate-cutovers.ts +49 -0
  57. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/index.ts +13 -2
  58. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/issue-validation.ts +148 -54
  59. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/envelope.ts +26 -3
  60. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/objectives-cutover-config.ts +31 -0
  61. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/objectives.ts +15 -6
  62. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/reader-resolvable-prose.ts +122 -23
  63. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/task-tools.ts +38 -3
  64. package/studio-standalone/apps/vinaya-studio/web/.next/BUILD_ID +1 -1
  65. package/studio-standalone/apps/vinaya-studio/web/.next/build-manifest.json +3 -3
  66. package/studio-standalone/apps/vinaya-studio/web/.next/prerender-manifest.json +3 -3
  67. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.html +1 -1
  68. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.rsc +1 -1
  69. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  70. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  71. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  72. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  73. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  74. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page/server-reference-manifest.json +2 -2
  75. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page.js.nft.json +1 -1
  76. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  77. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/api/coherence/route.js.nft.json +1 -1
  78. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page/server-reference-manifest.json +2 -2
  79. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page.js.nft.json +1 -1
  80. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page_client-reference-manifest.js +1 -1
  81. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page/server-reference-manifest.json +2 -2
  82. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page.js.nft.json +1 -1
  83. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page_client-reference-manifest.js +1 -1
  84. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page/server-reference-manifest.json +2 -2
  85. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page.js.nft.json +1 -1
  86. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page_client-reference-manifest.js +1 -1
  87. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page/server-reference-manifest.json +2 -2
  88. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page.js.nft.json +1 -1
  89. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page_client-reference-manifest.js +1 -1
  90. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page/server-reference-manifest.json +3 -3
  91. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page.js.nft.json +1 -1
  92. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page_client-reference-manifest.js +1 -1
  93. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page/server-reference-manifest.json +2 -2
  94. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page.js.nft.json +1 -1
  95. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page_client-reference-manifest.js +1 -1
  96. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page/server-reference-manifest.json +2 -2
  97. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page.js.nft.json +1 -1
  98. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page_client-reference-manifest.js +1 -1
  99. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page/server-reference-manifest.json +2 -2
  100. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page.js.nft.json +1 -1
  101. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page_client-reference-manifest.js +1 -1
  102. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/[root-of-the-server]__02a-3g8._.js +1 -1
  103. 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
  104. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__074w9nf._.js +1 -1
  105. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0ls23oh._.js +1 -1
  106. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1gjqmhq._.js +1 -1
  107. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1wc4-ip._.js +1 -1
  108. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{[root-of-the-server]__07uhu5z._.js → [root-of-the-server]__1wy7w66._.js} +1 -1
  109. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_08onyya._.js +1 -1
  110. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_096f46i._.js +1 -1
  111. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0af2one._.js +1 -1
  112. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0e5tkdd._.js +1 -1
  113. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0kf2g72._.js +1 -1
  114. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0zf4d27._.js +1 -1
  115. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1-wo68i._.js +1 -1
  116. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_15gdg48._.js +2 -2
  117. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1achbh9._.js +1 -1
  118. 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
  119. package/studio-standalone/apps/vinaya-studio/web/.next/server/middleware-build-manifest.js +3 -3
  120. package/studio-standalone/apps/vinaya-studio/web/.next/server/pages/500.html +1 -1
  121. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.js +1 -1
  122. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.json +4 -4
  123. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/00z3-ljjd1gj9.js +1 -0
  124. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{2174nz5he_oc4.js → 2o9l0b7eqbr57.js} +1 -1
  125. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{0q9p7c6vn-x2w.js → 3lqjwjrcvq481.js} +4 -4
  126. package/studio-standalone/apps/vinaya-studio/web/package.json +2 -2
  127. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/3xnma0-359j17.js +0 -1
  128. /package/studio-standalone/_node_modules/@attalabs/vinaya/studio-standalone/_node_modules/@attalabs/vinaya/studio-standalone/_node_modules/@attalabs/vinaya/studio-standalone/_node_modules/@attalabs/vinaya/studio-standalone/_node_modules/@attalabs/vinaya/studio-standalone/_node_modules/@attalabs/vinaya/studio-standalone/_node_modules/@attalabs/{aeg-core → vinaya/studio-standalone/_node_modules/@attalabs/vinaya/studio-standalone/_node_modules/@attalabs/aeg-core}/bin/verify-coherence.ts +0 -0
  129. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{HmoeqXdX1E4drt7GReFOO → z1fTSBP6ZlUjObzFIp-qq}/_buildManifest.js +0 -0
  130. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{HmoeqXdX1E4drt7GReFOO → z1fTSBP6ZlUjObzFIp-qq}/_clientMiddlewareManifest.js +0 -0
  131. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{HmoeqXdX1E4drt7GReFOO → z1fTSBP6ZlUjObzFIp-qq}/_ssgManifest.js +0 -0
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/checks/bin/check-exec-bits.ts
4
- import { execFileSync as execFileSync7 } from "node:child_process";
4
+ import { execFileSync as execFileSync8 } from "node:child_process";
5
5
  import { readFileSync as readFileSync7 } from "node:fs";
6
6
 
7
7
  // src/checks/contract.ts
@@ -12,7 +12,7 @@ function emitCheckError(error) {
12
12
  }
13
13
 
14
14
  // src/lib/diff-evidence.ts
15
- import { execFileSync as execFileSync6 } from "node:child_process";
15
+ import { execFileSync as execFileSync7 } from "node:child_process";
16
16
  import { join as join9, relative, resolve as resolve2 } from "node:path";
17
17
  // ../../packages/aeg-core/src/gate-audience.ts
18
18
  var GATE_AUDIENCE = {
@@ -2477,16 +2477,42 @@ function blockingSeverities(scale, threshold) {
2477
2477
  }
2478
2478
  return scale.slice(0, idx + 1);
2479
2479
  }
2480
- function evaluateReviewFindings(findings, scale, threshold) {
2481
- const blocking = new Set(blockingSeverities(scale, threshold));
2482
- const blockingFindings = findings.filter((f) => {
2483
- if (!scale.includes(f.severity)) {
2484
- throw new Error(`evaluateReviewFindings: severity "${f.severity}" is not one of ${scale.join(" > ")}`);
2485
- }
2486
- const effectiveSeverity = f.location !== undefined && isProseLocation(f.location) ? PROSE_CAP_SEVERITY : f.severity;
2487
- return blocking.has(effectiveSeverity);
2488
- });
2489
- return { outcome: blockingFindings.length > 0 ? "blocked" : "clean", blockingFindings };
2480
+ var DEFERRAL_REASON_TEXT = {
2481
+ "unchanged-line": "unchanged line",
2482
+ "outside-surface": "outside the Surface"
2483
+ };
2484
+ var SECURITY_HIGH_AND_ABOVE = blockingSeverities(SECURITY_SEVERITY_ORDER, "HIGH");
2485
+ function classifyFinding(finding, scale, threshold, context = {}) {
2486
+ if (!scale.includes(finding.severity)) {
2487
+ throw new Error(`classifyFinding: severity "${finding.severity}" is not one of ${scale.join(" > ")}`);
2488
+ }
2489
+ const location = finding.location;
2490
+ const effectiveSeverity = location !== undefined && isProseLocation(location) ? PROSE_CAP_SEVERITY : finding.severity;
2491
+ const wouldBlock = blockingSeverities(scale, threshold).includes(effectiveSeverity);
2492
+ if (!wouldBlock)
2493
+ return { outcome: "non_blocking", deferralReason: null };
2494
+ const hasLocation = location !== undefined && location.length > 0;
2495
+ if (hasLocation && context.inSurface && !context.inSurface(location)) {
2496
+ return { outcome: "deferred", deferralReason: "outside-surface" };
2497
+ }
2498
+ if (hasLocation && context.changedLine && !SECURITY_HIGH_AND_ABOVE.includes(effectiveSeverity)) {
2499
+ if (!context.changedLine(location)) {
2500
+ return { outcome: "deferred", deferralReason: "unchanged-line" };
2501
+ }
2502
+ }
2503
+ return { outcome: "blocking", deferralReason: null };
2504
+ }
2505
+ function evaluateReviewFindings(findings, scale, threshold, context = {}) {
2506
+ const blockingFindings = [];
2507
+ const deferredFindings = [];
2508
+ for (const f of findings) {
2509
+ const c = classifyFinding(f, scale, threshold, context);
2510
+ if (c.outcome === "blocking")
2511
+ blockingFindings.push(f);
2512
+ else if (c.outcome === "deferred")
2513
+ deferredFindings.push({ finding: f, reason: c.deferralReason });
2514
+ }
2515
+ return { outcome: blockingFindings.length > 0 ? "blocked" : "clean", blockingFindings, deferredFindings };
2490
2516
  }
2491
2517
  function isConsequentialFinding(finding) {
2492
2518
  return finding.state !== "resolved";
@@ -2494,11 +2520,11 @@ function isConsequentialFinding(finding) {
2494
2520
  function consequentialFindings(findings) {
2495
2521
  return findings.filter((f) => isConsequentialFinding(f));
2496
2522
  }
2497
- function evaluateCodeReview(findings, policy) {
2498
- return evaluateReviewFindings(findings, CODE_REVIEW_SEVERITY_ORDER, policy.codeReviewThreshold);
2523
+ function evaluateCodeReview(findings, policy, context = {}) {
2524
+ return evaluateReviewFindings(findings, CODE_REVIEW_SEVERITY_ORDER, policy.codeReviewThreshold, context);
2499
2525
  }
2500
- function evaluateSecurityReview(findings, policy) {
2501
- return evaluateReviewFindings(findings, SECURITY_SEVERITY_ORDER, policy.securityThreshold);
2526
+ function evaluateSecurityReview(findings, policy, context = {}) {
2527
+ return evaluateReviewFindings(findings, SECURITY_SEVERITY_ORDER, policy.securityThreshold, context);
2502
2528
  }
2503
2529
  function isKnownSeverity(scale, value) {
2504
2530
  return scale.includes(value);
@@ -3412,1511 +3438,1548 @@ function checkPrReportDensity(prBody) {
3412
3438
  const results = [checkDecisionsDensity(prBody), checkScopeDensity(prBody)];
3413
3439
  return { errors: results.flatMap((r) => r.errors) };
3414
3440
  }
3415
- // ../../packages/aeg-core/src/issue-validation.ts
3416
- function hasRationaleField(body, labelPattern) {
3417
- const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})`, "im");
3418
- return re.test(body);
3419
- }
3420
- var RATIONALE_FIELDS = [
3421
- { name: "Boundary", pattern: "Boundary" },
3422
- { name: "Sizing", pattern: "Sizing" },
3423
- { name: "Project(s) + blast radius", pattern: "Project\\(s\\)|Project(?:s)?\\s*\\+|blast radius" },
3424
- { name: "Dependency rationale", pattern: "Dependency rationale|Depends[- ]on" },
3425
- { name: "Traps to avoid", pattern: "Traps" },
3426
- { name: "Suggested agent-class", pattern: "(?:Suggested\\s+)?agent-class" },
3427
- { name: "Stop-and-escalate", pattern: "Stop-and-escalate" },
3428
- { name: "Docs to keep coherent", pattern: "Docs to keep coherent|§7" }
3441
+ // ../../packages/aeg-core/src/reader-resolvable-prose.ts
3442
+ var PRODUCT_SLUG_SCOPE = [
3443
+ "apps/cli/src",
3444
+ ".github/workflows",
3445
+ ".vinaya",
3446
+ "apps/cli/README.md",
3447
+ "packages/sources/README.md"
3429
3448
  ];
3430
- var DEPENDENCY_RATIONALE_FIELD_NAME = "Dependency rationale";
3431
- function checkIssueRationale(body) {
3432
- const errors = [];
3433
- for (const f of RATIONALE_FIELDS) {
3434
- if (!hasRationaleField(body, f.pattern)) {
3435
- errors.push(`issue-validation ${f.name}: rationale field not found in the Issue body — every task Issue carries the full Planner's rationale (aeg-root/contracts/planner-brief.md).`);
3436
- continue;
3437
- }
3438
- if (f.name === DEPENDENCY_RATIONALE_FIELD_NAME && !SECTION_HEADER.test(body)) {
3439
- errors.push(`issue-validation ${f.name}: rationale field found, but not in the form amend-deps requires — ` + "write `**Dependency rationale** — …`, not `**Dependency rationale:** …`. " + "`amendRationaleDeps` (the only sanctioned way to edit Depends-on/Conflicts-with) locates this " + "section by the exact anchor `**Dependency rationale**`; a colon inside the bold breaks that match " + "and the Issue becomes unamendable.");
3440
- }
3441
- }
3442
- return { status: errors.length > 0 ? "fail" : "pass", errors };
3443
- }
3444
- var OBJECTIVES_SINCE_ISSUE = 404;
3445
- function checkIssueObjectives(body, issueNumber, sinceIssue = OBJECTIVES_SINCE_ISSUE) {
3446
- if (sinceIssue !== null && issueNumber !== null && issueNumber < sinceIssue)
3447
- return { status: "pass", errors: [] };
3448
- const result = objectivesOf(body);
3449
- if (result.ok)
3450
- return { status: "pass", errors: [] };
3451
- return { status: "fail", errors: result.errors.map((e) => `issue-validation objectives: ${e}`) };
3449
+ function isUnderOrEqual(path, prefix) {
3450
+ return path === prefix || path.startsWith(`${prefix}/`);
3452
3451
  }
3453
- function topLevelSectionText(body, headingName) {
3454
- const headingRe = new RegExp(`^##[ \\t]*${headingName}[ \\t]*$`, "im");
3455
- const heading = headingRe.exec(body);
3456
- if (!heading)
3457
- return null;
3458
- const afterHeading = body.slice(heading.index + heading[0].length);
3459
- const next = /^##[ \t]/m.exec(afterHeading);
3460
- return next ? afterHeading.slice(0, next.index) : afterHeading;
3452
+ function isProductScopeFile(path) {
3453
+ return PRODUCT_SLUG_SCOPE.some((prefix) => isUnderOrEqual(path, prefix));
3461
3454
  }
3462
- function partHasBacktickedPath(text) {
3463
- let i = 0;
3464
- while (i < text.length) {
3465
- const start = text.indexOf("`", i);
3466
- if (start === -1)
3467
- return false;
3468
- const end = text.indexOf("`", start + 1);
3469
- if (end === -1)
3470
- return false;
3471
- if (text.slice(start + 1, end).includes("/"))
3472
- return true;
3473
- i = end + 1;
3474
- }
3475
- return false;
3455
+ var SHIPS_PREFIX = "aeg-root/";
3456
+ function shipsArchivePrefix(shipsPrefix) {
3457
+ return `${shipsPrefix}tranches/completed/`;
3476
3458
  }
3477
- var PART_MIN_WORDS_OUTSIDE_BACKTICKS = 3;
3478
- function stripPartBackticks(text) {
3479
- return text.replace(/`[^`\n]*`/g, " ");
3459
+ var DEFAULT_SPEC_PATHS = ["SPEC.md", "CONTEXT.md", "docs/adr"];
3460
+ function normalizeSpecPath(entry) {
3461
+ let out = entry.replace(/\\/g, "/");
3462
+ while (out.startsWith("./"))
3463
+ out = out.slice(2);
3464
+ out = out.replace(/\/{2,}/g, "/");
3465
+ while (out.endsWith("/"))
3466
+ out = out.slice(0, -1);
3467
+ return out;
3480
3468
  }
3481
- function partWordCount(text) {
3482
- return text.split(/\s+/).filter((w) => /[a-z]/i.test(w)).length;
3469
+ function isSpecFile2(path, specPaths) {
3470
+ if (path.startsWith("apps/") && path.includes("/specs/") && path.endsWith(".md"))
3471
+ return true;
3472
+ if (!path.endsWith(".md"))
3473
+ return false;
3474
+ return specPaths.some((entry) => isUnderOrEqual(path, normalizeSpecPath(entry)));
3483
3475
  }
3484
- function looksLikeFilePath(entry) {
3485
- const stripped = entry.replace(/\/\*\*?$/, "");
3486
- const lastSegment = stripped.split("/").pop() ?? stripped;
3487
- const extMatch = /\.[A-Za-z0-9]{1,6}$/.exec(lastSegment);
3488
- return extMatch !== null && extMatch.index > 0;
3476
+ function isClaudeMdFile(path) {
3477
+ return path === "CLAUDE.md" || path.endsWith("/CLAUDE.md");
3489
3478
  }
3490
- function splitGlobList(raw) {
3491
- return raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
3479
+ function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS) {
3480
+ if (path.startsWith(shipsPrefix)) {
3481
+ return path.startsWith(shipsArchivePrefix(shipsPrefix)) ? "internal" : "ships";
3482
+ }
3483
+ if (path.startsWith(readerFacingPrefix) && path.endsWith(readerFacingSuffix)) {
3484
+ return "reader-facing";
3485
+ }
3486
+ if (isClaudeMdFile(path))
3487
+ return "internal";
3488
+ if (isSpecFile2(path, specPaths))
3489
+ return "spec";
3490
+ if (isProductScopeFile(path))
3491
+ return "product";
3492
+ return null;
3492
3493
  }
3493
- function parseIssueSurface(body) {
3494
- const section = topLevelSectionText(body, "Surface");
3495
- if (section === null)
3496
- return { ok: false, errors: ["no `## Surface` heading found in the body."] };
3497
- const inLine = /^in:\s*(.+)$/im.exec(section);
3498
- const outLine = /^out:\s*(.+)$/im.exec(section);
3499
- const errors = [];
3500
- if (!inLine)
3501
- errors.push("`## Surface` has no `in:` line.");
3502
- if (!outLine)
3503
- errors.push("`## Surface` has no `out:` line.");
3504
- if (errors.length > 0)
3505
- return { ok: false, errors };
3506
- const inGlobs = splitGlobList(inLine[1]);
3507
- const outGlobs = splitGlobList(outLine[1]);
3508
- for (const g of [...inGlobs, ...outGlobs]) {
3509
- if (looksLikeFilePath(g)) {
3510
- errors.push(`\`${g}\` in \`## Surface\` looks like a file path — Surface entries are directory-level globs, never file paths.`);
3511
- }
3494
+ var SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
3495
+ function stripNonProse(path, content) {
3496
+ if (path.endsWith(".md")) {
3497
+ return content.replace(/```.*?```/gs, (m) => m.replace(/[^\n]/g, "")).replace(/`[^`\n]*`/g, (m) => m.replace(/[^\n]/g, ""));
3512
3498
  }
3513
- if (inGlobs.length === 0)
3514
- errors.push("`## Surface`'s `in:` line resolved to zero globs.");
3515
- if (errors.length > 0)
3516
- return { ok: false, errors };
3517
- return { ok: true, value: { in: inGlobs, out: outGlobs } };
3499
+ if (path.endsWith(".tsx") || path.endsWith(".ts")) {
3500
+ return content.replace(/\/\*.*?\*\//gs, (m) => m.replace(/[^\n]/g, "")).replace(/(^|[^:])\/\/[^\n]*/g, (m) => m.replace(/[^\n]/g, ""));
3501
+ }
3502
+ return content;
3518
3503
  }
3519
- function globCoversPath(glob, path) {
3520
- const g = glob.replace(/\/\*\*?$/, "").replace(/\/+$/, "");
3521
- const p = path.replace(/\/+$/, "");
3522
- return g === p || g.startsWith(`${p}/`) || p.startsWith(`${g}/`);
3504
+ function stripNonProseForProduct(path, content) {
3505
+ return path.endsWith(".md") ? stripNonProse(path, content) : content;
3523
3506
  }
3524
- function checkSurfaceGlobsResolve(body, resolvesToFile) {
3525
- const surface = parseIssueSurface(body);
3526
- if (!surface.ok)
3527
- return { status: "pass", errors: [] };
3528
- const errors = [];
3529
- for (const glob of surface.value.in) {
3530
- if (!resolvesToFile(glob)) {
3531
- errors.push(`issue-validation Surface: \`${glob}\` in \`## Surface\`'s \`in:\` list matches no tracked file — a Surface that cannot resolve cannot render a brief's file list.`);
3532
- }
3507
+ function lineAt(content, index) {
3508
+ let line = 1;
3509
+ for (let i = 0;i < index; i++) {
3510
+ if (content.charCodeAt(i) === 10)
3511
+ line++;
3533
3512
  }
3534
- return { status: errors.length > 0 ? "fail" : "pass", errors };
3513
+ return line;
3535
3514
  }
3536
- function checkSurfaceScope(changedFiles, outGlobs) {
3537
- if (outGlobs.length === 0)
3538
- return { ok: true };
3539
- const violations = [];
3540
- for (const file of changedFiles) {
3541
- const glob = outGlobs.find((g) => globCoversPath(g, file));
3542
- if (glob)
3543
- violations.push({ file, glob });
3544
- }
3545
- return violations.length > 0 ? { ok: false, violations } : { ok: true };
3515
+ var FORGE_NUMBER_PATTERN = /#[0-9]{2,4}/g;
3516
+ var TRANCHE_SLUG_VN_PATTERN = /[a-z][a-z-]+-v[0-9]/g;
3517
+ var TASK_NUMBER_PATTERN = /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi;
3518
+ function legacySlugPattern(legacySlugs) {
3519
+ if (legacySlugs.length === 0)
3520
+ return null;
3521
+ const alternation = legacySlugs.map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
3522
+ return new RegExp(`(^|[^a-zA-Z0-9\\n-])(${alternation})([^a-zA-Z0-9\\n-]|$)`, "g");
3546
3523
  }
3547
- var ISSUE_PART_LINE_RE = /^Part\s+(\d+)\s*\(([^)]*)\)\s*[-—–]\s*(.*)$/i;
3548
- function parseIssueParts(body) {
3549
- const section = topLevelSectionText(body, "Parts");
3550
- if (section === null)
3551
- return { ok: false, errors: ["no `## Parts` heading found in the body."] };
3552
- const lines = section.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
3553
- const parts = [];
3554
- const errors = [];
3555
- for (const line of lines) {
3556
- const m = ISSUE_PART_LINE_RE.exec(line);
3557
- if (!m) {
3558
- errors.push(`"${line}" is not a well-formed Parts line — expected \`Part <n> (<refs>) — <outcome>\`.`);
3524
+ function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
3525
+ const findings = [];
3526
+ const legacyPattern = legacySlugPattern(legacySlugs);
3527
+ const grandfathered = new Set(specGrandfather);
3528
+ const patterns = [
3529
+ { pattern: FORGE_NUMBER_PATTERN, what: "a forge number" },
3530
+ { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug" },
3531
+ ...legacyPattern ? [{ pattern: legacyPattern, what: "an internal tranche slug", group: 2 }] : []
3532
+ ];
3533
+ const productPatterns = [
3534
+ { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug in product code" }
3535
+ ];
3536
+ const specPatterns = [
3537
+ ...patterns,
3538
+ { pattern: TASK_NUMBER_PATTERN, what: "a task number", group: 2 }
3539
+ ];
3540
+ for (const file of files) {
3541
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths);
3542
+ if (!cls || cls === "internal")
3559
3543
  continue;
3560
- }
3561
- const n = Number.parseInt(m[1], 10);
3562
- const refs = m[2];
3563
- const text = m[3].trim();
3564
- if (text.length === 0) {
3565
- errors.push(`Part ${n} has no outcome text after the dash — every Part states one observable outcome.`);
3544
+ if (cls !== "product" && cls !== "spec" && !SWEPT_CLASSES.has(cls))
3566
3545
  continue;
3567
- }
3568
- if (partHasBacktickedPath(text) && partWordCount(stripPartBackticks(text)) < PART_MIN_WORDS_OUTSIDE_BACKTICKS) {
3569
- errors.push(`Part ${n} is little more than a file path — a Part names an outcome and symbols, never a bare path.`);
3546
+ if (cls === "spec" && grandfathered.has(file.path))
3570
3547
  continue;
3548
+ const blocking = cls === "product" || cls === "spec";
3549
+ const scrubbed = cls === "product" ? stripNonProseForProduct(file.path, file.content) : stripNonProse(file.path, file.content);
3550
+ const patternsToRun = cls === "product" ? productPatterns : cls === "spec" ? specPatterns : patterns;
3551
+ for (const { pattern, what, group } of patternsToRun) {
3552
+ pattern.lastIndex = 0;
3553
+ let match = pattern.exec(scrubbed);
3554
+ while (match !== null) {
3555
+ const cited = group !== undefined ? match[group] ?? match[0] : match[0];
3556
+ const citedIndex = match.index + match[0].indexOf(cited);
3557
+ findings.push({
3558
+ file: file.path,
3559
+ line: lineAt(scrubbed, citedIndex),
3560
+ message: `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
3561
+ blocking
3562
+ });
3563
+ match = pattern.exec(scrubbed);
3564
+ }
3571
3565
  }
3572
- const objectiveIds = [...refs.matchAll(/O(\d+)/g)].map((r) => Number.parseInt(r[1], 10));
3573
- parts.push({ n, objectiveIds, text });
3574
3566
  }
3575
- if (parts.length === 0) {
3576
- errors.push("the `## Parts` section has no well-formed `Part <n> (<refs>) — <outcome>` lines.");
3577
- }
3578
- if (errors.length > 0)
3579
- return { ok: false, errors };
3580
- return { ok: true, value: parts };
3581
- }
3582
- function checkPartsCiteDefinedObjectives(body) {
3583
- const parts = parseIssueParts(body);
3584
- const objectives = objectivesOf(body);
3585
- if (!parts.ok || !objectives.ok)
3586
- return { status: "pass", errors: [] };
3587
- const definedIds = new Set(objectives.objectives.map((o) => Number.parseInt(o.id.slice(1), 10)));
3588
- const errors = [];
3589
- for (const part of parts.value) {
3590
- for (const objectiveId of part.objectiveIds) {
3591
- if (!definedIds.has(objectiveId)) {
3592
- errors.push(`issue-validation Parts: Part ${part.n} cites O${objectiveId}, which the Issue's own \`## Objectives\` section does not define.`);
3593
- }
3594
- }
3595
- }
3596
- return { status: errors.length > 0 ? "fail" : "pass", errors };
3597
- }
3598
- function isTaskIssueLabelSet(labels) {
3599
- return hasLabel("tranche", labels);
3600
- }
3601
- function checkTrancheLabelPresence(_body, _labels) {
3602
- return { status: "pass", errors: [] };
3603
- }
3604
- function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTitle) {
3605
- if (!isTaskIssueLabelSet(labels))
3606
- return { status: "pass", errors: [] };
3607
- if (resolvedMilestoneTitle === null)
3608
- return { status: "pass", errors: [] };
3609
- if (currentMilestoneTitle === resolvedMilestoneTitle)
3610
- return { status: "pass", errors: [] };
3611
- return {
3612
- status: "fail",
3613
- errors: [
3614
- `issue-validation milestone attach: this task Issue's tranche label resolves to Milestone "${resolvedMilestoneTitle}", but its live Milestone is ${currentMilestoneTitle === null ? "unset" : `"${currentMilestoneTitle}"`} — attach it to "${resolvedMilestoneTitle}".`
3615
- ]
3616
- };
3617
- }
3618
- var TYPE_LABEL_IDS = LABELS.filter((l) => l.category === "type").map((l) => l.id);
3619
- function isControlCodePoint(codePoint) {
3620
- return codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
3621
- }
3622
- function isDisplayControlCodePoint(codePoint) {
3623
- return codePoint >= 8203 && codePoint <= 8207 || codePoint >= 8234 && codePoint <= 8238 || codePoint >= 8294 && codePoint <= 8297 || codePoint === 65279;
3567
+ return findings;
3624
3568
  }
3625
- var MESSAGE_VALUE_COUNT_MAX = 5;
3626
- function residueForMessage(values) {
3627
- const shown = values.slice(0, MESSAGE_VALUE_COUNT_MAX).map((v) => `\`${forMessage(v)}\``);
3628
- const rest = values.length - shown.length;
3629
- return rest > 0 ? `${shown.join(", ")} and ${rest} more` : shown.join(", ");
3569
+ function escapeTerm(term) {
3570
+ return term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3630
3571
  }
3631
- var MESSAGE_VALUE_MAX = 64;
3632
- function forMessage(value) {
3633
- const kept = [];
3634
- for (const ch of value.replace(/\s+/g, " ")) {
3635
- const codePoint = ch.codePointAt(0) ?? 0;
3636
- if (isControlCodePoint(codePoint) || isDisplayControlCodePoint(codePoint))
3637
- continue;
3638
- kept.push(ch);
3639
- }
3640
- const cleaned = kept.join("").trim();
3641
- if (cleaned.length === 0)
3642
- return "(unprintable)";
3643
- const points = Array.from(cleaned);
3644
- return points.length > MESSAGE_VALUE_MAX ? `${points.slice(0, MESSAGE_VALUE_MAX).join("")}…` : cleaned;
3572
+ function containsWholeWord(text, term) {
3573
+ const escaped = escapeTerm(term);
3574
+ const re = new RegExp(`(^|[^a-zA-Z])${escaped}([^a-zA-Z]|$)`, "i");
3575
+ return re.test(text);
3645
3576
  }
3646
- function checkProjectsRegistered(body, _labels, registeredNames) {
3647
- if (registeredNames.length === 0)
3648
- return { status: "pass", errors: [] };
3649
- const field = projectFieldFromBody(body);
3650
- if (!field.declared)
3651
- return { status: "pass", errors: [] };
3652
- const known = new Set(registeredNames.map((n) => n.trim()));
3653
- const registeredList = [...registeredNames].map(forMessage).join(", ");
3654
- const errors = [];
3655
- if (field.unreadable) {
3656
- return {
3657
- status: "fail",
3658
- errors: [
3659
- `issue-validation project registry: the body has an unterminated code fence, so its \`**Project:**\` field could not be read reliably — the fence runs to end of body (CommonMark, and how the forge renders it), swallowing everything after it including the foot field where the declaration lives by convention. Read from the raw body the field says ${residueForMessage(field.unparsed) || "(nothing)"}, but a line inside a swallowed region may be a quoted example rather than a real declaration, so this gate refuses rather than guessing which. Balance the fences — every opening run of backticks or tildes needs a closing run at least as long — and the field reads normally.`
3660
- ]
3661
- };
3662
- }
3663
- const unregistered = field.names.filter((p) => !known.has(p));
3664
- if (unregistered.length > 0) {
3665
- const caseHints = unregistered.map((p) => {
3666
- const row = [...known].find((k) => k.toLowerCase() === p.toLowerCase());
3667
- return row ? `\`${forMessage(p)}\` differs from the registered \`${forMessage(row)}\` only in case` : null;
3668
- }).filter((h) => h !== null);
3669
- errors.push(`issue-validation project registry: the \`**Project:**\` field declares ${unregistered.map(forMessage).join(", ")} — no such row in \`.vinaya/projects.md\`, which is the authority for valid project names (registered: ${registeredList}). Fix the name, or register the project with \`vinaya init product <name> --path <folder>\` first; an unregistered project has no specs to read and no per-project state to update.${caseHints.length > 0 ? ` Note: ${caseHints.join("; ")} — project names are matched exactly, because every downstream consumer compares them literally.` : ""} This reads the same field \`projectsFromBody\` derives the task's project from, so a name here that is not a row is a task that resolves to a project that does not exist.`);
3670
- }
3671
- if (field.names.length === 0) {
3672
- const residue = field.unparsed.length > 0 ? ` — ${residueForMessage(field.unparsed)}` : " — the field is empty";
3673
- errors.push(`issue-validation project registry: the \`**Project:**\` field is present but resolves to no project name${residue} (registered: ${registeredList}). A project name is a slug (\`[a-z0-9][a-z0-9-]*\`, matched exactly); prose, a parenthetical, or a sentence in this field resolves to no project at all, and this gate cannot check a name it never receives — which is how a declaration like this used to pass. Write the registered name on its own, or register the project with \`vinaya init product <name> --path <folder>\` first. If the task genuinely touches no registered project, omit the field rather than explaining its absence inside it — \`checkIssueRationale\` already requires the \`Project(s) + blast radius\` narrative field for that.`);
3674
- } else if (field.unparsed.length > 0) {
3675
- errors.push(`issue-validation project registry: the \`**Project:**\` field declares a value that is not a project name — ${residueForMessage(field.unparsed)} (registered: ${registeredList}). The rest of the field parsed, so this is a name the gate silently could not check rather than a field it could not read at all. A project name is a slug (\`[a-z0-9][a-z0-9-]*\`, matched exactly); write it on its own, or drop it if it names no project.`);
3577
+ function findWholeWordLine(content, term) {
3578
+ const lines = content.split(`
3579
+ `);
3580
+ let lineNo = 0;
3581
+ for (const line of lines) {
3582
+ lineNo++;
3583
+ if (containsWholeWord(line, term))
3584
+ return lineNo;
3676
3585
  }
3677
- return errors.length > 0 ? { status: "fail", errors } : { status: "pass", errors: [] };
3678
- }
3679
- var DOC_PATH_RE = /(?:(?:aeg-root|apps|packages|specs|docs|tools|\.claude|\.github)\/[\w./@-]*\.(?:md|mdx)|\.claude\/(?:skills|rules)\/[\w./-]+|\b(?:docs-index|decisions|projects|state-machine|enforcement|process|README|CLAUDE)\.md\b|\b[\w-]+-(?:spec|decisions|backlog)\.md\b)/i;
3680
- var DOC_PATH_RE_GLOBAL = new RegExp(DOC_PATH_RE.source, "gi");
3681
-
3682
- // ../../packages/aeg-core/src/task-branch-identity.ts
3683
- var ISSUE_BRANCH_PATTERN = /^task\/issue-(\d+)$/;
3684
- var TRANCHE_BRANCH_PATTERN = /^task\/([^/]+)\/([^/]+)$/;
3685
- function parseTaskBranchIdentity(branch) {
3686
- const issueMatch = ISSUE_BRANCH_PATTERN.exec(branch);
3687
- if (issueMatch)
3688
- return { kind: "issue", issueNumber: Number(issueMatch[1]) };
3689
- const trancheMatch = TRANCHE_BRANCH_PATTERN.exec(branch);
3690
- if (trancheMatch)
3691
- return { kind: "tranche", tranche: trancheMatch[1], taskId: trancheMatch[2] };
3692
3586
  return null;
3693
3587
  }
3694
-
3695
- // ../../packages/aeg-core/src/coherence-checks.ts
3696
- var COHERENCE_ENFORCED_FROM = "2026-07-01";
3697
- function isGrandfathered(isoDate) {
3698
- if (!isoDate)
3699
- return false;
3700
- return isoDate.slice(0, 10) < COHERENCE_ENFORCED_FROM;
3588
+ function definesOrLinksGlossary(content, term) {
3589
+ const escaped = escapeTerm(term);
3590
+ const definesInline = new RegExp(`(^|[^a-zA-Z])${escaped}([^a-zA-Z]|$)[^\\n]{0,3}—`, "i").test(content);
3591
+ if (definesInline)
3592
+ return true;
3593
+ return /docs\/glossary|glossary\.md/i.test(content);
3701
3594
  }
3702
- var R1_GRANDFATHERED_ISSUES = new Set([279, 280, 281, 282]);
3703
- function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
3704
- const failures = [];
3705
- for (const e of entries) {
3706
- if (!e.facts)
3707
- continue;
3708
- if (e.facts.stateReason === "not_planned")
3595
+ function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX) {
3596
+ const findings = [];
3597
+ for (const file of files) {
3598
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
3599
+ if (!cls || !SWEPT_CLASSES.has(cls))
3709
3600
  continue;
3710
- if (e.facts.issueState === "closed" && e.facts.prState !== "merged") {
3711
- const handClosed = e.facts.stateReason === "completed" && isPrincipal(e.facts.closedByActor, principalAllowlist);
3712
- if (handClosed)
3601
+ const scrubbed = stripNonProse(file.path, file.content);
3602
+ for (const term of glossaryTerms) {
3603
+ const line = findWholeWordLine(scrubbed, term);
3604
+ if (line === null)
3713
3605
  continue;
3714
- failures.push({
3715
- code: "closed-without-merge",
3716
- issue: e.task.issue,
3717
- tranche: e.trancheSlug,
3718
- task: e.task.id,
3719
- reason: `Issue closed but closing PR is not merged (prState: ${e.facts.prState})`,
3720
- grandfathered: isGrandfathered(e.facts.closedAt)
3606
+ if (definesOrLinksGlossary(scrubbed, term))
3607
+ continue;
3608
+ findings.push({
3609
+ file: file.path,
3610
+ line,
3611
+ message: `uses coined term "${term}" without defining it inline or linking the glossary`,
3612
+ blocking: false
3721
3613
  });
3722
3614
  }
3723
3615
  }
3724
- const activeFails = failures.filter((f) => !f.grandfathered);
3725
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3726
- return {
3727
- check: "A1",
3728
- status,
3729
- failures,
3730
- note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
3731
- };
3616
+ return findings;
3732
3617
  }
3733
- function checkA3(entries) {
3734
- const failures = [];
3735
- for (const e of entries) {
3736
- if (!e.facts)
3618
+ var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g;
3619
+ var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = /#[0-9]{2,}/g;
3620
+ function extractComments(path, content) {
3621
+ if (!path.endsWith(".ts") && !path.endsWith(".tsx"))
3622
+ return content.replace(/[^\n]/g, "");
3623
+ let state = "code";
3624
+ let out = "";
3625
+ const n = content.length;
3626
+ let i = 0;
3627
+ const blank = (ch) => ch === `
3628
+ ` ? `
3629
+ ` : " ";
3630
+ while (i < n) {
3631
+ const c = content[i];
3632
+ const next = i + 1 < n ? content[i + 1] : "";
3633
+ if (state === "code") {
3634
+ if (c === "/" && next === "/") {
3635
+ state = "line-comment";
3636
+ out += c;
3637
+ i++;
3638
+ continue;
3639
+ }
3640
+ if (c === "/" && next === "*") {
3641
+ state = "block-comment";
3642
+ out += c;
3643
+ i++;
3644
+ continue;
3645
+ }
3646
+ if (c === "'") {
3647
+ state = "single-quote";
3648
+ out += blank(c);
3649
+ i++;
3650
+ continue;
3651
+ }
3652
+ if (c === '"') {
3653
+ state = "double-quote";
3654
+ out += blank(c);
3655
+ i++;
3656
+ continue;
3657
+ }
3658
+ if (c === "`") {
3659
+ state = "template";
3660
+ out += blank(c);
3661
+ i++;
3662
+ continue;
3663
+ }
3664
+ out += blank(c);
3665
+ i++;
3737
3666
  continue;
3738
- if (e.facts.prState === "merged" && e.facts.issueState !== "closed") {
3739
- failures.push({
3740
- code: "auto-close-misfire",
3741
- issue: e.task.issue,
3742
- tranche: e.trancheSlug,
3743
- task: e.task.id,
3744
- reason: "Closing PR is merged but Issue is still open (GitHub auto-close misfire)",
3745
- grandfathered: isGrandfathered(e.facts.mergedAt)
3746
- });
3747
3667
  }
3748
- }
3749
- const activeFails = failures.filter((f) => !f.grandfathered);
3750
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3751
- return {
3752
- check: "A3",
3753
- status,
3754
- failures,
3755
- note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
3756
- };
3757
- }
3758
- function checkT1(entries) {
3759
- const failures = [];
3760
- for (const e of entries) {
3761
- if (e.task.issue === null)
3668
+ if (state === "line-comment") {
3669
+ if (c === `
3670
+ `) {
3671
+ state = "code";
3672
+ out += `
3673
+ `;
3674
+ i++;
3675
+ continue;
3676
+ }
3677
+ out += c;
3678
+ i++;
3762
3679
  continue;
3763
- if (e.facts === undefined) {
3764
- failures.push({
3765
- code: "phantom-issue-ref",
3766
- issue: e.task.issue,
3767
- tranche: e.trancheSlug,
3768
- task: e.task.id,
3769
- reason: `Issue #${e.task.issue} in topology does not resolve to a real GitHub Issue`
3770
- });
3771
3680
  }
3772
- }
3773
- return { check: "T1", status: failures.length > 0 ? "fail" : "pass", failures };
3774
- }
3775
- function checkT2(openIssuesBySlug, topologyIssuesBySlug, ciTrancheSlug) {
3776
- const failures = [];
3777
- for (const [slug, openNums] of openIssuesBySlug) {
3778
- if (ciTrancheSlug && slug !== ciTrancheSlug)
3779
- continue;
3780
- const topologySet = topologyIssuesBySlug.get(slug) ?? new Set;
3781
- for (const num of openNums) {
3782
- if (!topologySet.has(num)) {
3783
- failures.push({
3784
- code: "orphan-task",
3785
- issue: num,
3786
- tranche: slug,
3787
- reason: `Issue #${num} is open and labeled ${trancheLabel(slug)} but does not appear in the topology file`
3788
- });
3681
+ if (state === "block-comment") {
3682
+ if (c === "*" && next === "/") {
3683
+ out += c;
3684
+ out += next;
3685
+ state = "code";
3686
+ i += 2;
3687
+ continue;
3789
3688
  }
3689
+ out += c === `
3690
+ ` ? `
3691
+ ` : c;
3692
+ i++;
3693
+ continue;
3790
3694
  }
3791
- }
3792
- return { check: "T2", status: failures.length > 0 ? "fail" : "pass", failures };
3793
- }
3794
- function scopeT2ToPlanPr(result, isPlanPr) {
3795
- if (isPlanPr || result.status !== "fail")
3796
- return result;
3797
- return {
3798
- ...result,
3799
- status: "info",
3800
- note: result.note ?? "T2 findings are non-blocking outside plan PRs (point-of-power principle) — see aeg-root/enforcement.md."
3801
- };
3802
- }
3803
- function checkT3(entries, ciTrancheSlug, enrichedEntries, forgeUnavailableSlugs) {
3804
- const preEnforcement = new Set;
3805
- if (enrichedEntries) {
3806
- for (const e of enrichedEntries) {
3807
- if (isGrandfathered(e.facts?.closedAt) || isGrandfathered(e.facts?.mergedAt)) {
3808
- preEnforcement.add(e.trancheSlug);
3695
+ const closer = state === "single-quote" ? "'" : state === "double-quote" ? '"' : "`";
3696
+ if (c === "\\") {
3697
+ out += blank(c);
3698
+ i++;
3699
+ if (i < n) {
3700
+ out += blank(content[i]);
3701
+ i++;
3809
3702
  }
3703
+ continue;
3810
3704
  }
3811
- }
3812
- const failures = [];
3813
- for (const e of entries) {
3814
- if (!e.archived && e.task.issue === null) {
3815
- if (ciTrancheSlug && e.trancheSlug !== ciTrancheSlug)
3816
- continue;
3817
- if (forgeUnavailableSlugs?.has(e.trancheSlug)) {
3818
- failures.push({
3819
- code: "tbd-in-active-tranche",
3820
- issue: null,
3821
- tranche: e.trancheSlug,
3822
- task: e.task.id,
3823
- reason: `Task ${e.task.id} in active tranche has no Issue ref (#TBD or empty), but forge data for tranche "${e.trancheSlug}" was unavailable — cannot evaluate grandfather status, not silently failed`,
3824
- grandfathered: true
3825
- });
3826
- continue;
3827
- }
3828
- failures.push({
3829
- code: "tbd-in-active-tranche",
3830
- issue: null,
3831
- tranche: e.trancheSlug,
3832
- task: e.task.id,
3833
- reason: `Task ${e.task.id} in active tranche has no Issue ref (#TBD or empty) — the model requires all active tasks to have Issue numbers`,
3834
- grandfathered: preEnforcement.has(e.trancheSlug)
3835
- });
3705
+ if (c === closer) {
3706
+ state = "code";
3707
+ out += blank(c);
3708
+ i++;
3709
+ continue;
3836
3710
  }
3711
+ out += blank(c);
3712
+ i++;
3837
3713
  }
3838
- const activeFails = failures.filter((f) => !f.grandfathered);
3839
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3840
- return {
3841
- check: "T3",
3842
- status,
3843
- failures,
3844
- note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
3845
- };
3714
+ return out;
3846
3715
  }
3847
- function checkD1(entries, issueToEntry, taskToEntry) {
3848
- const failures = [];
3849
- for (const e of entries) {
3850
- if (!e.facts)
3716
+ function checkSourceComments(files, allowlist = []) {
3717
+ const findings = [];
3718
+ const allowed = new Set(allowlist);
3719
+ const patterns = [
3720
+ { pattern: SOURCE_COMMENT_TRANCHE_SLUG_PATTERN, what: "a tranche-slug citation" },
3721
+ { pattern: SOURCE_COMMENT_FORGE_NUMBER_PATTERN, what: "a forge-number citation" }
3722
+ ];
3723
+ for (const file of files) {
3724
+ if (!file.path.endsWith(".ts"))
3851
3725
  continue;
3852
- if (e.facts.prState !== "open")
3726
+ if (allowed.has(file.path))
3853
3727
  continue;
3854
- for (const dep of e.task.dependsOn) {
3855
- const depEntry = resolveDepEntry(dep, e.trancheSlug, issueToEntry, taskToEntry);
3856
- if (!depEntry)
3857
- continue;
3858
- const sameTask = depEntry.trancheSlug === e.trancheSlug && depEntry.task.id === e.task.id;
3859
- const sameIssue = depEntry.task.issue !== null && e.task.issue !== null && depEntry.task.issue === e.task.issue;
3860
- if (sameTask || sameIssue) {
3861
- failures.push({
3862
- code: "d1-self-dependency",
3863
- issue: e.task.issue,
3864
- tranche: e.trancheSlug,
3865
- task: e.task.id,
3866
- reason: `INTERNAL: parsed a self-dependency (depends-on ${dep}) — this is a parser bug in parseRationaleDeps, not a real dependency. Please report it upstream.`
3867
- });
3868
- continue;
3869
- }
3870
- const depFacts = depEntry.facts;
3871
- const depClosed = depFacts?.issueState === "closed";
3872
- if (!depClosed) {
3873
- failures.push({
3874
- code: "dispatched-on-unmet-deps",
3875
- issue: e.task.issue,
3876
- tranche: e.trancheSlug,
3877
- task: e.task.id,
3878
- reason: `Task has open PR but depends-on ${dep} (issue #${depEntry.task.issue ?? "?"}) is not closed`
3728
+ const comments = extractComments(file.path, file.content);
3729
+ for (const { pattern, what } of patterns) {
3730
+ pattern.lastIndex = 0;
3731
+ let match = pattern.exec(comments);
3732
+ while (match !== null) {
3733
+ findings.push({
3734
+ file: file.path,
3735
+ line: lineAt(comments, match.index),
3736
+ message: `comment cites ${what} ("${match[0]}") a reader outside this repo's tracker cannot resolve`,
3737
+ blocking: false
3879
3738
  });
3739
+ match = pattern.exec(comments);
3880
3740
  }
3881
3741
  }
3882
3742
  }
3883
- return { check: "D1", status: failures.length > 0 ? "fail" : "pass", failures };
3743
+ return findings;
3884
3744
  }
3885
- function resolveDepEntry(dep, trancheSlug, issueToEntry, taskToEntry) {
3886
- const issueMatch = dep.match(/^#(\d+)$/);
3887
- if (issueMatch?.[1])
3888
- return issueToEntry.get(Number(issueMatch[1]));
3889
- return taskToEntry.get(`${trancheSlug}/${dep}`) ?? taskToEntry.get(dep);
3745
+ function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
3746
+ return [
3747
+ ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths),
3748
+ ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix)
3749
+ ];
3890
3750
  }
3891
- function checkR1(issuesBySlug, grandfatheredIssues, registeredNames = [], objectivesSinceIssue) {
3892
- const failures = [];
3893
- for (const [slug, issues] of issuesBySlug) {
3894
- for (const issue of issues) {
3895
- if (!isTaskIssueLabelSet(issue.labels))
3896
- continue;
3897
- const errors = [
3898
- ...checkIssueRationale(issue.body).errors,
3899
- ...checkProjectsRegistered(issue.body, issue.labels, registeredNames).errors,
3900
- ...checkIssueObjectives(issue.body, issue.number, objectivesSinceIssue).errors,
3901
- ...checkPartsCiteDefinedObjectives(issue.body).errors
3902
- ];
3903
- if (errors.length === 0)
3904
- continue;
3905
- failures.push({
3906
- code: "missing-rationale-field",
3907
- issue: issue.number,
3908
- tranche: slug,
3909
- reason: `Issue #${issue.number} fails the rationale gate: ${errors.join(" | ")}`,
3910
- grandfathered: grandfatheredIssues.has(issue.number)
3911
- });
3912
- }
3751
+ function parseGlossaryTerms(glossaryContent) {
3752
+ const terms = [];
3753
+ const re = /^\*\*(.+?)\*\* —/gm;
3754
+ let match = re.exec(glossaryContent);
3755
+ while (match !== null) {
3756
+ if (match[1] !== undefined)
3757
+ terms.push(match[1]);
3758
+ match = re.exec(glossaryContent);
3913
3759
  }
3914
- const activeFails = failures.filter((f) => !f.grandfathered);
3915
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3916
- return {
3917
- check: "R1",
3918
- status,
3919
- failures,
3920
- note: status === "info" ? `${failures.length} grandfathered task Issue(s) predate this check's grammar (rationale fields and/or the project registry)` : undefined
3921
- };
3760
+ return terms;
3922
3761
  }
3923
- function checkL1(files, entriesBySlug) {
3924
- const failures = [];
3925
- for (const f of files) {
3926
- if (f.archived)
3927
- continue;
3928
- const entries = entriesBySlug.get(f.slug) ?? [];
3929
- const withFacts = entries.filter((e) => e.facts !== undefined);
3930
- if (withFacts.length === 0)
3931
- continue;
3932
- const allClosed = withFacts.every((e) => e.facts?.issueState === "closed");
3933
- if (allClosed) {
3934
- failures.push({
3935
- code: "archive-recommended",
3936
- tranche: f.slug,
3937
- reason: "Active tranche has no open task-Issues — consider archiving to completed/"
3938
- });
3939
- }
3940
- }
3941
- return {
3942
- check: "L1",
3943
- status: "info",
3944
- failures,
3945
- note: failures.length > 0 ? `${failures.length} active tranche(s) with no open task-Issues — consider archiving (advisory)` : undefined
3946
- };
3762
+
3763
+ // ../../packages/aeg-core/src/quoted-command.ts
3764
+ var QUOTED_COMMAND_SHIPS_PREFIX = "aeg-root/";
3765
+ var QUOTED_COMMAND_SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
3766
+ var START_PATTERN = /<!--\s*AEG:QUOTES-FILE:START:(\S+?)\s*-->/g;
3767
+ var END_PATTERN = /<!--\s*AEG:QUOTES-FILE:END\s*-->/;
3768
+ function isValidCitedFilePath(path) {
3769
+ if (path.length === 0)
3770
+ return false;
3771
+ if (path.startsWith("/") || path.startsWith("\\"))
3772
+ return false;
3773
+ if (/^[A-Za-z]:[\\/]/.test(path))
3774
+ return false;
3775
+ return !path.split(/[\\/]+/).includes("..");
3947
3776
  }
3948
- function checkL3(files) {
3949
- const active = files.filter((f) => !f.archived);
3950
- return {
3951
- check: "L3",
3952
- status: "info",
3953
- failures: [],
3954
- note: `${active.length} active tranche(s): ${active.map((f) => f.slug).join(", ") || "(none)"}`
3955
- };
3956
- }
3957
- function extractClosesReferences(prBody) {
3958
- const closesPattern = /(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s{0,8}:?\s{0,8}#(\d+)/gi;
3959
- const stripped = stripCode(prBody);
3960
- const searchIn = anchoredRegion(stripped, "CLOSES") ?? stripped;
3961
- const referenced = new Set;
3962
- for (const hit of searchIn.matchAll(closesPattern)) {
3963
- referenced.add(Number(hit[1]));
3777
+ function quotedCommandLineAt(content, index) {
3778
+ let line = 1;
3779
+ for (let i = 0;i < index; i++) {
3780
+ if (content.charCodeAt(i) === 10)
3781
+ line++;
3964
3782
  }
3965
- return referenced;
3783
+ return line;
3966
3784
  }
3967
- function checkClosesNTopology(branch, prBody, trancheFiles, taskIssueRefs) {
3968
- const referenced = extractClosesReferences(prBody);
3969
- if (taskIssueRefs) {
3970
- for (const n of referenced) {
3971
- const ref = taskIssueRefs.get(n);
3972
- if (!ref)
3973
- continue;
3974
- const expectedBranch = `task/${ref.trancheSlug}/${ref.taskId}`;
3975
- if (branch !== expectedBranch) {
3976
- return {
3977
- ok: false,
3978
- message: `closes-n-reverse: branch "${branch}" closes #${n} (task ${ref.taskId} of tranche "${ref.trancheSlug}") but is not named "${expectedBranch}" — rename the branch and re-push, or if this work is intentionally outside AEG's dispatch flow, remove the Closes reference.`
3979
- };
3980
- }
3785
+ function extractQuotedText(raw) {
3786
+ const trimmed = raw.trim();
3787
+ const fenced = /^(?:`{3,}|~{3,})[^\n]*\n([\s\S]*?)\n?(?:`{3,}|~{3,})$/.exec(trimmed);
3788
+ if (fenced)
3789
+ return (fenced[1] ?? "").trim();
3790
+ const inline = /^`([^`]+)`$/.exec(trimmed);
3791
+ if (inline)
3792
+ return (inline[1] ?? "").trim();
3793
+ return trimmed;
3794
+ }
3795
+ function findQuotesInFile(path, content) {
3796
+ const masked = maskCode(content);
3797
+ const quotes = [];
3798
+ START_PATTERN.lastIndex = 0;
3799
+ let start = START_PATTERN.exec(masked);
3800
+ while (start !== null) {
3801
+ const citedFile = start[1];
3802
+ const innerStart = start.index + start[0].length;
3803
+ const end = END_PATTERN.exec(masked.slice(innerStart));
3804
+ if (end === null) {
3805
+ START_PATTERN.lastIndex = innerStart;
3806
+ start = START_PATTERN.exec(masked);
3807
+ continue;
3981
3808
  }
3982
- }
3983
- const ref = parseTaskBranchIdentity(branch);
3984
- if (!ref)
3985
- return { ok: true };
3986
- if (ref.kind === "issue") {
3987
- const expectedIssue = ref.issueNumber;
3988
- if (!referenced.has(expectedIssue)) {
3989
- return {
3990
- ok: false,
3991
- expectedIssue,
3992
- message: `closes-n: PR body does not contain \`Closes #${expectedIssue}\` (required for branch "${branch}"). Add it to the PR body Summary section.`
3993
- };
3809
+ const innerEnd = innerStart + end.index;
3810
+ if (isValidCitedFilePath(citedFile)) {
3811
+ const quotedText = extractQuotedText(content.slice(innerStart, innerEnd));
3812
+ if (quotedText.length > 0) {
3813
+ quotes.push({ file: path, line: quotedCommandLineAt(content, innerStart), quotedText, citedFile });
3814
+ }
3994
3815
  }
3995
- return { ok: true, expectedIssue };
3996
- }
3997
- const trancheSlug = ref.tranche;
3998
- const taskId = ref.taskId;
3999
- const trancheFile = trancheFiles.find((f) => f.slug === trancheSlug);
4000
- if (!trancheFile) {
4001
- return {
4002
- ok: false,
4003
- message: `closes-n: branch "${branch}" references tranche "${trancheSlug}" but no topology file found at aeg-root/tranches/${trancheSlug}.md. Ensure the tranche file exists before opening the PR.`
4004
- };
4005
- }
4006
- const task = trancheFile.tranche.tasks.find((t) => t.id === taskId);
4007
- if (!task) {
4008
- return {
4009
- ok: false,
4010
- message: `closes-n: branch "${branch}" references task "${taskId}" not found in ${trancheSlug} topology. Verify the task ID matches the tranche file.`
4011
- };
3816
+ START_PATTERN.lastIndex = innerEnd + end[0].length;
3817
+ start = START_PATTERN.exec(masked);
4012
3818
  }
4013
- if (task.issue === null) {
4014
- return {
4015
- ok: false,
4016
- message: `closes-n: task "${taskId}" in "${trancheSlug}" has no Issue number (#TBD). The Planner must cut the Issue before this PR can be validated.`
4017
- };
3819
+ return quotes;
3820
+ }
3821
+ function findCitedQuotes(files, readerFacingPrefix, readerFacingSuffix, shipsPrefix = QUOTED_COMMAND_SHIPS_PREFIX) {
3822
+ const quotes = [];
3823
+ for (const file of files) {
3824
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
3825
+ if (!cls || !QUOTED_COMMAND_SWEPT_CLASSES.has(cls))
3826
+ continue;
3827
+ quotes.push(...findQuotesInFile(file.path, file.content));
4018
3828
  }
4019
- const expectedIssue = task.issue;
4020
- if (!referenced.has(expectedIssue)) {
4021
- return {
4022
- ok: false,
4023
- expectedIssue,
4024
- message: `closes-n: PR body does not contain \`Closes #${expectedIssue}\` (required for task "${taskId}" in tranche "${trancheSlug}"). Add it to the PR body Summary section.`
4025
- };
3829
+ return quotes;
3830
+ }
3831
+ function evaluateCitedQuotes(citedQuotes, citedFileContents) {
3832
+ const findings = [];
3833
+ for (const quote of citedQuotes) {
3834
+ const content = citedFileContents.get(quote.citedFile);
3835
+ if (content === undefined) {
3836
+ findings.push({
3837
+ file: quote.file,
3838
+ line: quote.line,
3839
+ citedFile: quote.citedFile,
3840
+ quotedText: quote.quotedText,
3841
+ message: `${quote.file}:${quote.line} quotes "${quote.quotedText}" as citing \`${quote.citedFile}\`, but that file could not be read`
3842
+ });
3843
+ continue;
3844
+ }
3845
+ if (!content.includes(quote.quotedText)) {
3846
+ findings.push({
3847
+ file: quote.file,
3848
+ line: quote.line,
3849
+ citedFile: quote.citedFile,
3850
+ quotedText: quote.quotedText,
3851
+ message: `${quote.file}:${quote.line} quotes "${quote.quotedText}" as citing \`${quote.citedFile}\`, but \`${quote.citedFile}\` no longer contains that text verbatim`
3852
+ });
3853
+ }
4026
3854
  }
4027
- return { ok: true, expectedIssue };
3855
+ return findings;
4028
3856
  }
4029
- // ../../packages/aeg-core/src/archive-task.ts
4030
- function closesRefs(text) {
4031
- return [...new Set([...text.matchAll(/Closes #(\d+)/gi)].map((m) => Number(m[1])))];
3857
+
3858
+ // ../../packages/aeg-core/src/issue-validation.ts
3859
+ function hasRationaleField(body, labelPattern) {
3860
+ const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})`, "im");
3861
+ return re.test(body);
4032
3862
  }
4033
- function extractIssue(body) {
4034
- const stripped = stripCode(body);
4035
- const bodyNums = closesRefs(stripped);
4036
- const anchored = anchoredRegion(stripped, "CLOSES");
4037
- if (anchored !== null) {
4038
- const anchorNums = closesRefs(anchored);
4039
- if (anchorNums.length === 0)
4040
- return { issue: null, extraIssues: bodyNums, outsideHeader: false };
4041
- const issue = anchorNums[0];
4042
- return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: false };
3863
+ var RATIONALE_FIELDS = [
3864
+ { name: "Boundary", pattern: "Boundary" },
3865
+ { name: "Sizing", pattern: "Sizing" },
3866
+ { name: "Project(s) + blast radius", pattern: "Project\\(s\\)|Project(?:s)?\\s*\\+|blast radius" },
3867
+ { name: "Dependency rationale", pattern: "Dependency rationale|Depends[- ]on" },
3868
+ { name: "Traps to avoid", pattern: "Traps" },
3869
+ { name: "Suggested agent-class", pattern: "(?:Suggested\\s+)?agent-class" },
3870
+ { name: "Stop-and-escalate", pattern: "Stop-and-escalate" },
3871
+ { name: "Docs to keep coherent", pattern: "Docs to keep coherent|§7" }
3872
+ ];
3873
+ var DEPENDENCY_RATIONALE_FIELD_NAME = "Dependency rationale";
3874
+ function checkIssueRationale(body) {
3875
+ const errors = [];
3876
+ for (const f of RATIONALE_FIELDS) {
3877
+ if (!hasRationaleField(body, f.pattern)) {
3878
+ errors.push(`issue-validation ${f.name}: rationale field not found in the Issue body — every task Issue carries the full Planner's rationale (aeg-root/contracts/planner-brief.md).`);
3879
+ continue;
3880
+ }
3881
+ if (f.name === DEPENDENCY_RATIONALE_FIELD_NAME && !SECTION_HEADER.test(body)) {
3882
+ errors.push(`issue-validation ${f.name}: rationale field found, but not in the form amend-deps requires — ` + "write `**Dependency rationale** — …`, not `**Dependency rationale:** …`. " + "`amendRationaleDeps` (the only sanctioned way to edit Depends-on/Conflicts-with) locates this " + "section by the exact anchor `**Dependency rationale**`; a colon inside the bold breaks that match " + "and the Issue becomes unamendable.");
3883
+ }
4043
3884
  }
4044
- const headerNums = closesRefs(headerRegion(stripped));
4045
- if (bodyNums.length === 0)
4046
- return { issue: null, extraIssues: [], outsideHeader: false };
4047
- const issue = headerNums.length > 0 ? headerNums[0] : bodyNums[0];
4048
- return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: headerNums.length === 0 };
3885
+ return { status: errors.length > 0 ? "fail" : "pass", errors };
4049
3886
  }
4050
- // ../../packages/aeg-core/src/review-input-manifest.ts
4051
- import { createHash as createHash4 } from "node:crypto";
4052
- function briefHash(brief) {
4053
- return createHash4("sha256").update(`${brief}
4054
- `).digest("hex");
3887
+ var OBJECTIVES_SINCE_ISSUE = 404;
3888
+ function checkIssueObjectives(body, issueNumber, sinceIssue = OBJECTIVES_SINCE_ISSUE) {
3889
+ if (sinceIssue !== null && issueNumber !== null && issueNumber < sinceIssue)
3890
+ return { status: "pass", errors: [] };
3891
+ const result = objectivesOf(body);
3892
+ if (result.ok)
3893
+ return { status: "pass", errors: [] };
3894
+ return { status: "fail", errors: result.errors.map((e) => `issue-validation objectives: ${e}`) };
4055
3895
  }
4056
- function policyDigest(policy) {
4057
- return createHash4("sha256").update(JSON.stringify({
4058
- codeReviewThreshold: policy.codeReviewThreshold,
4059
- securityThreshold: policy.securityThreshold,
4060
- maxRounds: policy.maxRounds
4061
- })).digest("hex");
3896
+ function topLevelSectionText(body, headingName) {
3897
+ const headingRe = new RegExp(`^##[ \\t]*${headingName}[ \\t]*$`, "im");
3898
+ const heading = headingRe.exec(body);
3899
+ if (!heading)
3900
+ return null;
3901
+ const afterHeading = body.slice(heading.index + heading[0].length);
3902
+ const next = /^##[ \t]/m.exec(afterHeading);
3903
+ return next ? afterHeading.slice(0, next.index) : afterHeading;
4062
3904
  }
4063
- function isBoundToHead(echoed, headSha) {
4064
- if (!echoed.headSha)
4065
- return false;
4066
- return headSha.toLowerCase().startsWith(echoed.headSha.toLowerCase());
3905
+ function partHasBacktickedPath(text) {
3906
+ let i = 0;
3907
+ while (i < text.length) {
3908
+ const start = text.indexOf("`", i);
3909
+ if (start === -1)
3910
+ return false;
3911
+ const end = text.indexOf("`", start + 1);
3912
+ if (end === -1)
3913
+ return false;
3914
+ if (text.slice(start + 1, end).includes("/"))
3915
+ return true;
3916
+ i = end + 1;
3917
+ }
3918
+ return false;
4067
3919
  }
4068
- function isBoundByPatchIdentity(echoed, headSha, patchIdOf) {
4069
- if (patchIdOf === undefined || !echoed.headSha)
4070
- return false;
4071
- const judged = patchIdOf(echoed.headSha);
4072
- const current = patchIdOf(headSha);
4073
- if (judged === null || current === null)
4074
- return false;
4075
- return judged === current;
3920
+ var PART_MIN_WORDS_OUTSIDE_BACKTICKS = 3;
3921
+ function stripPartBackticks(text) {
3922
+ return text.replace(/`[^`\n]*`/g, " ");
4076
3923
  }
4077
- function isBoundToBase(echoed, currentBase) {
4078
- if (currentBase === null)
4079
- return true;
4080
- if (!echoed.baseSha)
4081
- return false;
4082
- return currentBase.toLowerCase().startsWith(echoed.baseSha.toLowerCase());
3924
+ function partWordCount(text) {
3925
+ return text.split(/\s+/).filter((w) => /[a-z]/i.test(w)).length;
4083
3926
  }
4084
- function isBoundToObjectives(echoed, currentVersion) {
4085
- if (currentVersion === null)
4086
- return true;
4087
- return echoed.objectivesVersion === currentVersion;
3927
+ function looksLikeFilePath(entry) {
3928
+ const stripped = entry.replace(/\/\*\*?$/, "");
3929
+ const lastSegment = stripped.split("/").pop() ?? stripped;
3930
+ const extMatch = /\.[A-Za-z0-9]{1,6}$/.exec(lastSegment);
3931
+ return extMatch !== null && extMatch.index > 0;
4088
3932
  }
4089
- function isBoundToRulings(echoed, currentOrdinal) {
4090
- if (echoed.rulingOrdinal === null)
4091
- return currentOrdinal === 0;
4092
- return echoed.rulingOrdinal === currentOrdinal;
3933
+ function splitGlobList(raw) {
3934
+ return raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
4093
3935
  }
4094
- function isBoundToBriefHash(echoed, currentHash) {
4095
- if (currentHash === null)
4096
- return true;
4097
- return echoed.briefHash === currentHash;
3936
+ function parseIssueSurface(body) {
3937
+ const section = topLevelSectionText(body, "Surface");
3938
+ if (section === null)
3939
+ return { ok: false, errors: ["no `## Surface` heading found in the body."] };
3940
+ const inLine = /^in:\s*(.+)$/im.exec(section);
3941
+ const outLine = /^out:\s*(.+)$/im.exec(section);
3942
+ const errors = [];
3943
+ if (!inLine)
3944
+ errors.push("`## Surface` has no `in:` line.");
3945
+ if (!outLine)
3946
+ errors.push("`## Surface` has no `out:` line.");
3947
+ if (errors.length > 0)
3948
+ return { ok: false, errors };
3949
+ const inGlobs = splitGlobList(inLine[1]);
3950
+ const outGlobs = splitGlobList(outLine[1]);
3951
+ for (const g of [...inGlobs, ...outGlobs]) {
3952
+ if (looksLikeFilePath(g)) {
3953
+ errors.push(`\`${g}\` in \`## Surface\` looks like a file path — Surface entries are directory-level globs, never file paths.`);
3954
+ }
3955
+ }
3956
+ if (inGlobs.length === 0)
3957
+ errors.push("`## Surface`'s `in:` line resolved to zero globs.");
3958
+ if (errors.length > 0)
3959
+ return { ok: false, errors };
3960
+ return { ok: true, value: { in: inGlobs, out: outGlobs } };
4098
3961
  }
4099
- function isBoundToPolicy(echoed, currentDigest) {
4100
- return echoed.policyDigest === currentDigest;
3962
+ function globCoversPath(glob, path) {
3963
+ const g = glob.replace(/\/\*\*?$/, "").replace(/\/+$/, "");
3964
+ const p = path.replace(/\/+$/, "");
3965
+ if (g === "*")
3966
+ return !p.includes("/");
3967
+ return g === p || g.startsWith(`${p}/`) || p.startsWith(`${g}/`);
4101
3968
  }
4102
- function compareManifest(echoed, current, patchIdOf) {
4103
- const exactHead = isBoundToHead(echoed, current.headSha);
4104
- const patchHead = exactHead ? false : isBoundByPatchIdentity(echoed, current.headSha, patchIdOf);
4105
- const head = exactHead || patchHead;
4106
- const echoedShaLen = echoed.baseSha?.length ?? 0;
4107
- const currentShaLen = current.baseSha?.length ?? 0;
4108
- const bothFullShas = echoedShaLen >= 40 && currentShaLen >= 40;
4109
- const base = patchHead || exactHead && bothFullShas ? true : isBoundToBase(echoed, current.baseSha);
4110
- const briefHashBound = isBoundToBriefHash(echoed, current.briefHash);
4111
- const objectivesVersion = isBoundToObjectives(echoed, current.objectivesVersion);
4112
- const rulingOrdinal = isBoundToRulings(echoed, current.rulingOrdinal);
4113
- const policyDigestBound = isBoundToPolicy(echoed, current.policyDigest);
3969
+ function checkSurfaceGlobsResolve(body, resolvesToFile) {
3970
+ const surface = parseIssueSurface(body);
3971
+ if (!surface.ok)
3972
+ return { status: "pass", errors: [] };
3973
+ const errors = [];
3974
+ for (const glob of surface.value.in) {
3975
+ if (!resolvesToFile(glob)) {
3976
+ errors.push(`issue-validation Surface: \`${glob}\` in \`## Surface\`'s \`in:\` list matches no tracked file — a Surface that cannot resolve cannot render a brief's file list.`);
3977
+ }
3978
+ }
3979
+ return { status: errors.length > 0 ? "fail" : "pass", errors };
3980
+ }
3981
+ function checkSurfaceScope(changedFiles, outGlobs) {
3982
+ if (outGlobs.length === 0)
3983
+ return { ok: true };
3984
+ const violations = [];
3985
+ for (const file of changedFiles) {
3986
+ const glob = outGlobs.find((g) => globCoversPath(g, file));
3987
+ if (glob)
3988
+ violations.push({ file, glob });
3989
+ }
3990
+ return violations.length > 0 ? { ok: false, violations } : { ok: true };
3991
+ }
3992
+ var ISSUE_PART_LINE_RE = /^Part\s+(\d+)\s*\(([^)]*)\)\s*[-—–]\s*(.*)$/i;
3993
+ function parseIssueParts(body) {
3994
+ const section = topLevelSectionText(body, "Parts");
3995
+ if (section === null)
3996
+ return { ok: false, errors: ["no `## Parts` heading found in the body."] };
3997
+ const lines = section.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
3998
+ const parts = [];
3999
+ const errors = [];
4000
+ for (const line of lines) {
4001
+ const m = ISSUE_PART_LINE_RE.exec(line);
4002
+ if (!m) {
4003
+ errors.push(`"${line}" is not a well-formed Parts line — expected \`Part <n> (<refs>) — <outcome>\`.`);
4004
+ continue;
4005
+ }
4006
+ const n = Number.parseInt(m[1], 10);
4007
+ const refs = m[2];
4008
+ const text = m[3].trim();
4009
+ if (text.length === 0) {
4010
+ errors.push(`Part ${n} has no outcome text after the dash — every Part states one observable outcome.`);
4011
+ continue;
4012
+ }
4013
+ if (partHasBacktickedPath(text) && partWordCount(stripPartBackticks(text)) < PART_MIN_WORDS_OUTSIDE_BACKTICKS) {
4014
+ errors.push(`Part ${n} is little more than a file path — a Part names an outcome and symbols, never a bare path.`);
4015
+ continue;
4016
+ }
4017
+ const objectiveIds = [...refs.matchAll(/O(\d+)/g)].map((r) => Number.parseInt(r[1], 10));
4018
+ parts.push({ n, objectiveIds, text });
4019
+ }
4020
+ if (parts.length === 0) {
4021
+ errors.push("the `## Parts` section has no well-formed `Part <n> (<refs>) — <outcome>` lines.");
4022
+ }
4023
+ if (errors.length > 0)
4024
+ return { ok: false, errors };
4025
+ return { ok: true, value: parts };
4026
+ }
4027
+ function checkPartsCiteDefinedObjectives(body) {
4028
+ const parts = parseIssueParts(body);
4029
+ const objectives = objectivesOf(body);
4030
+ if (!parts.ok || !objectives.ok)
4031
+ return { status: "pass", errors: [] };
4032
+ const definedIds = new Set(objectives.objectives.map((o) => Number.parseInt(o.id.slice(1), 10)));
4033
+ const errors = [];
4034
+ for (const part of parts.value) {
4035
+ for (const objectiveId of part.objectiveIds) {
4036
+ if (!definedIds.has(objectiveId)) {
4037
+ errors.push(`issue-validation Parts: Part ${part.n} cites O${objectiveId}, which the Issue's own \`## Objectives\` section does not define.`);
4038
+ }
4039
+ }
4040
+ }
4041
+ return { status: errors.length > 0 ? "fail" : "pass", errors };
4042
+ }
4043
+ function isTaskIssueLabelSet(labels) {
4044
+ return hasLabel("tranche", labels);
4045
+ }
4046
+ function checkTrancheLabelPresence(_body, _labels) {
4047
+ return { status: "pass", errors: [] };
4048
+ }
4049
+ function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTitle) {
4050
+ if (!isTaskIssueLabelSet(labels))
4051
+ return { status: "pass", errors: [] };
4052
+ if (resolvedMilestoneTitle === null)
4053
+ return { status: "pass", errors: [] };
4054
+ if (currentMilestoneTitle === resolvedMilestoneTitle)
4055
+ return { status: "pass", errors: [] };
4114
4056
  return {
4115
- bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && policyDigestBound,
4116
- head,
4117
- base,
4118
- briefHash: briefHashBound,
4119
- objectivesVersion,
4120
- rulingOrdinal,
4121
- policyDigest: policyDigestBound
4057
+ status: "fail",
4058
+ errors: [
4059
+ `issue-validation milestone attach: this task Issue's tranche label resolves to Milestone "${resolvedMilestoneTitle}", but its live Milestone is ${currentMilestoneTitle === null ? "unset" : `"${currentMilestoneTitle}"`} — attach it to "${resolvedMilestoneTitle}".`
4060
+ ]
4122
4061
  };
4123
4062
  }
4124
-
4125
- // ../../packages/aeg-core/src/review-gate.ts
4126
- function checkReviewGate(input) {
4127
- const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
4128
- const waived = isWaiverLabelActorVerified({
4129
- label: WAIVER_LABEL_REVIEW,
4130
- labels: input.labels,
4131
- labelActor: input.waiverLabelActor,
4132
- principalAllowlist
4133
- });
4134
- if (waived) {
4135
- return {
4136
- verdict: "pass",
4137
- reason: `\`${WAIVER_LABEL_REVIEW}\` label is actor-verified — review requirement waived for this PR.`,
4138
- waived: true
4139
- };
4063
+ var TYPE_LABEL_IDS = LABELS.filter((l) => l.category === "type").map((l) => l.id);
4064
+ function isControlCodePoint(codePoint) {
4065
+ return codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
4066
+ }
4067
+ function isDisplayControlCodePoint(codePoint) {
4068
+ return codePoint >= 8203 && codePoint <= 8207 || codePoint >= 8234 && codePoint <= 8238 || codePoint >= 8294 && codePoint <= 8297 || codePoint === 65279;
4069
+ }
4070
+ var MESSAGE_VALUE_COUNT_MAX = 5;
4071
+ function residueForMessage(values) {
4072
+ const shown = values.slice(0, MESSAGE_VALUE_COUNT_MAX).map((v) => `\`${forMessage(v)}\``);
4073
+ const rest = values.length - shown.length;
4074
+ return rest > 0 ? `${shown.join(", ")} and ${rest} more` : shown.join(", ");
4075
+ }
4076
+ var MESSAGE_VALUE_MAX = 64;
4077
+ function forMessage(value) {
4078
+ const kept = [];
4079
+ for (const ch of value.replace(/\s+/g, " ")) {
4080
+ const codePoint = ch.codePointAt(0) ?? 0;
4081
+ if (isControlCodePoint(codePoint) || isDisplayControlCodePoint(codePoint))
4082
+ continue;
4083
+ kept.push(ch);
4140
4084
  }
4141
- const verified = input.comments.filter((c) => isPrincipal(c.author, principalAllowlist));
4142
- const ignoredCount = input.comments.filter((c) => !isPrincipal(c.author, principalAllowlist) && c.body.includes("VERDICT")).length;
4143
- const verifiedBodies = verified.map((c) => c.body);
4144
- const codeReview = extractCodeReviewVerdict(verifiedBodies);
4145
- const security = extractSecurityReviewVerdict(verifiedBodies);
4146
- const policy = input.policy ?? DEFAULT_REVIEW_POLICY;
4147
- let codeReviewPolicyEvaluation;
4148
- let securityPolicyEvaluation;
4149
- try {
4150
- codeReviewPolicyEvaluation = evaluateCodeReview(consequentialFindings(codeReview.findingSeverities), policy);
4151
- securityPolicyEvaluation = evaluateSecurityReview(consequentialFindings(security.findingSeverities), policy);
4152
- } catch (err) {
4085
+ const cleaned = kept.join("").trim();
4086
+ if (cleaned.length === 0)
4087
+ return "(unprintable)";
4088
+ const points = Array.from(cleaned);
4089
+ return points.length > MESSAGE_VALUE_MAX ? `${points.slice(0, MESSAGE_VALUE_MAX).join("")}…` : cleaned;
4090
+ }
4091
+ function checkProjectsRegistered(body, _labels, registeredNames) {
4092
+ if (registeredNames.length === 0)
4093
+ return { status: "pass", errors: [] };
4094
+ const field = projectFieldFromBody(body);
4095
+ if (!field.declared)
4096
+ return { status: "pass", errors: [] };
4097
+ const known = new Set(registeredNames.map((n) => n.trim()));
4098
+ const registeredList = [...registeredNames].map(forMessage).join(", ");
4099
+ const errors = [];
4100
+ if (field.unreadable) {
4153
4101
  return {
4154
- verdict: "fail",
4155
- reason: `a verdict comment carries a finding severity this repository's policy does not recognize: ${err instanceof Error ? err.message : String(err)}`,
4156
- waived: false
4102
+ status: "fail",
4103
+ errors: [
4104
+ `issue-validation project registry: the body has an unterminated code fence, so its \`**Project:**\` field could not be read reliably — the fence runs to end of body (CommonMark, and how the forge renders it), swallowing everything after it including the foot field where the declaration lives by convention. Read from the raw body the field says ${residueForMessage(field.unparsed) || "(nothing)"}, but a line inside a swallowed region may be a quoted example rather than a real declaration, so this gate refuses rather than guessing which. Balance the fences — every opening run of backticks or tildes needs a closing run at least as long — and the field reads normally.`
4105
+ ]
4157
4106
  };
4158
4107
  }
4159
- const codeReviewTextClean = codeReview.value === "APPROVE";
4160
- const securityTextClean = security.value === "PASS";
4161
- const codeReviewPolicyClean = codeReviewPolicyEvaluation.outcome === "clean";
4162
- const securityPolicyClean = securityPolicyEvaluation.outcome === "clean";
4163
- const codeReviewClean = codeReviewTextClean && codeReviewPolicyClean;
4164
- const securityClean = securityTextClean && securityPolicyClean;
4165
- const currentManifest = {
4166
- headSha: input.headSha,
4167
- baseSha: input.baseSha ?? null,
4168
- briefHash: input.briefHash ?? null,
4169
- objectivesVersion: input.objectivesVersion,
4170
- rulingOrdinal: input.rulingOrdinal,
4171
- policyDigest: policyDigest(policy)
4172
- };
4173
- const codeReviewEchoed = {
4174
- headSha: codeReview.headSha,
4175
- baseSha: codeReview.baseSha,
4176
- briefHash: codeReview.briefHash,
4177
- objectivesVersion: codeReview.objectivesVersion,
4178
- rulingOrdinal: codeReview.rulingOrdinal,
4179
- policyDigest: codeReview.policyDigest
4180
- };
4181
- const securityEchoed = {
4182
- headSha: security.headSha,
4183
- baseSha: security.baseSha,
4184
- briefHash: security.briefHash,
4185
- objectivesVersion: security.objectivesVersion,
4186
- rulingOrdinal: security.rulingOrdinal,
4187
- policyDigest: security.policyDigest
4188
- };
4189
- const codeReviewBinding = compareManifest(codeReviewEchoed, currentManifest, input.patchIdOf);
4190
- const securityBinding = compareManifest(securityEchoed, currentManifest, input.patchIdOf);
4191
- const codeReviewBound = codeReviewBinding.head;
4192
- const securityBound = securityBinding.head;
4193
- const codeReviewObjectivesBound = codeReviewBinding.objectivesVersion;
4194
- const securityObjectivesBound = securityBinding.objectivesVersion;
4195
- const codeReviewRulingsBound = codeReviewBinding.rulingOrdinal;
4196
- const securityRulingsBound = securityBinding.rulingOrdinal;
4197
- if (codeReviewClean && codeReviewBinding.bound && securityClean && securityBinding.bound) {
4198
- return {
4199
- verdict: "pass",
4200
- reason: `code-reviewer verdict is a clean APPROVE and security-review verdict is a clean PASS, both covering head ${input.headSha}.`,
4201
- waived: false
4202
- };
4108
+ const unregistered = field.names.filter((p) => !known.has(p));
4109
+ if (unregistered.length > 0) {
4110
+ const caseHints = unregistered.map((p) => {
4111
+ const row = [...known].find((k) => k.toLowerCase() === p.toLowerCase());
4112
+ return row ? `\`${forMessage(p)}\` differs from the registered \`${forMessage(row)}\` only in case` : null;
4113
+ }).filter((h) => h !== null);
4114
+ errors.push(`issue-validation project registry: the \`**Project:**\` field declares ${unregistered.map(forMessage).join(", ")} — no such row in \`.vinaya/projects.md\`, which is the authority for valid project names (registered: ${registeredList}). Fix the name, or register the project with \`vinaya init product <name> --path <folder>\` first; an unregistered project has no specs to read and no per-project state to update.${caseHints.length > 0 ? ` Note: ${caseHints.join("; ")} — project names are matched exactly, because every downstream consumer compares them literally.` : ""} This reads the same field \`projectsFromBody\` derives the task's project from, so a name here that is not a row is a task that resolves to a project that does not exist.`);
4203
4115
  }
4204
- const problems = [];
4205
- if (!codeReviewTextClean) {
4206
- problems.push(`code-reviewer verdict is not a clean APPROVE (found: ${codeReview.value})`);
4207
- } else if (!codeReviewPolicyClean) {
4208
- problems.push(`code-reviewer verdict says APPROVE but carries a finding (${codeReviewPolicyEvaluation.blockingFindings.map((f) => f.severity).join(", ")}) at or above this repository's code-review policy threshold (${policy.codeReviewThreshold}) — a reviewer's own APPROVE never overrides policy`);
4209
- } else if (!codeReviewBound) {
4210
- problems.push(`the newest code-review verdict covers ${codeReview.headSha ?? "no recorded commit"}, head is ${input.headSha}`);
4211
- } else if (!codeReviewBinding.base) {
4212
- problems.push(`the newest code-review verdict was cast against base ${codeReview.baseSha ?? "no recorded base"}, the PR's base is now ${currentManifest.baseSha ?? "unresolved"} (a base-only change under an unchanged candidate — same patch text on a new base is not automatically equivalent)`);
4213
- } else if (!codeReviewObjectivesBound) {
4214
- problems.push(`the newest code-review verdict was cast against objectives version ${codeReview.objectivesVersion ?? "none"}, the Issue's list is now ${input.objectivesVersion}`);
4215
- } else if (!codeReviewRulingsBound) {
4216
- problems.push(`the newest code-review verdict was cast against ruling ordinal ${codeReview.rulingOrdinal ?? "none"}, a newer ruling (ruling ${input.rulingOrdinal}) is now posted on this PR`);
4217
- } else if (!codeReviewBinding.briefHash) {
4218
- problems.push(`the newest code-review verdict was cast against brief hash ${codeReview.briefHash ?? "none"}, the frozen brief's current hash is ${currentManifest.briefHash ?? "none"}`);
4219
- } else if (!codeReviewBinding.policyDigest) {
4220
- problems.push(`the newest code-review verdict was cast against review policy digest ${codeReview.policyDigest ?? "none"}, this repository's current policy digest is ${currentManifest.policyDigest}`);
4116
+ if (field.names.length === 0) {
4117
+ const residue = field.unparsed.length > 0 ? ` — ${residueForMessage(field.unparsed)}` : " — the field is empty";
4118
+ errors.push(`issue-validation project registry: the \`**Project:**\` field is present but resolves to no project name${residue} (registered: ${registeredList}). A project name is a slug (\`[a-z0-9][a-z0-9-]*\`, matched exactly); prose, a parenthetical, or a sentence in this field resolves to no project at all, and this gate cannot check a name it never receives — which is how a declaration like this used to pass. Write the registered name on its own, or register the project with \`vinaya init product <name> --path <folder>\` first. If the task genuinely touches no registered project, omit the field rather than explaining its absence inside it — \`checkIssueRationale\` already requires the \`Project(s) + blast radius\` narrative field for that.`);
4119
+ } else if (field.unparsed.length > 0) {
4120
+ errors.push(`issue-validation project registry: the \`**Project:**\` field declares a value that is not a project name — ${residueForMessage(field.unparsed)} (registered: ${registeredList}). The rest of the field parsed, so this is a name the gate silently could not check rather than a field it could not read at all. A project name is a slug (\`[a-z0-9][a-z0-9-]*\`, matched exactly); write it on its own, or drop it if it names no project.`);
4221
4121
  }
4222
- if (!securityTextClean) {
4223
- problems.push(`security-review verdict is not a clean PASS (found: ${security.value})`);
4224
- } else if (!securityPolicyClean) {
4225
- problems.push(`security-review verdict says PASS but carries a finding (${securityPolicyEvaluation.blockingFindings.map((f) => f.severity).join(", ")}) at or above this repository's security policy threshold (${policy.securityThreshold}) — a reviewer's own PASS never overrides policy`);
4226
- } else if (!securityBound) {
4227
- problems.push(`the newest security-review verdict covers ${security.headSha ?? "no recorded commit"}, head is ${input.headSha}`);
4228
- } else if (!securityBinding.base) {
4229
- problems.push(`the newest security-review verdict was cast against base ${security.baseSha ?? "no recorded base"}, the PR's base is now ${currentManifest.baseSha ?? "unresolved"} (a base-only change under an unchanged candidate — same patch text on a new base is not automatically equivalent)`);
4230
- } else if (!securityObjectivesBound) {
4231
- problems.push(`the newest security-review verdict was cast against objectives version ${security.objectivesVersion ?? "none"}, the Issue's list is now ${input.objectivesVersion}`);
4232
- } else if (!securityRulingsBound) {
4233
- problems.push(`the newest security-review verdict was cast against ruling ordinal ${security.rulingOrdinal ?? "none"}, a newer ruling (ruling ${input.rulingOrdinal}) is now posted on this PR`);
4234
- } else if (!securityBinding.briefHash) {
4235
- problems.push(`the newest security-review verdict was cast against brief hash ${security.briefHash ?? "none"}, the frozen brief's current hash is ${currentManifest.briefHash ?? "none"}`);
4236
- } else if (!securityBinding.policyDigest) {
4237
- problems.push(`the newest security-review verdict was cast against review policy digest ${security.policyDigest ?? "none"}, this repository's current policy digest is ${currentManifest.policyDigest}`);
4122
+ return errors.length > 0 ? { status: "fail", errors } : { status: "pass", errors: [] };
4123
+ }
4124
+ var DOC_PATH_RE = /(?:(?:aeg-root|apps|packages|specs|docs|tools|\.claude|\.github)\/[\w./@-]*\.(?:md|mdx)|\.claude\/(?:skills|rules)\/[\w./-]+|\b(?:docs-index|decisions|projects|state-machine|enforcement|process|README|CLAUDE)\.md\b|\b[\w-]+-(?:spec|decisions|backlog)\.md\b)/i;
4125
+ var DOC_PATH_RE_GLOBAL = new RegExp(DOC_PATH_RE.source, "gi");
4126
+ var FILE_EXTENSIONS = new Set([
4127
+ "ts",
4128
+ "tsx",
4129
+ "js",
4130
+ "jsx",
4131
+ "mjs",
4132
+ "cjs",
4133
+ "json",
4134
+ "jsonc",
4135
+ "md",
4136
+ "mdx",
4137
+ "yml",
4138
+ "yaml",
4139
+ "txt",
4140
+ "sh",
4141
+ "lock",
4142
+ "toml",
4143
+ "ndjson",
4144
+ "html",
4145
+ "css"
4146
+ ]);
4147
+
4148
+ // ../../packages/aeg-core/src/task-branch-identity.ts
4149
+ var ISSUE_BRANCH_PATTERN = /^task\/issue-(\d+)$/;
4150
+ var TRANCHE_BRANCH_PATTERN = /^task\/([^/]+)\/([^/]+)$/;
4151
+ function parseTaskBranchIdentity(branch) {
4152
+ const issueMatch = ISSUE_BRANCH_PATTERN.exec(branch);
4153
+ if (issueMatch)
4154
+ return { kind: "issue", issueNumber: Number(issueMatch[1]) };
4155
+ const trancheMatch = TRANCHE_BRANCH_PATTERN.exec(branch);
4156
+ if (trancheMatch)
4157
+ return { kind: "tranche", tranche: trancheMatch[1], taskId: trancheMatch[2] };
4158
+ return null;
4159
+ }
4160
+
4161
+ // ../../packages/aeg-core/src/coherence-checks.ts
4162
+ var COHERENCE_ENFORCED_FROM = "2026-07-01";
4163
+ function isGrandfathered(isoDate) {
4164
+ if (!isoDate)
4165
+ return false;
4166
+ return isoDate.slice(0, 10) < COHERENCE_ENFORCED_FROM;
4167
+ }
4168
+ var R1_GRANDFATHERED_ISSUES = new Set([279, 280, 281, 282]);
4169
+ function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
4170
+ const failures = [];
4171
+ for (const e of entries) {
4172
+ if (!e.facts)
4173
+ continue;
4174
+ if (e.facts.stateReason === "not_planned")
4175
+ continue;
4176
+ if (e.facts.issueState === "closed" && e.facts.prState !== "merged") {
4177
+ const handClosed = e.facts.stateReason === "completed" && isPrincipal(e.facts.closedByActor, principalAllowlist);
4178
+ if (handClosed)
4179
+ continue;
4180
+ failures.push({
4181
+ code: "closed-without-merge",
4182
+ issue: e.task.issue,
4183
+ tranche: e.trancheSlug,
4184
+ task: e.task.id,
4185
+ reason: `Issue closed but closing PR is not merged (prState: ${e.facts.prState})`,
4186
+ grandfathered: isGrandfathered(e.facts.closedAt)
4187
+ });
4188
+ }
4189
+ }
4190
+ const activeFails = failures.filter((f) => !f.grandfathered);
4191
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
4192
+ return {
4193
+ check: "A1",
4194
+ status,
4195
+ failures,
4196
+ note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
4197
+ };
4198
+ }
4199
+ function checkA3(entries) {
4200
+ const failures = [];
4201
+ for (const e of entries) {
4202
+ if (!e.facts)
4203
+ continue;
4204
+ if (e.facts.prState === "merged" && e.facts.issueState !== "closed") {
4205
+ failures.push({
4206
+ code: "auto-close-misfire",
4207
+ issue: e.task.issue,
4208
+ tranche: e.trancheSlug,
4209
+ task: e.task.id,
4210
+ reason: "Closing PR is merged but Issue is still open (GitHub auto-close misfire)",
4211
+ grandfathered: isGrandfathered(e.facts.mergedAt)
4212
+ });
4213
+ }
4238
4214
  }
4239
- const ignoredNote = ignoredCount > 0 ? ` ${ignoredCount} verdict-shaped comment(s) from authors outside the principal allowlist were ignored.` : "";
4215
+ const activeFails = failures.filter((f) => !f.grandfathered);
4216
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
4240
4217
  return {
4241
- verdict: "fail",
4242
- reason: `${problems.join("; ")}. A principal can apply an actor-verified \`${WAIVER_LABEL_REVIEW}\` label to skip this requirement, or post the missing/clean verdict comment(s).${ignoredNote}`,
4243
- waived: false
4218
+ check: "A3",
4219
+ status,
4220
+ failures,
4221
+ note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
4244
4222
  };
4245
4223
  }
4246
- var CHANGESET_RELEASE_BRANCH = "changeset-release/main";
4247
- var DEFAULT_RELEASE_ACTOR = "github-actions[bot]";
4248
- function isChangesetsReleasePr(branch, author, expectedAuthor) {
4249
- return branch === CHANGESET_RELEASE_BRANCH && author === expectedAuthor;
4250
- }
4251
- // ../../packages/aeg-core/src/ruling-ordinal.ts
4252
- var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
4253
- function newestPrincipalRulingOrdinal(comments, allowlist) {
4254
- let best = 0;
4255
- for (const c of comments) {
4256
- if (!isPrincipal(c.author, allowlist))
4257
- continue;
4258
- const firstLine = (c.body.split(`
4259
- `)[0] ?? "").trim();
4260
- const m = RULING_MARKER_ORDINAL.exec(firstLine);
4261
- if (!m)
4224
+ function checkT1(entries) {
4225
+ const failures = [];
4226
+ for (const e of entries) {
4227
+ if (e.task.issue === null)
4262
4228
  continue;
4263
- const k = Number.parseInt(m[1], 10);
4264
- if (k > best)
4265
- best = k;
4229
+ if (e.facts === undefined) {
4230
+ failures.push({
4231
+ code: "phantom-issue-ref",
4232
+ issue: e.task.issue,
4233
+ tranche: e.trancheSlug,
4234
+ task: e.task.id,
4235
+ reason: `Issue #${e.task.issue} in topology does not resolve to a real GitHub Issue`
4236
+ });
4237
+ }
4266
4238
  }
4267
- return best;
4268
- }
4269
- // ../../packages/aeg-core/src/markdown-table.ts
4270
- function splitRow(line) {
4271
- const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
4272
- return trimmed.split("|").map((cell) => cell.trim());
4239
+ return { check: "T1", status: failures.length > 0 ? "fail" : "pass", failures };
4273
4240
  }
4274
- var TABLE_ROW_PATTERN = /^\s*\|.*\|\s*$/;
4275
- var SEPARATOR_ROW_PATTERN = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
4276
- function findTable(lines, fromLine, stopAtHeading = true) {
4277
- let i = fromLine - 1;
4278
- while (i < lines.length) {
4279
- const line = lines[i] ?? "";
4280
- if (stopAtHeading && i > fromLine - 1 && /^##\s/.test(line))
4281
- return null;
4282
- if (TABLE_ROW_PATTERN.test(line)) {
4283
- const headerLine = line;
4284
- const sepLine = lines[i + 1] ?? "";
4285
- if (!SEPARATOR_ROW_PATTERN.test(sepLine)) {
4286
- i++;
4287
- continue;
4288
- }
4289
- const headers = splitRow(headerLine);
4290
- const rows = [];
4291
- let j = i + 2;
4292
- while (j < lines.length && TABLE_ROW_PATTERN.test(lines[j] ?? "")) {
4293
- rows.push({ cells: splitRow(lines[j] ?? ""), line: j + 1 });
4294
- j++;
4241
+ function checkT2(openIssuesBySlug, topologyIssuesBySlug, ciTrancheSlug) {
4242
+ const failures = [];
4243
+ for (const [slug, openNums] of openIssuesBySlug) {
4244
+ if (ciTrancheSlug && slug !== ciTrancheSlug)
4245
+ continue;
4246
+ const topologySet = topologyIssuesBySlug.get(slug) ?? new Set;
4247
+ for (const num of openNums) {
4248
+ if (!topologySet.has(num)) {
4249
+ failures.push({
4250
+ code: "orphan-task",
4251
+ issue: num,
4252
+ tranche: slug,
4253
+ reason: `Issue #${num} is open and labeled ${trancheLabel(slug)} but does not appear in the topology file`
4254
+ });
4295
4255
  }
4296
- return { headers, rows };
4297
4256
  }
4298
- i++;
4299
4257
  }
4300
- return null;
4258
+ return { check: "T2", status: failures.length > 0 ? "fail" : "pass", failures };
4301
4259
  }
4302
- function findHeadingLine(lines, pattern) {
4303
- for (let i = 0;i < lines.length; i++) {
4304
- if (pattern.test(lines[i] ?? ""))
4305
- return i + 1;
4306
- }
4307
- return null;
4260
+ function scopeT2ToPlanPr(result, isPlanPr) {
4261
+ if (isPlanPr || result.status !== "fail")
4262
+ return result;
4263
+ return {
4264
+ ...result,
4265
+ status: "info",
4266
+ note: result.note ?? "T2 findings are non-blocking outside plan PRs (point-of-power principle) — see aeg-root/enforcement.md."
4267
+ };
4308
4268
  }
4309
- // ../../packages/aeg-core/src/diagram-model.ts
4310
- import matter from "gray-matter";
4311
-
4312
- // ../../packages/aeg-core/src/registry-parse.ts
4313
- var RING_HEADINGS = [
4314
- { ring: "ring0", pattern: /^##\s+Ring 0\b/ },
4315
- { ring: "ring1", pattern: /^##\s+Ring 1\b/ },
4316
- { ring: "ring2", pattern: /^##\s+Ring 2\b/ }
4317
- ];
4318
- function stripBackticks2(cell) {
4319
- const trimmed = cell.trim();
4320
- if (trimmed.length >= 2 && trimmed.startsWith("`") && trimmed.endsWith("`")) {
4321
- return trimmed.slice(1, -1);
4269
+ function checkT3(entries, ciTrancheSlug, enrichedEntries, forgeUnavailableSlugs) {
4270
+ const preEnforcement = new Set;
4271
+ if (enrichedEntries) {
4272
+ for (const e of enrichedEntries) {
4273
+ if (isGrandfathered(e.facts?.closedAt) || isGrandfathered(e.facts?.mergedAt)) {
4274
+ preEnforcement.add(e.trancheSlug);
4275
+ }
4276
+ }
4322
4277
  }
4323
- return trimmed;
4324
- }
4325
- function stripBold(cell) {
4326
- return cell.trim().replace(/\*\*/g, "");
4278
+ const failures = [];
4279
+ for (const e of entries) {
4280
+ if (!e.archived && e.task.issue === null) {
4281
+ if (ciTrancheSlug && e.trancheSlug !== ciTrancheSlug)
4282
+ continue;
4283
+ if (forgeUnavailableSlugs?.has(e.trancheSlug)) {
4284
+ failures.push({
4285
+ code: "tbd-in-active-tranche",
4286
+ issue: null,
4287
+ tranche: e.trancheSlug,
4288
+ task: e.task.id,
4289
+ reason: `Task ${e.task.id} in active tranche has no Issue ref (#TBD or empty), but forge data for tranche "${e.trancheSlug}" was unavailable — cannot evaluate grandfather status, not silently failed`,
4290
+ grandfathered: true
4291
+ });
4292
+ continue;
4293
+ }
4294
+ failures.push({
4295
+ code: "tbd-in-active-tranche",
4296
+ issue: null,
4297
+ tranche: e.trancheSlug,
4298
+ task: e.task.id,
4299
+ reason: `Task ${e.task.id} in active tranche has no Issue ref (#TBD or empty) — the model requires all active tasks to have Issue numbers`,
4300
+ grandfathered: preEnforcement.has(e.trancheSlug)
4301
+ });
4302
+ }
4303
+ }
4304
+ const activeFails = failures.filter((f) => !f.grandfathered);
4305
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
4306
+ return {
4307
+ check: "T3",
4308
+ status,
4309
+ failures,
4310
+ note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
4311
+ };
4327
4312
  }
4328
- function parseEnforcementRegistry(content) {
4329
- const lines = content.split(`
4330
- `);
4331
- const result = [];
4332
- for (const { ring, pattern } of RING_HEADINGS) {
4333
- const headingLine = findHeadingLine(lines, pattern);
4334
- if (headingLine === null)
4313
+ function checkD1(entries, issueToEntry, taskToEntry) {
4314
+ const failures = [];
4315
+ for (const e of entries) {
4316
+ if (!e.facts)
4335
4317
  continue;
4336
- const table = findTable(lines, headingLine + 1);
4337
- if (!table)
4318
+ if (e.facts.prState !== "open")
4338
4319
  continue;
4339
- const descriptionIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "description");
4340
- const implementationIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "implementation");
4341
- const audienceIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "audience");
4342
- for (const row of table.rows) {
4343
- const cells = row.cells;
4344
- if (cells.length < 3)
4320
+ for (const dep of e.task.dependsOn) {
4321
+ const depEntry = resolveDepEntry(dep, e.trancheSlug, issueToEntry, taskToEntry);
4322
+ if (!depEntry)
4345
4323
  continue;
4346
- const action = stripBold(cells[0] ?? "");
4347
- const summary = stripBackticks2(cells[1] ?? "");
4348
- const category = stripBackticks2(cells[2] ?? "");
4349
- const implementation = stripBackticks2((implementationIndex === -1 ? cells[cells.length - 1] : cells[implementationIndex]) ?? "");
4350
- const description = descriptionIndex === -1 ? undefined : stripBackticks2(cells[descriptionIndex] ?? "") || undefined;
4351
- const specIndex = (audienceIndex === -1 ? cells.length - 1 : audienceIndex) - 1;
4352
- const spec = specIndex >= 3 ? stripBackticks2(cells[specIndex] ?? "") || undefined : undefined;
4353
- const audience = audienceIndex === -1 ? "repo-own" : stripBackticks2(cells[audienceIndex] ?? "") === "product" ? "product" : "repo-own";
4354
- result.push({ ring, action, summary, category, description, spec, implementation, audience, line: row.line });
4324
+ const sameTask = depEntry.trancheSlug === e.trancheSlug && depEntry.task.id === e.task.id;
4325
+ const sameIssue = depEntry.task.issue !== null && e.task.issue !== null && depEntry.task.issue === e.task.issue;
4326
+ if (sameTask || sameIssue) {
4327
+ failures.push({
4328
+ code: "d1-self-dependency",
4329
+ issue: e.task.issue,
4330
+ tranche: e.trancheSlug,
4331
+ task: e.task.id,
4332
+ reason: `INTERNAL: parsed a self-dependency (depends-on ${dep}) — this is a parser bug in parseRationaleDeps, not a real dependency. Please report it upstream.`
4333
+ });
4334
+ continue;
4335
+ }
4336
+ const depFacts = depEntry.facts;
4337
+ const depClosed = depFacts?.issueState === "closed";
4338
+ if (!depClosed) {
4339
+ failures.push({
4340
+ code: "dispatched-on-unmet-deps",
4341
+ issue: e.task.issue,
4342
+ tranche: e.trancheSlug,
4343
+ task: e.task.id,
4344
+ reason: `Task has open PR but depends-on ${dep} (issue #${depEntry.task.issue ?? "?"}) is not closed`
4345
+ });
4346
+ }
4355
4347
  }
4356
4348
  }
4357
- return result;
4349
+ return { check: "D1", status: failures.length > 0 ? "fail" : "pass", failures };
4358
4350
  }
4359
- // ../../packages/aeg-core/src/registry-checks.ts
4360
- function checkG1(rows, existsFn) {
4361
- const findings = [];
4362
- for (const row of rows) {
4363
- if (row.implementation === "")
4364
- continue;
4365
- if (!existsFn(row.implementation)) {
4366
- findings.push({
4367
- row: row.action,
4368
- path: row.implementation,
4369
- reason: `${row.ring} row "${row.action}" names implementation "${row.implementation}", which does not exist on disk`
4351
+ function resolveDepEntry(dep, trancheSlug, issueToEntry, taskToEntry) {
4352
+ const issueMatch = dep.match(/^#(\d+)$/);
4353
+ if (issueMatch?.[1])
4354
+ return issueToEntry.get(Number(issueMatch[1]));
4355
+ return taskToEntry.get(`${trancheSlug}/${dep}`) ?? taskToEntry.get(dep);
4356
+ }
4357
+ function checkR1(issuesBySlug, grandfatheredIssues, registeredNames = [], objectivesSinceIssue) {
4358
+ const failures = [];
4359
+ for (const [slug, issues] of issuesBySlug) {
4360
+ for (const issue of issues) {
4361
+ if (!isTaskIssueLabelSet(issue.labels))
4362
+ continue;
4363
+ const errors = [
4364
+ ...checkIssueRationale(issue.body).errors,
4365
+ ...checkProjectsRegistered(issue.body, issue.labels, registeredNames).errors,
4366
+ ...checkIssueObjectives(issue.body, issue.number, objectivesSinceIssue).errors,
4367
+ ...checkPartsCiteDefinedObjectives(issue.body).errors
4368
+ ];
4369
+ if (errors.length === 0)
4370
+ continue;
4371
+ failures.push({
4372
+ code: "missing-rationale-field",
4373
+ issue: issue.number,
4374
+ tranche: slug,
4375
+ reason: `Issue #${issue.number} fails the rationale gate: ${errors.join(" | ")}`,
4376
+ grandfathered: grandfatheredIssues.has(issue.number)
4370
4377
  });
4371
4378
  }
4372
4379
  }
4373
- return { check: "G1", status: findings.length > 0 ? "fail" : "pass", findings };
4380
+ const activeFails = failures.filter((f) => !f.grandfathered);
4381
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
4382
+ return {
4383
+ check: "R1",
4384
+ status,
4385
+ failures,
4386
+ note: status === "info" ? `${failures.length} grandfathered task Issue(s) predate this check's grammar (rationale fields and/or the project registry)` : undefined
4387
+ };
4374
4388
  }
4375
- var SCAFFOLD_PLACEHOLDER = "[undocumented — fill in why]";
4376
- var NON_GATE_BIN_NAMES = NON_GATE_BINS;
4377
- var TWIN_CANDIDATE_EXCEPTIONS = {
4378
- "apps/cli/src/checks/bin/check-dead-branch-push.ts": 'Ring 0 "Pushing to a branch whose pull request already resolved" (implementation: check-push-target.ts)',
4379
- "apps/cli/src/checks/bin/check-issue-assignment.ts": `Ring 0 "A task branch's first push (Issue self-assignment)" (implementation: assign-task-issue.ts)`,
4380
- "apps/cli/src/checks/bin/check-closes-n.ts": 'Ring 1 "Closes linkage" (implementation: verify-coherence.ts)'
4381
- };
4382
- var NON_GATE_HOOK_SCRIPTS = [".claude/hooks/track-transcript.sh"];
4383
- function checkG2(rows, candidateFiles) {
4384
- const implementations = new Set(rows.map((r) => r.implementation).filter((p) => p !== ""));
4385
- const claimedNames = new Set(rows.flatMap((r) => claimedCheckNames(r.implementation)));
4386
- const findings = [];
4387
- for (const path of candidateFiles) {
4388
- if (implementations.has(path))
4389
- continue;
4390
- if (path.startsWith(AEG_CORE_BIN_PATH_PREFIX) && NON_GATE_BIN_NAMES.includes(basenameNoExt(path)))
4391
- continue;
4392
- if (NON_GATE_HOOK_SCRIPTS.includes(path))
4393
- continue;
4394
- if (path in TWIN_CANDIDATE_EXCEPTIONS)
4389
+ function checkL1(files, entriesBySlug) {
4390
+ const failures = [];
4391
+ for (const f of files) {
4392
+ if (f.archived)
4395
4393
  continue;
4396
- const candidateNames = claimedCheckNames(path);
4397
- if (candidateNames.length > 0 && candidateNames.some((n) => claimedNames.has(n)))
4394
+ const entries = entriesBySlug.get(f.slug) ?? [];
4395
+ const withFacts = entries.filter((e) => e.facts !== undefined);
4396
+ if (withFacts.length === 0)
4398
4397
  continue;
4399
- findings.push({
4400
- path,
4401
- reason: `"${path}" is not named as the implementation of any row in enforcement.md's ring tables`
4402
- });
4403
- }
4404
- for (const row of rows) {
4405
- const carriesPlaceholder = [row.summary, row.description, row.spec].some((cell) => cell === SCAFFOLD_PLACEHOLDER);
4406
- if (carriesPlaceholder) {
4407
- findings.push({
4408
- row: row.action,
4409
- path: row.implementation,
4410
- reason: `${row.ring} row "${row.action}" still carries the scaffold placeholder marker — the why is owed`
4398
+ const allClosed = withFacts.every((e) => e.facts?.issueState === "closed");
4399
+ if (allClosed) {
4400
+ failures.push({
4401
+ code: "archive-recommended",
4402
+ tranche: f.slug,
4403
+ reason: "Active tranche has no open task-Issues — consider archiving to completed/"
4411
4404
  });
4412
4405
  }
4413
4406
  }
4414
- return { check: "G2", status: findings.length > 0 ? "fail" : "pass", findings };
4407
+ return {
4408
+ check: "L1",
4409
+ status: "info",
4410
+ failures,
4411
+ note: failures.length > 0 ? `${failures.length} active tranche(s) with no open task-Issues — consider archiving (advisory)` : undefined
4412
+ };
4415
4413
  }
4416
- function checkG3(ring0Rows, crossingFiles) {
4417
- const ring0Implementations = new Set(ring0Rows.map((r) => r.implementation));
4418
- const findings = [];
4419
- for (const path of crossingFiles) {
4420
- if (!ring0Implementations.has(path)) {
4421
- findings.push({
4422
- path,
4423
- reason: `"${path}" makes a GitHub-crossing call but is not named by any Ring-0 row's implementation — a seventh, unlisted way into GitHub`
4424
- });
4425
- }
4426
- }
4427
- return { check: "G3", status: findings.length > 0 ? "fail" : "pass", findings };
4414
+ function checkL3(files) {
4415
+ const active = files.filter((f) => !f.archived);
4416
+ return {
4417
+ check: "L3",
4418
+ status: "info",
4419
+ failures: [],
4420
+ note: `${active.length} active tranche(s): ${active.map((f) => f.slug).join(", ") || "(none)"}`
4421
+ };
4428
4422
  }
4429
- function checkG4(content, resolveFn) {
4430
- const cited = new Set;
4431
- for (const hit of content.matchAll(/#(\d{3,})\b/g)) {
4432
- cited.add(Number(hit[1]));
4433
- }
4434
- const findings = [];
4435
- for (const n of cited) {
4436
- if (!resolveFn(n)) {
4437
- findings.push({
4438
- reason: `#${n} is cited in enforcement.md but does not resolve to a real Issue or PR in the forge`
4439
- });
4440
- }
4423
+ function extractClosesReferences(prBody) {
4424
+ const closesPattern = /(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s{0,8}:?\s{0,8}#(\d+)/gi;
4425
+ const stripped = stripCode(prBody);
4426
+ const searchIn = anchoredRegion(stripped, "CLOSES") ?? stripped;
4427
+ const referenced = new Set;
4428
+ for (const hit of searchIn.matchAll(closesPattern)) {
4429
+ referenced.add(Number(hit[1]));
4441
4430
  }
4442
- return { check: "G4", status: findings.length > 0 ? "fail" : "pass", findings };
4431
+ return referenced;
4443
4432
  }
4444
- function checkG5(roles, contracts) {
4445
- const roleIds = new Set(roles.map((r) => r.role_id));
4446
- const findings = [];
4447
- for (const contract of contracts) {
4448
- if (!roleIds.has(contract.producer)) {
4449
- findings.push({
4450
- path: contract.file,
4451
- reason: `contract "${contract.file}" names producer "${contract.producer}", which is not a real role_id`
4452
- });
4453
- }
4454
- if (!roleIds.has(contract.consumer)) {
4455
- findings.push({
4456
- path: contract.file,
4457
- reason: `contract "${contract.file}" names consumer "${contract.consumer}", which is not a real role_id`
4458
- });
4433
+ function checkClosesNTopology(branch, prBody, trancheFiles, taskIssueRefs) {
4434
+ const referenced = extractClosesReferences(prBody);
4435
+ if (taskIssueRefs) {
4436
+ for (const n of referenced) {
4437
+ const ref = taskIssueRefs.get(n);
4438
+ if (!ref)
4439
+ continue;
4440
+ const expectedBranch = `task/${ref.trancheSlug}/${ref.taskId}`;
4441
+ if (branch !== expectedBranch) {
4442
+ return {
4443
+ ok: false,
4444
+ message: `closes-n-reverse: branch "${branch}" closes #${n} (task ${ref.taskId} of tranche "${ref.trancheSlug}") but is not named "${expectedBranch}" — rename the branch and re-push, or if this work is intentionally outside AEG's dispatch flow, remove the Closes reference.`
4445
+ };
4446
+ }
4459
4447
  }
4460
4448
  }
4461
- for (const role of roles) {
4462
- if (role.performs.length === 0) {
4463
- findings.push({ path: role.file, reason: `role "${role.role_id}" has an empty performs array` });
4464
- }
4465
- if (role.refuses_when.trim() === "") {
4466
- findings.push({ path: role.file, reason: `role "${role.role_id}" has an empty refuses_when` });
4449
+ const ref = parseTaskBranchIdentity(branch);
4450
+ if (!ref)
4451
+ return { ok: true };
4452
+ if (ref.kind === "issue") {
4453
+ const expectedIssue = ref.issueNumber;
4454
+ if (!referenced.has(expectedIssue)) {
4455
+ return {
4456
+ ok: false,
4457
+ expectedIssue,
4458
+ message: `closes-n: PR body does not contain \`Closes #${expectedIssue}\` (required for branch "${branch}"). Add it to the PR body Summary section.`
4459
+ };
4467
4460
  }
4461
+ return { ok: true, expectedIssue };
4468
4462
  }
4469
- return { check: "G5", status: findings.length > 0 ? "fail" : "pass", findings };
4470
- }
4471
- var SHIPPED_BIN_PATH_PREFIX = "apps/cli/src/checks/bin/check-";
4472
- var AEG_CORE_BIN_PATH_PREFIX = "packages/aeg-core/bin/";
4473
- function basenameNoExt(path) {
4474
- const base = path.slice(path.lastIndexOf("/") + 1);
4475
- return base.replace(/\.ts$/, "");
4476
- }
4477
- function claimedCheckNames(implementation) {
4478
- if (implementation.startsWith(SHIPPED_BIN_PATH_PREFIX) && implementation.endsWith(".ts")) {
4479
- return [implementation.slice(SHIPPED_BIN_PATH_PREFIX.length, -".ts".length)];
4463
+ const trancheSlug = ref.tranche;
4464
+ const taskId = ref.taskId;
4465
+ const trancheFile = trancheFiles.find((f) => f.slug === trancheSlug);
4466
+ if (!trancheFile) {
4467
+ return {
4468
+ ok: false,
4469
+ message: `closes-n: branch "${branch}" references tranche "${trancheSlug}" but no topology file found at aeg-root/tranches/${trancheSlug}.md. Ensure the tranche file exists before opening the PR.`
4470
+ };
4480
4471
  }
4481
- if (implementation.startsWith(AEG_CORE_BIN_PATH_PREFIX)) {
4482
- const audience = GATE_AUDIENCE[basenameNoExt(implementation)];
4483
- if (audience && isShipped(audience)) {
4484
- return Array.isArray(audience.shippedAs) ? audience.shippedAs : [audience.shippedAs];
4485
- }
4472
+ const task = trancheFile.tranche.tasks.find((t) => t.id === taskId);
4473
+ if (!task) {
4474
+ return {
4475
+ ok: false,
4476
+ message: `closes-n: branch "${branch}" references task "${taskId}" not found in ${trancheSlug} topology. Verify the task ID matches the tranche file.`
4477
+ };
4486
4478
  }
4487
- return [];
4479
+ if (task.issue === null) {
4480
+ return {
4481
+ ok: false,
4482
+ message: `closes-n: task "${taskId}" in "${trancheSlug}" has no Issue number (#TBD). The Planner must cut the Issue before this PR can be validated.`
4483
+ };
4484
+ }
4485
+ const expectedIssue = task.issue;
4486
+ if (!referenced.has(expectedIssue)) {
4487
+ return {
4488
+ ok: false,
4489
+ expectedIssue,
4490
+ message: `closes-n: PR body does not contain \`Closes #${expectedIssue}\` (required for task "${taskId}" in tranche "${trancheSlug}"). Add it to the PR body Summary section.`
4491
+ };
4492
+ }
4493
+ return { ok: true, expectedIssue };
4488
4494
  }
4489
- function checkG6(rows, registeredCheckNames) {
4490
- const findings = [];
4491
- for (const row of rows) {
4492
- if (row.audience !== "product")
4493
- continue;
4494
- const candidates = claimedCheckNames(row.implementation);
4495
- if (!candidates.some((name) => registeredCheckNames.has(name))) {
4496
- findings.push({
4497
- row: row.action,
4498
- path: row.implementation,
4499
- reason: `${row.ring} row "${row.action}" is marked \`product\` but its implementation "${row.implementation}" does not resolve to a coreCheckRegistry() entry`
4500
- });
4501
- }
4495
+ // ../../packages/aeg-core/src/archive-task.ts
4496
+ function closesRefs(text) {
4497
+ return [...new Set([...text.matchAll(/Closes #(\d+)/gi)].map((m) => Number(m[1])))];
4498
+ }
4499
+ function extractIssue(body) {
4500
+ const stripped = stripCode(body);
4501
+ const bodyNums = closesRefs(stripped);
4502
+ const anchored = anchoredRegion(stripped, "CLOSES");
4503
+ if (anchored !== null) {
4504
+ const anchorNums = closesRefs(anchored);
4505
+ if (anchorNums.length === 0)
4506
+ return { issue: null, extraIssues: bodyNums, outsideHeader: false };
4507
+ const issue = anchorNums[0];
4508
+ return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: false };
4502
4509
  }
4503
- return { check: "G6", status: findings.length > 0 ? "fail" : "pass", findings };
4510
+ const headerNums = closesRefs(headerRegion(stripped));
4511
+ if (bodyNums.length === 0)
4512
+ return { issue: null, extraIssues: [], outsideHeader: false };
4513
+ const issue = headerNums.length > 0 ? headerNums[0] : bodyNums[0];
4514
+ return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: headerNums.length === 0 };
4504
4515
  }
4505
- // ../../packages/aeg-core/src/reader-resolvable-prose.ts
4506
- var PRODUCT_SLUG_SCOPE = [
4507
- "apps/cli/src",
4508
- ".github/workflows",
4509
- ".vinaya",
4510
- "apps/cli/README.md",
4511
- "packages/sources/README.md"
4512
- ];
4513
- function isUnderOrEqual(path, prefix) {
4514
- return path === prefix || path.startsWith(`${prefix}/`);
4516
+ // ../../packages/aeg-core/src/review-input-manifest.ts
4517
+ import { createHash as createHash4 } from "node:crypto";
4518
+ function briefHash(brief) {
4519
+ return createHash4("sha256").update(`${brief}
4520
+ `).digest("hex");
4515
4521
  }
4516
- function isProductScopeFile(path) {
4517
- return PRODUCT_SLUG_SCOPE.some((prefix) => isUnderOrEqual(path, prefix));
4522
+ function policyDigest(policy) {
4523
+ return createHash4("sha256").update(JSON.stringify({
4524
+ codeReviewThreshold: policy.codeReviewThreshold,
4525
+ securityThreshold: policy.securityThreshold,
4526
+ maxRounds: policy.maxRounds
4527
+ })).digest("hex");
4518
4528
  }
4519
- var SHIPS_PREFIX = "aeg-root/";
4520
- function shipsArchivePrefix(shipsPrefix) {
4521
- return `${shipsPrefix}tranches/completed/`;
4529
+ function isBoundToHead(echoed, headSha) {
4530
+ if (!echoed.headSha)
4531
+ return false;
4532
+ return headSha.toLowerCase().startsWith(echoed.headSha.toLowerCase());
4522
4533
  }
4523
- var DEFAULT_SPEC_PATHS = ["SPEC.md", "CONTEXT.md", "docs/adr"];
4524
- function normalizeSpecPath(entry) {
4525
- let out = entry.replace(/\\/g, "/");
4526
- while (out.startsWith("./"))
4527
- out = out.slice(2);
4528
- out = out.replace(/\/{2,}/g, "/");
4529
- while (out.endsWith("/"))
4530
- out = out.slice(0, -1);
4531
- return out;
4534
+ function isBoundByPatchIdentity(echoed, headSha, patchIdOf) {
4535
+ if (patchIdOf === undefined || !echoed.headSha)
4536
+ return false;
4537
+ const judged = patchIdOf(echoed.headSha);
4538
+ const current = patchIdOf(headSha);
4539
+ if (judged === null || current === null)
4540
+ return false;
4541
+ return judged === current;
4532
4542
  }
4533
- function isSpecFile2(path, specPaths) {
4534
- if (path.startsWith("apps/") && path.includes("/specs/") && path.endsWith(".md"))
4543
+ function isBoundToBase(echoed, currentBase) {
4544
+ if (currentBase === null)
4535
4545
  return true;
4536
- if (!path.endsWith(".md"))
4546
+ if (!echoed.baseSha)
4537
4547
  return false;
4538
- return specPaths.some((entry) => isUnderOrEqual(path, normalizeSpecPath(entry)));
4548
+ return currentBase.toLowerCase().startsWith(echoed.baseSha.toLowerCase());
4539
4549
  }
4540
- function isClaudeMdFile(path) {
4541
- return path === "CLAUDE.md" || path.endsWith("/CLAUDE.md");
4550
+ function isBoundToObjectives(echoed, currentVersion) {
4551
+ if (currentVersion === null)
4552
+ return true;
4553
+ return echoed.objectivesVersion === currentVersion;
4542
4554
  }
4543
- function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS) {
4544
- if (path.startsWith(shipsPrefix)) {
4545
- return path.startsWith(shipsArchivePrefix(shipsPrefix)) ? "internal" : "ships";
4555
+ function isBoundToRulings(echoed, currentOrdinal) {
4556
+ if (echoed.rulingOrdinal === null)
4557
+ return currentOrdinal === 0;
4558
+ return echoed.rulingOrdinal === currentOrdinal;
4559
+ }
4560
+ function isBoundToBriefHash(echoed, currentHash) {
4561
+ if (currentHash === null)
4562
+ return true;
4563
+ return echoed.briefHash === currentHash;
4564
+ }
4565
+ function isBoundToPolicy(echoed, currentDigest) {
4566
+ return echoed.policyDigest === currentDigest;
4567
+ }
4568
+ function compareManifest(echoed, current, patchIdOf) {
4569
+ const exactHead = isBoundToHead(echoed, current.headSha);
4570
+ const patchHead = exactHead ? false : isBoundByPatchIdentity(echoed, current.headSha, patchIdOf);
4571
+ const head = exactHead || patchHead;
4572
+ const echoedShaLen = echoed.baseSha?.length ?? 0;
4573
+ const currentShaLen = current.baseSha?.length ?? 0;
4574
+ const bothFullShas = echoedShaLen >= 40 && currentShaLen >= 40;
4575
+ const base = patchHead || exactHead && bothFullShas ? true : isBoundToBase(echoed, current.baseSha);
4576
+ const briefHashBound = isBoundToBriefHash(echoed, current.briefHash);
4577
+ const objectivesVersion = isBoundToObjectives(echoed, current.objectivesVersion);
4578
+ const rulingOrdinal = isBoundToRulings(echoed, current.rulingOrdinal);
4579
+ const policyDigestBound = isBoundToPolicy(echoed, current.policyDigest);
4580
+ return {
4581
+ bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && policyDigestBound,
4582
+ head,
4583
+ base,
4584
+ briefHash: briefHashBound,
4585
+ objectivesVersion,
4586
+ rulingOrdinal,
4587
+ policyDigest: policyDigestBound
4588
+ };
4589
+ }
4590
+
4591
+ // ../../packages/aeg-core/src/review-gate.ts
4592
+ function renderGateDeferred(deferred) {
4593
+ if (deferred.length === 0)
4594
+ return "";
4595
+ const items = deferred.map((d) => {
4596
+ const where = d.finding.location && d.finding.location.length > 0 ? d.finding.location : "(no location)";
4597
+ return `${d.finding.severity} ${where} (${DEFERRAL_REASON_TEXT[d.reason]})`;
4598
+ }).join("; ");
4599
+ return ` ${deferred.length} finding(s) deferred, not blocking this round: ${items}.`;
4600
+ }
4601
+ function checkReviewGate(input) {
4602
+ const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
4603
+ const waived = isWaiverLabelActorVerified({
4604
+ label: WAIVER_LABEL_REVIEW,
4605
+ labels: input.labels,
4606
+ labelActor: input.waiverLabelActor,
4607
+ principalAllowlist
4608
+ });
4609
+ if (waived) {
4610
+ return {
4611
+ verdict: "pass",
4612
+ reason: `\`${WAIVER_LABEL_REVIEW}\` label is actor-verified — review requirement waived for this PR.`,
4613
+ waived: true
4614
+ };
4546
4615
  }
4547
- if (path.startsWith(readerFacingPrefix) && path.endsWith(readerFacingSuffix)) {
4548
- return "reader-facing";
4616
+ const verified = input.comments.filter((c) => isPrincipal(c.author, principalAllowlist));
4617
+ const ignoredCount = input.comments.filter((c) => !isPrincipal(c.author, principalAllowlist) && c.body.includes("VERDICT")).length;
4618
+ const verifiedBodies = verified.map((c) => c.body);
4619
+ const codeReview = extractCodeReviewVerdict(verifiedBodies);
4620
+ const security = extractSecurityReviewVerdict(verifiedBodies);
4621
+ const policy = input.policy ?? DEFAULT_REVIEW_POLICY;
4622
+ let codeReviewPolicyEvaluation;
4623
+ let securityPolicyEvaluation;
4624
+ try {
4625
+ codeReviewPolicyEvaluation = evaluateCodeReview(consequentialFindings(codeReview.findingSeverities), policy, input.deferralContext);
4626
+ securityPolicyEvaluation = evaluateSecurityReview(consequentialFindings(security.findingSeverities), policy, input.deferralContext);
4627
+ } catch (err) {
4628
+ return {
4629
+ verdict: "fail",
4630
+ reason: `a verdict comment carries a finding severity this repository's policy does not recognize: ${err instanceof Error ? err.message : String(err)}`,
4631
+ waived: false
4632
+ };
4549
4633
  }
4550
- if (isClaudeMdFile(path))
4551
- return "internal";
4552
- if (isSpecFile2(path, specPaths))
4553
- return "spec";
4554
- if (isProductScopeFile(path))
4555
- return "product";
4556
- return null;
4557
- }
4558
- var SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
4559
- function stripNonProse(path, content) {
4560
- if (path.endsWith(".md")) {
4561
- return content.replace(/```.*?```/gs, (m) => m.replace(/[^\n]/g, "")).replace(/`[^`\n]*`/g, (m) => m.replace(/[^\n]/g, ""));
4634
+ const codeReviewTextClean = codeReview.value === "APPROVE";
4635
+ const securityTextClean = security.value === "PASS";
4636
+ const codeReviewPolicyClean = codeReviewPolicyEvaluation.outcome === "clean";
4637
+ const securityPolicyClean = securityPolicyEvaluation.outcome === "clean";
4638
+ const codeReviewClean = codeReviewTextClean && codeReviewPolicyClean;
4639
+ const securityClean = securityTextClean && securityPolicyClean;
4640
+ const currentManifest = {
4641
+ headSha: input.headSha,
4642
+ baseSha: input.baseSha ?? null,
4643
+ briefHash: input.briefHash ?? null,
4644
+ objectivesVersion: input.objectivesVersion,
4645
+ rulingOrdinal: input.rulingOrdinal,
4646
+ policyDigest: policyDigest(policy)
4647
+ };
4648
+ const codeReviewEchoed = {
4649
+ headSha: codeReview.headSha,
4650
+ baseSha: codeReview.baseSha,
4651
+ briefHash: codeReview.briefHash,
4652
+ objectivesVersion: codeReview.objectivesVersion,
4653
+ rulingOrdinal: codeReview.rulingOrdinal,
4654
+ policyDigest: codeReview.policyDigest
4655
+ };
4656
+ const securityEchoed = {
4657
+ headSha: security.headSha,
4658
+ baseSha: security.baseSha,
4659
+ briefHash: security.briefHash,
4660
+ objectivesVersion: security.objectivesVersion,
4661
+ rulingOrdinal: security.rulingOrdinal,
4662
+ policyDigest: security.policyDigest
4663
+ };
4664
+ const codeReviewBinding = compareManifest(codeReviewEchoed, currentManifest, input.patchIdOf);
4665
+ const securityBinding = compareManifest(securityEchoed, currentManifest, input.patchIdOf);
4666
+ const codeReviewBound = codeReviewBinding.head;
4667
+ const securityBound = securityBinding.head;
4668
+ const codeReviewObjectivesBound = codeReviewBinding.objectivesVersion;
4669
+ const securityObjectivesBound = securityBinding.objectivesVersion;
4670
+ const codeReviewRulingsBound = codeReviewBinding.rulingOrdinal;
4671
+ const securityRulingsBound = securityBinding.rulingOrdinal;
4672
+ const deferredNote = renderGateDeferred([
4673
+ ...codeReviewPolicyEvaluation.deferredFindings,
4674
+ ...securityPolicyEvaluation.deferredFindings
4675
+ ]);
4676
+ if (codeReviewClean && codeReviewBinding.bound && securityClean && securityBinding.bound) {
4677
+ return {
4678
+ verdict: "pass",
4679
+ reason: `code-reviewer verdict is a clean APPROVE and security-review verdict is a clean PASS, both covering head ${input.headSha}.${deferredNote}`,
4680
+ waived: false
4681
+ };
4562
4682
  }
4563
- if (path.endsWith(".tsx") || path.endsWith(".ts")) {
4564
- return content.replace(/\/\*.*?\*\//gs, (m) => m.replace(/[^\n]/g, "")).replace(/(^|[^:])\/\/[^\n]*/g, (m) => m.replace(/[^\n]/g, ""));
4683
+ const problems = [];
4684
+ if (!codeReviewTextClean) {
4685
+ problems.push(`code-reviewer verdict is not a clean APPROVE (found: ${codeReview.value})`);
4686
+ } else if (!codeReviewPolicyClean) {
4687
+ problems.push(`code-reviewer verdict says APPROVE but carries a finding (${codeReviewPolicyEvaluation.blockingFindings.map((f) => f.severity).join(", ")}) at or above this repository's code-review policy threshold (${policy.codeReviewThreshold}) — a reviewer's own APPROVE never overrides policy`);
4688
+ } else if (!codeReviewBound) {
4689
+ problems.push(`the newest code-review verdict covers ${codeReview.headSha ?? "no recorded commit"}, head is ${input.headSha}`);
4690
+ } else if (!codeReviewBinding.base) {
4691
+ problems.push(`the newest code-review verdict was cast against base ${codeReview.baseSha ?? "no recorded base"}, the PR's base is now ${currentManifest.baseSha ?? "unresolved"} (a base-only change under an unchanged candidate — same patch text on a new base is not automatically equivalent)`);
4692
+ } else if (!codeReviewObjectivesBound) {
4693
+ problems.push(`the newest code-review verdict was cast against objectives version ${codeReview.objectivesVersion ?? "none"}, the Issue's list is now ${input.objectivesVersion}`);
4694
+ } else if (!codeReviewRulingsBound) {
4695
+ problems.push(`the newest code-review verdict was cast against ruling ordinal ${codeReview.rulingOrdinal ?? "none"}, a newer ruling (ruling ${input.rulingOrdinal}) is now posted on this PR`);
4696
+ } else if (!codeReviewBinding.briefHash) {
4697
+ problems.push(`the newest code-review verdict was cast against brief hash ${codeReview.briefHash ?? "none"}, the frozen brief's current hash is ${currentManifest.briefHash ?? "none"}`);
4698
+ } else if (!codeReviewBinding.policyDigest) {
4699
+ problems.push(`the newest code-review verdict was cast against review policy digest ${codeReview.policyDigest ?? "none"}, this repository's current policy digest is ${currentManifest.policyDigest}`);
4565
4700
  }
4566
- return content;
4567
- }
4568
- function stripNonProseForProduct(path, content) {
4569
- return path.endsWith(".md") ? stripNonProse(path, content) : content;
4570
- }
4571
- function lineAt(content, index) {
4572
- let line = 1;
4573
- for (let i = 0;i < index; i++) {
4574
- if (content.charCodeAt(i) === 10)
4575
- line++;
4701
+ if (!securityTextClean) {
4702
+ problems.push(`security-review verdict is not a clean PASS (found: ${security.value})`);
4703
+ } else if (!securityPolicyClean) {
4704
+ problems.push(`security-review verdict says PASS but carries a finding (${securityPolicyEvaluation.blockingFindings.map((f) => f.severity).join(", ")}) at or above this repository's security policy threshold (${policy.securityThreshold}) — a reviewer's own PASS never overrides policy`);
4705
+ } else if (!securityBound) {
4706
+ problems.push(`the newest security-review verdict covers ${security.headSha ?? "no recorded commit"}, head is ${input.headSha}`);
4707
+ } else if (!securityBinding.base) {
4708
+ problems.push(`the newest security-review verdict was cast against base ${security.baseSha ?? "no recorded base"}, the PR's base is now ${currentManifest.baseSha ?? "unresolved"} (a base-only change under an unchanged candidate — same patch text on a new base is not automatically equivalent)`);
4709
+ } else if (!securityObjectivesBound) {
4710
+ problems.push(`the newest security-review verdict was cast against objectives version ${security.objectivesVersion ?? "none"}, the Issue's list is now ${input.objectivesVersion}`);
4711
+ } else if (!securityRulingsBound) {
4712
+ problems.push(`the newest security-review verdict was cast against ruling ordinal ${security.rulingOrdinal ?? "none"}, a newer ruling (ruling ${input.rulingOrdinal}) is now posted on this PR`);
4713
+ } else if (!securityBinding.briefHash) {
4714
+ problems.push(`the newest security-review verdict was cast against brief hash ${security.briefHash ?? "none"}, the frozen brief's current hash is ${currentManifest.briefHash ?? "none"}`);
4715
+ } else if (!securityBinding.policyDigest) {
4716
+ problems.push(`the newest security-review verdict was cast against review policy digest ${security.policyDigest ?? "none"}, this repository's current policy digest is ${currentManifest.policyDigest}`);
4576
4717
  }
4577
- return line;
4718
+ const ignoredNote = ignoredCount > 0 ? ` ${ignoredCount} verdict-shaped comment(s) from authors outside the principal allowlist were ignored.` : "";
4719
+ return {
4720
+ verdict: "fail",
4721
+ reason: `${problems.join("; ")}. A principal can apply an actor-verified \`${WAIVER_LABEL_REVIEW}\` label to skip this requirement, or post the missing/clean verdict comment(s).${ignoredNote}${deferredNote}`,
4722
+ waived: false
4723
+ };
4578
4724
  }
4579
- var FORGE_NUMBER_PATTERN = /#[0-9]{2,4}/g;
4580
- var TRANCHE_SLUG_VN_PATTERN = /[a-z][a-z-]+-v[0-9]/g;
4581
- var TASK_NUMBER_PATTERN = /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi;
4582
- function legacySlugPattern(legacySlugs) {
4583
- if (legacySlugs.length === 0)
4584
- return null;
4585
- const alternation = legacySlugs.map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
4586
- return new RegExp(`(^|[^a-zA-Z0-9\\n-])(${alternation})([^a-zA-Z0-9\\n-]|$)`, "g");
4725
+ var CHANGESET_RELEASE_BRANCH = "changeset-release/main";
4726
+ var DEFAULT_RELEASE_ACTOR = "github-actions[bot]";
4727
+ function isChangesetsReleasePr(branch, author, expectedAuthor) {
4728
+ return branch === CHANGESET_RELEASE_BRANCH && author === expectedAuthor;
4587
4729
  }
4588
- function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4589
- const findings = [];
4590
- const legacyPattern = legacySlugPattern(legacySlugs);
4591
- const grandfathered = new Set(specGrandfather);
4592
- const patterns = [
4593
- { pattern: FORGE_NUMBER_PATTERN, what: "a forge number" },
4594
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug" },
4595
- ...legacyPattern ? [{ pattern: legacyPattern, what: "an internal tranche slug", group: 2 }] : []
4596
- ];
4597
- const productPatterns = [
4598
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug in product code" }
4599
- ];
4600
- const specPatterns = [
4601
- ...patterns,
4602
- { pattern: TASK_NUMBER_PATTERN, what: "a task number", group: 2 }
4603
- ];
4604
- for (const file of files) {
4605
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths);
4606
- if (!cls || cls === "internal")
4607
- continue;
4608
- if (cls !== "product" && cls !== "spec" && !SWEPT_CLASSES.has(cls))
4730
+ // ../../packages/aeg-core/src/ruling-ordinal.ts
4731
+ var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
4732
+ function newestPrincipalRulingOrdinal(comments, allowlist) {
4733
+ let best = 0;
4734
+ for (const c of comments) {
4735
+ if (!isPrincipal(c.author, allowlist))
4609
4736
  continue;
4610
- if (cls === "spec" && grandfathered.has(file.path))
4737
+ const firstLine = (c.body.split(`
4738
+ `)[0] ?? "").trim();
4739
+ const m = RULING_MARKER_ORDINAL.exec(firstLine);
4740
+ if (!m)
4611
4741
  continue;
4612
- const blocking = cls === "product" || cls === "spec";
4613
- const scrubbed = cls === "product" ? stripNonProseForProduct(file.path, file.content) : stripNonProse(file.path, file.content);
4614
- const patternsToRun = cls === "product" ? productPatterns : cls === "spec" ? specPatterns : patterns;
4615
- for (const { pattern, what, group } of patternsToRun) {
4616
- pattern.lastIndex = 0;
4617
- let match = pattern.exec(scrubbed);
4618
- while (match !== null) {
4619
- const cited = group !== undefined ? match[group] ?? match[0] : match[0];
4620
- const citedIndex = match.index + match[0].indexOf(cited);
4621
- findings.push({
4622
- file: file.path,
4623
- line: lineAt(scrubbed, citedIndex),
4624
- message: `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
4625
- blocking
4626
- });
4627
- match = pattern.exec(scrubbed);
4742
+ const k = Number.parseInt(m[1], 10);
4743
+ if (k > best)
4744
+ best = k;
4745
+ }
4746
+ return best;
4747
+ }
4748
+ // ../../packages/aeg-core/src/markdown-table.ts
4749
+ function splitRow(line) {
4750
+ const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
4751
+ return trimmed.split("|").map((cell) => cell.trim());
4752
+ }
4753
+ var TABLE_ROW_PATTERN = /^\s*\|.*\|\s*$/;
4754
+ var SEPARATOR_ROW_PATTERN = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
4755
+ function findTable(lines, fromLine, stopAtHeading = true) {
4756
+ let i = fromLine - 1;
4757
+ while (i < lines.length) {
4758
+ const line = lines[i] ?? "";
4759
+ if (stopAtHeading && i > fromLine - 1 && /^##\s/.test(line))
4760
+ return null;
4761
+ if (TABLE_ROW_PATTERN.test(line)) {
4762
+ const headerLine = line;
4763
+ const sepLine = lines[i + 1] ?? "";
4764
+ if (!SEPARATOR_ROW_PATTERN.test(sepLine)) {
4765
+ i++;
4766
+ continue;
4767
+ }
4768
+ const headers = splitRow(headerLine);
4769
+ const rows = [];
4770
+ let j = i + 2;
4771
+ while (j < lines.length && TABLE_ROW_PATTERN.test(lines[j] ?? "")) {
4772
+ rows.push({ cells: splitRow(lines[j] ?? ""), line: j + 1 });
4773
+ j++;
4628
4774
  }
4775
+ return { headers, rows };
4629
4776
  }
4777
+ i++;
4630
4778
  }
4631
- return findings;
4779
+ return null;
4632
4780
  }
4633
- function escapeTerm(term) {
4634
- return term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4781
+ function findHeadingLine(lines, pattern) {
4782
+ for (let i = 0;i < lines.length; i++) {
4783
+ if (pattern.test(lines[i] ?? ""))
4784
+ return i + 1;
4785
+ }
4786
+ return null;
4635
4787
  }
4636
- function containsWholeWord(text, term) {
4637
- const escaped = escapeTerm(term);
4638
- const re = new RegExp(`(^|[^a-zA-Z])${escaped}([^a-zA-Z]|$)`, "i");
4639
- return re.test(text);
4788
+ // ../../packages/aeg-core/src/diagram-model.ts
4789
+ import matter from "gray-matter";
4790
+
4791
+ // ../../packages/aeg-core/src/registry-parse.ts
4792
+ var RING_HEADINGS = [
4793
+ { ring: "ring0", pattern: /^##\s+Ring 0\b/ },
4794
+ { ring: "ring1", pattern: /^##\s+Ring 1\b/ },
4795
+ { ring: "ring2", pattern: /^##\s+Ring 2\b/ }
4796
+ ];
4797
+ function stripBackticks2(cell) {
4798
+ const trimmed = cell.trim();
4799
+ if (trimmed.length >= 2 && trimmed.startsWith("`") && trimmed.endsWith("`")) {
4800
+ return trimmed.slice(1, -1);
4801
+ }
4802
+ return trimmed;
4640
4803
  }
4641
- function findWholeWordLine(content, term) {
4804
+ function stripBold(cell) {
4805
+ return cell.trim().replace(/\*\*/g, "");
4806
+ }
4807
+ function parseEnforcementRegistry(content) {
4642
4808
  const lines = content.split(`
4643
4809
  `);
4644
- let lineNo = 0;
4645
- for (const line of lines) {
4646
- lineNo++;
4647
- if (containsWholeWord(line, term))
4648
- return lineNo;
4810
+ const result = [];
4811
+ for (const { ring, pattern } of RING_HEADINGS) {
4812
+ const headingLine = findHeadingLine(lines, pattern);
4813
+ if (headingLine === null)
4814
+ continue;
4815
+ const table = findTable(lines, headingLine + 1);
4816
+ if (!table)
4817
+ continue;
4818
+ const descriptionIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "description");
4819
+ const implementationIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "implementation");
4820
+ const audienceIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "audience");
4821
+ for (const row of table.rows) {
4822
+ const cells = row.cells;
4823
+ if (cells.length < 3)
4824
+ continue;
4825
+ const action = stripBold(cells[0] ?? "");
4826
+ const summary = stripBackticks2(cells[1] ?? "");
4827
+ const category = stripBackticks2(cells[2] ?? "");
4828
+ const implementation = stripBackticks2((implementationIndex === -1 ? cells[cells.length - 1] : cells[implementationIndex]) ?? "");
4829
+ const description = descriptionIndex === -1 ? undefined : stripBackticks2(cells[descriptionIndex] ?? "") || undefined;
4830
+ const specIndex = (audienceIndex === -1 ? cells.length - 1 : audienceIndex) - 1;
4831
+ const spec = specIndex >= 3 ? stripBackticks2(cells[specIndex] ?? "") || undefined : undefined;
4832
+ const audience = audienceIndex === -1 ? "repo-own" : stripBackticks2(cells[audienceIndex] ?? "") === "product" ? "product" : "repo-own";
4833
+ result.push({ ring, action, summary, category, description, spec, implementation, audience, line: row.line });
4834
+ }
4649
4835
  }
4650
- return null;
4651
- }
4652
- function definesOrLinksGlossary(content, term) {
4653
- const escaped = escapeTerm(term);
4654
- const definesInline = new RegExp(`(^|[^a-zA-Z])${escaped}([^a-zA-Z]|$)[^\\n]{0,3}—`, "i").test(content);
4655
- if (definesInline)
4656
- return true;
4657
- return /docs\/glossary|glossary\.md/i.test(content);
4836
+ return result;
4658
4837
  }
4659
- function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX) {
4838
+ // ../../packages/aeg-core/src/registry-checks.ts
4839
+ function checkG1(rows, existsFn) {
4660
4840
  const findings = [];
4661
- for (const file of files) {
4662
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
4663
- if (!cls || !SWEPT_CLASSES.has(cls))
4841
+ for (const row of rows) {
4842
+ if (row.implementation === "")
4664
4843
  continue;
4665
- const scrubbed = stripNonProse(file.path, file.content);
4666
- for (const term of glossaryTerms) {
4667
- const line = findWholeWordLine(scrubbed, term);
4668
- if (line === null)
4669
- continue;
4670
- if (definesOrLinksGlossary(scrubbed, term))
4671
- continue;
4844
+ if (!existsFn(row.implementation)) {
4672
4845
  findings.push({
4673
- file: file.path,
4674
- line,
4675
- message: `uses coined term "${term}" without defining it inline or linking the glossary`,
4676
- blocking: false
4846
+ row: row.action,
4847
+ path: row.implementation,
4848
+ reason: `${row.ring} row "${row.action}" names implementation "${row.implementation}", which does not exist on disk`
4677
4849
  });
4678
4850
  }
4679
4851
  }
4680
- return findings;
4852
+ return { check: "G1", status: findings.length > 0 ? "fail" : "pass", findings };
4681
4853
  }
4682
- var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g;
4683
- var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = /#[0-9]{2,}/g;
4684
- function extractComments(path, content) {
4685
- if (!path.endsWith(".ts") && !path.endsWith(".tsx"))
4686
- return content.replace(/[^\n]/g, "");
4687
- let state = "code";
4688
- let out = "";
4689
- const n = content.length;
4690
- let i = 0;
4691
- const blank = (ch) => ch === `
4692
- ` ? `
4693
- ` : " ";
4694
- while (i < n) {
4695
- const c = content[i];
4696
- const next = i + 1 < n ? content[i + 1] : "";
4697
- if (state === "code") {
4698
- if (c === "/" && next === "/") {
4699
- state = "line-comment";
4700
- out += c;
4701
- i++;
4702
- continue;
4703
- }
4704
- if (c === "/" && next === "*") {
4705
- state = "block-comment";
4706
- out += c;
4707
- i++;
4708
- continue;
4709
- }
4710
- if (c === "'") {
4711
- state = "single-quote";
4712
- out += blank(c);
4713
- i++;
4714
- continue;
4715
- }
4716
- if (c === '"') {
4717
- state = "double-quote";
4718
- out += blank(c);
4719
- i++;
4720
- continue;
4721
- }
4722
- if (c === "`") {
4723
- state = "template";
4724
- out += blank(c);
4725
- i++;
4726
- continue;
4727
- }
4728
- out += blank(c);
4729
- i++;
4730
- continue;
4731
- }
4732
- if (state === "line-comment") {
4733
- if (c === `
4734
- `) {
4735
- state = "code";
4736
- out += `
4737
- `;
4738
- i++;
4739
- continue;
4740
- }
4741
- out += c;
4742
- i++;
4743
- continue;
4744
- }
4745
- if (state === "block-comment") {
4746
- if (c === "*" && next === "/") {
4747
- out += c;
4748
- out += next;
4749
- state = "code";
4750
- i += 2;
4751
- continue;
4752
- }
4753
- out += c === `
4754
- ` ? `
4755
- ` : c;
4756
- i++;
4854
+ var SCAFFOLD_PLACEHOLDER = "[undocumented — fill in why]";
4855
+ var NON_GATE_BIN_NAMES = NON_GATE_BINS;
4856
+ var TWIN_CANDIDATE_EXCEPTIONS = {
4857
+ "apps/cli/src/checks/bin/check-dead-branch-push.ts": 'Ring 0 "Pushing to a branch whose pull request already resolved" (implementation: check-push-target.ts)',
4858
+ "apps/cli/src/checks/bin/check-issue-assignment.ts": `Ring 0 "A task branch's first push (Issue self-assignment)" (implementation: assign-task-issue.ts)`,
4859
+ "apps/cli/src/checks/bin/check-closes-n.ts": 'Ring 1 "Closes linkage" (implementation: verify-coherence.ts)'
4860
+ };
4861
+ var NON_GATE_HOOK_SCRIPTS = [".claude/hooks/track-transcript.sh"];
4862
+ function checkG2(rows, candidateFiles) {
4863
+ const implementations = new Set(rows.map((r) => r.implementation).filter((p) => p !== ""));
4864
+ const claimedNames = new Set(rows.flatMap((r) => claimedCheckNames(r.implementation)));
4865
+ const findings = [];
4866
+ for (const path of candidateFiles) {
4867
+ if (implementations.has(path))
4757
4868
  continue;
4758
- }
4759
- const closer = state === "single-quote" ? "'" : state === "double-quote" ? '"' : "`";
4760
- if (c === "\\") {
4761
- out += blank(c);
4762
- i++;
4763
- if (i < n) {
4764
- out += blank(content[i]);
4765
- i++;
4766
- }
4869
+ if (path.startsWith(AEG_CORE_BIN_PATH_PREFIX) && NON_GATE_BIN_NAMES.includes(basenameNoExt(path)))
4767
4870
  continue;
4768
- }
4769
- if (c === closer) {
4770
- state = "code";
4771
- out += blank(c);
4772
- i++;
4871
+ if (NON_GATE_HOOK_SCRIPTS.includes(path))
4872
+ continue;
4873
+ if (path in TWIN_CANDIDATE_EXCEPTIONS)
4773
4874
  continue;
4875
+ const candidateNames = claimedCheckNames(path);
4876
+ if (candidateNames.length > 0 && candidateNames.some((n) => claimedNames.has(n)))
4877
+ continue;
4878
+ findings.push({
4879
+ path,
4880
+ reason: `"${path}" is not named as the implementation of any row in enforcement.md's ring tables`
4881
+ });
4882
+ }
4883
+ for (const row of rows) {
4884
+ const carriesPlaceholder = [row.summary, row.description, row.spec].some((cell) => cell === SCAFFOLD_PLACEHOLDER);
4885
+ if (carriesPlaceholder) {
4886
+ findings.push({
4887
+ row: row.action,
4888
+ path: row.implementation,
4889
+ reason: `${row.ring} row "${row.action}" still carries the scaffold placeholder marker — the why is owed`
4890
+ });
4774
4891
  }
4775
- out += blank(c);
4776
- i++;
4777
4892
  }
4778
- return out;
4893
+ return { check: "G2", status: findings.length > 0 ? "fail" : "pass", findings };
4779
4894
  }
4780
- function checkSourceComments(files, allowlist = []) {
4895
+ function checkG3(ring0Rows, crossingFiles) {
4896
+ const ring0Implementations = new Set(ring0Rows.map((r) => r.implementation));
4781
4897
  const findings = [];
4782
- const allowed = new Set(allowlist);
4783
- const patterns = [
4784
- { pattern: SOURCE_COMMENT_TRANCHE_SLUG_PATTERN, what: "a tranche-slug citation" },
4785
- { pattern: SOURCE_COMMENT_FORGE_NUMBER_PATTERN, what: "a forge-number citation" }
4786
- ];
4787
- for (const file of files) {
4788
- if (!file.path.endsWith(".ts"))
4789
- continue;
4790
- if (allowed.has(file.path))
4791
- continue;
4792
- const comments = extractComments(file.path, file.content);
4793
- for (const { pattern, what } of patterns) {
4794
- pattern.lastIndex = 0;
4795
- let match = pattern.exec(comments);
4796
- while (match !== null) {
4797
- findings.push({
4798
- file: file.path,
4799
- line: lineAt(comments, match.index),
4800
- message: `comment cites ${what} ("${match[0]}") a reader outside this repo's tracker cannot resolve`,
4801
- blocking: false
4802
- });
4803
- match = pattern.exec(comments);
4804
- }
4898
+ for (const path of crossingFiles) {
4899
+ if (!ring0Implementations.has(path)) {
4900
+ findings.push({
4901
+ path,
4902
+ reason: `"${path}" makes a GitHub-crossing call but is not named by any Ring-0 row's implementation — a seventh, unlisted way into GitHub`
4903
+ });
4805
4904
  }
4806
4905
  }
4807
- return findings;
4808
- }
4809
- function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4810
- return [
4811
- ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths),
4812
- ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix)
4813
- ];
4906
+ return { check: "G3", status: findings.length > 0 ? "fail" : "pass", findings };
4814
4907
  }
4815
- function parseGlossaryTerms(glossaryContent) {
4816
- const terms = [];
4817
- const re = /^\*\*(.+?)\*\* —/gm;
4818
- let match = re.exec(glossaryContent);
4819
- while (match !== null) {
4820
- if (match[1] !== undefined)
4821
- terms.push(match[1]);
4822
- match = re.exec(glossaryContent);
4908
+ function checkG4(content, resolveFn) {
4909
+ const cited = new Set;
4910
+ for (const hit of content.matchAll(/#(\d{3,})\b/g)) {
4911
+ cited.add(Number(hit[1]));
4823
4912
  }
4824
- return terms;
4825
- }
4826
-
4827
- // ../../packages/aeg-core/src/quoted-command.ts
4828
- var QUOTED_COMMAND_SHIPS_PREFIX = "aeg-root/";
4829
- var QUOTED_COMMAND_SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
4830
- var START_PATTERN = /<!--\s*AEG:QUOTES-FILE:START:(\S+?)\s*-->/g;
4831
- var END_PATTERN = /<!--\s*AEG:QUOTES-FILE:END\s*-->/;
4832
- function isValidCitedFilePath(path) {
4833
- if (path.length === 0)
4834
- return false;
4835
- if (path.startsWith("/") || path.startsWith("\\"))
4836
- return false;
4837
- if (/^[A-Za-z]:[\\/]/.test(path))
4838
- return false;
4839
- return !path.split(/[\\/]+/).includes("..");
4840
- }
4841
- function quotedCommandLineAt(content, index) {
4842
- let line = 1;
4843
- for (let i = 0;i < index; i++) {
4844
- if (content.charCodeAt(i) === 10)
4845
- line++;
4913
+ const findings = [];
4914
+ for (const n of cited) {
4915
+ if (!resolveFn(n)) {
4916
+ findings.push({
4917
+ reason: `#${n} is cited in enforcement.md but does not resolve to a real Issue or PR in the forge`
4918
+ });
4919
+ }
4846
4920
  }
4847
- return line;
4848
- }
4849
- function extractQuotedText(raw) {
4850
- const trimmed = raw.trim();
4851
- const fenced = /^(?:`{3,}|~{3,})[^\n]*\n([\s\S]*?)\n?(?:`{3,}|~{3,})$/.exec(trimmed);
4852
- if (fenced)
4853
- return (fenced[1] ?? "").trim();
4854
- const inline = /^`([^`]+)`$/.exec(trimmed);
4855
- if (inline)
4856
- return (inline[1] ?? "").trim();
4857
- return trimmed;
4921
+ return { check: "G4", status: findings.length > 0 ? "fail" : "pass", findings };
4858
4922
  }
4859
- function findQuotesInFile(path, content) {
4860
- const masked = maskCode(content);
4861
- const quotes = [];
4862
- START_PATTERN.lastIndex = 0;
4863
- let start = START_PATTERN.exec(masked);
4864
- while (start !== null) {
4865
- const citedFile = start[1];
4866
- const innerStart = start.index + start[0].length;
4867
- const end = END_PATTERN.exec(masked.slice(innerStart));
4868
- if (end === null) {
4869
- START_PATTERN.lastIndex = innerStart;
4870
- start = START_PATTERN.exec(masked);
4871
- continue;
4923
+ function checkG5(roles, contracts) {
4924
+ const roleIds = new Set(roles.map((r) => r.role_id));
4925
+ const findings = [];
4926
+ for (const contract of contracts) {
4927
+ if (!roleIds.has(contract.producer)) {
4928
+ findings.push({
4929
+ path: contract.file,
4930
+ reason: `contract "${contract.file}" names producer "${contract.producer}", which is not a real role_id`
4931
+ });
4872
4932
  }
4873
- const innerEnd = innerStart + end.index;
4874
- if (isValidCitedFilePath(citedFile)) {
4875
- const quotedText = extractQuotedText(content.slice(innerStart, innerEnd));
4876
- if (quotedText.length > 0) {
4877
- quotes.push({ file: path, line: quotedCommandLineAt(content, innerStart), quotedText, citedFile });
4878
- }
4933
+ if (!roleIds.has(contract.consumer)) {
4934
+ findings.push({
4935
+ path: contract.file,
4936
+ reason: `contract "${contract.file}" names consumer "${contract.consumer}", which is not a real role_id`
4937
+ });
4879
4938
  }
4880
- START_PATTERN.lastIndex = innerEnd + end[0].length;
4881
- start = START_PATTERN.exec(masked);
4882
4939
  }
4883
- return quotes;
4940
+ for (const role of roles) {
4941
+ if (role.performs.length === 0) {
4942
+ findings.push({ path: role.file, reason: `role "${role.role_id}" has an empty performs array` });
4943
+ }
4944
+ if (role.refuses_when.trim() === "") {
4945
+ findings.push({ path: role.file, reason: `role "${role.role_id}" has an empty refuses_when` });
4946
+ }
4947
+ }
4948
+ return { check: "G5", status: findings.length > 0 ? "fail" : "pass", findings };
4884
4949
  }
4885
- function findCitedQuotes(files, readerFacingPrefix, readerFacingSuffix, shipsPrefix = QUOTED_COMMAND_SHIPS_PREFIX) {
4886
- const quotes = [];
4887
- for (const file of files) {
4888
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
4889
- if (!cls || !QUOTED_COMMAND_SWEPT_CLASSES.has(cls))
4890
- continue;
4891
- quotes.push(...findQuotesInFile(file.path, file.content));
4950
+ var SHIPPED_BIN_PATH_PREFIX = "apps/cli/src/checks/bin/check-";
4951
+ var AEG_CORE_BIN_PATH_PREFIX = "packages/aeg-core/bin/";
4952
+ function basenameNoExt(path) {
4953
+ const base = path.slice(path.lastIndexOf("/") + 1);
4954
+ return base.replace(/\.ts$/, "");
4955
+ }
4956
+ function claimedCheckNames(implementation) {
4957
+ if (implementation.startsWith(SHIPPED_BIN_PATH_PREFIX) && implementation.endsWith(".ts")) {
4958
+ return [implementation.slice(SHIPPED_BIN_PATH_PREFIX.length, -".ts".length)];
4892
4959
  }
4893
- return quotes;
4960
+ if (implementation.startsWith(AEG_CORE_BIN_PATH_PREFIX)) {
4961
+ const audience = GATE_AUDIENCE[basenameNoExt(implementation)];
4962
+ if (audience && isShipped(audience)) {
4963
+ return Array.isArray(audience.shippedAs) ? audience.shippedAs : [audience.shippedAs];
4964
+ }
4965
+ }
4966
+ return [];
4894
4967
  }
4895
- function evaluateCitedQuotes(citedQuotes, citedFileContents) {
4968
+ function checkG6(rows, registeredCheckNames) {
4896
4969
  const findings = [];
4897
- for (const quote of citedQuotes) {
4898
- const content = citedFileContents.get(quote.citedFile);
4899
- if (content === undefined) {
4900
- findings.push({
4901
- file: quote.file,
4902
- line: quote.line,
4903
- citedFile: quote.citedFile,
4904
- quotedText: quote.quotedText,
4905
- message: `${quote.file}:${quote.line} quotes "${quote.quotedText}" as citing \`${quote.citedFile}\`, but that file could not be read`
4906
- });
4970
+ for (const row of rows) {
4971
+ if (row.audience !== "product")
4907
4972
  continue;
4908
- }
4909
- if (!content.includes(quote.quotedText)) {
4973
+ const candidates = claimedCheckNames(row.implementation);
4974
+ if (!candidates.some((name) => registeredCheckNames.has(name))) {
4910
4975
  findings.push({
4911
- file: quote.file,
4912
- line: quote.line,
4913
- citedFile: quote.citedFile,
4914
- quotedText: quote.quotedText,
4915
- message: `${quote.file}:${quote.line} quotes "${quote.quotedText}" as citing \`${quote.citedFile}\`, but \`${quote.citedFile}\` no longer contains that text verbatim`
4976
+ row: row.action,
4977
+ path: row.implementation,
4978
+ reason: `${row.ring} row "${row.action}" is marked \`product\` but its implementation "${row.implementation}" does not resolve to a coreCheckRegistry() entry`
4916
4979
  });
4917
4980
  }
4918
4981
  }
4919
- return findings;
4982
+ return { check: "G6", status: findings.length > 0 ? "fail" : "pass", findings };
4920
4983
  }
4921
4984
  // ../../packages/aeg-core/src/dead-branch-push-guard.ts
4922
4985
  function checkDeadBranchPush(input) {
@@ -5823,7 +5886,9 @@ var DevReviewLoopEventSchema = z2.discriminatedUnion("event", [
5823
5886
  "escalated",
5824
5887
  "principal_stop",
5825
5888
  "confidence",
5826
- "reappearance"
5889
+ "reappearance",
5890
+ "repeat_finding",
5891
+ "repeat_failure"
5827
5892
  ])
5828
5893
  }).strict(),
5829
5894
  z2.object({
@@ -6327,6 +6392,10 @@ var LoopStateRecordSchema = z3.object({
6327
6392
  budgets: LoopBudgetsSchema,
6328
6393
  heldResult: roundHeadIdentity.nullable(),
6329
6394
  deliveredFindings: roundHeadIdentity.nullable(),
6395
+ repeatMemory: z3.object({
6396
+ blockingFindings: z3.array(z3.string()),
6397
+ lastFailure: z3.object({ signature: z3.string(), message: z3.string() }).nullable()
6398
+ }).strict().optional(),
6330
6399
  recordedAt: isoTimestamp
6331
6400
  }).strict();
6332
6401
  var EffectRecordSchema = z3.object({
@@ -6378,7 +6447,7 @@ var ResolutionRecordSchema = z3.object({
6378
6447
  consumedAt: isoTimestamp
6379
6448
  }).strict();
6380
6449
  // src/lib/config.ts
6381
- import { execFile as execFile4, execFileSync as execFileSync2 } from "node:child_process";
6450
+ import { execFile as execFile4, execFileSync as execFileSync3 } from "node:child_process";
6382
6451
  import { promisify as promisify4 } from "node:util";
6383
6452
  import { existsSync, mkdirSync, readFileSync as readFileSync2, realpathSync, writeFileSync } from "node:fs";
6384
6453
  import { homedir } from "node:os";
@@ -6388,6 +6457,28 @@ import { z as z4 } from "zod";
6388
6457
  // src/lib/agent-vendors.ts
6389
6458
  var AGENT_VENDORS = ["skills", "claude", "gemini"];
6390
6459
 
6460
+ // src/lib/worker-boundary.ts
6461
+ import { execFileSync as execFileSync2 } from "node:child_process";
6462
+ var LOG_HEADER_KEYCHAIN_SERVICE = "Vinaya Log";
6463
+ var logHeaderKeychainCache = new Map;
6464
+ function readRealLogHeaderKeychainCredential(variable) {
6465
+ if (process.platform !== "darwin")
6466
+ return null;
6467
+ try {
6468
+ return execFileSync2("/usr/bin/security", ["find-generic-password", "-s", LOG_HEADER_KEYCHAIN_SERVICE, "-a", variable, "-w"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5000, maxBuffer: 1024 * 1024 }).replace(/\n$/, "");
6469
+ } catch {
6470
+ return null;
6471
+ }
6472
+ }
6473
+ function readLogHeaderKeychainCredential(variable) {
6474
+ const cached = logHeaderKeychainCache.get(variable);
6475
+ if (cached !== undefined)
6476
+ return cached;
6477
+ const value = readRealLogHeaderKeychainCredential(variable);
6478
+ logHeaderKeychainCache.set(variable, value);
6479
+ return value;
6480
+ }
6481
+
6391
6482
  // src/lib/config.ts
6392
6483
  var EnvEntrySchema = z4.union([
6393
6484
  z4.literal(true),
@@ -6563,6 +6654,9 @@ var VinayaConfigSchema = z4.object({
6563
6654
  briefRulesSincePr: z4.number().int().nonnegative().optional(),
6564
6655
  agentBoxesRefusedSincePr: z4.number().int().nonnegative().optional()
6565
6656
  }).optional(),
6657
+ planning: z4.object({
6658
+ collisionThreshold: z4.number().int().nonnegative().optional()
6659
+ }).optional(),
6566
6660
  prePush: z4.object({
6567
6661
  alwaysRun: z4.array(z4.string()).optional()
6568
6662
  }).optional(),
@@ -6737,12 +6831,17 @@ function resolveTrustAnchorLogsDestination(local, trustAnchorConfig) {
6737
6831
  return "url" in anchored && anchored.url === local.url ? anchored : null;
6738
6832
  return "folder" in anchored && anchored.folder === local.folder ? anchored : null;
6739
6833
  }
6740
- function resolveLogsHeaderValues(headers, env) {
6834
+ function resolveLogsHeaderValues(headers, env, readKeychain = readLogHeaderKeychainCredential) {
6741
6835
  if (!headers)
6742
6836
  return;
6743
6837
  const resolved = {};
6744
6838
  for (const [key, value] of Object.entries(headers)) {
6745
- resolved[key] = value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_match, name) => env[name] ?? "");
6839
+ resolved[key] = value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_match, name) => {
6840
+ const fromEnv = env[name];
6841
+ if (fromEnv !== undefined)
6842
+ return fromEnv;
6843
+ return readKeychain(name) ?? "";
6844
+ });
6746
6845
  }
6747
6846
  return resolved;
6748
6847
  }
@@ -6751,7 +6850,7 @@ function trustAnchorRepo() {
6751
6850
  if (fromRunner)
6752
6851
  return fromRunner;
6753
6852
  try {
6754
- const url = execFileSync2("git", ["remote", "get-url", "origin"], {
6853
+ const url = execFileSync3("git", ["remote", "get-url", "origin"], {
6755
6854
  encoding: "utf-8",
6756
6855
  stdio: ["ignore", "pipe", "pipe"]
6757
6856
  });
@@ -6767,7 +6866,8 @@ async function trustAnchorRepoAsync() {
6767
6866
  try {
6768
6867
  const { stdout } = await execFileAsync4("git", ["remote", "get-url", "origin"], {
6769
6868
  encoding: "utf-8",
6770
- timeout: 1e4
6869
+ timeout: 1e4,
6870
+ killSignal: "SIGKILL"
6771
6871
  });
6772
6872
  return trustAnchorRepoFromRemoteUrl(stdout);
6773
6873
  } catch {
@@ -6797,7 +6897,7 @@ function resolveCiTrustAnchorProbeRef(env = process.env) {
6797
6897
  return ref;
6798
6898
  }
6799
6899
  function readTrustAnchorConfigAtRef(ref) {
6800
- const raw = execFileSync2("git", ["show", `${ref}:${LOCAL_CONFIG_FILENAME}`], {
6900
+ const raw = execFileSync3("git", ["show", `${ref}:${LOCAL_CONFIG_FILENAME}`], {
6801
6901
  encoding: "utf-8",
6802
6902
  stdio: ["ignore", "pipe", "pipe"],
6803
6903
  timeout: 1e4
@@ -6811,7 +6911,7 @@ function ghFetchTrustAnchorConfig() {
6811
6911
  const repo = trustAnchorRepo();
6812
6912
  if (!repo)
6813
6913
  throw new Error("could not resolve repo identity for the trust-anchor read");
6814
- return execFileSync2("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], {
6914
+ return execFileSync3("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], {
6815
6915
  encoding: "utf-8",
6816
6916
  stdio: ["ignore", "pipe", "pipe"]
6817
6917
  });
@@ -6828,7 +6928,7 @@ async function ghFetchTrustAnchorConfigAsync() {
6828
6928
  const repo = await trustAnchorRepoAsync();
6829
6929
  if (!repo)
6830
6930
  throw new Error("could not resolve repo identity for the trust-anchor read");
6831
- const { stdout } = await execFileAsync4("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], { encoding: "utf-8", timeout: 1e4 });
6931
+ const { stdout } = await execFileAsync4("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], { encoding: "utf-8", timeout: 1e4, killSignal: "SIGKILL" });
6832
6932
  return stdout;
6833
6933
  }
6834
6934
  function firstLine(err) {
@@ -6902,7 +7002,7 @@ function loadConfig() {
6902
7002
  var TOKENS_COLLECT_TRUST_PATH = join(GLOBAL_VINAYA_HOME, "tokens-collect-trust.json");
6903
7003
 
6904
7004
  // src/lib/brief-assembly.ts
6905
- import { execFileSync as execFileSync5 } from "node:child_process";
7005
+ import { execFileSync as execFileSync6 } from "node:child_process";
6906
7006
  import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync as readdirSync2 } from "node:fs";
6907
7007
  import { join as join4 } from "node:path";
6908
7008
 
@@ -7598,6 +7698,27 @@ var COMMANDS = [
7598
7698
  "issue-711 O4: this command — `--task <n>`, `--resume <pr>`, `--cancel <pr>` alike — stays `task run`'s own one-shot debug/direct entry; the watching driver that survives a pause and continues on its own is `task run`'s (see that command's own entry)."
7599
7699
  ],
7600
7700
  status: "shipped"
7701
+ },
7702
+ {
7703
+ name: "log send",
7704
+ description: "Deliver this repository's locally-held log events to the configured `logs.url` server, once",
7705
+ flags: [{ flag: "--json", description: "Enveloped JSON output (schema: 1)" }],
7706
+ details: [
7707
+ "For a run whose events ended up on local disk instead of the configured server — an unattended run that fell back to the local folder because the trust-anchor read could not confirm its `logs.url` (a developer machine slower than the read deadline, or genuinely offline), or a retry queue holding a backlog or a `.draining.ndjson` a dead drain left behind. It moves the local folder's events into the retry queue and drains every queue for this repository through the SAME webhook delivery a live event uses.",
7708
+ "It resolves the destination exactly the way a normal event does — the sink's own decision over `vinaya.config.json`'s `logs` setting, trust-anchor-gated for an unattended caller — never a URL passed on the command line. A repository whose destination is a folder (or none) has nothing to send to a server and the command says so.",
7709
+ "Safe to run more than once: the server stores events by `event_id` and ignores one it already holds, so a re-sent chunk creates no duplicate, and a second run finds the folder emptied and the queue drained."
7710
+ ],
7711
+ status: "shipped"
7712
+ },
7713
+ {
7714
+ name: "log set-credential",
7715
+ description: "Store a `logs.headers` delivery credential in the macOS login Keychain, read from standard input",
7716
+ details: [
7717
+ 'For a `logs.url` server whose `headers` reference a credential by variable name (`{ "authorization": "Bearer ${VINAYA_LOG_TOKEN}" }`) on a host where that variable is not in the process environment — the case an Operator the Claude desktop app starts on macOS hits, since the token lives in an interactive shell file the app never reads. It stores the value so header resolution finds it in the Keychain when the environment does not, with no token copied into any settings file.',
7718
+ 'The value is read from STANDARD INPUT, never a command-line argument a `ps` listing could show — `printf %s "$TOKEN" | vinaya log set-credential VINAYA_LOG_TOKEN`. Only the variable NAME, which is not a secret, sits on the command line; the value is stored under the Keychain service `Vinaya Log` keyed by that name. The command prints a confirmation naming the variable and never echoes, returns, or logs the value.',
7719
+ "macOS only (Linux keyrings are out of scope); it refuses with a clear message elsewhere. The environment still wins over the Keychain wherever the variable is set, so this changes nothing for a host that already exports it."
7720
+ ],
7721
+ status: "shipped"
7601
7722
  }
7602
7723
  ];
7603
7724
  // ../../packages/sources/src/forge-adapter.ts
@@ -7615,7 +7736,7 @@ var StateSourceConfigSchema = z5.discriminatedUnion("kind", [
7615
7736
  z5.object({ kind: z5.literal("file"), root: z5.string().optional() })
7616
7737
  ]);
7617
7738
  // src/checks/edge-resolve.ts
7618
- import { execFileSync as execFileSync3 } from "node:child_process";
7739
+ import { execFileSync as execFileSync4 } from "node:child_process";
7619
7740
  var DIRECT_ISSUE_REF = /#(\d+)/;
7620
7741
  var issueCache = new Map;
7621
7742
  function fetchIssueState(num, repo) {
@@ -7624,7 +7745,7 @@ function fetchIssueState(num, repo) {
7624
7745
  return issueCache.get(key) ?? null;
7625
7746
  let out = null;
7626
7747
  try {
7627
- const raw = execFileSync3("gh", [
7748
+ const raw = execFileSync4("gh", [
7628
7749
  "issue",
7629
7750
  "view",
7630
7751
  String(num),
@@ -7750,7 +7871,7 @@ function packageRoot(moduleUrl) {
7750
7871
  }
7751
7872
 
7752
7873
  // src/commands/doctrine.ts
7753
- import { execFileSync as execFileSync4 } from "node:child_process";
7874
+ import { execFileSync as execFileSync5 } from "node:child_process";
7754
7875
  import { existsSync as existsSync3, readdirSync, readFileSync as readFileSync3 } from "node:fs";
7755
7876
  import { dirname as dirname3, join as join3, sep } from "node:path";
7756
7877
  import matter2 from "gray-matter";
@@ -7760,7 +7881,7 @@ function resolveDoctrineRoot(pkg = packageRoot(import.meta.url), cwd = process.c
7760
7881
  }
7761
7882
  function gitToplevel(cwd) {
7762
7883
  try {
7763
- return execFileSync4("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
7884
+ return execFileSync5("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
7764
7885
  encoding: "utf8",
7765
7886
  stdio: ["ignore", "pipe", "pipe"]
7766
7887
  }).trim();
@@ -7789,7 +7910,7 @@ var PACKAGED_TEMPLATE_PATH = join4(PACKAGE_ROOT, "aeg-root", "templates", "brief
7789
7910
  var TEMPLATE_PATH = existsSync4(PACKAGED_TEMPLATE_PATH) ? PACKAGED_TEMPLATE_PATH : join4(PACKAGE_ROOT, "..", "..", "aeg-root", "templates", "brief-template.md");
7790
7911
  function git(args) {
7791
7912
  try {
7792
- return execFileSync5("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
7913
+ return execFileSync6("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
7793
7914
  } catch {
7794
7915
  return "";
7795
7916
  }
@@ -8809,7 +8930,14 @@ async function drainOutboxToWebhook(outboxTask, webhookUrl, headers, fetchTimeou
8809
8930
 
8810
8931
  // src/lib/log-sink.ts
8811
8932
  var OUTBOX_MAX_BYTES = 8 * 1024 * 1024;
8933
+ function describeFolderFallback(reason) {
8934
+ if (reason.kind === "anchor-unreadable") {
8935
+ 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`";
8936
+ }
8937
+ return `not delivering to the working-tree log server ${reason.intendedUrl} — the default branch's ` + "vinaya.config.json does not declare it, so an unattended run does not honour it (a pull request cannot " + "redirect telemetry); events are written to the local folder";
8938
+ }
8812
8939
  var LOG_CONTEXT_LOOKUP_DEADLINE_MS = 3000;
8940
+ var LOG_DESTINATION_ANCHOR_DEADLINE_MS = 8000;
8813
8941
  function withDeadline(work, ms, fallback) {
8814
8942
  return new Promise((resolve) => {
8815
8943
  const timer = setTimeout(() => resolve(fallback), ms);
@@ -8824,7 +8952,7 @@ function withDeadline(work, ms, fallback) {
8824
8952
  });
8825
8953
  }
8826
8954
  async function safeLoadTrustAnchorConfig() {
8827
- return withDeadline(loadTrustAnchorConfigAsync(undefined, { quiet: true }), LOG_CONTEXT_LOOKUP_DEADLINE_MS, null);
8955
+ return withDeadline(loadTrustAnchorConfigAsync(undefined, { quiet: true }), LOG_DESTINATION_ANCHOR_DEADLINE_MS, null);
8828
8956
  }
8829
8957
  function logsCredentialMissing(headers, env) {
8830
8958
  if (!headers)
@@ -8841,8 +8969,16 @@ function logsCredentialMissing(headers, env) {
8841
8969
  function resolveLogDestinationFrom(input) {
8842
8970
  const local = resolveLogsSetting(input.localConfig);
8843
8971
  let effective = null;
8972
+ let fallbackReason;
8844
8973
  if (input.unattended) {
8845
- effective = local ? resolveTrustAnchorLogsDestination(local, input.trustAnchorConfig) : resolveLogsSetting(input.trustAnchorConfig);
8974
+ if (local) {
8975
+ effective = resolveTrustAnchorLogsDestination(local, input.trustAnchorConfig);
8976
+ if (effective === null && "url" in local) {
8977
+ fallbackReason = input.trustAnchorConfig === null ? { kind: "anchor-unreadable", intendedUrl: local.url } : { kind: "anchor-mismatch", intendedUrl: local.url };
8978
+ }
8979
+ } else {
8980
+ effective = resolveLogsSetting(input.trustAnchorConfig);
8981
+ }
8846
8982
  } else {
8847
8983
  effective = local;
8848
8984
  }
@@ -8868,7 +9004,7 @@ function resolveLogDestinationFrom(input) {
8868
9004
  effective = null;
8869
9005
  }
8870
9006
  const folder = effective && "folder" in effective ? effective.folder : input.defaultFolder;
8871
- return { kind: "folder", folder };
9007
+ return fallbackReason ? { kind: "folder", folder, fallbackReason } : { kind: "folder", folder };
8872
9008
  }
8873
9009
  var processTrustAnchorOnce;
8874
9010
  function processTrustAnchor() {
@@ -9247,6 +9383,10 @@ function createLogSink(overrides = {}) {
9247
9383
  `);
9248
9384
  return;
9249
9385
  }
9386
+ if (resolvedDestination.kind === "folder" && resolvedDestination.fallbackReason) {
9387
+ warnOnce(`vinaya: ${describeFolderFallback(resolvedDestination.fallbackReason)}
9388
+ `);
9389
+ }
9250
9390
  const branchIssue = envFields.task ? null : await branchIssueOnce(repo);
9251
9391
  const header = buildHeader({
9252
9392
  now,
@@ -9317,6 +9457,8 @@ var defaultSink = createLogSink();
9317
9457
  var activeChecks = new Map;
9318
9458
 
9319
9459
  // src/lib/forge-write.ts
9460
+ var IMPORTABLE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
9461
+ var IMPORT_SEARCH_PATHSPEC = IMPORTABLE_EXTENSIONS.map((e) => `*${e}`);
9320
9462
  var INFORMATIONAL_DISPATCH_BLOCKER_CLASSES = new Set([
9321
9463
  "depends-on-not-merged",
9322
9464
  "conflicts-with"
@@ -9353,7 +9495,7 @@ function parseChangedLineRanges(diffOutput) {
9353
9495
  function fileDiffAgainst(ref, path) {
9354
9496
  let out;
9355
9497
  try {
9356
- out = execFileSync6("git", ["diff", `${ref}...HEAD`, "--", path], {
9498
+ out = execFileSync7("git", ["diff", `${ref}...HEAD`, "--", path], {
9357
9499
  encoding: "utf8",
9358
9500
  stdio: ["ignore", "pipe", "pipe"]
9359
9501
  }).trim();
@@ -9364,7 +9506,7 @@ function fileDiffAgainst(ref, path) {
9364
9506
  }
9365
9507
  function revParse(ref) {
9366
9508
  try {
9367
- return execFileSync6("git", ["rev-parse", "--verify", ref], {
9509
+ return execFileSync7("git", ["rev-parse", "--verify", ref], {
9368
9510
  encoding: "utf8",
9369
9511
  stdio: ["ignore", "pipe", "pipe"]
9370
9512
  }).trim();
@@ -9374,7 +9516,7 @@ function revParse(ref) {
9374
9516
  }
9375
9517
  function repoRoot() {
9376
9518
  try {
9377
- return execFileSync6("git", ["rev-parse", "--show-toplevel"], {
9519
+ return execFileSync7("git", ["rev-parse", "--show-toplevel"], {
9378
9520
  encoding: "utf8",
9379
9521
  stdio: ["ignore", "pipe", "pipe"]
9380
9522
  }).trim();
@@ -9385,7 +9527,7 @@ function repoRoot() {
9385
9527
  function changedFiles(base) {
9386
9528
  let out;
9387
9529
  try {
9388
- out = execFileSync6("git", ["diff", "--name-only", `${base}...HEAD`], {
9530
+ out = execFileSync7("git", ["diff", "--name-only", `${base}...HEAD`], {
9389
9531
  encoding: "utf8",
9390
9532
  stdio: ["ignore", "pipe", "pipe"]
9391
9533
  }).trim();
@@ -9446,7 +9588,7 @@ var CHECK_NAME = "exec-bits";
9446
9588
  var EXECUTABLE_MODE = "100755";
9447
9589
  function git2(args) {
9448
9590
  try {
9449
- return execFileSync7("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
9591
+ return execFileSync8("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
9450
9592
  } catch {
9451
9593
  return null;
9452
9594
  }