@attalabs/vinaya 0.35.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 (118) hide show
  1. package/aeg-root/roles/planner/reference.md +20 -5
  2. package/aeg-root/roles/planner.md +2 -0
  3. package/aeg-root/roles/reviewer.md +3 -1
  4. package/aeg-root/templates/brief-template.md +4 -0
  5. package/dist/checks/bin/check-body-bare-digits.js +1447 -1350
  6. package/dist/checks/bin/check-branch-topology.js +1418 -1341
  7. package/dist/checks/bin/check-brief-shape.js +1448 -1351
  8. package/dist/checks/bin/check-changeset-coverage.js +1470 -1361
  9. package/dist/checks/bin/check-closes-n.js +1418 -1341
  10. package/dist/checks/bin/check-coherence.js +1459 -1352
  11. package/dist/checks/bin/check-dead-branch-push.js +1407 -1340
  12. package/dist/checks/bin/check-dispatch-readiness.js +1462 -1355
  13. package/dist/checks/bin/check-doc-coverage-push.js +1470 -1361
  14. package/dist/checks/bin/check-doc-coverage.js +1472 -1363
  15. package/dist/checks/bin/check-doctrine-no-procedures.js +1445 -1348
  16. package/dist/checks/bin/check-doctrine-portability.js +1470 -1361
  17. package/dist/checks/bin/check-evidence-fresh.js +1477 -1368
  18. package/dist/checks/bin/check-exec-bits.js +1471 -1362
  19. package/dist/checks/bin/check-first-push-dispatch.js +1461 -1354
  20. package/dist/checks/bin/check-issue-assignment.js +1418 -1341
  21. package/dist/checks/bin/check-issue-milestone-attach.js +1407 -1340
  22. package/dist/checks/bin/check-issue-objectives-numbering.js +1445 -1348
  23. package/dist/checks/bin/check-issue-parts-coverage.js +1407 -1340
  24. package/dist/checks/bin/check-issue-surface-globs.js +1461 -1354
  25. package/dist/checks/bin/check-issue-title-grammar.js +1407 -1340
  26. package/dist/checks/bin/check-issue-tranche-label.js +1407 -1340
  27. package/dist/checks/bin/check-main-branch-refusal.js +1409 -1342
  28. package/dist/checks/bin/check-no-disk-state.js +1409 -1342
  29. package/dist/checks/bin/check-pr-premise-reassert.js +1445 -1348
  30. package/dist/checks/bin/check-pr-report-density.js +1409 -1342
  31. package/dist/checks/bin/check-principal-test-plan-wait.js +1409 -1342
  32. package/dist/checks/bin/check-quoted-command.js +1468 -1359
  33. package/dist/checks/bin/check-reader-resolvable-prose.js +1468 -1359
  34. package/dist/checks/bin/check-registry-gates.js +1409 -1342
  35. package/dist/checks/bin/check-retired-vocabulary.js +1468 -1359
  36. package/dist/checks/bin/check-review-gate.js +1459 -1362
  37. package/dist/checks/bin/check-single-plan-pr.js +1407 -1340
  38. package/dist/checks/bin/check-surface-scope.js +1418 -1341
  39. package/dist/checks/bin/check-test-plan.js +1407 -1340
  40. package/dist/checks/bin/check-token-collection-wired.js +1409 -1342
  41. package/dist/checks/bin/check-token-report.js +1409 -1342
  42. package/dist/checks/bin/check-workspace-escape.js +1471 -1362
  43. package/dist/index.js +4029 -1880
  44. package/dist/lib/pre-push-cache-test-run.js +94 -14
  45. package/dist/lib/pre-push-select-tests.js +83 -15
  46. package/package.json +1 -1
  47. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/assess-round.ts +24 -2
  48. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/index.ts +1 -0
  49. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/render-summary.ts +33 -10
  50. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/types.ts +28 -0
  51. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/index.ts +1 -0
  52. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/issue-validation.ts +10 -0
  53. package/studio-standalone/apps/vinaya-studio/web/.next/BUILD_ID +1 -1
  54. package/studio-standalone/apps/vinaya-studio/web/.next/build-manifest.json +3 -3
  55. package/studio-standalone/apps/vinaya-studio/web/.next/prerender-manifest.json +3 -3
  56. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.html +1 -1
  57. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.rsc +1 -1
  58. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  59. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  60. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  61. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  62. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  63. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page/server-reference-manifest.json +2 -2
  64. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page.js.nft.json +1 -1
  65. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  66. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/api/coherence/route.js.nft.json +1 -1
  67. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page/server-reference-manifest.json +2 -2
  68. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page.js.nft.json +1 -1
  69. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page_client-reference-manifest.js +1 -1
  70. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page/server-reference-manifest.json +2 -2
  71. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page.js.nft.json +1 -1
  72. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page_client-reference-manifest.js +1 -1
  73. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page/server-reference-manifest.json +2 -2
  74. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page.js.nft.json +1 -1
  75. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page_client-reference-manifest.js +1 -1
  76. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page/server-reference-manifest.json +2 -2
  77. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page.js.nft.json +1 -1
  78. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page_client-reference-manifest.js +1 -1
  79. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page/server-reference-manifest.json +3 -3
  80. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page.js.nft.json +1 -1
  81. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page_client-reference-manifest.js +1 -1
  82. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page/server-reference-manifest.json +2 -2
  83. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page.js.nft.json +1 -1
  84. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page_client-reference-manifest.js +1 -1
  85. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page/server-reference-manifest.json +2 -2
  86. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page.js.nft.json +1 -1
  87. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page_client-reference-manifest.js +1 -1
  88. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page/server-reference-manifest.json +2 -2
  89. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page.js.nft.json +1 -1
  90. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page_client-reference-manifest.js +1 -1
  91. 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
  92. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__074w9nf._.js +1 -1
  93. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0ls23oh._.js +1 -1
  94. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1gjqmhq._.js +1 -1
  95. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1wc4-ip._.js +1 -1
  96. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{[root-of-the-server]__0zc_0gx._.js → [root-of-the-server]__1wy7w66._.js} +1 -1
  97. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_08onyya._.js +1 -1
  98. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_096f46i._.js +1 -1
  99. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0af2one._.js +1 -1
  100. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0e5tkdd._.js +1 -1
  101. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0kf2g72._.js +1 -1
  102. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0zf4d27._.js +1 -1
  103. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1-wo68i._.js +1 -1
  104. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1achbh9._.js +1 -1
  105. 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
  106. package/studio-standalone/apps/vinaya-studio/web/.next/server/middleware-build-manifest.js +3 -3
  107. package/studio-standalone/apps/vinaya-studio/web/.next/server/pages/500.html +1 -1
  108. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.js +1 -1
  109. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.json +4 -4
  110. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/00z3-ljjd1gj9.js +1 -0
  111. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{3goaig_rysc6p.js → 2o9l0b7eqbr57.js} +1 -1
  112. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{3ip5z3cf43bgo.js → 3lqjwjrcvq481.js} +1 -1
  113. package/studio-standalone/apps/vinaya-studio/web/package.json +2 -2
  114. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/3u9emqjwpd0t9.js +0 -1
  115. /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/vinaya/studio-standalone/_node_modules/@attalabs/{aeg-core → vinaya/studio-standalone/_node_modules/@attalabs/aeg-core}/bin/verify-coherence.ts +0 -0
  116. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{ca66rAHI_w9D7S7ceXDvR → z1fTSBP6ZlUjObzFIp-qq}/_buildManifest.js +0 -0
  117. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{ca66rAHI_w9D7S7ceXDvR → z1fTSBP6ZlUjObzFIp-qq}/_clientMiddlewareManifest.js +0 -0
  118. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{ca66rAHI_w9D7S7ceXDvR → 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,1513 +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
- if (g === "*")
3513
- return !p.includes("/");
3514
- return g === p || g.startsWith(`${p}/`) || p.startsWith(`${g}/`);
3494
+ function stripNonProseForProduct(path, content) {
3495
+ return path.endsWith(".md") ? stripNonProse(path, content) : content;
3515
3496
  }
3516
- function checkSurfaceGlobsResolve(body, resolvesToFile) {
3517
- const surface = parseIssueSurface(body);
3518
- if (!surface.ok)
3519
- return { status: "pass", errors: [] };
3520
- const errors = [];
3521
- for (const glob of surface.value.in) {
3522
- if (!resolvesToFile(glob)) {
3523
- 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.`);
3524
- }
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++;
3525
3502
  }
3526
- return { status: errors.length > 0 ? "fail" : "pass", errors };
3503
+ return line;
3527
3504
  }
3528
- function checkSurfaceScope(changedFiles, outGlobs) {
3529
- if (outGlobs.length === 0)
3530
- return { ok: true };
3531
- const violations = [];
3532
- for (const file of changedFiles) {
3533
- const glob = outGlobs.find((g) => globCoversPath(g, file));
3534
- if (glob)
3535
- violations.push({ file, glob });
3536
- }
3537
- 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");
3538
3513
  }
3539
- var ISSUE_PART_LINE_RE = /^Part\s+(\d+)\s*\(([^)]*)\)\s*[-—–]\s*(.*)$/i;
3540
- function parseIssueParts(body) {
3541
- const section = topLevelSectionText(body, "Parts");
3542
- if (section === null)
3543
- return { ok: false, errors: ["no `## Parts` heading found in the body."] };
3544
- const lines = section.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
3545
- const parts = [];
3546
- const errors = [];
3547
- for (const line of lines) {
3548
- const m = ISSUE_PART_LINE_RE.exec(line);
3549
- if (!m) {
3550
- 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")
3551
3533
  continue;
3552
- }
3553
- const n = Number.parseInt(m[1], 10);
3554
- const refs = m[2];
3555
- const text = m[3].trim();
3556
- if (text.length === 0) {
3557
- 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))
3558
3535
  continue;
3559
- }
3560
- if (partHasBacktickedPath(text) && partWordCount(stripPartBackticks(text)) < PART_MIN_WORDS_OUTSIDE_BACKTICKS) {
3561
- 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))
3562
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
+ }
3563
3555
  }
