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