@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
@@ -2462,16 +2462,42 @@ function blockingSeverities(scale, threshold) {
2462
2462
  }
2463
2463
  return scale.slice(0, idx + 1);
2464
2464
  }
2465
- function evaluateReviewFindings(findings, scale, threshold) {
2466
- const blocking = new Set(blockingSeverities(scale, threshold));
2467
- const blockingFindings = findings.filter((f) => {
2468
- if (!scale.includes(f.severity)) {
2469
- throw new Error(`evaluateReviewFindings: severity "${f.severity}" is not one of ${scale.join(" > ")}`);
2465
+ var DEFERRAL_REASON_TEXT = {
2466
+ "unchanged-line": "unchanged line",
2467
+ "outside-surface": "outside the Surface"
2468
+ };
2469
+ var SECURITY_HIGH_AND_ABOVE = blockingSeverities(SECURITY_SEVERITY_ORDER, "HIGH");
2470
+ function classifyFinding(finding, scale, threshold, context = {}) {
2471
+ if (!scale.includes(finding.severity)) {
2472
+ throw new Error(`classifyFinding: severity "${finding.severity}" is not one of ${scale.join(" > ")}`);
2473
+ }
2474
+ const location = finding.location;
2475
+ const effectiveSeverity = location !== undefined && isProseLocation(location) ? PROSE_CAP_SEVERITY : finding.severity;
2476
+ const wouldBlock = blockingSeverities(scale, threshold).includes(effectiveSeverity);
2477
+ if (!wouldBlock)
2478
+ return { outcome: "non_blocking", deferralReason: null };
2479
+ const hasLocation = location !== undefined && location.length > 0;
2480
+ if (hasLocation && context.inSurface && !context.inSurface(location)) {
2481
+ return { outcome: "deferred", deferralReason: "outside-surface" };
2482
+ }
2483
+ if (hasLocation && context.changedLine && !SECURITY_HIGH_AND_ABOVE.includes(effectiveSeverity)) {
2484
+ if (!context.changedLine(location)) {
2485
+ return { outcome: "deferred", deferralReason: "unchanged-line" };
2470
2486
  }
2471
- const effectiveSeverity = f.location !== undefined && isProseLocation(f.location) ? PROSE_CAP_SEVERITY : f.severity;
2472
- return blocking.has(effectiveSeverity);
2473
- });
2474
- return { outcome: blockingFindings.length > 0 ? "blocked" : "clean", blockingFindings };
2487
+ }
2488
+ return { outcome: "blocking", deferralReason: null };
2489
+ }
2490
+ function evaluateReviewFindings(findings, scale, threshold, context = {}) {
2491
+ const blockingFindings = [];
2492
+ const deferredFindings = [];
2493
+ for (const f of findings) {
2494
+ const c = classifyFinding(f, scale, threshold, context);
2495
+ if (c.outcome === "blocking")
2496
+ blockingFindings.push(f);
2497
+ else if (c.outcome === "deferred")
2498
+ deferredFindings.push({ finding: f, reason: c.deferralReason });
2499
+ }
2500
+ return { outcome: blockingFindings.length > 0 ? "blocked" : "clean", blockingFindings, deferredFindings };
2475
2501
  }
2476
2502
  function isConsequentialFinding(finding) {
2477
2503
  return finding.state !== "resolved";
@@ -2479,11 +2505,11 @@ function isConsequentialFinding(finding) {
2479
2505
  function consequentialFindings(findings) {
2480
2506
  return findings.filter((f) => isConsequentialFinding(f));
2481
2507
  }
2482
- function evaluateCodeReview(findings, policy) {
2483
- return evaluateReviewFindings(findings, CODE_REVIEW_SEVERITY_ORDER, policy.codeReviewThreshold);
2508
+ function evaluateCodeReview(findings, policy, context = {}) {
2509
+ return evaluateReviewFindings(findings, CODE_REVIEW_SEVERITY_ORDER, policy.codeReviewThreshold, context);
2484
2510
  }
2485
- function evaluateSecurityReview(findings, policy) {
2486
- return evaluateReviewFindings(findings, SECURITY_SEVERITY_ORDER, policy.securityThreshold);
2511
+ function evaluateSecurityReview(findings, policy, context = {}) {
2512
+ return evaluateReviewFindings(findings, SECURITY_SEVERITY_ORDER, policy.securityThreshold, context);
2487
2513
  }
2488
2514
  function isKnownSeverity(scale, value) {
2489
2515
  return scale.includes(value);
@@ -3397,1511 +3423,1548 @@ function checkPrReportDensity(prBody) {
3397
3423
  const results = [checkDecisionsDensity(prBody), checkScopeDensity(prBody)];
3398
3424
  return { errors: results.flatMap((r) => r.errors) };
3399
3425
  }
3400
- // ../../packages/aeg-core/src/issue-validation.ts
3401
- function hasRationaleField(body, labelPattern) {
3402
- const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})`, "im");
3403
- return re.test(body);
3404
- }
3405
- var RATIONALE_FIELDS = [
3406
- { name: "Boundary", pattern: "Boundary" },
3407
- { name: "Sizing", pattern: "Sizing" },
3408
- { name: "Project(s) + blast radius", pattern: "Project\\(s\\)|Project(?:s)?\\s*\\+|blast radius" },
3409
- { name: "Dependency rationale", pattern: "Dependency rationale|Depends[- ]on" },
3410
- { name: "Traps to avoid", pattern: "Traps" },
3411
- { name: "Suggested agent-class", pattern: "(?:Suggested\\s+)?agent-class" },
3412
- { name: "Stop-and-escalate", pattern: "Stop-and-escalate" },
3413
- { name: "Docs to keep coherent", pattern: "Docs to keep coherent|§7" }
3426
+ // ../../packages/aeg-core/src/reader-resolvable-prose.ts
3427
+ var PRODUCT_SLUG_SCOPE = [
3428
+ "apps/cli/src",
3429
+ ".github/workflows",
3430
+ ".vinaya",
3431
+ "apps/cli/README.md",
3432
+ "packages/sources/README.md"
3414
3433
  ];
3415
- var DEPENDENCY_RATIONALE_FIELD_NAME = "Dependency rationale";
3416
- function checkIssueRationale(body) {
3417
- const errors = [];
3418
- for (const f of RATIONALE_FIELDS) {
3419
- if (!hasRationaleField(body, f.pattern)) {
3420
- 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).`);
3421
- continue;
3422
- }
3423
- if (f.name === DEPENDENCY_RATIONALE_FIELD_NAME && !SECTION_HEADER.test(body)) {
3424
- 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.");
3425
- }
3426
- }
3427
- return { status: errors.length > 0 ? "fail" : "pass", errors };
3428
- }
3429
- var OBJECTIVES_SINCE_ISSUE = 404;
3430
- function checkIssueObjectives(body, issueNumber, sinceIssue = OBJECTIVES_SINCE_ISSUE) {
3431
- if (sinceIssue !== null && issueNumber !== null && issueNumber < sinceIssue)
3432
- return { status: "pass", errors: [] };
3433
- const result = objectivesOf(body);
3434
- if (result.ok)
3435
- return { status: "pass", errors: [] };
3436
- return { status: "fail", errors: result.errors.map((e) => `issue-validation objectives: ${e}`) };
3434
+ function isUnderOrEqual(path, prefix) {
3435
+ return path === prefix || path.startsWith(`${prefix}/`);
3437
3436
  }
3438
- function topLevelSectionText(body, headingName) {
3439
- const headingRe = new RegExp(`^##[ \\t]*${headingName}[ \\t]*$`, "im");
3440
- const heading = headingRe.exec(body);
3441
- if (!heading)
3442
- return null;
3443
- const afterHeading = body.slice(heading.index + heading[0].length);
3444
- const next = /^##[ \t]/m.exec(afterHeading);
3445
- return next ? afterHeading.slice(0, next.index) : afterHeading;
3437
+ function isProductScopeFile(path) {
3438
+ return PRODUCT_SLUG_SCOPE.some((prefix) => isUnderOrEqual(path, prefix));
3446
3439
  }
3447
- function partHasBacktickedPath(text) {
3448
- let i = 0;
3449
- while (i < text.length) {
3450
- const start = text.indexOf("`", i);
3451
- if (start === -1)
3452
- return false;
3453
- const end = text.indexOf("`", start + 1);
3454
- if (end === -1)
3455
- return false;
3456
- if (text.slice(start + 1, end).includes("/"))
3457
- return true;
3458
- i = end + 1;
3459
- }
3460
- return false;
3440
+ var SHIPS_PREFIX = "aeg-root/";
3441
+ function shipsArchivePrefix(shipsPrefix) {
3442
+ return `${shipsPrefix}tranches/completed/`;
3461
3443
  }
3462
- var PART_MIN_WORDS_OUTSIDE_BACKTICKS = 3;
3463
- function stripPartBackticks(text) {
3464
- return text.replace(/`[^`\n]*`/g, " ");
3444
+ var DEFAULT_SPEC_PATHS = ["SPEC.md", "CONTEXT.md", "docs/adr"];
3445
+ function normalizeSpecPath(entry) {
3446
+ let out = entry.replace(/\\/g, "/");
3447
+ while (out.startsWith("./"))
3448
+ out = out.slice(2);
3449
+ out = out.replace(/\/{2,}/g, "/");
3450
+ while (out.endsWith("/"))
3451
+ out = out.slice(0, -1);
3452
+ return out;
3465
3453
  }
3466
- function partWordCount(text) {
3467
- return text.split(/\s+/).filter((w) => /[a-z]/i.test(w)).length;
3454
+ function isSpecFile2(path, specPaths) {
3455
+ if (path.startsWith("apps/") && path.includes("/specs/") && path.endsWith(".md"))
3456
+ return true;
3457
+ if (!path.endsWith(".md"))
3458
+ return false;
3459
+ return specPaths.some((entry) => isUnderOrEqual(path, normalizeSpecPath(entry)));
3468
3460
  }
3469
- function looksLikeFilePath(entry) {
3470
- const stripped = entry.replace(/\/\*\*?$/, "");
3471
- const lastSegment = stripped.split("/").pop() ?? stripped;
3472
- const extMatch = /\.[A-Za-z0-9]{1,6}$/.exec(lastSegment);
3473
- return extMatch !== null && extMatch.index > 0;
3461
+ function isClaudeMdFile(path) {
3462
+ return path === "CLAUDE.md" || path.endsWith("/CLAUDE.md");
3474
3463
  }
3475
- function splitGlobList(raw) {
3476
- return raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
3464
+ function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS) {
3465
+ if (path.startsWith(shipsPrefix)) {
3466
+ return path.startsWith(shipsArchivePrefix(shipsPrefix)) ? "internal" : "ships";
3467
+ }
3468
+ if (path.startsWith(readerFacingPrefix) && path.endsWith(readerFacingSuffix)) {
3469
+ return "reader-facing";
3470
+ }
3471
+ if (isClaudeMdFile(path))
3472
+ return "internal";
3473
+ if (isSpecFile2(path, specPaths))
3474
+ return "spec";
3475
+ if (isProductScopeFile(path))
3476
+ return "product";
3477
+ return null;
3477
3478
  }
3478
- function parseIssueSurface(body) {
3479
- const section = topLevelSectionText(body, "Surface");
3480
- if (section === null)
3481
- return { ok: false, errors: ["no `## Surface` heading found in the body."] };
3482
- const inLine = /^in:\s*(.+)$/im.exec(section);
3483
- const outLine = /^out:\s*(.+)$/im.exec(section);
3484
- const errors = [];
3485
- if (!inLine)
3486
- errors.push("`## Surface` has no `in:` line.");
3487
- if (!outLine)
3488
- errors.push("`## Surface` has no `out:` line.");
3489
- if (errors.length > 0)
3490
- return { ok: false, errors };
3491
- const inGlobs = splitGlobList(inLine[1]);
3492
- const outGlobs = splitGlobList(outLine[1]);
3493
- for (const g of [...inGlobs, ...outGlobs]) {
3494
- if (looksLikeFilePath(g)) {
3495
- errors.push(`\`${g}\` in \`## Surface\` looks like a file path — Surface entries are directory-level globs, never file paths.`);
3496
- }
3479
+ var SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
3480
+ function stripNonProse(path, content) {
3481
+ if (path.endsWith(".md")) {
3482
+ return content.replace(/```.*?```/gs, (m) => m.replace(/[^\n]/g, "")).replace(/`[^`\n]*`/g, (m) => m.replace(/[^\n]/g, ""));
3497
3483
  }
3498
- if (inGlobs.length === 0)
3499
- errors.push("`## Surface`'s `in:` line resolved to zero globs.");
3500
- if (errors.length > 0)
3501
- return { ok: false, errors };
3502
- return { ok: true, value: { in: inGlobs, out: outGlobs } };
3484
+ if (path.endsWith(".tsx") || path.endsWith(".ts")) {
3485
+ return content.replace(/\/\*.*?\*\//gs, (m) => m.replace(/[^\n]/g, "")).replace(/(^|[^:])\/\/[^\n]*/g, (m) => m.replace(/[^\n]/g, ""));
3486
+ }
3487
+ return content;
3503
3488
  }
3504
- function globCoversPath(glob, path) {
3505
- const g = glob.replace(/\/\*\*?$/, "").replace(/\/+$/, "");
3506
- const p = path.replace(/\/+$/, "");
3507
- return g === p || g.startsWith(`${p}/`) || p.startsWith(`${g}/`);
3489
+ function stripNonProseForProduct(path, content) {
3490
+ return path.endsWith(".md") ? stripNonProse(path, content) : content;
3508
3491
  }
3509
- function checkSurfaceGlobsResolve(body, resolvesToFile) {
3510
- const surface = parseIssueSurface(body);
3511
- if (!surface.ok)
3512
- return { status: "pass", errors: [] };
3513
- const errors = [];
3514
- for (const glob of surface.value.in) {
3515
- if (!resolvesToFile(glob)) {
3516
- 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.`);
3517
- }
3492
+ function lineAt(content, index) {
3493
+ let line = 1;
3494
+ for (let i = 0;i < index; i++) {
3495
+ if (content.charCodeAt(i) === 10)
3496
+ line++;
3518
3497
  }
3519
- return { status: errors.length > 0 ? "fail" : "pass", errors };
3498
+ return line;
3520
3499
  }
3521
- function checkSurfaceScope(changedFiles, outGlobs) {
3522
- if (outGlobs.length === 0)
3523
- return { ok: true };
3524
- const violations = [];
3525
- for (const file of changedFiles) {
3526
- const glob = outGlobs.find((g) => globCoversPath(g, file));
3527
- if (glob)
3528
- violations.push({ file, glob });
3529
- }
3530
- return violations.length > 0 ? { ok: false, violations } : { ok: true };
3500
+ var FORGE_NUMBER_PATTERN = /#[0-9]{2,4}/g;
3501
+ var TRANCHE_SLUG_VN_PATTERN = /[a-z][a-z-]+-v[0-9]/g;
3502
+ var TASK_NUMBER_PATTERN = /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi;
3503
+ function legacySlugPattern(legacySlugs) {
3504
+ if (legacySlugs.length === 0)
3505
+ return null;
3506
+ const alternation = legacySlugs.map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
3507
+ return new RegExp(`(^|[^a-zA-Z0-9\\n-])(${alternation})([^a-zA-Z0-9\\n-]|$)`, "g");
3531
3508
  }
3532
- var ISSUE_PART_LINE_RE = /^Part\s+(\d+)\s*\(([^)]*)\)\s*[-—–]\s*(.*)$/i;
3533
- function parseIssueParts(body) {
3534
- const section = topLevelSectionText(body, "Parts");
3535
- if (section === null)
3536
- return { ok: false, errors: ["no `## Parts` heading found in the body."] };
3537
- const lines = section.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
3538
- const parts = [];
3539
- const errors = [];
3540
- for (const line of lines) {
3541
- const m = ISSUE_PART_LINE_RE.exec(line);
3542
- if (!m) {
3543
- errors.push(`"${line}" is not a well-formed Parts line — expected \`Part <n> (<refs>) — <outcome>\`.`);
3509
+ function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
3510
+ const findings = [];
3511
+ const legacyPattern = legacySlugPattern(legacySlugs);
3512
+ const grandfathered = new Set(specGrandfather);
3513
+ const patterns = [
3514
+ { pattern: FORGE_NUMBER_PATTERN, what: "a forge number" },
3515
+ { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug" },
3516
+ ...legacyPattern ? [{ pattern: legacyPattern, what: "an internal tranche slug", group: 2 }] : []
3517
+ ];
3518
+ const productPatterns = [
3519
+ { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug in product code" }
3520
+ ];
3521
+ const specPatterns = [
3522
+ ...patterns,
3523
+ { pattern: TASK_NUMBER_PATTERN, what: "a task number", group: 2 }
3524
+ ];
3525
+ for (const file of files) {
3526
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths);
3527
+ if (!cls || cls === "internal")
3544
3528
  continue;
3545
- }
3546
- const n = Number.parseInt(m[1], 10);
3547
- const refs = m[2];
3548
- const text = m[3].trim();
3549
- if (text.length === 0) {
3550
- errors.push(`Part ${n} has no outcome text after the dash — every Part states one observable outcome.`);
3529
+ if (cls !== "product" && cls !== "spec" && !SWEPT_CLASSES.has(cls))
3551
3530
  continue;
3552
- }
3553
- if (partHasBacktickedPath(text) && partWordCount(stripPartBackticks(text)) < PART_MIN_WORDS_OUTSIDE_BACKTICKS) {
3554
- errors.push(`Part ${n} is little more than a file path — a Part names an outcome and symbols, never a bare path.`);
3531
+ if (cls === "spec" && grandfathered.has(file.path))
3555
3532
  continue;
3533
+ const blocking = cls === "product" || cls === "spec";
3534
+ const scrubbed = cls === "product" ? stripNonProseForProduct(file.path, file.content) : stripNonProse(file.path, file.content);
3535
+ const patternsToRun = cls === "product" ? productPatterns : cls === "spec" ? specPatterns : patterns;
3536
+ for (const { pattern, what, group } of patternsToRun) {
3537
+ pattern.lastIndex = 0;
3538
+ let match = pattern.exec(scrubbed);
3539
+ while (match !== null) {
3540
+ const cited = group !== undefined ? match[group] ?? match[0] : match[0];
3541
+ const citedIndex = match.index + match[0].indexOf(cited);
3542
+ findings.push({
3543
+ file: file.path,
3544
+ line: lineAt(scrubbed, citedIndex),
3545
+ message: `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
3546
+ blocking
3547
+ });
3548
+ match = pattern.exec(scrubbed);
3549
+ }
3556
3550
  }
3557
- const objectiveIds = [...refs.matchAll(/O(\d+)/g)].map((r) => Number.parseInt(r[1], 10));
3558
- parts.push({ n, objectiveIds, text });
3559
- }
3560
- if (parts.length === 0) {
3561
- errors.push("the `## Parts` section has no well-formed `Part <n> (<refs>) — <outcome>` lines.");
3562
3551
  }
3563
- if (errors.length > 0)
3564
- return { ok: false, errors };
3565
- return { ok: true, value: parts };
3566
- }
3567
- function checkPartsCiteDefinedObjectives(body) {
3568
- const parts = parseIssueParts(body);
3569
- const objectives = objectivesOf(body);
3570
- if (!parts.ok || !objectives.ok)
3571
- return { status: "pass", errors: [] };
3572
- const definedIds = new Set(objectives.objectives.map((o) => Number.parseInt(o.id.slice(1), 10)));
3573
- const errors = [];
3574
- for (const part of parts.value) {
3575
- for (const objectiveId of part.objectiveIds) {
3576
- if (!definedIds.has(objectiveId)) {
3577
- errors.push(`issue-validation Parts: Part ${part.n} cites O${objectiveId}, which the Issue's own \`## Objectives\` section does not define.`);
3578
- }
3579
- }
3580
- }
3581
- return { status: errors.length > 0 ? "fail" : "pass", errors };
3582
- }
3583
- function isTaskIssueLabelSet(labels) {
3584
- return hasLabel("tranche", labels);
3585
- }
3586
- function checkTrancheLabelPresence(_body, _labels) {
3587
- return { status: "pass", errors: [] };
3588
- }
3589
- function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTitle) {
3590
- if (!isTaskIssueLabelSet(labels))
3591
- return { status: "pass", errors: [] };
3592
- if (resolvedMilestoneTitle === null)
3593
- return { status: "pass", errors: [] };
3594
- if (currentMilestoneTitle === resolvedMilestoneTitle)
3595
- return { status: "pass", errors: [] };
3596
- return {
3597
- status: "fail",
3598
- errors: [
3599
- `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}".`
3600
- ]
3601
- };
3602
- }
3603
- var TYPE_LABEL_IDS = LABELS.filter((l) => l.category === "type").map((l) => l.id);
3604
- function isControlCodePoint(codePoint) {
3605
- return codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
3606
- }
3607
- function isDisplayControlCodePoint(codePoint) {
3608
- return codePoint >= 8203 && codePoint <= 8207 || codePoint >= 8234 && codePoint <= 8238 || codePoint >= 8294 && codePoint <= 8297 || codePoint === 65279;
3552
+ return findings;
3609
3553
  }
3610
- var MESSAGE_VALUE_COUNT_MAX = 5;
3611
- function residueForMessage(values) {
3612
- const shown = values.slice(0, MESSAGE_VALUE_COUNT_MAX).map((v) => `\`${forMessage(v)}\``);
3613
- const rest = values.length - shown.length;
3614
- return rest > 0 ? `${shown.join(", ")} and ${rest} more` : shown.join(", ");
3554
+ function escapeTerm(term) {
3555
+ return term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3615
3556
  }
3616
- var MESSAGE_VALUE_MAX = 64;
3617
- function forMessage(value) {
3618
- const kept = [];
3619
- for (const ch of value.replace(/\s+/g, " ")) {
3620
- const codePoint = ch.codePointAt(0) ?? 0;
3621
- if (isControlCodePoint(codePoint) || isDisplayControlCodePoint(codePoint))
3622
- continue;
3623
- kept.push(ch);
3624
- }
3625
- const cleaned = kept.join("").trim();
3626
- if (cleaned.length === 0)
3627
- return "(unprintable)";
3628
- const points = Array.from(cleaned);
3629
- return points.length > MESSAGE_VALUE_MAX ? `${points.slice(0, MESSAGE_VALUE_MAX).join("")}…` : cleaned;
3557
+ function containsWholeWord(text, term) {
3558
+ const escaped = escapeTerm(term);
3559
+ const re = new RegExp(`(^|[^a-zA-Z])${escaped}([^a-zA-Z]|$)`, "i");
3560
+ return re.test(text);
3630
3561
  }
3631
- function checkProjectsRegistered(body, _labels, registeredNames) {
3632
- if (registeredNames.length === 0)
3633
- return { status: "pass", errors: [] };
3634
- const field = projectFieldFromBody(body);
3635
- if (!field.declared)
3636
- return { status: "pass", errors: [] };
3637
- const known = new Set(registeredNames.map((n) => n.trim()));
3638
- const registeredList = [...registeredNames].map(forMessage).join(", ");
3639
- const errors = [];
3640
- if (field.unreadable) {
3641
- return {
3642
- status: "fail",
3643
- errors: [
3644
- `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.`
3645
- ]
3646
- };
3647
- }
3648
- const unregistered = field.names.filter((p) => !known.has(p));
3649
- if (unregistered.length > 0) {
3650
- const caseHints = unregistered.map((p) => {
3651
- const row = [...known].find((k) => k.toLowerCase() === p.toLowerCase());
3652
- return row ? `\`${forMessage(p)}\` differs from the registered \`${forMessage(row)}\` only in case` : null;
3653
- }).filter((h) => h !== null);
3654
- 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.`);
3655
- }
3656
- if (field.names.length === 0) {
3657
- const residue = field.unparsed.length > 0 ? ` — ${residueForMessage(field.unparsed)}` : " — the field is empty";
3658
- 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.`);
3659
- } else if (field.unparsed.length > 0) {
3660
- 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.`);
3562
+ function findWholeWordLine(content, term) {
3563
+ const lines = content.split(`
3564
+ `);
3565
+ let lineNo = 0;
3566
+ for (const line of lines) {
3567
+ lineNo++;
3568
+ if (containsWholeWord(line, term))
3569
+ return lineNo;
3661
3570
  }
3662
- return errors.length > 0 ? { status: "fail", errors } : { status: "pass", errors: [] };
3663
- }
3664
- 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;
3665
- var DOC_PATH_RE_GLOBAL = new RegExp(DOC_PATH_RE.source, "gi");
3666
-
3667
- // ../../packages/aeg-core/src/task-branch-identity.ts
3668
- var ISSUE_BRANCH_PATTERN = /^task\/issue-(\d+)$/;
3669
- var TRANCHE_BRANCH_PATTERN = /^task\/([^/]+)\/([^/]+)$/;
3670
- function parseTaskBranchIdentity(branch) {
3671
- const issueMatch = ISSUE_BRANCH_PATTERN.exec(branch);
3672
- if (issueMatch)
3673
- return { kind: "issue", issueNumber: Number(issueMatch[1]) };
3674
- const trancheMatch = TRANCHE_BRANCH_PATTERN.exec(branch);
3675
- if (trancheMatch)
3676
- return { kind: "tranche", tranche: trancheMatch[1], taskId: trancheMatch[2] };
3677
3571
  return null;
3678
3572
  }
3679
-
3680
- // ../../packages/aeg-core/src/coherence-checks.ts
3681
- var COHERENCE_ENFORCED_FROM = "2026-07-01";
3682
- function isGrandfathered(isoDate) {
3683
- if (!isoDate)
3684
- return false;
3685
- return isoDate.slice(0, 10) < COHERENCE_ENFORCED_FROM;
3573
+ function definesOrLinksGlossary(content, term) {
3574
+ const escaped = escapeTerm(term);
3575
+ const definesInline = new RegExp(`(^|[^a-zA-Z])${escaped}([^a-zA-Z]|$)[^\\n]{0,3}—`, "i").test(content);
3576
+ if (definesInline)
3577
+ return true;
3578
+ return /docs\/glossary|glossary\.md/i.test(content);
3686
3579
  }
3687
- var R1_GRANDFATHERED_ISSUES = new Set([279, 280, 281, 282]);
3688
- function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
3689
- const failures = [];
3690
- for (const e of entries) {
3691
- if (!e.facts)
3692
- continue;
3693
- if (e.facts.stateReason === "not_planned")
3580
+ function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX) {
3581
+ const findings = [];
3582
+ for (const file of files) {
3583
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
3584
+ if (!cls || !SWEPT_CLASSES.has(cls))
3694
3585
  continue;
3695
- if (e.facts.issueState === "closed" && e.facts.prState !== "merged") {
3696
- const handClosed = e.facts.stateReason === "completed" && isPrincipal(e.facts.closedByActor, principalAllowlist);
3697
- if (handClosed)
3586
+ const scrubbed = stripNonProse(file.path, file.content);
3587
+ for (const term of glossaryTerms) {
3588
+ const line = findWholeWordLine(scrubbed, term);
3589
+ if (line === null)
3698
3590
  continue;
3699
- failures.push({
3700
- code: "closed-without-merge",
3701
- issue: e.task.issue,
3702
- tranche: e.trancheSlug,
3703
- task: e.task.id,
3704
- reason: `Issue closed but closing PR is not merged (prState: ${e.facts.prState})`,
3705
- grandfathered: isGrandfathered(e.facts.closedAt)
3591
+ if (definesOrLinksGlossary(scrubbed, term))
3592
+ continue;
3593
+ findings.push({
3594
+ file: file.path,
3595
+ line,
3596
+ message: `uses coined term "${term}" without defining it inline or linking the glossary`,
3597
+ blocking: false
3706
3598
  });
3707
3599
  }
3708
3600
  }
3709
- const activeFails = failures.filter((f) => !f.grandfathered);
3710
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3711
- return {
3712
- check: "A1",
3713
- status,
3714
- failures,
3715
- note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
3716
- };
3601
+ return findings;
3717
3602
  }
3718
- function checkA3(entries) {
3719
- const failures = [];
3720
- for (const e of entries) {
3721
- if (!e.facts)
3603
+ var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g;
3604
+ var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = /#[0-9]{2,}/g;
3605
+ function extractComments(path, content) {
3606
+ if (!path.endsWith(".ts") && !path.endsWith(".tsx"))
3607
+ return content.replace(/[^\n]/g, "");
3608
+ let state = "code";
3609
+ let out = "";
3610
+ const n = content.length;
3611
+ let i = 0;
3612
+ const blank = (ch) => ch === `
3613
+ ` ? `
3614
+ ` : " ";
3615
+ while (i < n) {
3616
+ const c = content[i];
3617
+ const next = i + 1 < n ? content[i + 1] : "";
3618
+ if (state === "code") {
3619
+ if (c === "/" && next === "/") {
3620
+ state = "line-comment";
3621
+ out += c;
3622
+ i++;
3623
+ continue;
3624
+ }
3625
+ if (c === "/" && next === "*") {
3626
+ state = "block-comment";
3627
+ out += c;
3628
+ i++;
3629
+ continue;
3630
+ }
3631
+ if (c === "'") {
3632
+ state = "single-quote";
3633
+ out += blank(c);
3634
+ i++;
3635
+ continue;
3636
+ }
3637
+ if (c === '"') {
3638
+ state = "double-quote";
3639
+ out += blank(c);
3640
+ i++;
3641
+ continue;
3642
+ }
3643
+ if (c === "`") {
3644
+ state = "template";
3645
+ out += blank(c);
3646
+ i++;
3647
+ continue;
3648
+ }
3649
+ out += blank(c);
3650
+ i++;
3722
3651
  continue;
3723
- if (e.facts.prState === "merged" && e.facts.issueState !== "closed") {
3724
- failures.push({
3725
- code: "auto-close-misfire",
3726
- issue: e.task.issue,
3727
- tranche: e.trancheSlug,
3728
- task: e.task.id,
3729
- reason: "Closing PR is merged but Issue is still open (GitHub auto-close misfire)",
3730
- grandfathered: isGrandfathered(e.facts.mergedAt)
3731
- });
3732
3652
  }
3733
- }
3734
- const activeFails = failures.filter((f) => !f.grandfathered);
3735
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3736
- return {
3737
- check: "A3",
3738
- status,
3739
- failures,
3740
- note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
3741
- };
3742
- }
3743
- function checkT1(entries) {
3744
- const failures = [];
3745
- for (const e of entries) {
3746
- if (e.task.issue === null)
3747
- continue;
3748
- if (e.facts === undefined) {
3749
- failures.push({
3750
- code: "phantom-issue-ref",
3751
- issue: e.task.issue,
3752
- tranche: e.trancheSlug,
3753
- task: e.task.id,
3754
- reason: `Issue #${e.task.issue} in topology does not resolve to a real GitHub Issue`
3755
- });
3756
- }
3757
- }
3758
- return { check: "T1", status: failures.length > 0 ? "fail" : "pass", failures };
3759
- }
3760
- function checkT2(openIssuesBySlug, topologyIssuesBySlug, ciTrancheSlug) {
3761
- const failures = [];
3762
- for (const [slug, openNums] of openIssuesBySlug) {
3763
- if (ciTrancheSlug && slug !== ciTrancheSlug)
3764
- continue;
3765
- const topologySet = topologyIssuesBySlug.get(slug) ?? new Set;
3766
- for (const num of openNums) {
3767
- if (!topologySet.has(num)) {
3768
- failures.push({
3769
- code: "orphan-task",
3770
- issue: num,
3771
- tranche: slug,
3772
- reason: `Issue #${num} is open and labeled ${trancheLabel(slug)} but does not appear in the topology file`
3773
- });
3653
+ if (state === "line-comment") {
3654
+ if (c === `
3655
+ `) {
3656
+ state = "code";
3657
+ out += `
3658
+ `;
3659
+ i++;
3660
+ continue;
3774
3661
  }
3662
+ out += c;
3663
+ i++;
3664
+ continue;
3775
3665
  }
3776
- }
3777
- return { check: "T2", status: failures.length > 0 ? "fail" : "pass", failures };
3778
- }
3779
- function scopeT2ToPlanPr(result, isPlanPr) {
3780
- if (isPlanPr || result.status !== "fail")
3781
- return result;
3782
- return {
3783
- ...result,
3784
- status: "info",
3785
- note: result.note ?? "T2 findings are non-blocking outside plan PRs (point-of-power principle) — see aeg-root/enforcement.md."
3786
- };
3787
- }
3788
- function checkT3(entries, ciTrancheSlug, enrichedEntries, forgeUnavailableSlugs) {
3789
- const preEnforcement = new Set;
3790
- if (enrichedEntries) {
3791
- for (const e of enrichedEntries) {
3792
- if (isGrandfathered(e.facts?.closedAt) || isGrandfathered(e.facts?.mergedAt)) {
3793
- preEnforcement.add(e.trancheSlug);
3666
+ if (state === "block-comment") {
3667
+ if (c === "*" && next === "/") {
3668
+ out += c;
3669
+ out += next;
3670
+ state = "code";
3671
+ i += 2;
3672
+ continue;
3794
3673
  }
3674
+ out += c === `
3675
+ ` ? `
3676
+ ` : c;
3677
+ i++;
3678
+ continue;
3795
3679
  }
3796
- }
3797
- const failures = [];
3798
- for (const e of entries) {
3799
- if (!e.archived && e.task.issue === null) {
3800
- if (ciTrancheSlug && e.trancheSlug !== ciTrancheSlug)
3801
- continue;
3802
- if (forgeUnavailableSlugs?.has(e.trancheSlug)) {
3803
- failures.push({
3804
- code: "tbd-in-active-tranche",
3805
- issue: null,
3806
- tranche: e.trancheSlug,
3807
- task: e.task.id,
3808
- 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`,
3809
- grandfathered: true
3810
- });
3811
- continue;
3680
+ const closer = state === "single-quote" ? "'" : state === "double-quote" ? '"' : "`";
3681
+ if (c === "\\") {
3682
+ out += blank(c);
3683
+ i++;
3684
+ if (i < n) {
3685
+ out += blank(content[i]);
3686
+ i++;
3812
3687
  }
3813
- failures.push({
3814
- code: "tbd-in-active-tranche",
3815
- issue: null,
3816
- tranche: e.trancheSlug,
3817
- task: e.task.id,
3818
- 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`,
3819
- grandfathered: preEnforcement.has(e.trancheSlug)
3820
- });
3688
+ continue;
3689
+ }
3690
+ if (c === closer) {
3691
+ state = "code";
3692
+ out += blank(c);
3693
+ i++;
3694
+ continue;
3821
3695
  }
3696
+ out += blank(c);
3697
+ i++;
3822
3698
  }
3823
- const activeFails = failures.filter((f) => !f.grandfathered);
3824
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3825
- return {
3826
- check: "T3",
3827
- status,
3828
- failures,
3829
- note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
3830
- };
3699
+ return out;
3831
3700
  }
3832
- function checkD1(entries, issueToEntry, taskToEntry) {
3833
- const failures = [];
3834
- for (const e of entries) {
3835
- if (!e.facts)
3701
+ function checkSourceComments(files, allowlist = []) {
3702
+ const findings = [];
3703
+ const allowed = new Set(allowlist);
3704
+ const patterns = [
3705
+ { pattern: SOURCE_COMMENT_TRANCHE_SLUG_PATTERN, what: "a tranche-slug citation" },
3706
+ { pattern: SOURCE_COMMENT_FORGE_NUMBER_PATTERN, what: "a forge-number citation" }
3707
+ ];
3708
+ for (const file of files) {
3709
+ if (!file.path.endsWith(".ts"))
3836
3710
  continue;
3837
- if (e.facts.prState !== "open")
3711
+ if (allowed.has(file.path))
3838
3712
  continue;
3839
- for (const dep of e.task.dependsOn) {
3840
- const depEntry = resolveDepEntry(dep, e.trancheSlug, issueToEntry, taskToEntry);
3841
- if (!depEntry)
3842
- continue;
3843
- const sameTask = depEntry.trancheSlug === e.trancheSlug && depEntry.task.id === e.task.id;
3844
- const sameIssue = depEntry.task.issue !== null && e.task.issue !== null && depEntry.task.issue === e.task.issue;
3845
- if (sameTask || sameIssue) {
3846
- failures.push({
3847
- code: "d1-self-dependency",
3848
- issue: e.task.issue,
3849
- tranche: e.trancheSlug,
3850
- task: e.task.id,
3851
- reason: `INTERNAL: parsed a self-dependency (depends-on ${dep}) — this is a parser bug in parseRationaleDeps, not a real dependency. Please report it upstream.`
3852
- });
3853
- continue;
3854
- }
3855
- const depFacts = depEntry.facts;
3856
- const depClosed = depFacts?.issueState === "closed";
3857
- if (!depClosed) {
3858
- failures.push({
3859
- code: "dispatched-on-unmet-deps",
3860
- issue: e.task.issue,
3861
- tranche: e.trancheSlug,
3862
- task: e.task.id,
3863
- reason: `Task has open PR but depends-on ${dep} (issue #${depEntry.task.issue ?? "?"}) is not closed`
3713
+ const comments = extractComments(file.path, file.content);
3714
+ for (const { pattern, what } of patterns) {
3715
+ pattern.lastIndex = 0;
3716
+ let match = pattern.exec(comments);
3717
+ while (match !== null) {
3718
+ findings.push({
3719
+ file: file.path,
3720
+ line: lineAt(comments, match.index),
3721
+ message: `comment cites ${what} ("${match[0]}") a reader outside this repo's tracker cannot resolve`,
3722
+ blocking: false
3864
3723
  });
3724
+ match = pattern.exec(comments);
3865
3725
  }
3866
3726
  }
3867
3727
  }
3868
- return { check: "D1", status: failures.length > 0 ? "fail" : "pass", failures };
3728
+ return findings;
3869
3729
  }
3870
- function resolveDepEntry(dep, trancheSlug, issueToEntry, taskToEntry) {
3871
- const issueMatch = dep.match(/^#(\d+)$/);
3872
- if (issueMatch?.[1])
3873
- return issueToEntry.get(Number(issueMatch[1]));
3874
- return taskToEntry.get(`${trancheSlug}/${dep}`) ?? taskToEntry.get(dep);
3730
+ function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
3731
+ return [
3732
+ ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths),
3733
+ ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix)
3734
+ ];
3875
3735
  }
3876
- function checkR1(issuesBySlug, grandfatheredIssues, registeredNames = [], objectivesSinceIssue) {
3877
- const failures = [];
3878
- for (const [slug, issues] of issuesBySlug) {
3879
- for (const issue of issues) {
3880
- if (!isTaskIssueLabelSet(issue.labels))
3881
- continue;
3882
- const errors = [
3883
- ...checkIssueRationale(issue.body).errors,
3884
- ...checkProjectsRegistered(issue.body, issue.labels, registeredNames).errors,
3885
- ...checkIssueObjectives(issue.body, issue.number, objectivesSinceIssue).errors,
3886
- ...checkPartsCiteDefinedObjectives(issue.body).errors
3887
- ];
3888
- if (errors.length === 0)
3889
- continue;
3890
- failures.push({
3891
- code: "missing-rationale-field",
3892
- issue: issue.number,
3893
- tranche: slug,
3894
- reason: `Issue #${issue.number} fails the rationale gate: ${errors.join(" | ")}`,
3895
- grandfathered: grandfatheredIssues.has(issue.number)
3896
- });
3897
- }
3736
+ function parseGlossaryTerms(glossaryContent) {
3737
+ const terms = [];
3738
+ const re = /^\*\*(.+?)\*\* —/gm;
3739
+ let match = re.exec(glossaryContent);
3740
+ while (match !== null) {
3741
+ if (match[1] !== undefined)
3742
+ terms.push(match[1]);
3743
+ match = re.exec(glossaryContent);
3898
3744
  }
3899
- const activeFails = failures.filter((f) => !f.grandfathered);
3900
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3901
- return {
3902
- check: "R1",
3903
- status,
3904
- failures,
3905
- note: status === "info" ? `${failures.length} grandfathered task Issue(s) predate this check's grammar (rationale fields and/or the project registry)` : undefined
3906
- };
3745
+ return terms;
3907
3746
  }
3908
- function checkL1(files, entriesBySlug) {
3909
- const failures = [];
3910
- for (const f of files) {
3911
- if (f.archived)
3912
- continue;
3913
- const entries = entriesBySlug.get(f.slug) ?? [];
3914
- const withFacts = entries.filter((e) => e.facts !== undefined);
3915
- if (withFacts.length === 0)
3916
- continue;
3917
- const allClosed = withFacts.every((e) => e.facts?.issueState === "closed");
3918
- if (allClosed) {
3919
- failures.push({
3920
- code: "archive-recommended",
3921
- tranche: f.slug,
3922
- reason: "Active tranche has no open task-Issues — consider archiving to completed/"
3923
- });
3924
- }
3925
- }
3926
- return {
3927
- check: "L1",
3928
- status: "info",
3929
- failures,
3930
- note: failures.length > 0 ? `${failures.length} active tranche(s) with no open task-Issues — consider archiving (advisory)` : undefined
3931
- };
3747
+
3748
+ // ../../packages/aeg-core/src/quoted-command.ts
3749
+ var QUOTED_COMMAND_SHIPS_PREFIX = "aeg-root/";
3750
+ var QUOTED_COMMAND_SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
3751
+ var START_PATTERN = /<!--\s*AEG:QUOTES-FILE:START:(\S+?)\s*-->/g;
3752
+ var END_PATTERN = /<!--\s*AEG:QUOTES-FILE:END\s*-->/;
3753
+ function isValidCitedFilePath(path) {
3754
+ if (path.length === 0)
3755
+ return false;
3756
+ if (path.startsWith("/") || path.startsWith("\\"))
3757
+ return false;
3758
+ if (/^[A-Za-z]:[\\/]/.test(path))
3759
+ return false;
3760
+ return !path.split(/[\\/]+/).includes("..");
3932
3761
  }
3933
- function checkL3(files) {
3934
- const active = files.filter((f) => !f.archived);
3935
- return {
3936
- check: "L3",
3937
- status: "info",
3938
- failures: [],
3939
- note: `${active.length} active tranche(s): ${active.map((f) => f.slug).join(", ") || "(none)"}`
3940
- };
3941
- }
3942
- function extractClosesReferences(prBody) {
3943
- const closesPattern = /(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s{0,8}:?\s{0,8}#(\d+)/gi;
3944
- const stripped = stripCode(prBody);
3945
- const searchIn = anchoredRegion(stripped, "CLOSES") ?? stripped;
3946
- const referenced = new Set;
3947
- for (const hit of searchIn.matchAll(closesPattern)) {
3948
- referenced.add(Number(hit[1]));
3762
+ function quotedCommandLineAt(content, index) {
3763
+ let line = 1;
3764
+ for (let i = 0;i < index; i++) {
3765
+ if (content.charCodeAt(i) === 10)
3766
+ line++;
3949
3767
  }
3950
- return referenced;
3768
+ return line;
3951
3769
  }
3952
- function checkClosesNTopology(branch, prBody, trancheFiles, taskIssueRefs) {
3953
- const referenced = extractClosesReferences(prBody);
3954
- if (taskIssueRefs) {
3955
- for (const n of referenced) {
3956
- const ref = taskIssueRefs.get(n);
3957
- if (!ref)
3958
- continue;
3959
- const expectedBranch = `task/${ref.trancheSlug}/${ref.taskId}`;
3960
- if (branch !== expectedBranch) {
3961
- return {
3962
- ok: false,
3963
- 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.`
3964
- };
3965
- }
3770
+ function extractQuotedText(raw) {
3771
+ const trimmed = raw.trim();
3772
+ const fenced = /^(?:`{3,}|~{3,})[^\n]*\n([\s\S]*?)\n?(?:`{3,}|~{3,})$/.exec(trimmed);
3773
+ if (fenced)
3774
+ return (fenced[1] ?? "").trim();
3775
+ const inline = /^`([^`]+)`$/.exec(trimmed);
3776
+ if (inline)
3777
+ return (inline[1] ?? "").trim();
3778
+ return trimmed;
3779
+ }
3780
+ function findQuotesInFile(path, content) {
3781
+ const masked = maskCode(content);
3782
+ const quotes = [];
3783
+ START_PATTERN.lastIndex = 0;
3784
+ let start = START_PATTERN.exec(masked);
3785
+ while (start !== null) {
3786
+ const citedFile = start[1];
3787
+ const innerStart = start.index + start[0].length;
3788
+ const end = END_PATTERN.exec(masked.slice(innerStart));
3789
+ if (end === null) {
3790
+ START_PATTERN.lastIndex = innerStart;
3791
+ start = START_PATTERN.exec(masked);
3792
+ continue;
3966
3793
  }
3967
- }
3968
- const ref = parseTaskBranchIdentity(branch);
3969
- if (!ref)
3970
- return { ok: true };
3971
- if (ref.kind === "issue") {
3972
- const expectedIssue = ref.issueNumber;
3973
- if (!referenced.has(expectedIssue)) {
3974
- return {
3975
- ok: false,
3976
- expectedIssue,
3977
- message: `closes-n: PR body does not contain \`Closes #${expectedIssue}\` (required for branch "${branch}"). Add it to the PR body Summary section.`
3978
- };
3794
+ const innerEnd = innerStart + end.index;
3795
+ if (isValidCitedFilePath(citedFile)) {
3796
+ const quotedText = extractQuotedText(content.slice(innerStart, innerEnd));
3797
+ if (quotedText.length > 0) {
3798
+ quotes.push({ file: path, line: quotedCommandLineAt(content, innerStart), quotedText, citedFile });
3799
+ }
3979
3800
  }
3980
- return { ok: true, expectedIssue };
3981
- }
3982
- const trancheSlug = ref.tranche;
3983
- const taskId = ref.taskId;
3984
- const trancheFile = trancheFiles.find((f) => f.slug === trancheSlug);
3985
- if (!trancheFile) {
3986
- return {
3987
- ok: false,
3988
- 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.`
3989
- };
3990
- }
3991
- const task = trancheFile.tranche.tasks.find((t) => t.id === taskId);
3992
- if (!task) {
3993
- return {
3994
- ok: false,
3995
- message: `closes-n: branch "${branch}" references task "${taskId}" not found in ${trancheSlug} topology. Verify the task ID matches the tranche file.`
3996
- };
3801
+ START_PATTERN.lastIndex = innerEnd + end[0].length;
3802
+ start = START_PATTERN.exec(masked);
3997
3803
  }
3998
- if (task.issue === null) {
3999
- return {
4000
- ok: false,
4001
- message: `closes-n: task "${taskId}" in "${trancheSlug}" has no Issue number (#TBD). The Planner must cut the Issue before this PR can be validated.`
4002
- };
3804
+ return quotes;
3805
+ }
3806
+ function findCitedQuotes(files, readerFacingPrefix, readerFacingSuffix, shipsPrefix = QUOTED_COMMAND_SHIPS_PREFIX) {
3807
+ const quotes = [];
3808
+ for (const file of files) {
3809
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
3810
+ if (!cls || !QUOTED_COMMAND_SWEPT_CLASSES.has(cls))
3811
+ continue;
3812
+ quotes.push(...findQuotesInFile(file.path, file.content));
4003
3813
  }
4004
- const expectedIssue = task.issue;
4005
- if (!referenced.has(expectedIssue)) {
4006
- return {
4007
- ok: false,
4008
- expectedIssue,
4009
- 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.`
4010
- };
3814
+ return quotes;
3815
+ }
3816
+ function evaluateCitedQuotes(citedQuotes, citedFileContents) {
3817
+ const findings = [];
3818
+ for (const quote of citedQuotes) {
3819
+ const content = citedFileContents.get(quote.citedFile);
3820
+ if (content === undefined) {
3821
+ findings.push({
3822
+ file: quote.file,
3823
+ line: quote.line,
3824
+ citedFile: quote.citedFile,
3825
+ quotedText: quote.quotedText,
3826
+ message: `${quote.file}:${quote.line} quotes "${quote.quotedText}" as citing \`${quote.citedFile}\`, but that file could not be read`
3827
+ });
3828
+ continue;
3829
+ }
3830
+ if (!content.includes(quote.quotedText)) {
3831
+ findings.push({
3832
+ file: quote.file,
3833
+ line: quote.line,
3834
+ citedFile: quote.citedFile,
3835
+ quotedText: quote.quotedText,
3836
+ message: `${quote.file}:${quote.line} quotes "${quote.quotedText}" as citing \`${quote.citedFile}\`, but \`${quote.citedFile}\` no longer contains that text verbatim`
3837
+ });
3838
+ }
4011
3839
  }
4012
- return { ok: true, expectedIssue };
3840
+ return findings;
4013
3841
  }
4014
- // ../../packages/aeg-core/src/archive-task.ts
4015
- function closesRefs(text) {
4016
- return [...new Set([...text.matchAll(/Closes #(\d+)/gi)].map((m) => Number(m[1])))];
3842
+
3843
+ // ../../packages/aeg-core/src/issue-validation.ts
3844
+ function hasRationaleField(body, labelPattern) {
3845
+ const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})`, "im");
3846
+ return re.test(body);
4017
3847
  }
4018
- function extractIssue(body) {
4019
- const stripped = stripCode(body);
4020
- const bodyNums = closesRefs(stripped);
4021
- const anchored = anchoredRegion(stripped, "CLOSES");
4022
- if (anchored !== null) {
4023
- const anchorNums = closesRefs(anchored);
4024
- if (anchorNums.length === 0)
4025
- return { issue: null, extraIssues: bodyNums, outsideHeader: false };
4026
- const issue = anchorNums[0];
4027
- return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: false };
3848
+ var RATIONALE_FIELDS = [
3849
+ { name: "Boundary", pattern: "Boundary" },
3850
+ { name: "Sizing", pattern: "Sizing" },
3851
+ { name: "Project(s) + blast radius", pattern: "Project\\(s\\)|Project(?:s)?\\s*\\+|blast radius" },
3852
+ { name: "Dependency rationale", pattern: "Dependency rationale|Depends[- ]on" },
3853
+ { name: "Traps to avoid", pattern: "Traps" },
3854
+ { name: "Suggested agent-class", pattern: "(?:Suggested\\s+)?agent-class" },
3855
+ { name: "Stop-and-escalate", pattern: "Stop-and-escalate" },
3856
+ { name: "Docs to keep coherent", pattern: "Docs to keep coherent|§7" }
3857
+ ];
3858
+ var DEPENDENCY_RATIONALE_FIELD_NAME = "Dependency rationale";
3859
+ function checkIssueRationale(body) {
3860
+ const errors = [];
3861
+ for (const f of RATIONALE_FIELDS) {
3862
+ if (!hasRationaleField(body, f.pattern)) {
3863
+ 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).`);
3864
+ continue;
3865
+ }
3866
+ if (f.name === DEPENDENCY_RATIONALE_FIELD_NAME && !SECTION_HEADER.test(body)) {
3867
+ 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.");
3868
+ }
4028
3869
  }
4029
- const headerNums = closesRefs(headerRegion(stripped));
4030
- if (bodyNums.length === 0)
4031
- return { issue: null, extraIssues: [], outsideHeader: false };
4032
- const issue = headerNums.length > 0 ? headerNums[0] : bodyNums[0];
4033
- return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: headerNums.length === 0 };
3870
+ return { status: errors.length > 0 ? "fail" : "pass", errors };
4034
3871
  }
4035
- // ../../packages/aeg-core/src/review-input-manifest.ts
4036
- import { createHash as createHash4 } from "node:crypto";
4037
- function briefHash(brief) {
4038
- return createHash4("sha256").update(`${brief}
4039
- `).digest("hex");
3872
+ var OBJECTIVES_SINCE_ISSUE = 404;
3873
+ function checkIssueObjectives(body, issueNumber, sinceIssue = OBJECTIVES_SINCE_ISSUE) {
3874
+ if (sinceIssue !== null && issueNumber !== null && issueNumber < sinceIssue)
3875
+ return { status: "pass", errors: [] };
3876
+ const result = objectivesOf(body);
3877
+ if (result.ok)
3878
+ return { status: "pass", errors: [] };
3879
+ return { status: "fail", errors: result.errors.map((e) => `issue-validation objectives: ${e}`) };
4040
3880
  }
4041
- function policyDigest(policy) {
4042
- return createHash4("sha256").update(JSON.stringify({
4043
- codeReviewThreshold: policy.codeReviewThreshold,
4044
- securityThreshold: policy.securityThreshold,
4045
- maxRounds: policy.maxRounds
4046
- })).digest("hex");
3881
+ function topLevelSectionText(body, headingName) {
3882
+ const headingRe = new RegExp(`^##[ \\t]*${headingName}[ \\t]*$`, "im");
3883
+ const heading = headingRe.exec(body);
3884
+ if (!heading)
3885
+ return null;
3886
+ const afterHeading = body.slice(heading.index + heading[0].length);
3887
+ const next = /^##[ \t]/m.exec(afterHeading);
3888
+ return next ? afterHeading.slice(0, next.index) : afterHeading;
4047
3889
  }
4048
- function isBoundToHead(echoed, headSha) {
4049
- if (!echoed.headSha)
4050
- return false;
4051
- return headSha.toLowerCase().startsWith(echoed.headSha.toLowerCase());
3890
+ function partHasBacktickedPath(text) {
3891
+ let i = 0;
3892
+ while (i < text.length) {
3893
+ const start = text.indexOf("`", i);
3894
+ if (start === -1)
3895
+ return false;
3896
+ const end = text.indexOf("`", start + 1);
3897
+ if (end === -1)
3898
+ return false;
3899
+ if (text.slice(start + 1, end).includes("/"))
3900
+ return true;
3901
+ i = end + 1;
3902
+ }
3903
+ return false;
4052
3904
  }
4053
- function isBoundByPatchIdentity(echoed, headSha, patchIdOf) {
4054
- if (patchIdOf === undefined || !echoed.headSha)
4055
- return false;
4056
- const judged = patchIdOf(echoed.headSha);
4057
- const current = patchIdOf(headSha);
4058
- if (judged === null || current === null)
4059
- return false;
4060
- return judged === current;
3905
+ var PART_MIN_WORDS_OUTSIDE_BACKTICKS = 3;
3906
+ function stripPartBackticks(text) {
3907
+ return text.replace(/`[^`\n]*`/g, " ");
4061
3908
  }
4062
- function isBoundToBase(echoed, currentBase) {
4063
- if (currentBase === null)
4064
- return true;
4065
- if (!echoed.baseSha)
4066
- return false;
4067
- return currentBase.toLowerCase().startsWith(echoed.baseSha.toLowerCase());
3909
+ function partWordCount(text) {
3910
+ return text.split(/\s+/).filter((w) => /[a-z]/i.test(w)).length;
4068
3911
  }
4069
- function isBoundToObjectives(echoed, currentVersion) {
4070
- if (currentVersion === null)
4071
- return true;
4072
- return echoed.objectivesVersion === currentVersion;
3912
+ function looksLikeFilePath(entry) {
3913
+ const stripped = entry.replace(/\/\*\*?$/, "");
3914
+ const lastSegment = stripped.split("/").pop() ?? stripped;
3915
+ const extMatch = /\.[A-Za-z0-9]{1,6}$/.exec(lastSegment);
3916
+ return extMatch !== null && extMatch.index > 0;
4073
3917
  }
4074
- function isBoundToRulings(echoed, currentOrdinal) {
4075
- if (echoed.rulingOrdinal === null)
4076
- return currentOrdinal === 0;
4077
- return echoed.rulingOrdinal === currentOrdinal;
3918
+ function splitGlobList(raw) {
3919
+ return raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
4078
3920
  }
4079
- function isBoundToBriefHash(echoed, currentHash) {
4080
- if (currentHash === null)
4081
- return true;
4082
- return echoed.briefHash === currentHash;
3921
+ function parseIssueSurface(body) {
3922
+ const section = topLevelSectionText(body, "Surface");
3923
+ if (section === null)
3924
+ return { ok: false, errors: ["no `## Surface` heading found in the body."] };
3925
+ const inLine = /^in:\s*(.+)$/im.exec(section);
3926
+ const outLine = /^out:\s*(.+)$/im.exec(section);
3927
+ const errors = [];
3928
+ if (!inLine)
3929
+ errors.push("`## Surface` has no `in:` line.");
3930
+ if (!outLine)
3931
+ errors.push("`## Surface` has no `out:` line.");
3932
+ if (errors.length > 0)
3933
+ return { ok: false, errors };
3934
+ const inGlobs = splitGlobList(inLine[1]);
3935
+ const outGlobs = splitGlobList(outLine[1]);
3936
+ for (const g of [...inGlobs, ...outGlobs]) {
3937
+ if (looksLikeFilePath(g)) {
3938
+ errors.push(`\`${g}\` in \`## Surface\` looks like a file path — Surface entries are directory-level globs, never file paths.`);
3939
+ }
3940
+ }
3941
+ if (inGlobs.length === 0)
3942
+ errors.push("`## Surface`'s `in:` line resolved to zero globs.");
3943
+ if (errors.length > 0)
3944
+ return { ok: false, errors };
3945
+ return { ok: true, value: { in: inGlobs, out: outGlobs } };
4083
3946
  }
4084
- function isBoundToPolicy(echoed, currentDigest) {
4085
- return echoed.policyDigest === currentDigest;
3947
+ function globCoversPath(glob, path) {
3948
+ const g = glob.replace(/\/\*\*?$/, "").replace(/\/+$/, "");
3949
+ const p = path.replace(/\/+$/, "");
3950
+ if (g === "*")
3951
+ return !p.includes("/");
3952
+ return g === p || g.startsWith(`${p}/`) || p.startsWith(`${g}/`);
4086
3953
  }
4087
- function compareManifest(echoed, current, patchIdOf) {
4088
- const exactHead = isBoundToHead(echoed, current.headSha);
4089
- const patchHead = exactHead ? false : isBoundByPatchIdentity(echoed, current.headSha, patchIdOf);
4090
- const head = exactHead || patchHead;
4091
- const echoedShaLen = echoed.baseSha?.length ?? 0;
4092
- const currentShaLen = current.baseSha?.length ?? 0;
4093
- const bothFullShas = echoedShaLen >= 40 && currentShaLen >= 40;
4094
- const base = patchHead || exactHead && bothFullShas ? true : isBoundToBase(echoed, current.baseSha);
4095
- const briefHashBound = isBoundToBriefHash(echoed, current.briefHash);
4096
- const objectivesVersion = isBoundToObjectives(echoed, current.objectivesVersion);
4097
- const rulingOrdinal = isBoundToRulings(echoed, current.rulingOrdinal);
4098
- const policyDigestBound = isBoundToPolicy(echoed, current.policyDigest);
3954
+ function checkSurfaceGlobsResolve(body, resolvesToFile) {
3955
+ const surface = parseIssueSurface(body);
3956
+ if (!surface.ok)
3957
+ return { status: "pass", errors: [] };
3958
+ const errors = [];
3959
+ for (const glob of surface.value.in) {
3960
+ if (!resolvesToFile(glob)) {
3961
+ 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.`);
3962
+ }
3963
+ }
3964
+ return { status: errors.length > 0 ? "fail" : "pass", errors };
3965
+ }
3966
+ function checkSurfaceScope(changedFiles, outGlobs) {
3967
+ if (outGlobs.length === 0)
3968
+ return { ok: true };
3969
+ const violations = [];
3970
+ for (const file of changedFiles) {
3971
+ const glob = outGlobs.find((g) => globCoversPath(g, file));
3972
+ if (glob)
3973
+ violations.push({ file, glob });
3974
+ }
3975
+ return violations.length > 0 ? { ok: false, violations } : { ok: true };
3976
+ }
3977
+ var ISSUE_PART_LINE_RE = /^Part\s+(\d+)\s*\(([^)]*)\)\s*[-—–]\s*(.*)$/i;
3978
+ function parseIssueParts(body) {
3979
+ const section = topLevelSectionText(body, "Parts");
3980
+ if (section === null)
3981
+ return { ok: false, errors: ["no `## Parts` heading found in the body."] };
3982
+ const lines = section.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
3983
+ const parts = [];
3984
+ const errors = [];
3985
+ for (const line of lines) {
3986
+ const m = ISSUE_PART_LINE_RE.exec(line);
3987
+ if (!m) {
3988
+ errors.push(`"${line}" is not a well-formed Parts line — expected \`Part <n> (<refs>) — <outcome>\`.`);
3989
+ continue;
3990
+ }
3991
+ const n = Number.parseInt(m[1], 10);
3992
+ const refs = m[2];
3993
+ const text = m[3].trim();
3994
+ if (text.length === 0) {
3995
+ errors.push(`Part ${n} has no outcome text after the dash — every Part states one observable outcome.`);
3996
+ continue;
3997
+ }
3998
+ if (partHasBacktickedPath(text) && partWordCount(stripPartBackticks(text)) < PART_MIN_WORDS_OUTSIDE_BACKTICKS) {
3999
+ errors.push(`Part ${n} is little more than a file path — a Part names an outcome and symbols, never a bare path.`);
4000
+ continue;
4001
+ }
4002
+ const objectiveIds = [...refs.matchAll(/O(\d+)/g)].map((r) => Number.parseInt(r[1], 10));
4003
+ parts.push({ n, objectiveIds, text });
4004
+ }
4005
+ if (parts.length === 0) {
4006
+ errors.push("the `## Parts` section has no well-formed `Part <n> (<refs>) — <outcome>` lines.");
4007
+ }
4008
+ if (errors.length > 0)
4009
+ return { ok: false, errors };
4010
+ return { ok: true, value: parts };
4011
+ }
4012
+ function checkPartsCiteDefinedObjectives(body) {
4013
+ const parts = parseIssueParts(body);
4014
+ const objectives = objectivesOf(body);
4015
+ if (!parts.ok || !objectives.ok)
4016
+ return { status: "pass", errors: [] };
4017
+ const definedIds = new Set(objectives.objectives.map((o) => Number.parseInt(o.id.slice(1), 10)));
4018
+ const errors = [];
4019
+ for (const part of parts.value) {
4020
+ for (const objectiveId of part.objectiveIds) {
4021
+ if (!definedIds.has(objectiveId)) {
4022
+ errors.push(`issue-validation Parts: Part ${part.n} cites O${objectiveId}, which the Issue's own \`## Objectives\` section does not define.`);
4023
+ }
4024
+ }
4025
+ }
4026
+ return { status: errors.length > 0 ? "fail" : "pass", errors };
4027
+ }
4028
+ function isTaskIssueLabelSet(labels) {
4029
+ return hasLabel("tranche", labels);
4030
+ }
4031
+ function checkTrancheLabelPresence(_body, _labels) {
4032
+ return { status: "pass", errors: [] };
4033
+ }
4034
+ function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTitle) {
4035
+ if (!isTaskIssueLabelSet(labels))
4036
+ return { status: "pass", errors: [] };
4037
+ if (resolvedMilestoneTitle === null)
4038
+ return { status: "pass", errors: [] };
4039
+ if (currentMilestoneTitle === resolvedMilestoneTitle)
4040
+ return { status: "pass", errors: [] };
4099
4041
  return {
4100
- bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && policyDigestBound,
4101
- head,
4102
- base,
4103
- briefHash: briefHashBound,
4104
- objectivesVersion,
4105
- rulingOrdinal,
4106
- policyDigest: policyDigestBound
4042
+ status: "fail",
4043
+ errors: [
4044
+ `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}".`
4045
+ ]
4107
4046
  };
4108
4047
  }
4109
-
4110
- // ../../packages/aeg-core/src/review-gate.ts
4111
- function checkReviewGate(input) {
4112
- const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
4113
- const waived = isWaiverLabelActorVerified({
4114
- label: WAIVER_LABEL_REVIEW,
4115
- labels: input.labels,
4116
- labelActor: input.waiverLabelActor,
4117
- principalAllowlist
4118
- });
4119
- if (waived) {
4120
- return {
4121
- verdict: "pass",
4122
- reason: `\`${WAIVER_LABEL_REVIEW}\` label is actor-verified — review requirement waived for this PR.`,
4123
- waived: true
4124
- };
4048
+ var TYPE_LABEL_IDS = LABELS.filter((l) => l.category === "type").map((l) => l.id);
4049
+ function isControlCodePoint(codePoint) {
4050
+ return codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
4051
+ }
4052
+ function isDisplayControlCodePoint(codePoint) {
4053
+ return codePoint >= 8203 && codePoint <= 8207 || codePoint >= 8234 && codePoint <= 8238 || codePoint >= 8294 && codePoint <= 8297 || codePoint === 65279;
4054
+ }
4055
+ var MESSAGE_VALUE_COUNT_MAX = 5;
4056
+ function residueForMessage(values) {
4057
+ const shown = values.slice(0, MESSAGE_VALUE_COUNT_MAX).map((v) => `\`${forMessage(v)}\``);
4058
+ const rest = values.length - shown.length;
4059
+ return rest > 0 ? `${shown.join(", ")} and ${rest} more` : shown.join(", ");
4060
+ }
4061
+ var MESSAGE_VALUE_MAX = 64;
4062
+ function forMessage(value) {
4063
+ const kept = [];
4064
+ for (const ch of value.replace(/\s+/g, " ")) {
4065
+ const codePoint = ch.codePointAt(0) ?? 0;
4066
+ if (isControlCodePoint(codePoint) || isDisplayControlCodePoint(codePoint))
4067
+ continue;
4068
+ kept.push(ch);
4125
4069
  }
4126
- const verified = input.comments.filter((c) => isPrincipal(c.author, principalAllowlist));
4127
- const ignoredCount = input.comments.filter((c) => !isPrincipal(c.author, principalAllowlist) && c.body.includes("VERDICT")).length;
4128
- const verifiedBodies = verified.map((c) => c.body);
4129
- const codeReview = extractCodeReviewVerdict(verifiedBodies);
4130
- const security = extractSecurityReviewVerdict(verifiedBodies);
4131
- const policy = input.policy ?? DEFAULT_REVIEW_POLICY;
4132
- let codeReviewPolicyEvaluation;
4133
- let securityPolicyEvaluation;
4134
- try {
4135
- codeReviewPolicyEvaluation = evaluateCodeReview(consequentialFindings(codeReview.findingSeverities), policy);
4136
- securityPolicyEvaluation = evaluateSecurityReview(consequentialFindings(security.findingSeverities), policy);
4137
- } catch (err) {
4070
+ const cleaned = kept.join("").trim();
4071
+ if (cleaned.length === 0)
4072
+ return "(unprintable)";
4073
+ const points = Array.from(cleaned);
4074
+ return points.length > MESSAGE_VALUE_MAX ? `${points.slice(0, MESSAGE_VALUE_MAX).join("")}…` : cleaned;
4075
+ }
4076
+ function checkProjectsRegistered(body, _labels, registeredNames) {
4077
+ if (registeredNames.length === 0)
4078
+ return { status: "pass", errors: [] };
4079
+ const field = projectFieldFromBody(body);
4080
+ if (!field.declared)
4081
+ return { status: "pass", errors: [] };
4082
+ const known = new Set(registeredNames.map((n) => n.trim()));
4083
+ const registeredList = [...registeredNames].map(forMessage).join(", ");
4084
+ const errors = [];
4085
+ if (field.unreadable) {
4138
4086
  return {
4139
- verdict: "fail",
4140
- reason: `a verdict comment carries a finding severity this repository's policy does not recognize: ${err instanceof Error ? err.message : String(err)}`,
4141
- waived: false
4087
+ status: "fail",
4088
+ errors: [
4089
+ `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.`
4090
+ ]
4142
4091
  };
4143
4092
  }
4144
- const codeReviewTextClean = codeReview.value === "APPROVE";
4145
- const securityTextClean = security.value === "PASS";
4146
- const codeReviewPolicyClean = codeReviewPolicyEvaluation.outcome === "clean";
4147
- const securityPolicyClean = securityPolicyEvaluation.outcome === "clean";
4148
- const codeReviewClean = codeReviewTextClean && codeReviewPolicyClean;
4149
- const securityClean = securityTextClean && securityPolicyClean;
4150
- const currentManifest = {
4151
- headSha: input.headSha,
4152
- baseSha: input.baseSha ?? null,
4153
- briefHash: input.briefHash ?? null,
4154
- objectivesVersion: input.objectivesVersion,
4155
- rulingOrdinal: input.rulingOrdinal,
4156
- policyDigest: policyDigest(policy)
4157
- };
4158
- const codeReviewEchoed = {
4159
- headSha: codeReview.headSha,
4160
- baseSha: codeReview.baseSha,
4161
- briefHash: codeReview.briefHash,
4162
- objectivesVersion: codeReview.objectivesVersion,
4163
- rulingOrdinal: codeReview.rulingOrdinal,
4164
- policyDigest: codeReview.policyDigest
4165
- };
4166
- const securityEchoed = {
4167
- headSha: security.headSha,
4168
- baseSha: security.baseSha,
4169
- briefHash: security.briefHash,
4170
- objectivesVersion: security.objectivesVersion,
4171
- rulingOrdinal: security.rulingOrdinal,
4172
- policyDigest: security.policyDigest
4173
- };
4174
- const codeReviewBinding = compareManifest(codeReviewEchoed, currentManifest, input.patchIdOf);
4175
- const securityBinding = compareManifest(securityEchoed, currentManifest, input.patchIdOf);
4176
- const codeReviewBound = codeReviewBinding.head;
4177
- const securityBound = securityBinding.head;
4178
- const codeReviewObjectivesBound = codeReviewBinding.objectivesVersion;
4179
- const securityObjectivesBound = securityBinding.objectivesVersion;
4180
- const codeReviewRulingsBound = codeReviewBinding.rulingOrdinal;
4181
- const securityRulingsBound = securityBinding.rulingOrdinal;
4182
- if (codeReviewClean && codeReviewBinding.bound && securityClean && securityBinding.bound) {
4183
- return {
4184
- verdict: "pass",
4185
- reason: `code-reviewer verdict is a clean APPROVE and security-review verdict is a clean PASS, both covering head ${input.headSha}.`,
4186
- waived: false
4187
- };
4093
+ const unregistered = field.names.filter((p) => !known.has(p));
4094
+ if (unregistered.length > 0) {
4095
+ const caseHints = unregistered.map((p) => {
4096
+ const row = [...known].find((k) => k.toLowerCase() === p.toLowerCase());
4097
+ return row ? `\`${forMessage(p)}\` differs from the registered \`${forMessage(row)}\` only in case` : null;
4098
+ }).filter((h) => h !== null);
4099
+ 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.`);
4188
4100
  }
4189
- const problems = [];
4190
- if (!codeReviewTextClean) {
4191
- problems.push(`code-reviewer verdict is not a clean APPROVE (found: ${codeReview.value})`);
4192
- } else if (!codeReviewPolicyClean) {
4193
- 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`);
4194
- } else if (!codeReviewBound) {
4195
- problems.push(`the newest code-review verdict covers ${codeReview.headSha ?? "no recorded commit"}, head is ${input.headSha}`);
4196
- } else if (!codeReviewBinding.base) {
4197
- 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)`);
4198
- } else if (!codeReviewObjectivesBound) {
4199
- problems.push(`the newest code-review verdict was cast against objectives version ${codeReview.objectivesVersion ?? "none"}, the Issue's list is now ${input.objectivesVersion}`);
4200
- } else if (!codeReviewRulingsBound) {
4201
- 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`);
4202
- } else if (!codeReviewBinding.briefHash) {
4203
- 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"}`);
4204
- } else if (!codeReviewBinding.policyDigest) {
4205
- 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}`);
4101
+ if (field.names.length === 0) {
4102
+ const residue = field.unparsed.length > 0 ? ` — ${residueForMessage(field.unparsed)}` : " — the field is empty";
4103
+ 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.`);
4104
+ } else if (field.unparsed.length > 0) {
4105
+ 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.`);
4206
4106
  }
4207
- if (!securityTextClean) {
4208
- problems.push(`security-review verdict is not a clean PASS (found: ${security.value})`);
4209
- } else if (!securityPolicyClean) {
4210
- 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`);
4211
- } else if (!securityBound) {
4212
- problems.push(`the newest security-review verdict covers ${security.headSha ?? "no recorded commit"}, head is ${input.headSha}`);
4213
- } else if (!securityBinding.base) {
4214
- 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)`);
4215
- } else if (!securityObjectivesBound) {
4216
- problems.push(`the newest security-review verdict was cast against objectives version ${security.objectivesVersion ?? "none"}, the Issue's list is now ${input.objectivesVersion}`);
4217
- } else if (!securityRulingsBound) {
4218
- 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`);
4219
- } else if (!securityBinding.briefHash) {
4220
- 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"}`);
4221
- } else if (!securityBinding.policyDigest) {
4222
- 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}`);
4107
+ return errors.length > 0 ? { status: "fail", errors } : { status: "pass", errors: [] };
4108
+ }
4109
+ 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;
4110
+ var DOC_PATH_RE_GLOBAL = new RegExp(DOC_PATH_RE.source, "gi");
4111
+ var FILE_EXTENSIONS = new Set([
4112
+ "ts",
4113
+ "tsx",
4114
+ "js",
4115
+ "jsx",
4116
+ "mjs",
4117
+ "cjs",
4118
+ "json",
4119
+ "jsonc",
4120
+ "md",
4121
+ "mdx",
4122
+ "yml",
4123
+ "yaml",
4124
+ "txt",
4125
+ "sh",
4126
+ "lock",
4127
+ "toml",
4128
+ "ndjson",
4129
+ "html",
4130
+ "css"
4131
+ ]);
4132
+
4133
+ // ../../packages/aeg-core/src/task-branch-identity.ts
4134
+ var ISSUE_BRANCH_PATTERN = /^task\/issue-(\d+)$/;
4135
+ var TRANCHE_BRANCH_PATTERN = /^task\/([^/]+)\/([^/]+)$/;
4136
+ function parseTaskBranchIdentity(branch) {
4137
+ const issueMatch = ISSUE_BRANCH_PATTERN.exec(branch);
4138
+ if (issueMatch)
4139
+ return { kind: "issue", issueNumber: Number(issueMatch[1]) };
4140
+ const trancheMatch = TRANCHE_BRANCH_PATTERN.exec(branch);
4141
+ if (trancheMatch)
4142
+ return { kind: "tranche", tranche: trancheMatch[1], taskId: trancheMatch[2] };
4143
+ return null;
4144
+ }
4145
+
4146
+ // ../../packages/aeg-core/src/coherence-checks.ts
4147
+ var COHERENCE_ENFORCED_FROM = "2026-07-01";
4148
+ function isGrandfathered(isoDate) {
4149
+ if (!isoDate)
4150
+ return false;
4151
+ return isoDate.slice(0, 10) < COHERENCE_ENFORCED_FROM;
4152
+ }
4153
+ var R1_GRANDFATHERED_ISSUES = new Set([279, 280, 281, 282]);
4154
+ function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
4155
+ const failures = [];
4156
+ for (const e of entries) {
4157
+ if (!e.facts)
4158
+ continue;
4159
+ if (e.facts.stateReason === "not_planned")
4160
+ continue;
4161
+ if (e.facts.issueState === "closed" && e.facts.prState !== "merged") {
4162
+ const handClosed = e.facts.stateReason === "completed" && isPrincipal(e.facts.closedByActor, principalAllowlist);
4163
+ if (handClosed)
4164
+ continue;
4165
+ failures.push({
4166
+ code: "closed-without-merge",
4167
+ issue: e.task.issue,
4168
+ tranche: e.trancheSlug,
4169
+ task: e.task.id,
4170
+ reason: `Issue closed but closing PR is not merged (prState: ${e.facts.prState})`,
4171
+ grandfathered: isGrandfathered(e.facts.closedAt)
4172
+ });
4173
+ }
4223
4174
  }
4224
- const ignoredNote = ignoredCount > 0 ? ` ${ignoredCount} verdict-shaped comment(s) from authors outside the principal allowlist were ignored.` : "";
4175
+ const activeFails = failures.filter((f) => !f.grandfathered);
4176
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
4225
4177
  return {
4226
- verdict: "fail",
4227
- 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}`,
4228
- waived: false
4178
+ check: "A1",
4179
+ status,
4180
+ failures,
4181
+ note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
4229
4182
  };
4230
4183
  }
4231
- var CHANGESET_RELEASE_BRANCH = "changeset-release/main";
4232
- var DEFAULT_RELEASE_ACTOR = "github-actions[bot]";
4233
- function isChangesetsReleasePr(branch, author, expectedAuthor) {
4234
- return branch === CHANGESET_RELEASE_BRANCH && author === expectedAuthor;
4235
- }
4236
- // ../../packages/aeg-core/src/ruling-ordinal.ts
4237
- var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
4238
- function newestPrincipalRulingOrdinal(comments, allowlist) {
4239
- let best = 0;
4240
- for (const c of comments) {
4241
- if (!isPrincipal(c.author, allowlist))
4242
- continue;
4243
- const firstLine = (c.body.split(`
4244
- `)[0] ?? "").trim();
4245
- const m = RULING_MARKER_ORDINAL.exec(firstLine);
4246
- if (!m)
4184
+ function checkA3(entries) {
4185
+ const failures = [];
4186
+ for (const e of entries) {
4187
+ if (!e.facts)
4247
4188
  continue;
4248
- const k = Number.parseInt(m[1], 10);
4249
- if (k > best)
4250
- best = k;
4189
+ if (e.facts.prState === "merged" && e.facts.issueState !== "closed") {
4190
+ failures.push({
4191
+ code: "auto-close-misfire",
4192
+ issue: e.task.issue,
4193
+ tranche: e.trancheSlug,
4194
+ task: e.task.id,
4195
+ reason: "Closing PR is merged but Issue is still open (GitHub auto-close misfire)",
4196
+ grandfathered: isGrandfathered(e.facts.mergedAt)
4197
+ });
4198
+ }
4251
4199
  }
4252
- return best;
4200
+ const activeFails = failures.filter((f) => !f.grandfathered);
4201
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
4202
+ return {
4203
+ check: "A3",
4204
+ status,
4205
+ failures,
4206
+ note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
4207
+ };
4253
4208
  }
4254
- // ../../packages/aeg-core/src/markdown-table.ts
4255
- function splitRow(line) {
4256
- const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
4257
- return trimmed.split("|").map((cell) => cell.trim());
4209
+ function checkT1(entries) {
4210
+ const failures = [];
4211
+ for (const e of entries) {
4212
+ if (e.task.issue === null)
4213
+ continue;
4214
+ if (e.facts === undefined) {
4215
+ failures.push({
4216
+ code: "phantom-issue-ref",
4217
+ issue: e.task.issue,
4218
+ tranche: e.trancheSlug,
4219
+ task: e.task.id,
4220
+ reason: `Issue #${e.task.issue} in topology does not resolve to a real GitHub Issue`
4221
+ });
4222
+ }
4223
+ }
4224
+ return { check: "T1", status: failures.length > 0 ? "fail" : "pass", failures };
4258
4225
  }
4259
- var TABLE_ROW_PATTERN = /^\s*\|.*\|\s*$/;
4260
- var SEPARATOR_ROW_PATTERN = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
4261
- function findTable(lines, fromLine, stopAtHeading = true) {
4262
- let i = fromLine - 1;
4263
- while (i < lines.length) {
4264
- const line = lines[i] ?? "";
4265
- if (stopAtHeading && i > fromLine - 1 && /^##\s/.test(line))
4266
- return null;
4267
- if (TABLE_ROW_PATTERN.test(line)) {
4268
- const headerLine = line;
4269
- const sepLine = lines[i + 1] ?? "";
4270
- if (!SEPARATOR_ROW_PATTERN.test(sepLine)) {
4271
- i++;
4272
- continue;
4273
- }
4274
- const headers = splitRow(headerLine);
4275
- const rows = [];
4276
- let j = i + 2;
4277
- while (j < lines.length && TABLE_ROW_PATTERN.test(lines[j] ?? "")) {
4278
- rows.push({ cells: splitRow(lines[j] ?? ""), line: j + 1 });
4279
- j++;
4226
+ function checkT2(openIssuesBySlug, topologyIssuesBySlug, ciTrancheSlug) {
4227
+ const failures = [];
4228
+ for (const [slug, openNums] of openIssuesBySlug) {
4229
+ if (ciTrancheSlug && slug !== ciTrancheSlug)
4230
+ continue;
4231
+ const topologySet = topologyIssuesBySlug.get(slug) ?? new Set;
4232
+ for (const num of openNums) {
4233
+ if (!topologySet.has(num)) {
4234
+ failures.push({
4235
+ code: "orphan-task",
4236
+ issue: num,
4237
+ tranche: slug,
4238
+ reason: `Issue #${num} is open and labeled ${trancheLabel(slug)} but does not appear in the topology file`
4239
+ });
4280
4240
  }
4281
- return { headers, rows };
4282
4241
  }
4283
- i++;
4284
4242
  }
4285
- return null;
4243
+ return { check: "T2", status: failures.length > 0 ? "fail" : "pass", failures };
4286
4244
  }
4287
- function findHeadingLine(lines, pattern) {
4288
- for (let i = 0;i < lines.length; i++) {
4289
- if (pattern.test(lines[i] ?? ""))
4290
- return i + 1;
4291
- }
4292
- return null;
4245
+ function scopeT2ToPlanPr(result, isPlanPr) {
4246
+ if (isPlanPr || result.status !== "fail")
4247
+ return result;
4248
+ return {
4249
+ ...result,
4250
+ status: "info",
4251
+ note: result.note ?? "T2 findings are non-blocking outside plan PRs (point-of-power principle) — see aeg-root/enforcement.md."
4252
+ };
4293
4253
  }
4294
- // ../../packages/aeg-core/src/diagram-model.ts
4295
- import matter from "gray-matter";
4296
-
4297
- // ../../packages/aeg-core/src/registry-parse.ts
4298
- var RING_HEADINGS = [
4299
- { ring: "ring0", pattern: /^##\s+Ring 0\b/ },
4300
- { ring: "ring1", pattern: /^##\s+Ring 1\b/ },
4301
- { ring: "ring2", pattern: /^##\s+Ring 2\b/ }
4302
- ];
4303
- function stripBackticks2(cell) {
4304
- const trimmed = cell.trim();
4305
- if (trimmed.length >= 2 && trimmed.startsWith("`") && trimmed.endsWith("`")) {
4306
- return trimmed.slice(1, -1);
4254
+ function checkT3(entries, ciTrancheSlug, enrichedEntries, forgeUnavailableSlugs) {
4255
+ const preEnforcement = new Set;
4256
+ if (enrichedEntries) {
4257
+ for (const e of enrichedEntries) {
4258
+ if (isGrandfathered(e.facts?.closedAt) || isGrandfathered(e.facts?.mergedAt)) {
4259
+ preEnforcement.add(e.trancheSlug);
4260
+ }
4261
+ }
4307
4262
  }
4308
- return trimmed;
4309
- }
4310
- function stripBold(cell) {
4311
- return cell.trim().replace(/\*\*/g, "");
4263
+ const failures = [];
4264
+ for (const e of entries) {
4265
+ if (!e.archived && e.task.issue === null) {
4266
+ if (ciTrancheSlug && e.trancheSlug !== ciTrancheSlug)
4267
+ continue;
4268
+ if (forgeUnavailableSlugs?.has(e.trancheSlug)) {
4269
+ failures.push({
4270
+ code: "tbd-in-active-tranche",
4271
+ issue: null,
4272
+ tranche: e.trancheSlug,
4273
+ task: e.task.id,
4274
+ 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`,
4275
+ grandfathered: true
4276
+ });
4277
+ continue;
4278
+ }
4279
+ failures.push({
4280
+ code: "tbd-in-active-tranche",
4281
+ issue: null,
4282
+ tranche: e.trancheSlug,
4283
+ task: e.task.id,
4284
+ 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`,
4285
+ grandfathered: preEnforcement.has(e.trancheSlug)
4286
+ });
4287
+ }
4288
+ }
4289
+ const activeFails = failures.filter((f) => !f.grandfathered);
4290
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
4291
+ return {
4292
+ check: "T3",
4293
+ status,
4294
+ failures,
4295
+ note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
4296
+ };
4312
4297
  }
4313
- function parseEnforcementRegistry(content) {
4314
- const lines = content.split(`
4315
- `);
4316
- const result = [];
4317
- for (const { ring, pattern } of RING_HEADINGS) {
4318
- const headingLine = findHeadingLine(lines, pattern);
4319
- if (headingLine === null)
4298
+ function checkD1(entries, issueToEntry, taskToEntry) {
4299
+ const failures = [];
4300
+ for (const e of entries) {
4301
+ if (!e.facts)
4320
4302
  continue;
4321
- const table = findTable(lines, headingLine + 1);
4322
- if (!table)
4303
+ if (e.facts.prState !== "open")
4323
4304
  continue;
4324
- const descriptionIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "description");
4325
- const implementationIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "implementation");
4326
- const audienceIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "audience");
4327
- for (const row of table.rows) {
4328
- const cells = row.cells;
4329
- if (cells.length < 3)
4305
+ for (const dep of e.task.dependsOn) {
4306
+ const depEntry = resolveDepEntry(dep, e.trancheSlug, issueToEntry, taskToEntry);
4307
+ if (!depEntry)
4330
4308
  continue;
4331
- const action = stripBold(cells[0] ?? "");
4332
- const summary = stripBackticks2(cells[1] ?? "");
4333
- const category = stripBackticks2(cells[2] ?? "");
4334
- const implementation = stripBackticks2((implementationIndex === -1 ? cells[cells.length - 1] : cells[implementationIndex]) ?? "");
4335
- const description = descriptionIndex === -1 ? undefined : stripBackticks2(cells[descriptionIndex] ?? "") || undefined;
4336
- const specIndex = (audienceIndex === -1 ? cells.length - 1 : audienceIndex) - 1;
4337
- const spec = specIndex >= 3 ? stripBackticks2(cells[specIndex] ?? "") || undefined : undefined;
4338
- const audience = audienceIndex === -1 ? "repo-own" : stripBackticks2(cells[audienceIndex] ?? "") === "product" ? "product" : "repo-own";
4339
- result.push({ ring, action, summary, category, description, spec, implementation, audience, line: row.line });
4309
+ const sameTask = depEntry.trancheSlug === e.trancheSlug && depEntry.task.id === e.task.id;
4310
+ const sameIssue = depEntry.task.issue !== null && e.task.issue !== null && depEntry.task.issue === e.task.issue;
4311
+ if (sameTask || sameIssue) {
4312
+ failures.push({
4313
+ code: "d1-self-dependency",
4314
+ issue: e.task.issue,
4315
+ tranche: e.trancheSlug,
4316
+ task: e.task.id,
4317
+ reason: `INTERNAL: parsed a self-dependency (depends-on ${dep}) — this is a parser bug in parseRationaleDeps, not a real dependency. Please report it upstream.`
4318
+ });
4319
+ continue;
4320
+ }
4321
+ const depFacts = depEntry.facts;
4322
+ const depClosed = depFacts?.issueState === "closed";
4323
+ if (!depClosed) {
4324
+ failures.push({
4325
+ code: "dispatched-on-unmet-deps",
4326
+ issue: e.task.issue,
4327
+ tranche: e.trancheSlug,
4328
+ task: e.task.id,
4329
+ reason: `Task has open PR but depends-on ${dep} (issue #${depEntry.task.issue ?? "?"}) is not closed`
4330
+ });
4331
+ }
4340
4332
  }
4341
4333
  }
4342
- return result;
4334
+ return { check: "D1", status: failures.length > 0 ? "fail" : "pass", failures };
4335
+ }
4336
+ function resolveDepEntry(dep, trancheSlug, issueToEntry, taskToEntry) {
4337
+ const issueMatch = dep.match(/^#(\d+)$/);
4338
+ if (issueMatch?.[1])
4339
+ return issueToEntry.get(Number(issueMatch[1]));
4340
+ return taskToEntry.get(`${trancheSlug}/${dep}`) ?? taskToEntry.get(dep);
4343
4341
  }
4344
- // ../../packages/aeg-core/src/registry-checks.ts
4345
- function checkG1(rows, existsFn) {
4346
- const findings = [];
4347
- for (const row of rows) {
4348
- if (row.implementation === "")
4349
- continue;
4350
- if (!existsFn(row.implementation)) {
4351
- findings.push({
4352
- row: row.action,
4353
- path: row.implementation,
4354
- reason: `${row.ring} row "${row.action}" names implementation "${row.implementation}", which does not exist on disk`
4342
+ function checkR1(issuesBySlug, grandfatheredIssues, registeredNames = [], objectivesSinceIssue) {
4343
+ const failures = [];
4344
+ for (const [slug, issues] of issuesBySlug) {
4345
+ for (const issue of issues) {
4346
+ if (!isTaskIssueLabelSet(issue.labels))
4347
+ continue;
4348
+ const errors = [
4349
+ ...checkIssueRationale(issue.body).errors,
4350
+ ...checkProjectsRegistered(issue.body, issue.labels, registeredNames).errors,
4351
+ ...checkIssueObjectives(issue.body, issue.number, objectivesSinceIssue).errors,
4352
+ ...checkPartsCiteDefinedObjectives(issue.body).errors
4353
+ ];
4354
+ if (errors.length === 0)
4355
+ continue;
4356
+ failures.push({
4357
+ code: "missing-rationale-field",
4358
+ issue: issue.number,
4359
+ tranche: slug,
4360
+ reason: `Issue #${issue.number} fails the rationale gate: ${errors.join(" | ")}`,
4361
+ grandfathered: grandfatheredIssues.has(issue.number)
4355
4362
  });
4356
4363
  }
4357
4364
  }
4358
- return { check: "G1", status: findings.length > 0 ? "fail" : "pass", findings };
4365
+ const activeFails = failures.filter((f) => !f.grandfathered);
4366
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
4367
+ return {
4368
+ check: "R1",
4369
+ status,
4370
+ failures,
4371
+ note: status === "info" ? `${failures.length} grandfathered task Issue(s) predate this check's grammar (rationale fields and/or the project registry)` : undefined
4372
+ };
4359
4373
  }
4360
- var SCAFFOLD_PLACEHOLDER = "[undocumented — fill in why]";
4361
- var NON_GATE_BIN_NAMES = NON_GATE_BINS;
4362
- var TWIN_CANDIDATE_EXCEPTIONS = {
4363
- "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)',
4364
- "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)`,
4365
- "apps/cli/src/checks/bin/check-closes-n.ts": 'Ring 1 "Closes linkage" (implementation: verify-coherence.ts)'
4366
- };
4367
- var NON_GATE_HOOK_SCRIPTS = [".claude/hooks/track-transcript.sh"];
4368
- function checkG2(rows, candidateFiles) {
4369
- const implementations = new Set(rows.map((r) => r.implementation).filter((p) => p !== ""));
4370
- const claimedNames = new Set(rows.flatMap((r) => claimedCheckNames(r.implementation)));
4371
- const findings = [];
4372
- for (const path of candidateFiles) {
4373
- if (implementations.has(path))
4374
- continue;
4375
- if (path.startsWith(AEG_CORE_BIN_PATH_PREFIX) && NON_GATE_BIN_NAMES.includes(basenameNoExt(path)))
4376
- continue;
4377
- if (NON_GATE_HOOK_SCRIPTS.includes(path))
4378
- continue;
4379
- if (path in TWIN_CANDIDATE_EXCEPTIONS)
4374
+ function checkL1(files, entriesBySlug) {
4375
+ const failures = [];
4376
+ for (const f of files) {
4377
+ if (f.archived)
4380
4378
  continue;
4381
- const candidateNames = claimedCheckNames(path);
4382
- if (candidateNames.length > 0 && candidateNames.some((n) => claimedNames.has(n)))
4379
+ const entries = entriesBySlug.get(f.slug) ?? [];
4380
+ const withFacts = entries.filter((e) => e.facts !== undefined);
4381
+ if (withFacts.length === 0)
4383
4382
  continue;
4384
- findings.push({
4385
- path,
4386
- reason: `"${path}" is not named as the implementation of any row in enforcement.md's ring tables`
4387
- });
4388
- }
4389
- for (const row of rows) {
4390
- const carriesPlaceholder = [row.summary, row.description, row.spec].some((cell) => cell === SCAFFOLD_PLACEHOLDER);
4391
- if (carriesPlaceholder) {
4392
- findings.push({
4393
- row: row.action,
4394
- path: row.implementation,
4395
- reason: `${row.ring} row "${row.action}" still carries the scaffold placeholder marker — the why is owed`
4383
+ const allClosed = withFacts.every((e) => e.facts?.issueState === "closed");
4384
+ if (allClosed) {
4385
+ failures.push({
4386
+ code: "archive-recommended",
4387
+ tranche: f.slug,
4388
+ reason: "Active tranche has no open task-Issues — consider archiving to completed/"
4396
4389
  });
4397
4390
  }
4398
4391
  }
4399
- return { check: "G2", status: findings.length > 0 ? "fail" : "pass", findings };
4392
+ return {
4393
+ check: "L1",
4394
+ status: "info",
4395
+ failures,
4396
+ note: failures.length > 0 ? `${failures.length} active tranche(s) with no open task-Issues — consider archiving (advisory)` : undefined
4397
+ };
4400
4398
  }
4401
- function checkG3(ring0Rows, crossingFiles) {
4402
- const ring0Implementations = new Set(ring0Rows.map((r) => r.implementation));
4403
- const findings = [];
4404
- for (const path of crossingFiles) {
4405
- if (!ring0Implementations.has(path)) {
4406
- findings.push({
4407
- path,
4408
- reason: `"${path}" makes a GitHub-crossing call but is not named by any Ring-0 row's implementation — a seventh, unlisted way into GitHub`
4409
- });
4410
- }
4411
- }
4412
- return { check: "G3", status: findings.length > 0 ? "fail" : "pass", findings };
4399
+ function checkL3(files) {
4400
+ const active = files.filter((f) => !f.archived);
4401
+ return {
4402
+ check: "L3",
4403
+ status: "info",
4404
+ failures: [],
4405
+ note: `${active.length} active tranche(s): ${active.map((f) => f.slug).join(", ") || "(none)"}`
4406
+ };
4413
4407
  }
4414
- function checkG4(content, resolveFn) {
4415
- const cited = new Set;
4416
- for (const hit of content.matchAll(/#(\d{3,})\b/g)) {
4417
- cited.add(Number(hit[1]));
4418
- }
4419
- const findings = [];
4420
- for (const n of cited) {
4421
- if (!resolveFn(n)) {
4422
- findings.push({
4423
- reason: `#${n} is cited in enforcement.md but does not resolve to a real Issue or PR in the forge`
4424
- });
4425
- }
4408
+ function extractClosesReferences(prBody) {
4409
+ const closesPattern = /(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s{0,8}:?\s{0,8}#(\d+)/gi;
4410
+ const stripped = stripCode(prBody);
4411
+ const searchIn = anchoredRegion(stripped, "CLOSES") ?? stripped;
4412
+ const referenced = new Set;
4413
+ for (const hit of searchIn.matchAll(closesPattern)) {
4414
+ referenced.add(Number(hit[1]));
4426
4415
  }
4427
- return { check: "G4", status: findings.length > 0 ? "fail" : "pass", findings };
4416
+ return referenced;
4428
4417
  }
4429
- function checkG5(roles, contracts) {
4430
- const roleIds = new Set(roles.map((r) => r.role_id));
4431
- const findings = [];
4432
- for (const contract of contracts) {
4433
- if (!roleIds.has(contract.producer)) {
4434
- findings.push({
4435
- path: contract.file,
4436
- reason: `contract "${contract.file}" names producer "${contract.producer}", which is not a real role_id`
4437
- });
4438
- }
4439
- if (!roleIds.has(contract.consumer)) {
4440
- findings.push({
4441
- path: contract.file,
4442
- reason: `contract "${contract.file}" names consumer "${contract.consumer}", which is not a real role_id`
4443
- });
4418
+ function checkClosesNTopology(branch, prBody, trancheFiles, taskIssueRefs) {
4419
+ const referenced = extractClosesReferences(prBody);
4420
+ if (taskIssueRefs) {
4421
+ for (const n of referenced) {
4422
+ const ref = taskIssueRefs.get(n);
4423
+ if (!ref)
4424
+ continue;
4425
+ const expectedBranch = `task/${ref.trancheSlug}/${ref.taskId}`;
4426
+ if (branch !== expectedBranch) {
4427
+ return {
4428
+ ok: false,
4429
+ 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.`
4430
+ };
4431
+ }
4444
4432
  }
4445
4433
  }
4446
- for (const role of roles) {
4447
- if (role.performs.length === 0) {
4448
- findings.push({ path: role.file, reason: `role "${role.role_id}" has an empty performs array` });
4449
- }
4450
- if (role.refuses_when.trim() === "") {
4451
- findings.push({ path: role.file, reason: `role "${role.role_id}" has an empty refuses_when` });
4434
+ const ref = parseTaskBranchIdentity(branch);
4435
+ if (!ref)
4436
+ return { ok: true };
4437
+ if (ref.kind === "issue") {
4438
+ const expectedIssue = ref.issueNumber;
4439
+ if (!referenced.has(expectedIssue)) {
4440
+ return {
4441
+ ok: false,
4442
+ expectedIssue,
4443
+ message: `closes-n: PR body does not contain \`Closes #${expectedIssue}\` (required for branch "${branch}"). Add it to the PR body Summary section.`
4444
+ };
4452
4445
  }
4446
+ return { ok: true, expectedIssue };
4453
4447
  }
4454
- return { check: "G5", status: findings.length > 0 ? "fail" : "pass", findings };
4455
- }
4456
- var SHIPPED_BIN_PATH_PREFIX = "apps/cli/src/checks/bin/check-";
4457
- var AEG_CORE_BIN_PATH_PREFIX = "packages/aeg-core/bin/";
4458
- function basenameNoExt(path) {
4459
- const base = path.slice(path.lastIndexOf("/") + 1);
4460
- return base.replace(/\.ts$/, "");
4461
- }
4462
- function claimedCheckNames(implementation) {
4463
- if (implementation.startsWith(SHIPPED_BIN_PATH_PREFIX) && implementation.endsWith(".ts")) {
4464
- return [implementation.slice(SHIPPED_BIN_PATH_PREFIX.length, -".ts".length)];
4448
+ const trancheSlug = ref.tranche;
4449
+ const taskId = ref.taskId;
4450
+ const trancheFile = trancheFiles.find((f) => f.slug === trancheSlug);
4451
+ if (!trancheFile) {
4452
+ return {
4453
+ ok: false,
4454
+ 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.`
4455
+ };
4465
4456
  }
4466
- if (implementation.startsWith(AEG_CORE_BIN_PATH_PREFIX)) {
4467
- const audience = GATE_AUDIENCE[basenameNoExt(implementation)];
4468
- if (audience && isShipped(audience)) {
4469
- return Array.isArray(audience.shippedAs) ? audience.shippedAs : [audience.shippedAs];
4470
- }
4457
+ const task = trancheFile.tranche.tasks.find((t) => t.id === taskId);
4458
+ if (!task) {
4459
+ return {
4460
+ ok: false,
4461
+ message: `closes-n: branch "${branch}" references task "${taskId}" not found in ${trancheSlug} topology. Verify the task ID matches the tranche file.`
4462
+ };
4471
4463
  }
4472
- return [];
4464
+ if (task.issue === null) {
4465
+ return {
4466
+ ok: false,
4467
+ message: `closes-n: task "${taskId}" in "${trancheSlug}" has no Issue number (#TBD). The Planner must cut the Issue before this PR can be validated.`
4468
+ };
4469
+ }
4470
+ const expectedIssue = task.issue;
4471
+ if (!referenced.has(expectedIssue)) {
4472
+ return {
4473
+ ok: false,
4474
+ expectedIssue,
4475
+ 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.`
4476
+ };
4477
+ }
4478
+ return { ok: true, expectedIssue };
4473
4479
  }
4474
- function checkG6(rows, registeredCheckNames) {
4475
- const findings = [];
4476
- for (const row of rows) {
4477
- if (row.audience !== "product")
4478
- continue;
4479
- const candidates = claimedCheckNames(row.implementation);
4480
- if (!candidates.some((name) => registeredCheckNames.has(name))) {
4481
- findings.push({
4482
- row: row.action,
4483
- path: row.implementation,
4484
- reason: `${row.ring} row "${row.action}" is marked \`product\` but its implementation "${row.implementation}" does not resolve to a coreCheckRegistry() entry`
4485
- });
4486
- }
4480
+ // ../../packages/aeg-core/src/archive-task.ts
4481
+ function closesRefs(text) {
4482
+ return [...new Set([...text.matchAll(/Closes #(\d+)/gi)].map((m) => Number(m[1])))];
4483
+ }
4484
+ function extractIssue(body) {
4485
+ const stripped = stripCode(body);
4486
+ const bodyNums = closesRefs(stripped);
4487
+ const anchored = anchoredRegion(stripped, "CLOSES");
4488
+ if (anchored !== null) {
4489
+ const anchorNums = closesRefs(anchored);
4490
+ if (anchorNums.length === 0)
4491
+ return { issue: null, extraIssues: bodyNums, outsideHeader: false };
4492
+ const issue = anchorNums[0];
4493
+ return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: false };
4487
4494
  }
4488
- return { check: "G6", status: findings.length > 0 ? "fail" : "pass", findings };
4495
+ const headerNums = closesRefs(headerRegion(stripped));
4496
+ if (bodyNums.length === 0)
4497
+ return { issue: null, extraIssues: [], outsideHeader: false };
4498
+ const issue = headerNums.length > 0 ? headerNums[0] : bodyNums[0];
4499
+ return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: headerNums.length === 0 };
4489
4500
  }
4490
- // ../../packages/aeg-core/src/reader-resolvable-prose.ts
4491
- var PRODUCT_SLUG_SCOPE = [
4492
- "apps/cli/src",
4493
- ".github/workflows",
4494
- ".vinaya",
4495
- "apps/cli/README.md",
4496
- "packages/sources/README.md"
4497
- ];
4498
- function isUnderOrEqual(path, prefix) {
4499
- return path === prefix || path.startsWith(`${prefix}/`);
4501
+ // ../../packages/aeg-core/src/review-input-manifest.ts
4502
+ import { createHash as createHash4 } from "node:crypto";
4503
+ function briefHash(brief) {
4504
+ return createHash4("sha256").update(`${brief}
4505
+ `).digest("hex");
4500
4506
  }
4501
- function isProductScopeFile(path) {
4502
- return PRODUCT_SLUG_SCOPE.some((prefix) => isUnderOrEqual(path, prefix));
4507
+ function policyDigest(policy) {
4508
+ return createHash4("sha256").update(JSON.stringify({
4509
+ codeReviewThreshold: policy.codeReviewThreshold,
4510
+ securityThreshold: policy.securityThreshold,
4511
+ maxRounds: policy.maxRounds
4512
+ })).digest("hex");
4503
4513
  }
4504
- var SHIPS_PREFIX = "aeg-root/";
4505
- function shipsArchivePrefix(shipsPrefix) {
4506
- return `${shipsPrefix}tranches/completed/`;
4514
+ function isBoundToHead(echoed, headSha) {
4515
+ if (!echoed.headSha)
4516
+ return false;
4517
+ return headSha.toLowerCase().startsWith(echoed.headSha.toLowerCase());
4507
4518
  }
4508
- var DEFAULT_SPEC_PATHS = ["SPEC.md", "CONTEXT.md", "docs/adr"];
4509
- function normalizeSpecPath(entry) {
4510
- let out = entry.replace(/\\/g, "/");
4511
- while (out.startsWith("./"))
4512
- out = out.slice(2);
4513
- out = out.replace(/\/{2,}/g, "/");
4514
- while (out.endsWith("/"))
4515
- out = out.slice(0, -1);
4516
- return out;
4519
+ function isBoundByPatchIdentity(echoed, headSha, patchIdOf) {
4520
+ if (patchIdOf === undefined || !echoed.headSha)
4521
+ return false;
4522
+ const judged = patchIdOf(echoed.headSha);
4523
+ const current = patchIdOf(headSha);
4524
+ if (judged === null || current === null)
4525
+ return false;
4526
+ return judged === current;
4517
4527
  }
4518
- function isSpecFile2(path, specPaths) {
4519
- if (path.startsWith("apps/") && path.includes("/specs/") && path.endsWith(".md"))
4528
+ function isBoundToBase(echoed, currentBase) {
4529
+ if (currentBase === null)
4520
4530
  return true;
4521
- if (!path.endsWith(".md"))
4531
+ if (!echoed.baseSha)
4522
4532
  return false;
4523
- return specPaths.some((entry) => isUnderOrEqual(path, normalizeSpecPath(entry)));
4533
+ return currentBase.toLowerCase().startsWith(echoed.baseSha.toLowerCase());
4524
4534
  }
4525
- function isClaudeMdFile(path) {
4526
- return path === "CLAUDE.md" || path.endsWith("/CLAUDE.md");
4535
+ function isBoundToObjectives(echoed, currentVersion) {
4536
+ if (currentVersion === null)
4537
+ return true;
4538
+ return echoed.objectivesVersion === currentVersion;
4527
4539
  }
4528
- function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS) {
4529
- if (path.startsWith(shipsPrefix)) {
4530
- return path.startsWith(shipsArchivePrefix(shipsPrefix)) ? "internal" : "ships";
4540
+ function isBoundToRulings(echoed, currentOrdinal) {
4541
+ if (echoed.rulingOrdinal === null)
4542
+ return currentOrdinal === 0;
4543
+ return echoed.rulingOrdinal === currentOrdinal;
4544
+ }
4545
+ function isBoundToBriefHash(echoed, currentHash) {
4546
+ if (currentHash === null)
4547
+ return true;
4548
+ return echoed.briefHash === currentHash;
4549
+ }
4550
+ function isBoundToPolicy(echoed, currentDigest) {
4551
+ return echoed.policyDigest === currentDigest;
4552
+ }
4553
+ function compareManifest(echoed, current, patchIdOf) {
4554
+ const exactHead = isBoundToHead(echoed, current.headSha);
4555
+ const patchHead = exactHead ? false : isBoundByPatchIdentity(echoed, current.headSha, patchIdOf);
4556
+ const head = exactHead || patchHead;
4557
+ const echoedShaLen = echoed.baseSha?.length ?? 0;
4558
+ const currentShaLen = current.baseSha?.length ?? 0;
4559
+ const bothFullShas = echoedShaLen >= 40 && currentShaLen >= 40;
4560
+ const base = patchHead || exactHead && bothFullShas ? true : isBoundToBase(echoed, current.baseSha);
4561
+ const briefHashBound = isBoundToBriefHash(echoed, current.briefHash);
4562
+ const objectivesVersion = isBoundToObjectives(echoed, current.objectivesVersion);
4563
+ const rulingOrdinal = isBoundToRulings(echoed, current.rulingOrdinal);
4564
+ const policyDigestBound = isBoundToPolicy(echoed, current.policyDigest);
4565
+ return {
4566
+ bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && policyDigestBound,
4567
+ head,
4568
+ base,
4569
+ briefHash: briefHashBound,
4570
+ objectivesVersion,
4571
+ rulingOrdinal,
4572
+ policyDigest: policyDigestBound
4573
+ };
4574
+ }
4575
+
4576
+ // ../../packages/aeg-core/src/review-gate.ts
4577
+ function renderGateDeferred(deferred) {
4578
+ if (deferred.length === 0)
4579
+ return "";
4580
+ const items = deferred.map((d) => {
4581
+ const where = d.finding.location && d.finding.location.length > 0 ? d.finding.location : "(no location)";
4582
+ return `${d.finding.severity} ${where} (${DEFERRAL_REASON_TEXT[d.reason]})`;
4583
+ }).join("; ");
4584
+ return ` ${deferred.length} finding(s) deferred, not blocking this round: ${items}.`;
4585
+ }
4586
+ function checkReviewGate(input) {
4587
+ const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
4588
+ const waived = isWaiverLabelActorVerified({
4589
+ label: WAIVER_LABEL_REVIEW,
4590
+ labels: input.labels,
4591
+ labelActor: input.waiverLabelActor,
4592
+ principalAllowlist
4593
+ });
4594
+ if (waived) {
4595
+ return {
4596
+ verdict: "pass",
4597
+ reason: `\`${WAIVER_LABEL_REVIEW}\` label is actor-verified — review requirement waived for this PR.`,
4598
+ waived: true
4599
+ };
4531
4600
  }
4532
- if (path.startsWith(readerFacingPrefix) && path.endsWith(readerFacingSuffix)) {
4533
- return "reader-facing";
4601
+ const verified = input.comments.filter((c) => isPrincipal(c.author, principalAllowlist));
4602
+ const ignoredCount = input.comments.filter((c) => !isPrincipal(c.author, principalAllowlist) && c.body.includes("VERDICT")).length;
4603
+ const verifiedBodies = verified.map((c) => c.body);
4604
+ const codeReview = extractCodeReviewVerdict(verifiedBodies);
4605
+ const security = extractSecurityReviewVerdict(verifiedBodies);
4606
+ const policy = input.policy ?? DEFAULT_REVIEW_POLICY;
4607
+ let codeReviewPolicyEvaluation;
4608
+ let securityPolicyEvaluation;
4609
+ try {
4610
+ codeReviewPolicyEvaluation = evaluateCodeReview(consequentialFindings(codeReview.findingSeverities), policy, input.deferralContext);
4611
+ securityPolicyEvaluation = evaluateSecurityReview(consequentialFindings(security.findingSeverities), policy, input.deferralContext);
4612
+ } catch (err) {
4613
+ return {
4614
+ verdict: "fail",
4615
+ reason: `a verdict comment carries a finding severity this repository's policy does not recognize: ${err instanceof Error ? err.message : String(err)}`,
4616
+ waived: false
4617
+ };
4534
4618
  }
4535
- if (isClaudeMdFile(path))
4536
- return "internal";
4537
- if (isSpecFile2(path, specPaths))
4538
- return "spec";
4539
- if (isProductScopeFile(path))
4540
- return "product";
4541
- return null;
4542
- }
4543
- var SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
4544
- function stripNonProse(path, content) {
4545
- if (path.endsWith(".md")) {
4546
- return content.replace(/```.*?```/gs, (m) => m.replace(/[^\n]/g, "")).replace(/`[^`\n]*`/g, (m) => m.replace(/[^\n]/g, ""));
4619
+ const codeReviewTextClean = codeReview.value === "APPROVE";
4620
+ const securityTextClean = security.value === "PASS";
4621
+ const codeReviewPolicyClean = codeReviewPolicyEvaluation.outcome === "clean";
4622
+ const securityPolicyClean = securityPolicyEvaluation.outcome === "clean";
4623
+ const codeReviewClean = codeReviewTextClean && codeReviewPolicyClean;
4624
+ const securityClean = securityTextClean && securityPolicyClean;
4625
+ const currentManifest = {
4626
+ headSha: input.headSha,
4627
+ baseSha: input.baseSha ?? null,
4628
+ briefHash: input.briefHash ?? null,
4629
+ objectivesVersion: input.objectivesVersion,
4630
+ rulingOrdinal: input.rulingOrdinal,
4631
+ policyDigest: policyDigest(policy)
4632
+ };
4633
+ const codeReviewEchoed = {
4634
+ headSha: codeReview.headSha,
4635
+ baseSha: codeReview.baseSha,
4636
+ briefHash: codeReview.briefHash,
4637
+ objectivesVersion: codeReview.objectivesVersion,
4638
+ rulingOrdinal: codeReview.rulingOrdinal,
4639
+ policyDigest: codeReview.policyDigest
4640
+ };
4641
+ const securityEchoed = {
4642
+ headSha: security.headSha,
4643
+ baseSha: security.baseSha,
4644
+ briefHash: security.briefHash,
4645
+ objectivesVersion: security.objectivesVersion,
4646
+ rulingOrdinal: security.rulingOrdinal,
4647
+ policyDigest: security.policyDigest
4648
+ };
4649
+ const codeReviewBinding = compareManifest(codeReviewEchoed, currentManifest, input.patchIdOf);
4650
+ const securityBinding = compareManifest(securityEchoed, currentManifest, input.patchIdOf);
4651
+ const codeReviewBound = codeReviewBinding.head;
4652
+ const securityBound = securityBinding.head;
4653
+ const codeReviewObjectivesBound = codeReviewBinding.objectivesVersion;
4654
+ const securityObjectivesBound = securityBinding.objectivesVersion;
4655
+ const codeReviewRulingsBound = codeReviewBinding.rulingOrdinal;
4656
+ const securityRulingsBound = securityBinding.rulingOrdinal;
4657
+ const deferredNote = renderGateDeferred([
4658
+ ...codeReviewPolicyEvaluation.deferredFindings,
4659
+ ...securityPolicyEvaluation.deferredFindings
4660
+ ]);
4661
+ if (codeReviewClean && codeReviewBinding.bound && securityClean && securityBinding.bound) {
4662
+ return {
4663
+ verdict: "pass",
4664
+ reason: `code-reviewer verdict is a clean APPROVE and security-review verdict is a clean PASS, both covering head ${input.headSha}.${deferredNote}`,
4665
+ waived: false
4666
+ };
4547
4667
  }
4548
- if (path.endsWith(".tsx") || path.endsWith(".ts")) {
4549
- return content.replace(/\/\*.*?\*\//gs, (m) => m.replace(/[^\n]/g, "")).replace(/(^|[^:])\/\/[^\n]*/g, (m) => m.replace(/[^\n]/g, ""));
4668
+ const problems = [];
4669
+ if (!codeReviewTextClean) {
4670
+ problems.push(`code-reviewer verdict is not a clean APPROVE (found: ${codeReview.value})`);
4671
+ } else if (!codeReviewPolicyClean) {
4672
+ 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`);
4673
+ } else if (!codeReviewBound) {
4674
+ problems.push(`the newest code-review verdict covers ${codeReview.headSha ?? "no recorded commit"}, head is ${input.headSha}`);
4675
+ } else if (!codeReviewBinding.base) {
4676
+ 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)`);
4677
+ } else if (!codeReviewObjectivesBound) {
4678
+ problems.push(`the newest code-review verdict was cast against objectives version ${codeReview.objectivesVersion ?? "none"}, the Issue's list is now ${input.objectivesVersion}`);
4679
+ } else if (!codeReviewRulingsBound) {
4680
+ 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`);
4681
+ } else if (!codeReviewBinding.briefHash) {
4682
+ 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"}`);
4683
+ } else if (!codeReviewBinding.policyDigest) {
4684
+ 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}`);
4550
4685
  }
4551
- return content;
4552
- }
4553
- function stripNonProseForProduct(path, content) {
4554
- return path.endsWith(".md") ? stripNonProse(path, content) : content;
4555
- }
4556
- function lineAt(content, index) {
4557
- let line = 1;
4558
- for (let i = 0;i < index; i++) {
4559
- if (content.charCodeAt(i) === 10)
4560
- line++;
4686
+ if (!securityTextClean) {
4687
+ problems.push(`security-review verdict is not a clean PASS (found: ${security.value})`);
4688
+ } else if (!securityPolicyClean) {
4689
+ 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`);
4690
+ } else if (!securityBound) {
4691
+ problems.push(`the newest security-review verdict covers ${security.headSha ?? "no recorded commit"}, head is ${input.headSha}`);
4692
+ } else if (!securityBinding.base) {
4693
+ 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)`);
4694
+ } else if (!securityObjectivesBound) {
4695
+ problems.push(`the newest security-review verdict was cast against objectives version ${security.objectivesVersion ?? "none"}, the Issue's list is now ${input.objectivesVersion}`);
4696
+ } else if (!securityRulingsBound) {
4697
+ 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`);
4698
+ } else if (!securityBinding.briefHash) {
4699
+ 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"}`);
4700
+ } else if (!securityBinding.policyDigest) {
4701
+ 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}`);
4561
4702
  }
4562
- return line;
4563
- }
4564
- var FORGE_NUMBER_PATTERN = /#[0-9]{2,4}/g;
4565
- var TRANCHE_SLUG_VN_PATTERN = /[a-z][a-z-]+-v[0-9]/g;
4566
- var TASK_NUMBER_PATTERN = /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi;
4567
- function legacySlugPattern(legacySlugs) {
4568
- if (legacySlugs.length === 0)
4569
- return null;
4570
- const alternation = legacySlugs.map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
4571
- return new RegExp(`(^|[^a-zA-Z0-9\\n-])(${alternation})([^a-zA-Z0-9\\n-]|$)`, "g");
4703
+ const ignoredNote = ignoredCount > 0 ? ` ${ignoredCount} verdict-shaped comment(s) from authors outside the principal allowlist were ignored.` : "";
4704
+ return {
4705
+ verdict: "fail",
4706
+ 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}`,
4707
+ waived: false
4708
+ };
4572
4709
  }
4573
- function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4574
- const findings = [];
4575
- const legacyPattern = legacySlugPattern(legacySlugs);
4576
- const grandfathered = new Set(specGrandfather);
4577
- const patterns = [
4578
- { pattern: FORGE_NUMBER_PATTERN, what: "a forge number" },
4579
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug" },
4580
- ...legacyPattern ? [{ pattern: legacyPattern, what: "an internal tranche slug", group: 2 }] : []
4581
- ];
4582
- const productPatterns = [
4583
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug in product code" }
4584
- ];
4585
- const specPatterns = [
4586
- ...patterns,
4587
- { pattern: TASK_NUMBER_PATTERN, what: "a task number", group: 2 }
4588
- ];
4589
- for (const file of files) {
4590
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths);
4591
- if (!cls || cls === "internal")
4592
- continue;
4593
- if (cls !== "product" && cls !== "spec" && !SWEPT_CLASSES.has(cls))
4710
+ var CHANGESET_RELEASE_BRANCH = "changeset-release/main";
4711
+ var DEFAULT_RELEASE_ACTOR = "github-actions[bot]";
4712
+ function isChangesetsReleasePr(branch, author, expectedAuthor) {
4713
+ return branch === CHANGESET_RELEASE_BRANCH && author === expectedAuthor;
4714
+ }
4715
+ // ../../packages/aeg-core/src/ruling-ordinal.ts
4716
+ var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
4717
+ function newestPrincipalRulingOrdinal(comments, allowlist) {
4718
+ let best = 0;
4719
+ for (const c of comments) {
4720
+ if (!isPrincipal(c.author, allowlist))
4594
4721
  continue;
4595
- if (cls === "spec" && grandfathered.has(file.path))
4722
+ const firstLine = (c.body.split(`
4723
+ `)[0] ?? "").trim();
4724
+ const m = RULING_MARKER_ORDINAL.exec(firstLine);
4725
+ if (!m)
4596
4726
  continue;
4597
- const blocking = cls === "product" || cls === "spec";
4598
- const scrubbed = cls === "product" ? stripNonProseForProduct(file.path, file.content) : stripNonProse(file.path, file.content);
4599
- const patternsToRun = cls === "product" ? productPatterns : cls === "spec" ? specPatterns : patterns;
4600
- for (const { pattern, what, group } of patternsToRun) {
4601
- pattern.lastIndex = 0;
4602
- let match = pattern.exec(scrubbed);
4603
- while (match !== null) {
4604
- const cited = group !== undefined ? match[group] ?? match[0] : match[0];
4605
- const citedIndex = match.index + match[0].indexOf(cited);
4606
- findings.push({
4607
- file: file.path,
4608
- line: lineAt(scrubbed, citedIndex),
4609
- message: `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
4610
- blocking
4611
- });
4612
- match = pattern.exec(scrubbed);
4613
- }
4614
- }
4727
+ const k = Number.parseInt(m[1], 10);
4728
+ if (k > best)
4729
+ best = k;
4615
4730
  }
4616
- return findings;
4617
- }
4618
- function escapeTerm(term) {
4619
- return term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4731
+ return best;
4620
4732
  }
4621
- function containsWholeWord(text, term) {
4622
- const escaped = escapeTerm(term);
4623
- const re = new RegExp(`(^|[^a-zA-Z])${escaped}([^a-zA-Z]|$)`, "i");
4624
- return re.test(text);
4733
+ // ../../packages/aeg-core/src/markdown-table.ts
4734
+ function splitRow(line) {
4735
+ const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
4736
+ return trimmed.split("|").map((cell) => cell.trim());
4625
4737
  }
4626
- function findWholeWordLine(content, term) {
4627
- const lines = content.split(`
4628
- `);
4629
- let lineNo = 0;
4630
- for (const line of lines) {
4631
- lineNo++;
4632
- if (containsWholeWord(line, term))
4633
- return lineNo;
4738
+ var TABLE_ROW_PATTERN = /^\s*\|.*\|\s*$/;
4739
+ var SEPARATOR_ROW_PATTERN = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
4740
+ function findTable(lines, fromLine, stopAtHeading = true) {
4741
+ let i = fromLine - 1;
4742
+ while (i < lines.length) {
4743
+ const line = lines[i] ?? "";
4744
+ if (stopAtHeading && i > fromLine - 1 && /^##\s/.test(line))
4745
+ return null;
4746
+ if (TABLE_ROW_PATTERN.test(line)) {
4747
+ const headerLine = line;
4748
+ const sepLine = lines[i + 1] ?? "";
4749
+ if (!SEPARATOR_ROW_PATTERN.test(sepLine)) {
4750
+ i++;
4751
+ continue;
4752
+ }
4753
+ const headers = splitRow(headerLine);
4754
+ const rows = [];
4755
+ let j = i + 2;
4756
+ while (j < lines.length && TABLE_ROW_PATTERN.test(lines[j] ?? "")) {
4757
+ rows.push({ cells: splitRow(lines[j] ?? ""), line: j + 1 });
4758
+ j++;
4759
+ }
4760
+ return { headers, rows };
4761
+ }
4762
+ i++;
4634
4763
  }
4635
4764
  return null;
4636
4765
  }
4637
- function definesOrLinksGlossary(content, term) {
4638
- const escaped = escapeTerm(term);
4639
- const definesInline = new RegExp(`(^|[^a-zA-Z])${escaped}([^a-zA-Z]|$)[^\\n]{0,3}—`, "i").test(content);
4640
- if (definesInline)
4641
- return true;
4642
- return /docs\/glossary|glossary\.md/i.test(content);
4766
+ function findHeadingLine(lines, pattern) {
4767
+ for (let i = 0;i < lines.length; i++) {
4768
+ if (pattern.test(lines[i] ?? ""))
4769
+ return i + 1;
4770
+ }
4771
+ return null;
4643
4772
  }
4644
- function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX) {
4645
- const findings = [];
4646
- for (const file of files) {
4647
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
4648
- if (!cls || !SWEPT_CLASSES.has(cls))
4649
- continue;
4650
- const scrubbed = stripNonProse(file.path, file.content);
4651
- for (const term of glossaryTerms) {
4652
- const line = findWholeWordLine(scrubbed, term);
4653
- if (line === null)
4654
- continue;
4655
- if (definesOrLinksGlossary(scrubbed, term))
4656
- continue;
4657
- findings.push({
4658
- file: file.path,
4659
- line,
4660
- message: `uses coined term "${term}" without defining it inline or linking the glossary`,
4661
- blocking: false
4662
- });
4663
- }
4773
+ // ../../packages/aeg-core/src/diagram-model.ts
4774
+ import matter from "gray-matter";
4775
+
4776
+ // ../../packages/aeg-core/src/registry-parse.ts
4777
+ var RING_HEADINGS = [
4778
+ { ring: "ring0", pattern: /^##\s+Ring 0\b/ },
4779
+ { ring: "ring1", pattern: /^##\s+Ring 1\b/ },
4780
+ { ring: "ring2", pattern: /^##\s+Ring 2\b/ }
4781
+ ];
4782
+ function stripBackticks2(cell) {
4783
+ const trimmed = cell.trim();
4784
+ if (trimmed.length >= 2 && trimmed.startsWith("`") && trimmed.endsWith("`")) {
4785
+ return trimmed.slice(1, -1);
4664
4786
  }
4665
- return findings;
4787
+ return trimmed;
4666
4788
  }
4667
- var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g;
4668
- var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = /#[0-9]{2,}/g;
4669
- function extractComments(path, content) {
4670
- if (!path.endsWith(".ts") && !path.endsWith(".tsx"))
4671
- return content.replace(/[^\n]/g, "");
4672
- let state = "code";
4673
- let out = "";
4674
- const n = content.length;
4675
- let i = 0;
4676
- const blank = (ch) => ch === `
4677
- ` ? `
4678
- ` : " ";
4679
- while (i < n) {
4680
- const c = content[i];
4681
- const next = i + 1 < n ? content[i + 1] : "";
4682
- if (state === "code") {
4683
- if (c === "/" && next === "/") {
4684
- state = "line-comment";
4685
- out += c;
4686
- i++;
4687
- continue;
4688
- }
4689
- if (c === "/" && next === "*") {
4690
- state = "block-comment";
4691
- out += c;
4692
- i++;
4693
- continue;
4694
- }
4695
- if (c === "'") {
4696
- state = "single-quote";
4697
- out += blank(c);
4698
- i++;
4699
- continue;
4700
- }
4701
- if (c === '"') {
4702
- state = "double-quote";
4703
- out += blank(c);
4704
- i++;
4705
- continue;
4706
- }
4707
- if (c === "`") {
4708
- state = "template";
4709
- out += blank(c);
4710
- i++;
4711
- continue;
4712
- }
4713
- out += blank(c);
4714
- i++;
4789
+ function stripBold(cell) {
4790
+ return cell.trim().replace(/\*\*/g, "");
4791
+ }
4792
+ function parseEnforcementRegistry(content) {
4793
+ const lines = content.split(`
4794
+ `);
4795
+ const result = [];
4796
+ for (const { ring, pattern } of RING_HEADINGS) {
4797
+ const headingLine = findHeadingLine(lines, pattern);
4798
+ if (headingLine === null)
4715
4799
  continue;
4716
- }
4717
- if (state === "line-comment") {
4718
- if (c === `
4719
- `) {
4720
- state = "code";
4721
- out += `
4722
- `;
4723
- i++;
4724
- continue;
4725
- }
4726
- out += c;
4727
- i++;
4800
+ const table = findTable(lines, headingLine + 1);
4801
+ if (!table)
4728
4802
  continue;
4729
- }
4730
- if (state === "block-comment") {
4731
- if (c === "*" && next === "/") {
4732
- out += c;
4733
- out += next;
4734
- state = "code";
4735
- i += 2;
4803
+ const descriptionIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "description");
4804
+ const implementationIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "implementation");
4805
+ const audienceIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "audience");
4806
+ for (const row of table.rows) {
4807
+ const cells = row.cells;
4808
+ if (cells.length < 3)
4736
4809
  continue;
4737
- }
4738
- out += c === `
4739
- ` ? `
4740
- ` : c;
4741
- i++;
4742
- continue;
4743
- }
4744
- const closer = state === "single-quote" ? "'" : state === "double-quote" ? '"' : "`";
4745
- if (c === "\\") {
4746
- out += blank(c);
4747
- i++;
4748
- if (i < n) {
4749
- out += blank(content[i]);
4750
- i++;
4751
- }
4752
- continue;
4810
+ const action = stripBold(cells[0] ?? "");
4811
+ const summary = stripBackticks2(cells[1] ?? "");
4812
+ const category = stripBackticks2(cells[2] ?? "");
4813
+ const implementation = stripBackticks2((implementationIndex === -1 ? cells[cells.length - 1] : cells[implementationIndex]) ?? "");
4814
+ const description = descriptionIndex === -1 ? undefined : stripBackticks2(cells[descriptionIndex] ?? "") || undefined;
4815
+ const specIndex = (audienceIndex === -1 ? cells.length - 1 : audienceIndex) - 1;
4816
+ const spec = specIndex >= 3 ? stripBackticks2(cells[specIndex] ?? "") || undefined : undefined;
4817
+ const audience = audienceIndex === -1 ? "repo-own" : stripBackticks2(cells[audienceIndex] ?? "") === "product" ? "product" : "repo-own";
4818
+ result.push({ ring, action, summary, category, description, spec, implementation, audience, line: row.line });
4753
4819
  }
4754
- if (c === closer) {
4755
- state = "code";
4756
- out += blank(c);
4757
- i++;
4820
+ }
4821
+ return result;
4822
+ }
4823
+ // ../../packages/aeg-core/src/registry-checks.ts
4824
+ function checkG1(rows, existsFn) {
4825
+ const findings = [];
4826
+ for (const row of rows) {
4827
+ if (row.implementation === "")
4758
4828
  continue;
4829
+ if (!existsFn(row.implementation)) {
4830
+ findings.push({
4831
+ row: row.action,
4832
+ path: row.implementation,
4833
+ reason: `${row.ring} row "${row.action}" names implementation "${row.implementation}", which does not exist on disk`
4834
+ });
4759
4835
  }
4760
- out += blank(c);
4761
- i++;
4762
4836
  }
4763
- return out;
4837
+ return { check: "G1", status: findings.length > 0 ? "fail" : "pass", findings };
4764
4838
  }
4765
- function checkSourceComments(files, allowlist = []) {
4839
+ var SCAFFOLD_PLACEHOLDER = "[undocumented — fill in why]";
4840
+ var NON_GATE_BIN_NAMES = NON_GATE_BINS;
4841
+ var TWIN_CANDIDATE_EXCEPTIONS = {
4842
+ "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)',
4843
+ "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)`,
4844
+ "apps/cli/src/checks/bin/check-closes-n.ts": 'Ring 1 "Closes linkage" (implementation: verify-coherence.ts)'
4845
+ };
4846
+ var NON_GATE_HOOK_SCRIPTS = [".claude/hooks/track-transcript.sh"];
4847
+ function checkG2(rows, candidateFiles) {
4848
+ const implementations = new Set(rows.map((r) => r.implementation).filter((p) => p !== ""));
4849
+ const claimedNames = new Set(rows.flatMap((r) => claimedCheckNames(r.implementation)));
4766
4850
  const findings = [];
4767
- const allowed = new Set(allowlist);
4768
- const patterns = [
4769
- { pattern: SOURCE_COMMENT_TRANCHE_SLUG_PATTERN, what: "a tranche-slug citation" },
4770
- { pattern: SOURCE_COMMENT_FORGE_NUMBER_PATTERN, what: "a forge-number citation" }
4771
- ];
4772
- for (const file of files) {
4773
- if (!file.path.endsWith(".ts"))
4851
+ for (const path of candidateFiles) {
4852
+ if (implementations.has(path))
4774
4853
  continue;
4775
- if (allowed.has(file.path))
4854
+ if (path.startsWith(AEG_CORE_BIN_PATH_PREFIX) && NON_GATE_BIN_NAMES.includes(basenameNoExt(path)))
4776
4855
  continue;
4777
- const comments = extractComments(file.path, file.content);
4778
- for (const { pattern, what } of patterns) {
4779
- pattern.lastIndex = 0;
4780
- let match = pattern.exec(comments);
4781
- while (match !== null) {
4782
- findings.push({
4783
- file: file.path,
4784
- line: lineAt(comments, match.index),
4785
- message: `comment cites ${what} ("${match[0]}") a reader outside this repo's tracker cannot resolve`,
4786
- blocking: false
4787
- });
4788
- match = pattern.exec(comments);
4789
- }
4856
+ if (NON_GATE_HOOK_SCRIPTS.includes(path))
4857
+ continue;
4858
+ if (path in TWIN_CANDIDATE_EXCEPTIONS)
4859
+ continue;
4860
+ const candidateNames = claimedCheckNames(path);
4861
+ if (candidateNames.length > 0 && candidateNames.some((n) => claimedNames.has(n)))
4862
+ continue;
4863
+ findings.push({
4864
+ path,
4865
+ reason: `"${path}" is not named as the implementation of any row in enforcement.md's ring tables`
4866
+ });
4867
+ }
4868
+ for (const row of rows) {
4869
+ const carriesPlaceholder = [row.summary, row.description, row.spec].some((cell) => cell === SCAFFOLD_PLACEHOLDER);
4870
+ if (carriesPlaceholder) {
4871
+ findings.push({
4872
+ row: row.action,
4873
+ path: row.implementation,
4874
+ reason: `${row.ring} row "${row.action}" still carries the scaffold placeholder marker — the why is owed`
4875
+ });
4790
4876
  }
4791
4877
  }
4792
- return findings;
4793
- }
4794
- function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4795
- return [
4796
- ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths),
4797
- ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix)
4798
- ];
4878
+ return { check: "G2", status: findings.length > 0 ? "fail" : "pass", findings };
4799
4879
  }
4800
- function parseGlossaryTerms(glossaryContent) {
4801
- const terms = [];
4802
- const re = /^\*\*(.+?)\*\* —/gm;
4803
- let match = re.exec(glossaryContent);
4804
- while (match !== null) {
4805
- if (match[1] !== undefined)
4806
- terms.push(match[1]);
4807
- match = re.exec(glossaryContent);
4880
+ function checkG3(ring0Rows, crossingFiles) {
4881
+ const ring0Implementations = new Set(ring0Rows.map((r) => r.implementation));
4882
+ const findings = [];
4883
+ for (const path of crossingFiles) {
4884
+ if (!ring0Implementations.has(path)) {
4885
+ findings.push({
4886
+ path,
4887
+ reason: `"${path}" makes a GitHub-crossing call but is not named by any Ring-0 row's implementation — a seventh, unlisted way into GitHub`
4888
+ });
4889
+ }
4808
4890
  }
4809
- return terms;
4810
- }
4811
-
4812
- // ../../packages/aeg-core/src/quoted-command.ts
4813
- var QUOTED_COMMAND_SHIPS_PREFIX = "aeg-root/";
4814
- var QUOTED_COMMAND_SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
4815
- var START_PATTERN = /<!--\s*AEG:QUOTES-FILE:START:(\S+?)\s*-->/g;
4816
- var END_PATTERN = /<!--\s*AEG:QUOTES-FILE:END\s*-->/;
4817
- function isValidCitedFilePath(path) {
4818
- if (path.length === 0)
4819
- return false;
4820
- if (path.startsWith("/") || path.startsWith("\\"))
4821
- return false;
4822
- if (/^[A-Za-z]:[\\/]/.test(path))
4823
- return false;
4824
- return !path.split(/[\\/]+/).includes("..");
4891
+ return { check: "G3", status: findings.length > 0 ? "fail" : "pass", findings };
4825
4892
  }
4826
- function quotedCommandLineAt(content, index) {
4827
- let line = 1;
4828
- for (let i = 0;i < index; i++) {
4829
- if (content.charCodeAt(i) === 10)
4830
- line++;
4893
+ function checkG4(content, resolveFn) {
4894
+ const cited = new Set;
4895
+ for (const hit of content.matchAll(/#(\d{3,})\b/g)) {
4896
+ cited.add(Number(hit[1]));
4831
4897
  }
4832
- return line;
4833
- }
4834
- function extractQuotedText(raw) {
4835
- const trimmed = raw.trim();
4836
- const fenced = /^(?:`{3,}|~{3,})[^\n]*\n([\s\S]*?)\n?(?:`{3,}|~{3,})$/.exec(trimmed);
4837
- if (fenced)
4838
- return (fenced[1] ?? "").trim();
4839
- const inline = /^`([^`]+)`$/.exec(trimmed);
4840
- if (inline)
4841
- return (inline[1] ?? "").trim();
4842
- return trimmed;
4898
+ const findings = [];
4899
+ for (const n of cited) {
4900
+ if (!resolveFn(n)) {
4901
+ findings.push({
4902
+ reason: `#${n} is cited in enforcement.md but does not resolve to a real Issue or PR in the forge`
4903
+ });
4904
+ }
4905
+ }
4906
+ return { check: "G4", status: findings.length > 0 ? "fail" : "pass", findings };
4843
4907
  }
4844
- function findQuotesInFile(path, content) {
4845
- const masked = maskCode(content);
4846
- const quotes = [];
4847
- START_PATTERN.lastIndex = 0;
4848
- let start = START_PATTERN.exec(masked);
4849
- while (start !== null) {
4850
- const citedFile = start[1];
4851
- const innerStart = start.index + start[0].length;
4852
- const end = END_PATTERN.exec(masked.slice(innerStart));
4853
- if (end === null) {
4854
- START_PATTERN.lastIndex = innerStart;
4855
- start = START_PATTERN.exec(masked);
4856
- continue;
4908
+ function checkG5(roles, contracts) {
4909
+ const roleIds = new Set(roles.map((r) => r.role_id));
4910
+ const findings = [];
4911
+ for (const contract of contracts) {
4912
+ if (!roleIds.has(contract.producer)) {
4913
+ findings.push({
4914
+ path: contract.file,
4915
+ reason: `contract "${contract.file}" names producer "${contract.producer}", which is not a real role_id`
4916
+ });
4857
4917
  }
4858
- const innerEnd = innerStart + end.index;
4859
- if (isValidCitedFilePath(citedFile)) {
4860
- const quotedText = extractQuotedText(content.slice(innerStart, innerEnd));
4861
- if (quotedText.length > 0) {
4862
- quotes.push({ file: path, line: quotedCommandLineAt(content, innerStart), quotedText, citedFile });
4863
- }
4918
+ if (!roleIds.has(contract.consumer)) {
4919
+ findings.push({
4920
+ path: contract.file,
4921
+ reason: `contract "${contract.file}" names consumer "${contract.consumer}", which is not a real role_id`
4922
+ });
4864
4923
  }
4865
- START_PATTERN.lastIndex = innerEnd + end[0].length;
4866
- start = START_PATTERN.exec(masked);
4867
4924
  }
4868
- return quotes;
4925
+ for (const role of roles) {
4926
+ if (role.performs.length === 0) {
4927
+ findings.push({ path: role.file, reason: `role "${role.role_id}" has an empty performs array` });
4928
+ }
4929
+ if (role.refuses_when.trim() === "") {
4930
+ findings.push({ path: role.file, reason: `role "${role.role_id}" has an empty refuses_when` });
4931
+ }
4932
+ }
4933
+ return { check: "G5", status: findings.length > 0 ? "fail" : "pass", findings };
4869
4934
  }
4870
- function findCitedQuotes(files, readerFacingPrefix, readerFacingSuffix, shipsPrefix = QUOTED_COMMAND_SHIPS_PREFIX) {
4871
- const quotes = [];
4872
- for (const file of files) {
4873
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
4874
- if (!cls || !QUOTED_COMMAND_SWEPT_CLASSES.has(cls))
4875
- continue;
4876
- quotes.push(...findQuotesInFile(file.path, file.content));
4935
+ var SHIPPED_BIN_PATH_PREFIX = "apps/cli/src/checks/bin/check-";
4936
+ var AEG_CORE_BIN_PATH_PREFIX = "packages/aeg-core/bin/";
4937
+ function basenameNoExt(path) {
4938
+ const base = path.slice(path.lastIndexOf("/") + 1);
4939
+ return base.replace(/\.ts$/, "");
4940
+ }
4941
+ function claimedCheckNames(implementation) {
4942
+ if (implementation.startsWith(SHIPPED_BIN_PATH_PREFIX) && implementation.endsWith(".ts")) {
4943
+ return [implementation.slice(SHIPPED_BIN_PATH_PREFIX.length, -".ts".length)];
4877
4944
  }
4878
- return quotes;
4945
+ if (implementation.startsWith(AEG_CORE_BIN_PATH_PREFIX)) {
4946
+ const audience = GATE_AUDIENCE[basenameNoExt(implementation)];
4947
+ if (audience && isShipped(audience)) {
4948
+ return Array.isArray(audience.shippedAs) ? audience.shippedAs : [audience.shippedAs];
4949
+ }
4950
+ }
4951
+ return [];
4879
4952
  }
4880
- function evaluateCitedQuotes(citedQuotes, citedFileContents) {
4953
+ function checkG6(rows, registeredCheckNames) {
4881
4954
  const findings = [];
4882
- for (const quote of citedQuotes) {
4883
- const content = citedFileContents.get(quote.citedFile);
4884
- if (content === undefined) {
4885
- findings.push({
4886
- file: quote.file,
4887
- line: quote.line,
4888
- citedFile: quote.citedFile,
4889
- quotedText: quote.quotedText,
4890
- message: `${quote.file}:${quote.line} quotes "${quote.quotedText}" as citing \`${quote.citedFile}\`, but that file could not be read`
4891
- });
4955
+ for (const row of rows) {
4956
+ if (row.audience !== "product")
4892
4957
  continue;
4893
- }
4894
- if (!content.includes(quote.quotedText)) {
4958
+ const candidates = claimedCheckNames(row.implementation);
4959
+ if (!candidates.some((name) => registeredCheckNames.has(name))) {
4895
4960
  findings.push({
4896
- file: quote.file,
4897
- line: quote.line,
4898
- citedFile: quote.citedFile,
4899
- quotedText: quote.quotedText,
4900
- message: `${quote.file}:${quote.line} quotes "${quote.quotedText}" as citing \`${quote.citedFile}\`, but \`${quote.citedFile}\` no longer contains that text verbatim`
4961
+ row: row.action,
4962
+ path: row.implementation,
4963
+ reason: `${row.ring} row "${row.action}" is marked \`product\` but its implementation "${row.implementation}" does not resolve to a coreCheckRegistry() entry`
4901
4964
  });
4902
4965
  }
4903
4966
  }
4904
- return findings;
4967
+ return { check: "G6", status: findings.length > 0 ? "fail" : "pass", findings };
4905
4968
  }
4906
4969
  // ../../packages/aeg-core/src/dead-branch-push-guard.ts
4907
4970
  function checkDeadBranchPush(input) {
@@ -5808,7 +5871,9 @@ var DevReviewLoopEventSchema = z2.discriminatedUnion("event", [
5808
5871
  "escalated",
5809
5872
  "principal_stop",
5810
5873
  "confidence",
5811
- "reappearance"
5874
+ "reappearance",
5875
+ "repeat_finding",
5876
+ "repeat_failure"
5812
5877
  ])
5813
5878
  }).strict(),
5814
5879
  z2.object({
@@ -6312,6 +6377,10 @@ var LoopStateRecordSchema = z3.object({
6312
6377
  budgets: LoopBudgetsSchema,
6313
6378
  heldResult: roundHeadIdentity.nullable(),
6314
6379
  deliveredFindings: roundHeadIdentity.nullable(),
6380
+ repeatMemory: z3.object({
6381
+ blockingFindings: z3.array(z3.string()),
6382
+ lastFailure: z3.object({ signature: z3.string(), message: z3.string() }).nullable()
6383
+ }).strict().optional(),
6315
6384
  recordedAt: isoTimestamp
6316
6385
  }).strict();
6317
6386
  var EffectRecordSchema = z3.object({