3564
- const objectiveIds = [...refs.matchAll(/O(\d+)/g)].map((r) => Number.parseInt(r[1], 10));
3565
- parts.push({ n, objectiveIds, text });
3566
3556
  }
3567
- if (parts.length === 0) {
3568
- errors.push("the `## Parts` section has no well-formed `Part <n> (<refs>) — <outcome>` lines.");
3569
- }
3570
- if (errors.length > 0)
3571
- return { ok: false, errors };
3572
- return { ok: true, value: parts };
3573
- }
3574
- function checkPartsCiteDefinedObjectives(body) {
3575
- const parts = parseIssueParts(body);
3576
- const objectives = objectivesOf(body);
3577
- if (!parts.ok || !objectives.ok)
3578
- return { status: "pass", errors: [] };
3579
- const definedIds = new Set(objectives.objectives.map((o) => Number.parseInt(o.id.slice(1), 10)));
3580
- const errors = [];
3581
- for (const part of parts.value) {
3582
- for (const objectiveId of part.objectiveIds) {
3583
- if (!definedIds.has(objectiveId)) {
3584
- errors.push(`issue-validation Parts: Part ${part.n} cites O${objectiveId}, which the Issue's own \`## Objectives\` section does not define.`);
3585
- }
3586
- }
3587
- }
3588
- return { status: errors.length > 0 ? "fail" : "pass", errors };
3589
- }
3590
- function isTaskIssueLabelSet(labels) {
3591
- return hasLabel("tranche", labels);
3592
- }
3593
- function checkTrancheLabelPresence(_body, _labels) {
3594
- return { status: "pass", errors: [] };
3595
- }
3596
- function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTitle) {
3597
- if (!isTaskIssueLabelSet(labels))
3598
- return { status: "pass", errors: [] };
3599
- if (resolvedMilestoneTitle === null)
3600
- return { status: "pass", errors: [] };
3601
- if (currentMilestoneTitle === resolvedMilestoneTitle)
3602
- return { status: "pass", errors: [] };
3603
- return {
3604
- status: "fail",
3605
- errors: [
3606
- `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}".`
3607
- ]
3608
- };
3609
- }
3610
- var TYPE_LABEL_IDS = LABELS.filter((l) => l.category === "type").map((l) => l.id);
3611
- function isControlCodePoint(codePoint) {
3612
- return codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
3613
- }
3614
- function isDisplayControlCodePoint(codePoint) {
3615
- return codePoint >= 8203 && codePoint <= 8207 || codePoint >= 8234 && codePoint <= 8238 || codePoint >= 8294 && codePoint <= 8297 || codePoint === 65279;
3557
+ return findings;
3616
3558
  }
3617
- var MESSAGE_VALUE_COUNT_MAX = 5;
3618
- function residueForMessage(values) {
3619
- const shown = values.slice(0, MESSAGE_VALUE_COUNT_MAX).map((v) => `\`${forMessage(v)}\``);
3620
- const rest = values.length - shown.length;
3621
- return rest > 0 ? `${shown.join(", ")} and ${rest} more` : shown.join(", ");
3559
+ function escapeTerm(term) {
3560
+ return term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3622
3561
  }
3623
- var MESSAGE_VALUE_MAX = 64;
3624
- function forMessage(value) {
3625
- const kept = [];
3626
- for (const ch of value.replace(/\s+/g, " ")) {
3627
- const codePoint = ch.codePointAt(0) ?? 0;
3628
- if (isControlCodePoint(codePoint) || isDisplayControlCodePoint(codePoint))
3629
- continue;
3630
- kept.push(ch);
3631
- }
3632
- const cleaned = kept.join("").trim();
3633
- if (cleaned.length === 0)
3634
- return "(unprintable)";
3635
- const points = Array.from(cleaned);
3636
- 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);
3637
3566
  }
3638
- function checkProjectsRegistered(body, _labels, registeredNames) {
3639
- if (registeredNames.length === 0)
3640
- return { status: "pass", errors: [] };
3641
- const field = projectFieldFromBody(body);
3642
- if (!field.declared)
3643
- return { status: "pass", errors: [] };
3644
- const known = new Set(registeredNames.map((n) => n.trim()));
3645
- const registeredList = [...registeredNames].map(forMessage).join(", ");
3646
- const errors = [];
3647
- if (field.unreadable) {
3648
- return {
3649
- status: "fail",
3650
- errors: [
3651
- `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.`
3652
- ]
3653
- };
3654
- }
3655
- const unregistered = field.names.filter((p) => !known.has(p));
3656
- if (unregistered.length > 0) {
3657
- const caseHints = unregistered.map((p) => {
3658
- const row = [...known].find((k) => k.toLowerCase() === p.toLowerCase());
3659
- return row ? `\`${forMessage(p)}\` differs from the registered \`${forMessage(row)}\` only in case` : null;
3660
- }).filter((h) => h !== null);
3661
- 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.`);
3662
- }
3663
- if (field.names.length === 0) {
3664
- const residue = field.unparsed.length > 0 ? ` — ${residueForMessage(field.unparsed)}` : " — the field is empty";
3665
- 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.`);
3666
- } else if (field.unparsed.length > 0) {
3667
- 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;
3668
3575
  }
3669
- return errors.length > 0 ? { status: "fail", errors } : { status: "pass", errors: [] };
3670
- }
3671
- 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;
3672
- var DOC_PATH_RE_GLOBAL = new RegExp(DOC_PATH_RE.source, "gi");
3673
-
3674
- // ../../packages/aeg-core/src/task-branch-identity.ts
3675
- var ISSUE_BRANCH_PATTERN = /^task\/issue-(\d+)$/;
3676
- var TRANCHE_BRANCH_PATTERN = /^task\/([^/]+)\/([^/]+)$/;
3677
- function parseTaskBranchIdentity(branch) {
3678
- const issueMatch = ISSUE_BRANCH_PATTERN.exec(branch);
3679
- if (issueMatch)
3680
- return { kind: "issue", issueNumber: Number(issueMatch[1]) };
3681
- const trancheMatch = TRANCHE_BRANCH_PATTERN.exec(branch);
3682
- if (trancheMatch)
3683
- return { kind: "tranche", tranche: trancheMatch[1], taskId: trancheMatch[2] };
3684
3576
  return null;
3685
3577
  }
3686
-
3687
- // ../../packages/aeg-core/src/coherence-checks.ts
3688
- var COHERENCE_ENFORCED_FROM = "2026-07-01";
3689
- function isGrandfathered(isoDate) {
3690
- if (!isoDate)
3691
- return false;
3692
- 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);
3693
3584
  }
3694
- var R1_GRANDFATHERED_ISSUES = new Set([279, 280, 281, 282]);
3695
- function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
3696
- const failures = [];
3697
- for (const e of entries) {
3698
- if (!e.facts)
3699
- continue;
3700
- 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))
3701
3590
  continue;
3702
- if (e.facts.issueState === "closed" && e.facts.prState !== "merged") {
3703
- const handClosed = e.facts.stateReason === "completed" && isPrincipal(e.facts.closedByActor, principalAllowlist);
3704
- 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)
3705
3595
  continue;
3706
- failures.push({
3707
- code: "closed-without-merge",
3708
- issue: e.task.issue,
3709
- tranche: e.trancheSlug,
3710
- task: e.task.id,
3711
- reason: `Issue closed but closing PR is not merged (prState: ${e.facts.prState})`,
3712
- 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
3713
3603
  });
3714
3604
  }
3715
3605
  }
3716
- const activeFails = failures.filter((f) => !f.grandfathered);
3717
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3718
- return {
3719
- check: "A1",
3720
- status,
3721
- failures,
3722
- note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
3723
- };
3606
+ return findings;
3724
3607
  }
3725
- function checkA3(entries) {
3726
- const failures = [];
3727
- for (const e of entries) {
3728
- 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++;
3729
3656
  continue;
3730
- if (e.facts.prState === "merged" && e.facts.issueState !== "closed") {
3731
- failures.push({
3732
- code: "auto-close-misfire",
3733
- issue: e.task.issue,
3734
- tranche: e.trancheSlug,
3735
- task: e.task.id,
3736
- reason: "Closing PR is merged but Issue is still open (GitHub auto-close misfire)",
3737
- grandfathered: isGrandfathered(e.facts.mergedAt)
3738
- });
3739
3657
  }
3740
- }
3741
- const activeFails = failures.filter((f) => !f.grandfathered);
3742
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3743
- return {
3744
- check: "A3",
3745
- status,
3746
- failures,
3747
- note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
3748
- };
3749
- }
3750
- function checkT1(entries) {
3751
- const failures = [];
3752
- for (const e of entries) {
3753
- if (e.task.issue === null)
3754
- continue;
3755
- if (e.facts === undefined) {
3756
- failures.push({
3757
- code: "phantom-issue-ref",
3758
- issue: e.task.issue,
3759
- tranche: e.trancheSlug,
3760
- task: e.task.id,
3761
- reason: `Issue #${e.task.issue} in topology does not resolve to a real GitHub Issue`
3762
- });
3763
- }
3764
- }
3765
- return { check: "T1", status: failures.length > 0 ? "fail" : "pass", failures };
3766
- }
3767
- function checkT2(openIssuesBySlug, topologyIssuesBySlug, ciTrancheSlug) {
3768
- const failures = [];
3769
- for (const [slug, openNums] of openIssuesBySlug) {
3770
- if (ciTrancheSlug && slug !== ciTrancheSlug)
3771
- continue;
3772
- const topologySet = topologyIssuesBySlug.get(slug) ?? new Set;
3773
- for (const num of openNums) {
3774
- if (!topologySet.has(num)) {
3775
- failures.push({
3776
- code: "orphan-task",
3777
- issue: num,
3778
- tranche: slug,
3779
- reason: `Issue #${num} is open and labeled ${trancheLabel(slug)} but does not appear in the topology file`
3780
- });
3658
+ if (state === "line-comment") {
3659
+ if (c === `
3660
+ `) {
3661
+ state = "code";
3662
+ out += `
3663
+ `;
3664
+ i++;
3665
+ continue;
3781
3666
  }
3667
+ out += c;
3668
+ i++;
3669
+ continue;
3782
3670
  }
3783
- }
3784
- return { check: "T2", status: failures.length > 0 ? "fail" : "pass", failures };
3785
- }
3786
- function scopeT2ToPlanPr(result, isPlanPr) {
3787
- if (isPlanPr || result.status !== "fail")
3788
- return result;
3789
- return {
3790
- ...result,
3791
- status: "info",
3792
- note: result.note ?? "T2 findings are non-blocking outside plan PRs (point-of-power principle) — see aeg-root/enforcement.md."
3793
- };
3794
- }
3795
- function checkT3(entries, ciTrancheSlug, enrichedEntries, forgeUnavailableSlugs) {
3796
- const preEnforcement = new Set;
3797
- if (enrichedEntries) {
3798
- for (const e of enrichedEntries) {
3799
- if (isGrandfathered(e.facts?.closedAt) || isGrandfathered(e.facts?.mergedAt)) {
3800
- 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;
3801
3678
  }
3679
+ out += c === `
3680
+ ` ? `
3681
+ ` : c;
3682
+ i++;
3683
+ continue;
3802
3684
  }
3803
- }
3804
- const failures = [];
3805
- for (const e of entries) {
3806
- if (!e.archived && e.task.issue === null) {
3807
- if (ciTrancheSlug && e.trancheSlug !== ciTrancheSlug)
3808
- continue;
3809
- if (forgeUnavailableSlugs?.has(e.trancheSlug)) {
3810
- failures.push({
3811
- code: "tbd-in-active-tranche",
3812
- issue: null,
3813
- tranche: e.trancheSlug,
3814
- task: e.task.id,
3815
- 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`,
3816
- grandfathered: true
3817
- });
3818
- 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++;
3819
3692
  }
3820
- failures.push({
3821
- code: "tbd-in-active-tranche",
3822
- issue: null,
3823
- tranche: e.trancheSlug,
3824
- task: e.task.id,
3825
- 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`,
3826
- grandfathered: preEnforcement.has(e.trancheSlug)
3827
- });
3693
+ continue;
3694
+ }
3695
+ if (c === closer) {
3696
+ state = "code";
3697
+ out += blank(c);
3698
+ i++;
3699
+ continue;
3828
3700
  }
3701
+ out += blank(c);
3702
+ i++;
3829
3703
  }
3830
- const activeFails = failures.filter((f) => !f.grandfathered);
3831
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3832
- return {
3833
- check: "T3",
3834
- status,
3835
- failures,
3836
- note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
3837
- };
3704
+ return out;
3838
3705
  }
3839
- function checkD1(entries, issueToEntry, taskToEntry) {
3840
- const failures = [];
3841
- for (const e of entries) {
3842
- 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"))
3843
3715
  continue;
3844
- if (e.facts.prState !== "open")
3716
+ if (allowed.has(file.path))
3845
3717
  continue;
3846
- for (const dep of e.task.dependsOn) {
3847
- const depEntry = resolveDepEntry(dep, e.trancheSlug, issueToEntry, taskToEntry);
3848
- if (!depEntry)
3849
- continue;
3850
- const sameTask = depEntry.trancheSlug === e.trancheSlug && depEntry.task.id === e.task.id;
3851
- const sameIssue = depEntry.task.issue !== null && e.task.issue !== null && depEntry.task.issue === e.task.issue;
3852
- if (sameTask || sameIssue) {
3853
- failures.push({
3854
- code: "d1-self-dependency",
3855
- issue: e.task.issue,
3856
- tranche: e.trancheSlug,
3857
- task: e.task.id,
3858
- reason: `INTERNAL: parsed a self-dependency (depends-on ${dep}) — this is a parser bug in parseRationaleDeps, not a real dependency. Please report it upstream.`
3859
- });
3860
- continue;
3861
- }
3862
- const depFacts = depEntry.facts;
3863
- const depClosed = depFacts?.issueState === "closed";
3864
- if (!depClosed) {
3865
- failures.push({
3866
- code: "dispatched-on-unmet-deps",
3867
- issue: e.task.issue,
3868
- tranche: e.trancheSlug,
3869
- task: e.task.id,
3870
- 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
3871
3728
  });
3729
+ match = pattern.exec(comments);
3872
3730
  }
3873
3731
  }
3874
3732
  }
3875
- return { check: "D1", status: failures.length > 0 ? "fail" : "pass", failures };
3733
+ return findings;
3876
3734
  }
3877
- function resolveDepEntry(dep, trancheSlug, issueToEntry, taskToEntry) {
3878
- const issueMatch = dep.match(/^#(\d+)$/);
3879
- if (issueMatch?.[1])
3880
- return issueToEntry.get(Number(issueMatch[1]));
3881
- 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
+ ];
3882
3740
  }
3883
- function checkR1(issuesBySlug, grandfatheredIssues, registeredNames = [], objectivesSinceIssue) {
3884
- const failures = [];
3885
- for (const [slug, issues] of issuesBySlug) {
3886
- for (const issue of issues) {
3887
- if (!isTaskIssueLabelSet(issue.labels))
3888
- continue;
3889
- const errors = [
3890
- ...checkIssueRationale(issue.body).errors,
3891
- ...checkProjectsRegistered(issue.body, issue.labels, registeredNames).errors,
3892
- ...checkIssueObjectives(issue.body, issue.number, objectivesSinceIssue).errors,
3893
- ...checkPartsCiteDefinedObjectives(issue.body).errors
3894
- ];
3895
- if (errors.length === 0)
3896
- continue;
3897
- failures.push({
3898
- code: "missing-rationale-field",
3899
- issue: issue.number,
3900
- tranche: slug,
3901
- reason: `Issue #${issue.number} fails the rationale gate: ${errors.join(" | ")}`,
3902
- grandfathered: grandfatheredIssues.has(issue.number)
3903
- });
3904
- }
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);
3905
3749
  }
3906
- const activeFails = failures.filter((f) => !f.grandfathered);
3907
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3908
- return {
3909
- check: "R1",
3910
- status,
3911
- failures,
3912
- note: status === "info" ? `${failures.length} grandfathered task Issue(s) predate this check's grammar (rationale fields and/or the project registry)` : undefined
3913
- };
3750
+ return terms;
3914
3751
  }
3915
- function checkL1(files, entriesBySlug) {
3916
- const failures = [];
3917
- for (const f of files) {
3918
- if (f.archived)
3919
- continue;
3920
- const entries = entriesBySlug.get(f.slug) ?? [];
3921
- const withFacts = entries.filter((e) => e.facts !== undefined);
3922
- if (withFacts.length === 0)
3923
- continue;
3924
- const allClosed = withFacts.every((e) => e.facts?.issueState === "closed");
3925
- if (allClosed) {
3926
- failures.push({
3927
- code: "archive-recommended",
3928
- tranche: f.slug,
3929
- reason: "Active tranche has no open task-Issues — consider archiving to completed/"
3930
- });
3931
- }
3932
- }
3933
- return {
3934
- check: "L1",
3935
- status: "info",
3936
- failures,
3937
- note: failures.length > 0 ? `${failures.length} active tranche(s) with no open task-Issues — consider archiving (advisory)` : undefined
3938
- };
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("..");
3939
3766
  }
3940
- function checkL3(files) {
3941
- const active = files.filter((f) => !f.archived);
3942
- return {
3943
- check: "L3",
3944
- status: "info",
3945
- failures: [],
3946
- note: `${active.length} active tranche(s): ${active.map((f) => f.slug).join(", ") || "(none)"}`
3947
- };
3948
- }
3949
- function extractClosesReferences(prBody) {
3950
- const closesPattern = /(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s{0,8}:?\s{0,8}#(\d+)/gi;
3951
- const stripped = stripCode(prBody);
3952
- const searchIn = anchoredRegion(stripped, "CLOSES") ?? stripped;
3953
- const referenced = new Set;
3954
- for (const hit of searchIn.matchAll(closesPattern)) {
3955
- 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++;
3956
3772
  }
3957
- return referenced;
3773
+ return line;
3958
3774
  }
3959
- function checkClosesNTopology(branch, prBody, trancheFiles, taskIssueRefs) {
3960
- const referenced = extractClosesReferences(prBody);
3961
- if (taskIssueRefs) {
3962
- for (const n of referenced) {
3963
- const ref = taskIssueRefs.get(n);
3964
- if (!ref)
3965
- continue;
3966
- const expectedBranch = `task/${ref.trancheSlug}/${ref.taskId}`;
3967
- if (branch !== expectedBranch) {
3968
- return {
3969
- ok: false,
3970
- 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.`
3971
- };
3972
- }
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;
3973
3798
  }
3974
- }
3975
- const ref = parseTaskBranchIdentity(branch);
3976
- if (!ref)
3977
- return { ok: true };
3978
- if (ref.kind === "issue") {
3979
- const expectedIssue = ref.issueNumber;
3980
- if (!referenced.has(expectedIssue)) {
3981
- return {
3982
- ok: false,
3983
- expectedIssue,
3984
- message: `closes-n: PR body does not contain \`Closes #${expectedIssue}\` (required for branch "${branch}"). Add it to the PR body Summary section.`
3985
- };
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
+ }
3986
3805
  }
3987
- return { ok: true, expectedIssue };
3988
- }
3989
- const trancheSlug = ref.tranche;
3990
- const taskId = ref.taskId;
3991
- const trancheFile = trancheFiles.find((f) => f.slug === trancheSlug);
3992
- if (!trancheFile) {
3993
- return {
3994
- ok: false,
3995
- 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.`
3996
- };
3997
- }
3998
- const task = trancheFile.tranche.tasks.find((t) => t.id === taskId);
3999
- if (!task) {
4000
- return {
4001
- ok: false,
4002
- message: `closes-n: branch "${branch}" references task "${taskId}" not found in ${trancheSlug} topology. Verify the task ID matches the tranche file.`
4003
- };
3806
+ START_PATTERN.lastIndex = innerEnd + end[0].length;
3807
+ start = START_PATTERN.exec(masked);
4004
3808
  }
4005
- if (task.issue === null) {
4006
- return {
4007
- ok: false,
4008
- message: `closes-n: task "${taskId}" in "${trancheSlug}" has no Issue number (#TBD). The Planner must cut the Issue before this PR can be validated.`
4009
- };
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));
4010
3818
  }
4011
- const expectedIssue = task.issue;
4012
- if (!referenced.has(expectedIssue)) {
4013
- return {
4014
- ok: false,
4015
- expectedIssue,
4016
- 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.`
4017
- };
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
+ }
4018
3844
  }
4019
- return { ok: true, expectedIssue };
3845
+ return findings;
4020
3846
  }
4021
- // ../../packages/aeg-core/src/archive-task.ts
4022
- function closesRefs(text) {
4023
- 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);
4024
3852
  }
4025
- function extractIssue(body) {
4026
- const stripped = stripCode(body);
4027
- const bodyNums = closesRefs(stripped);
4028
- const anchored = anchoredRegion(stripped, "CLOSES");
4029
- if (anchored !== null) {
4030
- const anchorNums = closesRefs(anchored);
4031
- if (anchorNums.length === 0)
4032
- return { issue: null, extraIssues: bodyNums, outsideHeader: false };
4033
- const issue = anchorNums[0];
4034
- 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
+ }
4035
3874
  }
4036
- const headerNums = closesRefs(headerRegion(stripped));
4037
- if (bodyNums.length === 0)
4038
- return { issue: null, extraIssues: [], outsideHeader: false };
4039
- const issue = headerNums.length > 0 ? headerNums[0] : bodyNums[0];
4040
- return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: headerNums.length === 0 };
3875
+ return { status: errors.length > 0 ? "fail" : "pass", errors };
4041
3876
  }
4042
- // ../../packages/aeg-core/src/review-input-manifest.ts
4043
- import { createHash as createHash4 } from "node:crypto";
4044
- function briefHash(brief) {
4045
- return createHash4("sha256").update(`${brief}
4046
- `).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}`) };
4047
3885
  }
4048
- function policyDigest(policy) {
4049
- return createHash4("sha256").update(JSON.stringify({
4050
- codeReviewThreshold: policy.codeReviewThreshold,
4051
- securityThreshold: policy.securityThreshold,
4052
- maxRounds: policy.maxRounds
4053
- })).digest("hex");
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;
4054
3894
  }
4055
- function isBoundToHead(echoed, headSha) {
4056
- if (!echoed.headSha)
4057
- return false;
4058
- return headSha.toLowerCase().startsWith(echoed.headSha.toLowerCase());
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;
4059
3909
  }
4060
- function isBoundByPatchIdentity(echoed, headSha, patchIdOf) {
4061
- if (patchIdOf === undefined || !echoed.headSha)
4062
- return false;
4063
- const judged = patchIdOf(echoed.headSha);
4064
- const current = patchIdOf(headSha);
4065
- if (judged === null || current === null)
4066
- return false;
4067
- return judged === current;
3910
+ var PART_MIN_WORDS_OUTSIDE_BACKTICKS = 3;
3911
+ function stripPartBackticks(text) {
3912
+ return text.replace(/`[^`\n]*`/g, " ");
4068
3913
  }
4069
- function isBoundToBase(echoed, currentBase) {
4070
- if (currentBase === null)
4071
- return true;
4072
- if (!echoed.baseSha)
4073
- return false;
4074
- return currentBase.toLowerCase().startsWith(echoed.baseSha.toLowerCase());
3914
+ function partWordCount(text) {
3915
+ return text.split(/\s+/).filter((w) => /[a-z]/i.test(w)).length;
4075
3916
  }
4076
- function isBoundToObjectives(echoed, currentVersion) {
4077
- if (currentVersion === null)
4078
- return true;
4079
- return echoed.objectivesVersion === currentVersion;
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;
4080
3922
  }
4081
- function isBoundToRulings(echoed, currentOrdinal) {
4082
- if (echoed.rulingOrdinal === null)
4083
- return currentOrdinal === 0;
4084
- return echoed.rulingOrdinal === currentOrdinal;
3923
+ function splitGlobList(raw) {
3924
+ return raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
4085
3925
  }
4086
- function isBoundToBriefHash(echoed, currentHash) {
4087
- if (currentHash === null)
4088
- return true;
4089
- return echoed.briefHash === currentHash;
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 } };
4090
3951
  }
4091
- function isBoundToPolicy(echoed, currentDigest) {
4092
- return echoed.policyDigest === currentDigest;
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}/`);
4093
3958
  }
4094
- function compareManifest(echoed, current, patchIdOf) {
4095
- const exactHead = isBoundToHead(echoed, current.headSha);
4096
- const patchHead = exactHead ? false : isBoundByPatchIdentity(echoed, current.headSha, patchIdOf);
4097
- const head = exactHead || patchHead;
4098
- const echoedShaLen = echoed.baseSha?.length ?? 0;
4099
- const currentShaLen = current.baseSha?.length ?? 0;
4100
- const bothFullShas = echoedShaLen >= 40 && currentShaLen >= 40;
4101
- const base = patchHead || exactHead && bothFullShas ? true : isBoundToBase(echoed, current.baseSha);
4102
- const briefHashBound = isBoundToBriefHash(echoed, current.briefHash);
4103
- const objectivesVersion = isBoundToObjectives(echoed, current.objectivesVersion);
4104
- const rulingOrdinal = isBoundToRulings(echoed, current.rulingOrdinal);
4105
- const policyDigestBound = isBoundToPolicy(echoed, current.policyDigest);
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: [] };
4106
4046
  return {
4107
- bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && policyDigestBound,
4108
- head,
4109
- base,
4110
- briefHash: briefHashBound,
4111
- objectivesVersion,
4112
- rulingOrdinal,
4113
- 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
+ ]
4114
4051
  };
4115
4052
  }
4116
-
4117
- // ../../packages/aeg-core/src/review-gate.ts
4118
- function checkReviewGate(input) {
4119
- const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
4120
- const waived = isWaiverLabelActorVerified({
4121
- label: WAIVER_LABEL_REVIEW,
4122
- labels: input.labels,
4123
- labelActor: input.waiverLabelActor,
4124
- principalAllowlist
4125
- });
4126
- if (waived) {
4127
- return {
4128
- verdict: "pass",
4129
- reason: `\`${WAIVER_LABEL_REVIEW}\` label is actor-verified — review requirement waived for this PR.`,
4130
- waived: true
4131
- };
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);
4132
4074
  }
4133
- const verified = input.comments.filter((c) => isPrincipal(c.author, principalAllowlist));
4134
- const ignoredCount = input.comments.filter((c) => !isPrincipal(c.author, principalAllowlist) && c.body.includes("VERDICT")).length;
4135
- const verifiedBodies = verified.map((c) => c.body);
4136
- const codeReview = extractCodeReviewVerdict(verifiedBodies);
4137
- const security = extractSecurityReviewVerdict(verifiedBodies);
4138
- const policy = input.policy ?? DEFAULT_REVIEW_POLICY;
4139
- let codeReviewPolicyEvaluation;
4140
- let securityPolicyEvaluation;
4141
- try {
4142
- codeReviewPolicyEvaluation = evaluateCodeReview(consequentialFindings(codeReview.findingSeverities), policy);
4143
- securityPolicyEvaluation = evaluateSecurityReview(consequentialFindings(security.findingSeverities), policy);
4144
- } 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) {
4145
4091
  return {
4146
- verdict: "fail",
4147
- reason: `a verdict comment carries a finding severity this repository's policy does not recognize: ${err instanceof Error ? err.message : String(err)}`,
4148
- 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
+ ]
4149
4096
  };
4150
4097
  }
4151
- const codeReviewTextClean = codeReview.value === "APPROVE";
4152
- const securityTextClean = security.value === "PASS";
4153
- const codeReviewPolicyClean = codeReviewPolicyEvaluation.outcome === "clean";
4154
- const securityPolicyClean = securityPolicyEvaluation.outcome === "clean";
4155
- const codeReviewClean = codeReviewTextClean && codeReviewPolicyClean;
4156
- const securityClean = securityTextClean && securityPolicyClean;
4157
- const currentManifest = {
4158
- headSha: input.headSha,
4159
- baseSha: input.baseSha ?? null,
4160
- briefHash: input.briefHash ?? null,
4161
- objectivesVersion: input.objectivesVersion,
4162
- rulingOrdinal: input.rulingOrdinal,
4163
- policyDigest: policyDigest(policy)
4164
- };
4165
- const codeReviewEchoed = {
4166
- headSha: codeReview.headSha,
4167
- baseSha: codeReview.baseSha,
4168
- briefHash: codeReview.briefHash,
4169
- objectivesVersion: codeReview.objectivesVersion,
4170
- rulingOrdinal: codeReview.rulingOrdinal,
4171
- policyDigest: codeReview.policyDigest
4172
- };
4173
- const securityEchoed = {
4174
- headSha: security.headSha,
4175
- baseSha: security.baseSha,
4176
- briefHash: security.briefHash,
4177
- objectivesVersion: security.objectivesVersion,
4178
- rulingOrdinal: security.rulingOrdinal,
4179
- policyDigest: security.policyDigest
4180
- };
4181
- const codeReviewBinding = compareManifest(codeReviewEchoed, currentManifest, input.patchIdOf);
4182
- const securityBinding = compareManifest(securityEchoed, currentManifest, input.patchIdOf);
4183
- const codeReviewBound = codeReviewBinding.head;
4184
- const securityBound = securityBinding.head;
4185
- const codeReviewObjectivesBound = codeReviewBinding.objectivesVersion;
4186
- const securityObjectivesBound = securityBinding.objectivesVersion;
4187
- const codeReviewRulingsBound = codeReviewBinding.rulingOrdinal;
4188
- const securityRulingsBound = securityBinding.rulingOrdinal;
4189
- if (codeReviewClean && codeReviewBinding.bound && securityClean && securityBinding.bound) {
4190
- return {
4191
- verdict: "pass",
4192
- reason: `code-reviewer verdict is a clean APPROVE and security-review verdict is a clean PASS, both covering head ${input.headSha}.`,
4193
- waived: false
4194
- };
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.`);
4195
4105
  }
4196
- const problems = [];
4197
- if (!codeReviewTextClean) {
4198
- problems.push(`code-reviewer verdict is not a clean APPROVE (found: ${codeReview.value})`);
4199
- } else if (!codeReviewPolicyClean) {
4200
- 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`);
4201
- } else if (!codeReviewBound) {
4202
- problems.push(`the newest code-review verdict covers ${codeReview.headSha ?? "no recorded commit"}, head is ${input.headSha}`);
4203
- } else if (!codeReviewBinding.base) {
4204
- 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)`);
4205
- } else if (!codeReviewObjectivesBound) {
4206
- problems.push(`the newest code-review verdict was cast against objectives version ${codeReview.objectivesVersion ?? "none"}, the Issue's list is now ${input.objectivesVersion}`);
4207
- } else if (!codeReviewRulingsBound) {
4208
- 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`);
4209
- } else if (!codeReviewBinding.briefHash) {
4210
- 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"}`);
4211
- } else if (!codeReviewBinding.policyDigest) {
4212
- 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.`);
4213
4111
  }
4214
- if (!securityTextClean) {
4215
- problems.push(`security-review verdict is not a clean PASS (found: ${security.value})`);
4216
- } else if (!securityPolicyClean) {
4217
- 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`);
4218
- } else if (!securityBound) {
4219
- problems.push(`the newest security-review verdict covers ${security.headSha ?? "no recorded commit"}, head is ${input.headSha}`);
4220
- } else if (!securityBinding.base) {
4221
- 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)`);
4222
- } else if (!securityObjectivesBound) {
4223
- problems.push(`the newest security-review verdict was cast against objectives version ${security.objectivesVersion ?? "none"}, the Issue's list is now ${input.objectivesVersion}`);
4224
- } else if (!securityRulingsBound) {
4225
- 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`);
4226
- } else if (!securityBinding.briefHash) {
4227
- 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"}`);
4228
- } else if (!securityBinding.policyDigest) {
4229
- 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
+ }
4230
4179
  }
4231
- 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";
4232
4182
  return {
4233
- verdict: "fail",
4234
- 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}`,
4235
- waived: false
4183
+ check: "A1",
4184
+ status,
4185
+ failures,
4186
+ note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
4236
4187
  };
4237
4188
  }
4238
- var CHANGESET_RELEASE_BRANCH = "changeset-release/main";
4239
- var DEFAULT_RELEASE_ACTOR = "github-actions[bot]";
4240
- function isChangesetsReleasePr(branch, author, expectedAuthor) {
4241
- return branch === CHANGESET_RELEASE_BRANCH && author === expectedAuthor;
4242
- }
4243
- // ../../packages/aeg-core/src/ruling-ordinal.ts
4244
- var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
4245
- function newestPrincipalRulingOrdinal(comments, allowlist) {
4246
- let best = 0;
4247
- for (const c of comments) {
4248
- if (!isPrincipal(c.author, allowlist))
4249
- continue;
4250
- const firstLine = (c.body.split(`
4251
- `)[0] ?? "").trim();
4252
- const m = RULING_MARKER_ORDINAL.exec(firstLine);
4253
- if (!m)
4189
+ function checkA3(entries) {
4190
+ const failures = [];
4191
+ for (const e of entries) {
4192
+ if (!e.facts)
4254
4193
  continue;
4255
- const k = Number.parseInt(m[1], 10);
4256
- if (k > best)
4257
- 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
+ }
4258
4204
  }
4259
- 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
+ };
4260
4213
  }
4261
- // ../../packages/aeg-core/src/markdown-table.ts
4262
- function splitRow(line) {
4263
- const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
4264
- 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 };
4265
4230
  }
4266
- var TABLE_ROW_PATTERN = /^\s*\|.*\|\s*$/;
4267
- var SEPARATOR_ROW_PATTERN = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
4268
- function findTable(lines, fromLine, stopAtHeading = true) {
4269
- let i = fromLine - 1;
4270
- while (i < lines.length) {
4271
- const line = lines[i] ?? "";
4272
- if (stopAtHeading && i > fromLine - 1 && /^##\s/.test(line))
4273
- return null;
4274
- if (TABLE_ROW_PATTERN.test(line)) {
4275
- const headerLine = line;
4276
- const sepLine = lines[i + 1] ?? "";
4277
- if (!SEPARATOR_ROW_PATTERN.test(sepLine)) {
4278
- i++;
4279
- continue;
4280
- }
4281
- const headers = splitRow(headerLine);
4282
- const rows = [];
4283
- let j = i + 2;
4284
- while (j < lines.length && TABLE_ROW_PATTERN.test(lines[j] ?? "")) {
4285
- rows.push({ cells: splitRow(lines[j] ?? ""), line: j + 1 });
4286
- 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
+ });
4287
4245
  }
4288
- return { headers, rows };
4289
4246
  }
4290
- i++;
4291
4247
  }
4292
- return null;
4248
+ return { check: "T2", status: failures.length > 0 ? "fail" : "pass", failures };
4293
4249
  }
4294
- function findHeadingLine(lines, pattern) {
4295
- for (let i = 0;i < lines.length; i++) {
4296
- if (pattern.test(lines[i] ?? ""))
4297
- return i + 1;
4298
- }
4299
- 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
+ };
4300
4258
  }
4301
- // ../../packages/aeg-core/src/diagram-model.ts
4302
- import matter from "gray-matter";
4303
-
4304
- // ../../packages/aeg-core/src/registry-parse.ts
4305
- var RING_HEADINGS = [
4306
- { ring: "ring0", pattern: /^##\s+Ring 0\b/ },
4307
- { ring: "ring1", pattern: /^##\s+Ring 1\b/ },
4308
- { ring: "ring2", pattern: /^##\s+Ring 2\b/ }
4309
- ];
4310
- function stripBackticks2(cell) {
4311
- const trimmed = cell.trim();
4312
- if (trimmed.length >= 2 && trimmed.startsWith("`") && trimmed.endsWith("`")) {
4313
- 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
+ }
4314
4267
  }
4315
- return trimmed;
4316
- }
4317
- function stripBold(cell) {
4318
- 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
+ };
4319
4302
  }
4320
- function parseEnforcementRegistry(content) {
4321
- const lines = content.split(`
4322
- `);
4323
- const result = [];
4324
- for (const { ring, pattern } of RING_HEADINGS) {
4325
- const headingLine = findHeadingLine(lines, pattern);
4326
- if (headingLine === null)
4303
+ function checkD1(entries, issueToEntry, taskToEntry) {
4304
+ const failures = [];
4305
+ for (const e of entries) {
4306
+ if (!e.facts)
4327
4307
  continue;
4328
- const table = findTable(lines, headingLine + 1);
4329
- if (!table)
4308
+ if (e.facts.prState !== "open")
4330
4309
  continue;
4331
- const descriptionIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "description");
4332
- const implementationIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "implementation");
4333
- const audienceIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "audience");
4334
- for (const row of table.rows) {
4335
- const cells = row.cells;
4336
- if (cells.length < 3)
4310
+ for (const dep of e.task.dependsOn) {
4311
+ const depEntry = resolveDepEntry(dep, e.trancheSlug, issueToEntry, taskToEntry);
4312
+ if (!depEntry)
4337
4313
  continue;
4338
- const action = stripBold(cells[0] ?? "");
4339
- const summary = stripBackticks2(cells[1] ?? "");
4340
- const category = stripBackticks2(cells[2] ?? "");
4341
- const implementation = stripBackticks2((implementationIndex === -1 ? cells[cells.length - 1] : cells[implementationIndex]) ?? "");
4342
- const description = descriptionIndex === -1 ? undefined : stripBackticks2(cells[descriptionIndex] ?? "") || undefined;
4343
- const specIndex = (audienceIndex === -1 ? cells.length - 1 : audienceIndex) - 1;
4344
- const spec = specIndex >= 3 ? stripBackticks2(cells[specIndex] ?? "") || undefined : undefined;
4345
- const audience = audienceIndex === -1 ? "repo-own" : stripBackticks2(cells[audienceIndex] ?? "") === "product" ? "product" : "repo-own";
4346
- 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
+ }
4347
4337
  }
4348
4338
  }
4349
- 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);
4350
4346
  }
4351
- // ../../packages/aeg-core/src/registry-checks.ts
4352
- function checkG1(rows, existsFn) {
4353
- const findings = [];
4354
- for (const row of rows) {
4355
- if (row.implementation === "")
4356
- continue;
4357
- if (!existsFn(row.implementation)) {
4358
- findings.push({
4359
- row: row.action,
4360
- path: row.implementation,
4361
- 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)
4362
4367
  });
4363
4368
  }
4364
4369
  }
4365
- 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
+ };
4366
4378
  }
4367
- var SCAFFOLD_PLACEHOLDER = "[undocumented — fill in why]";
4368
- var NON_GATE_BIN_NAMES = NON_GATE_BINS;
4369
- var TWIN_CANDIDATE_EXCEPTIONS = {
4370
- "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)',
4371
- "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)`,
4372
- "apps/cli/src/checks/bin/check-closes-n.ts": 'Ring 1 "Closes linkage" (implementation: verify-coherence.ts)'
4373
- };
4374
- var NON_GATE_HOOK_SCRIPTS = [".claude/hooks/track-transcript.sh"];
4375
- function checkG2(rows, candidateFiles) {
4376
- const implementations = new Set(rows.map((r) => r.implementation).filter((p) => p !== ""));
4377
- const claimedNames = new Set(rows.flatMap((r) => claimedCheckNames(r.implementation)));
4378
- const findings = [];
4379
- for (const path of candidateFiles) {
4380
- if (implementations.has(path))
4381
- continue;
4382
- if (path.startsWith(AEG_CORE_BIN_PATH_PREFIX) && NON_GATE_BIN_NAMES.includes(basenameNoExt(path)))
4383
- continue;
4384
- if (NON_GATE_HOOK_SCRIPTS.includes(path))
4385
- continue;
4386
- if (path in TWIN_CANDIDATE_EXCEPTIONS)
4379
+ function checkL1(files, entriesBySlug) {
4380
+ const failures = [];
4381
+ for (const f of files) {
4382
+ if (f.archived)
4387
4383
  continue;
4388
- const candidateNames = claimedCheckNames(path);
4389
- 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)
4390
4387
  continue;
4391
- findings.push({
4392
- path,
4393
- reason: `"${path}" is not named as the implementation of any row in enforcement.md's ring tables`
4394
- });
4395
- }
4396
- for (const row of rows) {
4397
- const carriesPlaceholder = [row.summary, row.description, row.spec].some((cell) => cell === SCAFFOLD_PLACEHOLDER);
4398
- if (carriesPlaceholder) {
4399
- findings.push({
4400
- row: row.action,
4401
- path: row.implementation,
4402
- 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/"
4403
4394
  });
4404
4395
  }
4405
4396
  }
4406
- 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
+ };
4407
4403
  }
4408
- function checkG3(ring0Rows, crossingFiles) {
4409
- const ring0Implementations = new Set(ring0Rows.map((r) => r.implementation));
4410
- const findings = [];
4411
- for (const path of crossingFiles) {
4412
- if (!ring0Implementations.has(path)) {
4413
- findings.push({
4414
- path,
4415
- reason: `"${path}" makes a GitHub-crossing call but is not named by any Ring-0 row's implementation — a seventh, unlisted way into GitHub`
4416
- });
4417
- }
4418
- }
4419
- 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
+ };
4420
4412
  }
4421
- function checkG4(content, resolveFn) {
4422
- const cited = new Set;
4423
- for (const hit of content.matchAll(/#(\d{3,})\b/g)) {
4424
- cited.add(Number(hit[1]));
4425
- }
4426
- const findings = [];
4427
- for (const n of cited) {
4428
- if (!resolveFn(n)) {
4429
- findings.push({
4430
- reason: `#${n} is cited in enforcement.md but does not resolve to a real Issue or PR in the forge`
4431
- });
4432
- }
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]));
4433
4420
  }
4434
- return { check: "G4", status: findings.length > 0 ? "fail" : "pass", findings };
4421
+ return referenced;
4435
4422
  }
4436
- function checkG5(roles, contracts) {
4437
- const roleIds = new Set(roles.map((r) => r.role_id));
4438
- const findings = [];
4439
- for (const contract of contracts) {
4440
- if (!roleIds.has(contract.producer)) {
4441
- findings.push({
4442
- path: contract.file,
4443
- reason: `contract "${contract.file}" names producer "${contract.producer}", which is not a real role_id`
4444
- });
4445
- }
4446
- if (!roleIds.has(contract.consumer)) {
4447
- findings.push({
4448
- path: contract.file,
4449
- reason: `contract "${contract.file}" names consumer "${contract.consumer}", which is not a real role_id`
4450
- });
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
+ }
4451
4437
  }
4452
4438
  }
4453
- for (const role of roles) {
4454
- if (role.performs.length === 0) {
4455
- findings.push({ path: role.file, reason: `role "${role.role_id}" has an empty performs array` });
4456
- }
4457
- if (role.refuses_when.trim() === "") {
4458
- 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
+ };
4459
4450
  }
4451
+ return { ok: true, expectedIssue };
4460
4452
  }
4461
- return { check: "G5", status: findings.length > 0 ? "fail" : "pass", findings };
4462
- }
4463
- var SHIPPED_BIN_PATH_PREFIX = "apps/cli/src/checks/bin/check-";
4464
- var AEG_CORE_BIN_PATH_PREFIX = "packages/aeg-core/bin/";
4465
- function basenameNoExt(path) {
4466
- const base = path.slice(path.lastIndexOf("/") + 1);
4467
- return base.replace(/\.ts$/, "");
4468
- }
4469
- function claimedCheckNames(implementation) {
4470
- if (implementation.startsWith(SHIPPED_BIN_PATH_PREFIX) && implementation.endsWith(".ts")) {
4471
- 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
+ };
4472
4461
  }
4473
- if (implementation.startsWith(AEG_CORE_BIN_PATH_PREFIX)) {
4474
- const audience = GATE_AUDIENCE[basenameNoExt(implementation)];
4475
- if (audience && isShipped(audience)) {
4476
- return Array.isArray(audience.shippedAs) ? audience.shippedAs : [audience.shippedAs];
4477
- }
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
+ };
4478
4468
  }
4479
- 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 };
4480
4484
  }
4481
- function checkG6(rows, registeredCheckNames) {
4482
- const findings = [];
4483
- for (const row of rows) {
4484
- if (row.audience !== "product")
4485
- continue;
4486
- const candidates = claimedCheckNames(row.implementation);
4487
- if (!candidates.some((name) => registeredCheckNames.has(name))) {
4488
- findings.push({
4489
- row: row.action,
4490
- path: row.implementation,
4491
- reason: `${row.ring} row "${row.action}" is marked \`product\` but its implementation "${row.implementation}" does not resolve to a coreCheckRegistry() entry`
4492
- });
4493
- }
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 };
4494
4499
  }
4495
- 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 };
4496
4505
  }
4497
- // ../../packages/aeg-core/src/reader-resolvable-prose.ts
4498
- var PRODUCT_SLUG_SCOPE = [
4499
- "apps/cli/src",
4500
- ".github/workflows",
4501
- ".vinaya",
4502
- "apps/cli/README.md",
4503
- "packages/sources/README.md"
4504
- ];
4505
- function isUnderOrEqual(path, prefix) {
4506
- 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");
4507
4511
  }
4508
- function isProductScopeFile(path) {
4509
- 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");
4510
4518
  }
4511
- var SHIPS_PREFIX = "aeg-root/";
4512
- function shipsArchivePrefix(shipsPrefix) {
4513
- return `${shipsPrefix}tranches/completed/`;
4519
+ function isBoundToHead(echoed, headSha) {
4520
+ if (!echoed.headSha)
4521
+ return false;
4522
+ return headSha.toLowerCase().startsWith(echoed.headSha.toLowerCase());
4514
4523
  }
4515
- var DEFAULT_SPEC_PATHS = ["SPEC.md", "CONTEXT.md", "docs/adr"];
4516
- function normalizeSpecPath(entry) {
4517
- let out = entry.replace(/\\/g, "/");
4518
- while (out.startsWith("./"))
4519
- out = out.slice(2);
4520
- out = out.replace(/\/{2,}/g, "/");
4521
- while (out.endsWith("/"))
4522
- out = out.slice(0, -1);
4523
- 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;
4524
4532
  }
4525
- function isSpecFile2(path, specPaths) {
4526
- if (path.startsWith("apps/") && path.includes("/specs/") && path.endsWith(".md"))
4533
+ function isBoundToBase(echoed, currentBase) {
4534
+ if (currentBase === null)
4527
4535
  return true;
4528
- if (!path.endsWith(".md"))
4536
+ if (!echoed.baseSha)
4529
4537
  return false;
4530
- return specPaths.some((entry) => isUnderOrEqual(path, normalizeSpecPath(entry)));
4538
+ return currentBase.toLowerCase().startsWith(echoed.baseSha.toLowerCase());
4531
4539
  }
4532
- function isClaudeMdFile(path) {
4533
- 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;
4534
4544
  }
4535
- function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS) {
4536
- if (path.startsWith(shipsPrefix)) {
4537
- 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
+ };
4538
4605
  }
4539
- if (path.startsWith(readerFacingPrefix) && path.endsWith(readerFacingSuffix)) {
4540
- 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
+ };
4541
4623
  }
4542
- if (isClaudeMdFile(path))
4543
- return "internal";
4544
- if (isSpecFile2(path, specPaths))
4545
- return "spec";
4546
- if (isProductScopeFile(path))
4547
- return "product";
4548
- return null;
4549
- }
4550
- var SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
4551
- function stripNonProse(path, content) {
4552
- if (path.endsWith(".md")) {
4553
- 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
+ };
4554
4672
  }
4555
- if (path.endsWith(".tsx") || path.endsWith(".ts")) {
4556
- 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}`);
4557
4690
  }
4558
- return content;
4559
- }
4560
- function stripNonProseForProduct(path, content) {
4561
- return path.endsWith(".md") ? stripNonProse(path, content) : content;
4562
- }
4563
- function lineAt(content, index) {
4564
- let line = 1;
4565
- for (let i = 0;i < index; i++) {
4566
- if (content.charCodeAt(i) === 10)
4567
- 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}`);
4568
4707
  }
4569
- return line;
4570
- }
4571
- var FORGE_NUMBER_PATTERN = /#[0-9]{2,4}/g;
4572
- var TRANCHE_SLUG_VN_PATTERN = /[a-z][a-z-]+-v[0-9]/g;
4573
- var TASK_NUMBER_PATTERN = /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi;
4574
- function legacySlugPattern(legacySlugs) {
4575
- if (legacySlugs.length === 0)
4576
- return null;
4577
- const alternation = legacySlugs.map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
4578
- 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
+ };
4579
4714
  }
4580
- function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4581
- const findings = [];
4582
- const legacyPattern = legacySlugPattern(legacySlugs);
4583
- const grandfathered = new Set(specGrandfather);
4584
- const patterns = [
4585
- { pattern: FORGE_NUMBER_PATTERN, what: "a forge number" },
4586
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug" },
4587
- ...legacyPattern ? [{ pattern: legacyPattern, what: "an internal tranche slug", group: 2 }] : []
4588
- ];
4589
- const productPatterns = [
4590
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug in product code" }
4591
- ];
4592
- const specPatterns = [
4593
- ...patterns,
4594
- { pattern: TASK_NUMBER_PATTERN, what: "a task number", group: 2 }
4595
- ];
4596
- for (const file of files) {
4597
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths);
4598
- if (!cls || cls === "internal")
4599
- continue;
4600
- 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))
4601
4726
  continue;
4602
- 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)
4603
4731
  continue;
4604
- const blocking = cls === "product" || cls === "spec";
4605
- const scrubbed = cls === "product" ? stripNonProseForProduct(file.path, file.content) : stripNonProse(file.path, file.content);
4606
- const patternsToRun = cls === "product" ? productPatterns : cls === "spec" ? specPatterns : patterns;
4607
- for (const { pattern, what, group } of patternsToRun) {
4608
- pattern.lastIndex = 0;
4609
- let match = pattern.exec(scrubbed);
4610
- while (match !== null) {
4611
- const cited = group !== undefined ? match[group] ?? match[0] : match[0];
4612
- const citedIndex = match.index + match[0].indexOf(cited);
4613
- findings.push({
4614
- file: file.path,
4615
- line: lineAt(scrubbed, citedIndex),
4616
- message: `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
4617
- blocking
4618
- });
4619
- match = pattern.exec(scrubbed);
4620
- }
4621
- }
4732
+ const k = Number.parseInt(m[1], 10);
4733
+ if (k > best)
4734
+ best = k;
4622
4735
  }
4623
- return findings;
4624
- }
4625
- function escapeTerm(term) {
4626
- return term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4736
+ return best;
4627
4737
  }
4628
- function containsWholeWord(text, term) {
4629
- const escaped = escapeTerm(term);
4630
- const re = new RegExp(`(^|[^a-zA-Z])${escaped}([^a-zA-Z]|$)`, "i");
4631
- 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());
4632
4742
  }
4633
- function findWholeWordLine(content, term) {
4634
- const lines = content.split(`
4635
- `);
4636
- let lineNo = 0;
4637
- for (const line of lines) {
4638
- lineNo++;
4639
- if (containsWholeWord(line, term))
4640
- 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++;
4641
4768
  }
4642
4769
  return null;
4643
4770
  }
4644
- function definesOrLinksGlossary(content, term) {
4645
- const escaped = escapeTerm(term);
4646
- const definesInline = new RegExp(`(^|[^a-zA-Z])${escaped}([^a-zA-Z]|$)[^\\n]{0,3}—`, "i").test(content);
4647
- if (definesInline)
4648
- return true;
4649
- 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;
4650
4777
  }
4651
- function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX) {
4652
- const findings = [];
4653
- for (const file of files) {
4654
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
4655
- if (!cls || !SWEPT_CLASSES.has(cls))
4656
- continue;
4657
- const scrubbed = stripNonProse(file.path, file.content);
4658
- for (const term of glossaryTerms) {
4659
- const line = findWholeWordLine(scrubbed, term);
4660
- if (line === null)
4661
- continue;
4662
- if (definesOrLinksGlossary(scrubbed, term))
4663
- continue;
4664
- findings.push({
4665
- file: file.path,
4666
- line,
4667
- message: `uses coined term "${term}" without defining it inline or linking the glossary`,
4668
- blocking: false
4669
- });
4670
- }
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);
4671
4791
  }
4672
- return findings;
4792
+ return trimmed;
4673
4793
  }
4674
- var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g;
4675
- var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = /#[0-9]{2,}/g;
4676
- function extractComments(path, content) {
4677
- if (!path.endsWith(".ts") && !path.endsWith(".tsx"))
4678
- return content.replace(/[^\n]/g, "");
4679
- let state = "code";
4680
- let out = "";
4681
- const n = content.length;
4682
- let i = 0;
4683
- const blank = (ch) => ch === `
4684
- ` ? `
4685
- ` : " ";
4686
- while (i < n) {
4687
- const c = content[i];
4688
- const next = i + 1 < n ? content[i + 1] : "";
4689
- if (state === "code") {
4690
- if (c === "/" && next === "/") {
4691
- state = "line-comment";
4692
- out += c;
4693
- i++;
4694
- continue;
4695
- }
4696
- if (c === "/" && next === "*") {
4697
- state = "block-comment";
4698
- out += c;
4699
- i++;
4700
- continue;
4701
- }
4702
- if (c === "'") {
4703
- state = "single-quote";
4704
- out += blank(c);
4705
- i++;
4706
- continue;
4707
- }
4708
- if (c === '"') {
4709
- state = "double-quote";
4710
- out += blank(c);
4711
- i++;
4712
- continue;
4713
- }
4714
- if (c === "`") {
4715
- state = "template";
4716
- out += blank(c);
4717
- i++;
4718
- continue;
4719
- }
4720
- out += blank(c);
4721
- 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)
4722
4804
  continue;
4723
- }
4724
- if (state === "line-comment") {
4725
- if (c === `
4726
- `) {
4727
- state = "code";
4728
- out += `
4729
- `;
4730
- i++;
4731
- continue;
4732
- }
4733
- out += c;
4734
- i++;
4805
+ const table = findTable(lines, headingLine + 1);
4806
+ if (!table)
4735
4807
  continue;
4736
- }
4737
- if (state === "block-comment") {
4738
- if (c === "*" && next === "/") {
4739
- out += c;
4740
- out += next;
4741
- state = "code";
4742
- 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)
4743
4814
  continue;
4744
- }
4745
- out += c === `
4746
- ` ? `
4747
- ` : c;
4748
- i++;
4749
- continue;
4750
- }
4751
- const closer = state === "single-quote" ? "'" : state === "double-quote" ? '"' : "`";
4752
- if (c === "\\") {
4753
- out += blank(c);
4754
- i++;
4755
- if (i < n) {
4756
- out += blank(content[i]);
4757
- i++;
4758
- }
4759
- 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 });
4760
4824
  }
4761
- if (c === closer) {
4762
- state = "code";
4763
- out += blank(c);
4764
- 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 === "")
4765
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
+ });
4766
4840
  }
4767
- out += blank(c);
4768
- i++;
4769
4841
  }
4770
- return out;
4842
+ return { check: "G1", status: findings.length > 0 ? "fail" : "pass", findings };
4771
4843
  }
4772
- 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)));
4773
4855
  const findings = [];
4774
- const allowed = new Set(allowlist);
4775
- const patterns = [
4776
- { pattern: SOURCE_COMMENT_TRANCHE_SLUG_PATTERN, what: "a tranche-slug citation" },
4777
- { pattern: SOURCE_COMMENT_FORGE_NUMBER_PATTERN, what: "a forge-number citation" }
4778
- ];
4779
- for (const file of files) {
4780
- if (!file.path.endsWith(".ts"))
4856
+ for (const path of candidateFiles) {
4857
+ if (implementations.has(path))
4781
4858
  continue;
4782
- if (allowed.has(file.path))
4859
+ if (path.startsWith(AEG_CORE_BIN_PATH_PREFIX) && NON_GATE_BIN_NAMES.includes(basenameNoExt(path)))
4783
4860
  continue;
4784
- const comments = extractComments(file.path, file.content);
4785
- for (const { pattern, what } of patterns) {
4786
- pattern.lastIndex = 0;
4787
- let match = pattern.exec(comments);
4788
- while (match !== null) {
4789
- findings.push({
4790
- file: file.path,
4791
- line: lineAt(comments, match.index),
4792
- message: `comment cites ${what} ("${match[0]}") a reader outside this repo's tracker cannot resolve`,
4793
- blocking: false
4794
- });
4795
- match = pattern.exec(comments);
4796
- }
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
+ });
4797
4881
  }
4798
4882
  }
4799
- return findings;
4800
- }
4801
- function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4802
- return [
4803
- ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths),
4804
- ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix)
4805
- ];
4883
+ return { check: "G2", status: findings.length > 0 ? "fail" : "pass", findings };
4806
4884
  }
4807
- function parseGlossaryTerms(glossaryContent) {
4808
- const terms = [];
4809
- const re = /^\*\*(.+?)\*\* —/gm;
4810
- let match = re.exec(glossaryContent);
4811
- while (match !== null) {
4812
- if (match[1] !== undefined)
4813
- terms.push(match[1]);
4814
- 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
+ }
4815
4895
  }
4816
- return terms;
4817
- }
4818
-
4819
- // ../../packages/aeg-core/src/quoted-command.ts
4820
- var QUOTED_COMMAND_SHIPS_PREFIX = "aeg-root/";
4821
- var QUOTED_COMMAND_SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
4822
- var START_PATTERN = /<!--\s*AEG:QUOTES-FILE:START:(\S+?)\s*-->/g;
4823
- var END_PATTERN = /<!--\s*AEG:QUOTES-FILE:END\s*-->/;
4824
- function isValidCitedFilePath(path) {
4825
- if (path.length === 0)
4826
- return false;
4827
- if (path.startsWith("/") || path.startsWith("\\"))
4828
- return false;
4829
- if (/^[A-Za-z]:[\\/]/.test(path))
4830
- return false;
4831
- return !path.split(/[\\/]+/).includes("..");
4896
+ return { check: "G3", status: findings.length > 0 ? "fail" : "pass", findings };
4832
4897
  }
4833
- function quotedCommandLineAt(content, index) {
4834
- let line = 1;
4835
- for (let i = 0;i < index; i++) {
4836
- if (content.charCodeAt(i) === 10)
4837
- 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]));
4838
4902
  }
4839
- return line;
4840
- }
4841
- function extractQuotedText(raw) {
4842
- const trimmed = raw.trim();
4843
- const fenced = /^(?:`{3,}|~{3,})[^\n]*\n([\s\S]*?)\n?(?:`{3,}|~{3,})$/.exec(trimmed);
4844
- if (fenced)
4845
- return (fenced[1] ?? "").trim();
4846
- const inline = /^`([^`]+)`$/.exec(trimmed);
4847
- if (inline)
4848
- return (inline[1] ?? "").trim();
4849
- 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 };
4850
4912
  }
4851
- function findQuotesInFile(path, content) {
4852
- const masked = maskCode(content);
4853
- const quotes = [];
4854
- START_PATTERN.lastIndex = 0;
4855
- let start = START_PATTERN.exec(masked);
4856
- while (start !== null) {
4857
- const citedFile = start[1];
4858
- const innerStart = start.index + start[0].length;
4859
- const end = END_PATTERN.exec(masked.slice(innerStart));
4860
- if (end === null) {
4861
- START_PATTERN.lastIndex = innerStart;
4862
- start = START_PATTERN.exec(masked);
4863
- 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
+ });
4864
4922
  }
4865
- const innerEnd = innerStart + end.index;
4866
- if (isValidCitedFilePath(citedFile)) {
4867
- const quotedText = extractQuotedText(content.slice(innerStart, innerEnd));
4868
- if (quotedText.length > 0) {
4869
- quotes.push({ file: path, line: quotedCommandLineAt(content, innerStart), quotedText, citedFile });
4870
- }
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
+ });
4871
4928
  }
4872
- START_PATTERN.lastIndex = innerEnd + end[0].length;
4873
- start = START_PATTERN.exec(masked);
4874
4929
  }
4875
- 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 };
4876
4939
  }
4877
- function findCitedQuotes(files, readerFacingPrefix, readerFacingSuffix, shipsPrefix = QUOTED_COMMAND_SHIPS_PREFIX) {
4878
- const quotes = [];
4879
- for (const file of files) {
4880
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
4881
- if (!cls || !QUOTED_COMMAND_SWEPT_CLASSES.has(cls))
4882
- continue;
4883
- 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)];
4884
4949
  }
4885
- 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 [];
4886
4957
  }
4887
- function evaluateCitedQuotes(citedQuotes, citedFileContents) {
4958
+ function checkG6(rows, registeredCheckNames) {
4888
4959
  const findings = [];
4889
- for (const quote of citedQuotes) {
4890
- const content = citedFileContents.get(quote.citedFile);
4891
- if (content === undefined) {
4892
- findings.push({
4893
- file: quote.file,
4894
- line: quote.line,
4895
- citedFile: quote.citedFile,
4896
- quotedText: quote.quotedText,
4897
- message: `${quote.file}:${quote.line} quotes "${quote.quotedText}" as citing \`${quote.citedFile}\`, but that file could not be read`
4898
- });
4960
+ for (const row of rows) {
4961
+ if (row.audience !== "product")
4899
4962
  continue;
4900
- }
4901
- if (!content.includes(quote.quotedText)) {
4963
+ const candidates = claimedCheckNames(row.implementation);
4964
+ if (!candidates.some((name) => registeredCheckNames.has(name))) {
4902
4965
  findings.push({
4903
- file: quote.file,
4904
- line: quote.line,
4905
- citedFile: quote.citedFile,
4906
- quotedText: quote.quotedText,
4907
- 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`
4908
4969
  });
4909
4970
  }
4910
4971
  }
4911
- return findings;
4972
+ return { check: "G6", status: findings.length > 0 ? "fail" : "pass", findings };
4912
4973
  }
4913
4974
  // ../../packages/aeg-core/src/dead-branch-push-guard.ts
4914
4975
  function checkDeadBranchPush(input) {
@@ -5815,7 +5876,9 @@ var DevReviewLoopEventSchema = z2.discriminatedUnion("event", [
5815
5876
  "escalated",
5816
5877
  "principal_stop",
5817
5878
  "confidence",
5818
- "reappearance"
5879
+ "reappearance",
5880
+ "repeat_finding",
5881
+ "repeat_failure"
5819
5882
  ])
5820
5883
  }).strict(),
5821
5884
  z2.object({
@@ -6319,6 +6382,10 @@ var LoopStateRecordSchema = z3.object({
6319
6382
  budgets: LoopBudgetsSchema,
6320
6383
  heldResult: roundHeadIdentity.nullable(),
6321
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(),
6322
6389
  recordedAt: isoTimestamp
6323
6390
  }).strict();
6324
6391
  var EffectRecordSchema = z3.object({