@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
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/checks/bin/check-evidence-fresh.ts
4
- import { execFileSync as execFileSync8 } from "node:child_process";
4
+ import { execFileSync as execFileSync9 } from "node:child_process";
5
5
  // ../../packages/aeg-core/src/gate-audience.ts
6
6
  var GATE_AUDIENCE = {
7
7
  "check-branch-topology": { shippedAs: "branch-topology", ring: 0 },
@@ -2465,16 +2465,42 @@ function blockingSeverities(scale, threshold) {
2465
2465
  }
2466
2466
  return scale.slice(0, idx + 1);
2467
2467
  }
2468
- function evaluateReviewFindings(findings, scale, threshold) {
2469
- const blocking = new Set(blockingSeverities(scale, threshold));
2470
- const blockingFindings = findings.filter((f) => {
2471
- if (!scale.includes(f.severity)) {
2472
- throw new Error(`evaluateReviewFindings: severity "${f.severity}" is not one of ${scale.join(" > ")}`);
2473
- }
2474
- const effectiveSeverity = f.location !== undefined && isProseLocation(f.location) ? PROSE_CAP_SEVERITY : f.severity;
2475
- return blocking.has(effectiveSeverity);
2476
- });
2477
- return { outcome: blockingFindings.length > 0 ? "blocked" : "clean", blockingFindings };
2468
+ var DEFERRAL_REASON_TEXT = {
2469
+ "unchanged-line": "unchanged line",
2470
+ "outside-surface": "outside the Surface"
2471
+ };
2472
+ var SECURITY_HIGH_AND_ABOVE = blockingSeverities(SECURITY_SEVERITY_ORDER, "HIGH");
2473
+ function classifyFinding(finding, scale, threshold, context = {}) {
2474
+ if (!scale.includes(finding.severity)) {
2475
+ throw new Error(`classifyFinding: severity "${finding.severity}" is not one of ${scale.join(" > ")}`);
2476
+ }
2477
+ const location = finding.location;
2478
+ const effectiveSeverity = location !== undefined && isProseLocation(location) ? PROSE_CAP_SEVERITY : finding.severity;
2479
+ const wouldBlock = blockingSeverities(scale, threshold).includes(effectiveSeverity);
2480
+ if (!wouldBlock)
2481
+ return { outcome: "non_blocking", deferralReason: null };
2482
+ const hasLocation = location !== undefined && location.length > 0;
2483
+ if (hasLocation && context.inSurface && !context.inSurface(location)) {
2484
+ return { outcome: "deferred", deferralReason: "outside-surface" };
2485
+ }
2486
+ if (hasLocation && context.changedLine && !SECURITY_HIGH_AND_ABOVE.includes(effectiveSeverity)) {
2487
+ if (!context.changedLine(location)) {
2488
+ return { outcome: "deferred", deferralReason: "unchanged-line" };
2489
+ }
2490
+ }
2491
+ return { outcome: "blocking", deferralReason: null };
2492
+ }
2493
+ function evaluateReviewFindings(findings, scale, threshold, context = {}) {
2494
+ const blockingFindings = [];
2495
+ const deferredFindings = [];
2496
+ for (const f of findings) {
2497
+ const c = classifyFinding(f, scale, threshold, context);
2498
+ if (c.outcome === "blocking")
2499
+ blockingFindings.push(f);
2500
+ else if (c.outcome === "deferred")
2501
+ deferredFindings.push({ finding: f, reason: c.deferralReason });
2502
+ }
2503
+ return { outcome: blockingFindings.length > 0 ? "blocked" : "clean", blockingFindings, deferredFindings };
2478
2504
  }
2479
2505
  function isConsequentialFinding(finding) {
2480
2506
  return finding.state !== "resolved";
@@ -2482,11 +2508,11 @@ function isConsequentialFinding(finding) {
2482
2508
  function consequentialFindings(findings) {
2483
2509
  return findings.filter((f) => isConsequentialFinding(f));
2484
2510
  }
2485
- function evaluateCodeReview(findings, policy) {
2486
- return evaluateReviewFindings(findings, CODE_REVIEW_SEVERITY_ORDER, policy.codeReviewThreshold);
2511
+ function evaluateCodeReview(findings, policy, context = {}) {
2512
+ return evaluateReviewFindings(findings, CODE_REVIEW_SEVERITY_ORDER, policy.codeReviewThreshold, context);
2487
2513
  }
2488
- function evaluateSecurityReview(findings, policy) {
2489
- return evaluateReviewFindings(findings, SECURITY_SEVERITY_ORDER, policy.securityThreshold);
2514
+ function evaluateSecurityReview(findings, policy, context = {}) {
2515
+ return evaluateReviewFindings(findings, SECURITY_SEVERITY_ORDER, policy.securityThreshold, context);
2490
2516
  }
2491
2517
  function isKnownSeverity(scale, value) {
2492
2518
  return scale.includes(value);
@@ -3400,1513 +3426,1548 @@ function checkPrReportDensity(prBody) {
3400
3426
  const results = [checkDecisionsDensity(prBody), checkScopeDensity(prBody)];
3401
3427
  return { errors: results.flatMap((r) => r.errors) };
3402
3428
  }
3403
- // ../../packages/aeg-core/src/issue-validation.ts
3404
- function hasRationaleField(body, labelPattern) {
3405
- const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})`, "im");
3406
- return re.test(body);
3407
- }
3408
- var RATIONALE_FIELDS = [
3409
- { name: "Boundary", pattern: "Boundary" },
3410
- { name: "Sizing", pattern: "Sizing" },
3411
- { name: "Project(s) + blast radius", pattern: "Project\\(s\\)|Project(?:s)?\\s*\\+|blast radius" },
3412
- { name: "Dependency rationale", pattern: "Dependency rationale|Depends[- ]on" },
3413
- { name: "Traps to avoid", pattern: "Traps" },
3414
- { name: "Suggested agent-class", pattern: "(?:Suggested\\s+)?agent-class" },
3415
- { name: "Stop-and-escalate", pattern: "Stop-and-escalate" },
3416
- { name: "Docs to keep coherent", pattern: "Docs to keep coherent|§7" }
3429
+ // ../../packages/aeg-core/src/reader-resolvable-prose.ts
3430
+ var PRODUCT_SLUG_SCOPE = [
3431
+ "apps/cli/src",
3432
+ ".github/workflows",
3433
+ ".vinaya",
3434
+ "apps/cli/README.md",
3435
+ "packages/sources/README.md"
3417
3436
  ];
3418
- var DEPENDENCY_RATIONALE_FIELD_NAME = "Dependency rationale";
3419
- function checkIssueRationale(body) {
3420
- const errors = [];
3421
- for (const f of RATIONALE_FIELDS) {
3422
- if (!hasRationaleField(body, f.pattern)) {
3423
- 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).`);
3424
- continue;
3425
- }
3426
- if (f.name === DEPENDENCY_RATIONALE_FIELD_NAME && !SECTION_HEADER.test(body)) {
3427
- 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.");
3428
- }
3429
- }
3430
- return { status: errors.length > 0 ? "fail" : "pass", errors };
3431
- }
3432
- var OBJECTIVES_SINCE_ISSUE = 404;
3433
- function checkIssueObjectives(body, issueNumber, sinceIssue = OBJECTIVES_SINCE_ISSUE) {
3434
- if (sinceIssue !== null && issueNumber !== null && issueNumber < sinceIssue)
3435
- return { status: "pass", errors: [] };
3436
- const result = objectivesOf(body);
3437
- if (result.ok)
3438
- return { status: "pass", errors: [] };
3439
- return { status: "fail", errors: result.errors.map((e) => `issue-validation objectives: ${e}`) };
3437
+ function isUnderOrEqual(path, prefix) {
3438
+ return path === prefix || path.startsWith(`${prefix}/`);
3440
3439
  }
3441
- function topLevelSectionText(body, headingName) {
3442
- const headingRe = new RegExp(`^##[ \\t]*${headingName}[ \\t]*$`, "im");
3443
- const heading = headingRe.exec(body);
3444
- if (!heading)
3445
- return null;
3446
- const afterHeading = body.slice(heading.index + heading[0].length);
3447
- const next = /^##[ \t]/m.exec(afterHeading);
3448
- return next ? afterHeading.slice(0, next.index) : afterHeading;
3440
+ function isProductScopeFile(path) {
3441
+ return PRODUCT_SLUG_SCOPE.some((prefix) => isUnderOrEqual(path, prefix));
3449
3442
  }
3450
- function partHasBacktickedPath(text) {
3451
- let i = 0;
3452
- while (i < text.length) {
3453
- const start = text.indexOf("`", i);
3454
- if (start === -1)
3455
- return false;
3456
- const end = text.indexOf("`", start + 1);
3457
- if (end === -1)
3458
- return false;
3459
- if (text.slice(start + 1, end).includes("/"))
3460
- return true;
3461
- i = end + 1;
3462
- }
3463
- return false;
3443
+ var SHIPS_PREFIX = "aeg-root/";
3444
+ function shipsArchivePrefix(shipsPrefix) {
3445
+ return `${shipsPrefix}tranches/completed/`;
3464
3446
  }
3465
- var PART_MIN_WORDS_OUTSIDE_BACKTICKS = 3;
3466
- function stripPartBackticks(text) {
3467
- return text.replace(/`[^`\n]*`/g, " ");
3447
+ var DEFAULT_SPEC_PATHS = ["SPEC.md", "CONTEXT.md", "docs/adr"];
3448
+ function normalizeSpecPath(entry) {
3449
+ let out = entry.replace(/\\/g, "/");
3450
+ while (out.startsWith("./"))
3451
+ out = out.slice(2);
3452
+ out = out.replace(/\/{2,}/g, "/");
3453
+ while (out.endsWith("/"))
3454
+ out = out.slice(0, -1);
3455
+ return out;
3468
3456
  }
3469
- function partWordCount(text) {
3470
- return text.split(/\s+/).filter((w) => /[a-z]/i.test(w)).length;
3457
+ function isSpecFile2(path, specPaths) {
3458
+ if (path.startsWith("apps/") && path.includes("/specs/") && path.endsWith(".md"))
3459
+ return true;
3460
+ if (!path.endsWith(".md"))
3461
+ return false;
3462
+ return specPaths.some((entry) => isUnderOrEqual(path, normalizeSpecPath(entry)));
3471
3463
  }
3472
- function looksLikeFilePath(entry) {
3473
- const stripped = entry.replace(/\/\*\*?$/, "");
3474
- const lastSegment = stripped.split("/").pop() ?? stripped;
3475
- const extMatch = /\.[A-Za-z0-9]{1,6}$/.exec(lastSegment);
3476
- return extMatch !== null && extMatch.index > 0;
3464
+ function isClaudeMdFile(path) {
3465
+ return path === "CLAUDE.md" || path.endsWith("/CLAUDE.md");
3477
3466
  }
3478
- function splitGlobList(raw) {
3479
- return raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
3467
+ function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS) {
3468
+ if (path.startsWith(shipsPrefix)) {
3469
+ return path.startsWith(shipsArchivePrefix(shipsPrefix)) ? "internal" : "ships";
3470
+ }
3471
+ if (path.startsWith(readerFacingPrefix) && path.endsWith(readerFacingSuffix)) {
3472
+ return "reader-facing";
3473
+ }
3474
+ if (isClaudeMdFile(path))
3475
+ return "internal";
3476
+ if (isSpecFile2(path, specPaths))
3477
+ return "spec";
3478
+ if (isProductScopeFile(path))
3479
+ return "product";
3480
+ return null;
3480
3481
  }
3481
- function parseIssueSurface(body) {
3482
- const section = topLevelSectionText(body, "Surface");
3483
- if (section === null)
3484
- return { ok: false, errors: ["no `## Surface` heading found in the body."] };
3485
- const inLine = /^in:\s*(.+)$/im.exec(section);
3486
- const outLine = /^out:\s*(.+)$/im.exec(section);
3487
- const errors = [];
3488
- if (!inLine)
3489
- errors.push("`## Surface` has no `in:` line.");
3490
- if (!outLine)
3491
- errors.push("`## Surface` has no `out:` line.");
3492
- if (errors.length > 0)
3493
- return { ok: false, errors };
3494
- const inGlobs = splitGlobList(inLine[1]);
3495
- const outGlobs = splitGlobList(outLine[1]);
3496
- for (const g of [...inGlobs, ...outGlobs]) {
3497
- if (looksLikeFilePath(g)) {
3498
- errors.push(`\`${g}\` in \`## Surface\` looks like a file path — Surface entries are directory-level globs, never file paths.`);
3499
- }
3482
+ var SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
3483
+ function stripNonProse(path, content) {
3484
+ if (path.endsWith(".md")) {
3485
+ return content.replace(/```.*?```/gs, (m) => m.replace(/[^\n]/g, "")).replace(/`[^`\n]*`/g, (m) => m.replace(/[^\n]/g, ""));
3500
3486
  }
3501
- if (inGlobs.length === 0)
3502
- errors.push("`## Surface`'s `in:` line resolved to zero globs.");
3503
- if (errors.length > 0)
3504
- return { ok: false, errors };
3505
- return { ok: true, value: { in: inGlobs, out: outGlobs } };
3487
+ if (path.endsWith(".tsx") || path.endsWith(".ts")) {
3488
+ return content.replace(/\/\*.*?\*\//gs, (m) => m.replace(/[^\n]/g, "")).replace(/(^|[^:])\/\/[^\n]*/g, (m) => m.replace(/[^\n]/g, ""));
3489
+ }
3490
+ return content;
3506
3491
  }
3507
- function globCoversPath(glob, path) {
3508
- const g = glob.replace(/\/\*\*?$/, "").replace(/\/+$/, "");
3509
- const p = path.replace(/\/+$/, "");
3510
- if (g === "*")
3511
- return !p.includes("/");
3512
- return g === p || g.startsWith(`${p}/`) || p.startsWith(`${g}/`);
3492
+ function stripNonProseForProduct(path, content) {
3493
+ return path.endsWith(".md") ? stripNonProse(path, content) : content;
3513
3494
  }
3514
- function checkSurfaceGlobsResolve(body, resolvesToFile) {
3515
- const surface = parseIssueSurface(body);
3516
- if (!surface.ok)
3517
- return { status: "pass", errors: [] };
3518
- const errors = [];
3519
- for (const glob of surface.value.in) {
3520
- if (!resolvesToFile(glob)) {
3521
- errors.push(`issue-validation Surface: \`${glob}\` in \`## Surface\`'s \`in:\` list matches no tracked file — a Surface that cannot resolve cannot render a brief's file list.`);
3522
- }
3495
+ function lineAt(content, index) {
3496
+ let line = 1;
3497
+ for (let i = 0;i < index; i++) {
3498
+ if (content.charCodeAt(i) === 10)
3499
+ line++;
3523
3500
  }
3524
- return { status: errors.length > 0 ? "fail" : "pass", errors };
3501
+ return line;
3525
3502
  }
3526
- function checkSurfaceScope(changedFiles, outGlobs) {
3527
- if (outGlobs.length === 0)
3528
- return { ok: true };
3529
- const violations = [];
3530
- for (const file of changedFiles) {
3531
- const glob = outGlobs.find((g) => globCoversPath(g, file));
3532
- if (glob)
3533
- violations.push({ file, glob });
3534
- }
3535
- return violations.length > 0 ? { ok: false, violations } : { ok: true };
3503
+ var FORGE_NUMBER_PATTERN = /#[0-9]{2,4}/g;
3504
+ var TRANCHE_SLUG_VN_PATTERN = /[a-z][a-z-]+-v[0-9]/g;
3505
+ var TASK_NUMBER_PATTERN = /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi;
3506
+ function legacySlugPattern(legacySlugs) {
3507
+ if (legacySlugs.length === 0)
3508
+ return null;
3509
+ const alternation = legacySlugs.map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
3510
+ return new RegExp(`(^|[^a-zA-Z0-9\\n-])(${alternation})([^a-zA-Z0-9\\n-]|$)`, "g");
3536
3511
  }
3537
- var ISSUE_PART_LINE_RE = /^Part\s+(\d+)\s*\(([^)]*)\)\s*[-—–]\s*(.*)$/i;
3538
- function parseIssueParts(body) {
3539
- const section = topLevelSectionText(body, "Parts");
3540
- if (section === null)
3541
- return { ok: false, errors: ["no `## Parts` heading found in the body."] };
3542
- const lines = section.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
3543
- const parts = [];
3544
- const errors = [];
3545
- for (const line of lines) {
3546
- const m = ISSUE_PART_LINE_RE.exec(line);
3547
- if (!m) {
3548
- errors.push(`"${line}" is not a well-formed Parts line — expected \`Part <n> (<refs>) — <outcome>\`.`);
3512
+ function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
3513
+ const findings = [];
3514
+ const legacyPattern = legacySlugPattern(legacySlugs);
3515
+ const grandfathered = new Set(specGrandfather);
3516
+ const patterns = [
3517
+ { pattern: FORGE_NUMBER_PATTERN, what: "a forge number" },
3518
+ { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug" },
3519
+ ...legacyPattern ? [{ pattern: legacyPattern, what: "an internal tranche slug", group: 2 }] : []
3520
+ ];
3521
+ const productPatterns = [
3522
+ { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug in product code" }
3523
+ ];
3524
+ const specPatterns = [
3525
+ ...patterns,
3526
+ { pattern: TASK_NUMBER_PATTERN, what: "a task number", group: 2 }
3527
+ ];
3528
+ for (const file of files) {
3529
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths);
3530
+ if (!cls || cls === "internal")
3549
3531
  continue;
3550
- }
3551
- const n = Number.parseInt(m[1], 10);
3552
- const refs = m[2];
3553
- const text = m[3].trim();
3554
- if (text.length === 0) {
3555
- errors.push(`Part ${n} has no outcome text after the dash — every Part states one observable outcome.`);
3532
+ if (cls !== "product" && cls !== "spec" && !SWEPT_CLASSES.has(cls))
3556
3533
  continue;
3557
- }
3558
- if (partHasBacktickedPath(text) && partWordCount(stripPartBackticks(text)) < PART_MIN_WORDS_OUTSIDE_BACKTICKS) {
3559
- errors.push(`Part ${n} is little more than a file path — a Part names an outcome and symbols, never a bare path.`);
3534
+ if (cls === "spec" && grandfathered.has(file.path))
3560
3535
  continue;
3536
+ const blocking = cls === "product" || cls === "spec";
3537
+ const scrubbed = cls === "product" ? stripNonProseForProduct(file.path, file.content) : stripNonProse(file.path, file.content);
3538
+ const patternsToRun = cls === "product" ? productPatterns : cls === "spec" ? specPatterns : patterns;
3539
+ for (const { pattern, what, group } of patternsToRun) {
3540
+ pattern.lastIndex = 0;
3541
+ let match = pattern.exec(scrubbed);
3542
+ while (match !== null) {
3543
+ const cited = group !== undefined ? match[group] ?? match[0] : match[0];
3544
+ const citedIndex = match.index + match[0].indexOf(cited);
3545
+ findings.push({
3546
+ file: file.path,
3547
+ line: lineAt(scrubbed, citedIndex),
3548
+ message: `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
3549
+ blocking
3550
+ });
3551
+ match = pattern.exec(scrubbed);
3552
+ }
3561
3553
  }
3562
- const objectiveIds = [...refs.matchAll(/O(\d+)/g)].map((r) => Number.parseInt(r[1], 10));
3563
- parts.push({ n, objectiveIds, text });
3564
3554
  }
3565
- if (parts.length === 0) {
3566
- errors.push("the `## Parts` section has no well-formed `Part <n> (<refs>) — <outcome>` lines.");
3567
- }
3568
- if (errors.length > 0)
3569
- return { ok: false, errors };
3570
- return { ok: true, value: parts };
3571
- }
3572
- function checkPartsCiteDefinedObjectives(body) {
3573
- const parts = parseIssueParts(body);
3574
- const objectives = objectivesOf(body);
3575
- if (!parts.ok || !objectives.ok)
3576
- return { status: "pass", errors: [] };
3577
- const definedIds = new Set(objectives.objectives.map((o) => Number.parseInt(o.id.slice(1), 10)));
3578
- const errors = [];
3579
- for (const part of parts.value) {
3580
- for (const objectiveId of part.objectiveIds) {
3581
- if (!definedIds.has(objectiveId)) {
3582
- errors.push(`issue-validation Parts: Part ${part.n} cites O${objectiveId}, which the Issue's own \`## Objectives\` section does not define.`);
3583
- }
3584
- }
3585
- }
3586
- return { status: errors.length > 0 ? "fail" : "pass", errors };
3587
- }
3588
- function isTaskIssueLabelSet(labels) {
3589
- return hasLabel("tranche", labels);
3590
- }
3591
- function checkTrancheLabelPresence(_body, _labels) {
3592
- return { status: "pass", errors: [] };
3593
- }
3594
- function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTitle) {
3595
- if (!isTaskIssueLabelSet(labels))
3596
- return { status: "pass", errors: [] };
3597
- if (resolvedMilestoneTitle === null)
3598
- return { status: "pass", errors: [] };
3599
- if (currentMilestoneTitle === resolvedMilestoneTitle)
3600
- return { status: "pass", errors: [] };
3601
- return {
3602
- status: "fail",
3603
- errors: [
3604
- `issue-validation milestone attach: this task Issue's tranche label resolves to Milestone "${resolvedMilestoneTitle}", but its live Milestone is ${currentMilestoneTitle === null ? "unset" : `"${currentMilestoneTitle}"`} — attach it to "${resolvedMilestoneTitle}".`
3605
- ]
3606
- };
3607
- }
3608
- var TYPE_LABEL_IDS = LABELS.filter((l) => l.category === "type").map((l) => l.id);
3609
- function isControlCodePoint(codePoint) {
3610
- return codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
3611
- }
3612
- function isDisplayControlCodePoint(codePoint) {
3613
- return codePoint >= 8203 && codePoint <= 8207 || codePoint >= 8234 && codePoint <= 8238 || codePoint >= 8294 && codePoint <= 8297 || codePoint === 65279;
3555
+ return findings;
3614
3556
  }
3615
- var MESSAGE_VALUE_COUNT_MAX = 5;
3616
- function residueForMessage(values) {
3617
- const shown = values.slice(0, MESSAGE_VALUE_COUNT_MAX).map((v) => `\`${forMessage(v)}\``);
3618
- const rest = values.length - shown.length;
3619
- return rest > 0 ? `${shown.join(", ")} and ${rest} more` : shown.join(", ");
3557
+ function escapeTerm(term) {
3558
+ return term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3620
3559
  }
3621
- var MESSAGE_VALUE_MAX = 64;
3622
- function forMessage(value) {
3623
- const kept = [];
3624
- for (const ch of value.replace(/\s+/g, " ")) {
3625
- const codePoint = ch.codePointAt(0) ?? 0;
3626
- if (isControlCodePoint(codePoint) || isDisplayControlCodePoint(codePoint))
3627
- continue;
3628
- kept.push(ch);
3629
- }
3630
- const cleaned = kept.join("").trim();
3631
- if (cleaned.length === 0)
3632
- return "(unprintable)";
3633
- const points = Array.from(cleaned);
3634
- return points.length > MESSAGE_VALUE_MAX ? `${points.slice(0, MESSAGE_VALUE_MAX).join("")}…` : cleaned;
3560
+ function containsWholeWord(text, term) {
3561
+ const escaped = escapeTerm(term);
3562
+ const re = new RegExp(`(^|[^a-zA-Z])${escaped}([^a-zA-Z]|$)`, "i");
3563
+ return re.test(text);
3635
3564
  }
3636
- function checkProjectsRegistered(body, _labels, registeredNames) {
3637
- if (registeredNames.length === 0)
3638
- return { status: "pass", errors: [] };
3639
- const field = projectFieldFromBody(body);
3640
- if (!field.declared)
3641
- return { status: "pass", errors: [] };
3642
- const known = new Set(registeredNames.map((n) => n.trim()));
3643
- const registeredList = [...registeredNames].map(forMessage).join(", ");
3644
- const errors = [];
3645
- if (field.unreadable) {
3646
- return {
3647
- status: "fail",
3648
- errors: [
3649
- `issue-validation project registry: the body has an unterminated code fence, so its \`**Project:**\` field could not be read reliably — the fence runs to end of body (CommonMark, and how the forge renders it), swallowing everything after it including the foot field where the declaration lives by convention. Read from the raw body the field says ${residueForMessage(field.unparsed) || "(nothing)"}, but a line inside a swallowed region may be a quoted example rather than a real declaration, so this gate refuses rather than guessing which. Balance the fences — every opening run of backticks or tildes needs a closing run at least as long — and the field reads normally.`
3650
- ]
3651
- };
3652
- }
3653
- const unregistered = field.names.filter((p) => !known.has(p));
3654
- if (unregistered.length > 0) {
3655
- const caseHints = unregistered.map((p) => {
3656
- const row = [...known].find((k) => k.toLowerCase() === p.toLowerCase());
3657
- return row ? `\`${forMessage(p)}\` differs from the registered \`${forMessage(row)}\` only in case` : null;
3658
- }).filter((h) => h !== null);
3659
- errors.push(`issue-validation project registry: the \`**Project:**\` field declares ${unregistered.map(forMessage).join(", ")} — no such row in \`.vinaya/projects.md\`, which is the authority for valid project names (registered: ${registeredList}). Fix the name, or register the project with \`vinaya init product <name> --path <folder>\` first; an unregistered project has no specs to read and no per-project state to update.${caseHints.length > 0 ? ` Note: ${caseHints.join("; ")} — project names are matched exactly, because every downstream consumer compares them literally.` : ""} This reads the same field \`projectsFromBody\` derives the task's project from, so a name here that is not a row is a task that resolves to a project that does not exist.`);
3660
- }
3661
- if (field.names.length === 0) {
3662
- const residue = field.unparsed.length > 0 ? ` — ${residueForMessage(field.unparsed)}` : " — the field is empty";
3663
- errors.push(`issue-validation project registry: the \`**Project:**\` field is present but resolves to no project name${residue} (registered: ${registeredList}). A project name is a slug (\`[a-z0-9][a-z0-9-]*\`, matched exactly); prose, a parenthetical, or a sentence in this field resolves to no project at all, and this gate cannot check a name it never receives — which is how a declaration like this used to pass. Write the registered name on its own, or register the project with \`vinaya init product <name> --path <folder>\` first. If the task genuinely touches no registered project, omit the field rather than explaining its absence inside it — \`checkIssueRationale\` already requires the \`Project(s) + blast radius\` narrative field for that.`);
3664
- } else if (field.unparsed.length > 0) {
3665
- errors.push(`issue-validation project registry: the \`**Project:**\` field declares a value that is not a project name — ${residueForMessage(field.unparsed)} (registered: ${registeredList}). The rest of the field parsed, so this is a name the gate silently could not check rather than a field it could not read at all. A project name is a slug (\`[a-z0-9][a-z0-9-]*\`, matched exactly); write it on its own, or drop it if it names no project.`);
3565
+ function findWholeWordLine(content, term) {
3566
+ const lines = content.split(`
3567
+ `);
3568
+ let lineNo = 0;
3569
+ for (const line of lines) {
3570
+ lineNo++;
3571
+ if (containsWholeWord(line, term))
3572
+ return lineNo;
3666
3573
  }
3667
- return errors.length > 0 ? { status: "fail", errors } : { status: "pass", errors: [] };
3668
- }
3669
- var DOC_PATH_RE = /(?:(?:aeg-root|apps|packages|specs|docs|tools|\.claude|\.github)\/[\w./@-]*\.(?:md|mdx)|\.claude\/(?:skills|rules)\/[\w./-]+|\b(?:docs-index|decisions|projects|state-machine|enforcement|process|README|CLAUDE)\.md\b|\b[\w-]+-(?:spec|decisions|backlog)\.md\b)/i;
3670
- var DOC_PATH_RE_GLOBAL = new RegExp(DOC_PATH_RE.source, "gi");
3671
-
3672
- // ../../packages/aeg-core/src/task-branch-identity.ts
3673
- var ISSUE_BRANCH_PATTERN = /^task\/issue-(\d+)$/;
3674
- var TRANCHE_BRANCH_PATTERN = /^task\/([^/]+)\/([^/]+)$/;
3675
- function parseTaskBranchIdentity(branch) {
3676
- const issueMatch = ISSUE_BRANCH_PATTERN.exec(branch);
3677
- if (issueMatch)
3678
- return { kind: "issue", issueNumber: Number(issueMatch[1]) };
3679
- const trancheMatch = TRANCHE_BRANCH_PATTERN.exec(branch);
3680
- if (trancheMatch)
3681
- return { kind: "tranche", tranche: trancheMatch[1], taskId: trancheMatch[2] };
3682
3574
  return null;
3683
3575
  }
3684
-
3685
- // ../../packages/aeg-core/src/coherence-checks.ts
3686
- var COHERENCE_ENFORCED_FROM = "2026-07-01";
3687
- function isGrandfathered(isoDate) {
3688
- if (!isoDate)
3689
- return false;
3690
- return isoDate.slice(0, 10) < COHERENCE_ENFORCED_FROM;
3576
+ function definesOrLinksGlossary(content, term) {
3577
+ const escaped = escapeTerm(term);
3578
+ const definesInline = new RegExp(`(^|[^a-zA-Z])${escaped}([^a-zA-Z]|$)[^\\n]{0,3}—`, "i").test(content);
3579
+ if (definesInline)
3580
+ return true;
3581
+ return /docs\/glossary|glossary\.md/i.test(content);
3691
3582
  }
3692
- var R1_GRANDFATHERED_ISSUES = new Set([279, 280, 281, 282]);
3693
- function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
3694
- const failures = [];
3695
- for (const e of entries) {
3696
- if (!e.facts)
3697
- continue;
3698
- if (e.facts.stateReason === "not_planned")
3583
+ function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX) {
3584
+ const findings = [];
3585
+ for (const file of files) {
3586
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
3587
+ if (!cls || !SWEPT_CLASSES.has(cls))
3699
3588
  continue;
3700
- if (e.facts.issueState === "closed" && e.facts.prState !== "merged") {
3701
- const handClosed = e.facts.stateReason === "completed" && isPrincipal(e.facts.closedByActor, principalAllowlist);
3702
- if (handClosed)
3589
+ const scrubbed = stripNonProse(file.path, file.content);
3590
+ for (const term of glossaryTerms) {
3591
+ const line = findWholeWordLine(scrubbed, term);
3592
+ if (line === null)
3703
3593
  continue;
3704
- failures.push({
3705
- code: "closed-without-merge",
3706
- issue: e.task.issue,
3707
- tranche: e.trancheSlug,
3708
- task: e.task.id,
3709
- reason: `Issue closed but closing PR is not merged (prState: ${e.facts.prState})`,
3710
- grandfathered: isGrandfathered(e.facts.closedAt)
3594
+ if (definesOrLinksGlossary(scrubbed, term))
3595
+ continue;
3596
+ findings.push({
3597
+ file: file.path,
3598
+ line,
3599
+ message: `uses coined term "${term}" without defining it inline or linking the glossary`,
3600
+ blocking: false
3711
3601
  });
3712
3602
  }
3713
3603
  }
3714
- const activeFails = failures.filter((f) => !f.grandfathered);
3715
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3716
- return {
3717
- check: "A1",
3718
- status,
3719
- failures,
3720
- note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
3721
- };
3604
+ return findings;
3722
3605
  }
3723
- function checkA3(entries) {
3724
- const failures = [];
3725
- for (const e of entries) {
3726
- if (!e.facts)
3606
+ var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g;
3607
+ var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = /#[0-9]{2,}/g;
3608
+ function extractComments(path, content) {
3609
+ if (!path.endsWith(".ts") && !path.endsWith(".tsx"))
3610
+ return content.replace(/[^\n]/g, "");
3611
+ let state = "code";
3612
+ let out = "";
3613
+ const n = content.length;
3614
+ let i = 0;
3615
+ const blank = (ch) => ch === `
3616
+ ` ? `
3617
+ ` : " ";
3618
+ while (i < n) {
3619
+ const c = content[i];
3620
+ const next = i + 1 < n ? content[i + 1] : "";
3621
+ if (state === "code") {
3622
+ if (c === "/" && next === "/") {
3623
+ state = "line-comment";
3624
+ out += c;
3625
+ i++;
3626
+ continue;
3627
+ }
3628
+ if (c === "/" && next === "*") {
3629
+ state = "block-comment";
3630
+ out += c;
3631
+ i++;
3632
+ continue;
3633
+ }
3634
+ if (c === "'") {
3635
+ state = "single-quote";
3636
+ out += blank(c);
3637
+ i++;
3638
+ continue;
3639
+ }
3640
+ if (c === '"') {
3641
+ state = "double-quote";
3642
+ out += blank(c);
3643
+ i++;
3644
+ continue;
3645
+ }
3646
+ if (c === "`") {
3647
+ state = "template";
3648
+ out += blank(c);
3649
+ i++;
3650
+ continue;
3651
+ }
3652
+ out += blank(c);
3653
+ i++;
3727
3654
  continue;
3728
- if (e.facts.prState === "merged" && e.facts.issueState !== "closed") {
3729
- failures.push({
3730
- code: "auto-close-misfire",
3731
- issue: e.task.issue,
3732
- tranche: e.trancheSlug,
3733
- task: e.task.id,
3734
- reason: "Closing PR is merged but Issue is still open (GitHub auto-close misfire)",
3735
- grandfathered: isGrandfathered(e.facts.mergedAt)
3736
- });
3737
3655
  }
3738
- }
3739
- const activeFails = failures.filter((f) => !f.grandfathered);
3740
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3741
- return {
3742
- check: "A3",
3743
- status,
3744
- failures,
3745
- note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
3746
- };
3747
- }
3748
- function checkT1(entries) {
3749
- const failures = [];
3750
- for (const e of entries) {
3751
- if (e.task.issue === null)
3656
+ if (state === "line-comment") {
3657
+ if (c === `
3658
+ `) {
3659
+ state = "code";
3660
+ out += `
3661
+ `;
3662
+ i++;
3663
+ continue;
3664
+ }
3665
+ out += c;
3666
+ i++;
3752
3667
  continue;
3753
- if (e.facts === undefined) {
3754
- failures.push({
3755
- code: "phantom-issue-ref",
3756
- issue: e.task.issue,
3757
- tranche: e.trancheSlug,
3758
- task: e.task.id,
3759
- reason: `Issue #${e.task.issue} in topology does not resolve to a real GitHub Issue`
3760
- });
3761
3668
  }
3762
- }
3763
- return { check: "T1", status: failures.length > 0 ? "fail" : "pass", failures };
3764
- }
3765
- function checkT2(openIssuesBySlug, topologyIssuesBySlug, ciTrancheSlug) {
3766
- const failures = [];
3767
- for (const [slug, openNums] of openIssuesBySlug) {
3768
- if (ciTrancheSlug && slug !== ciTrancheSlug)
3769
- continue;
3770
- const topologySet = topologyIssuesBySlug.get(slug) ?? new Set;
3771
- for (const num of openNums) {
3772
- if (!topologySet.has(num)) {
3773
- failures.push({
3774
- code: "orphan-task",
3775
- issue: num,
3776
- tranche: slug,
3777
- reason: `Issue #${num} is open and labeled ${trancheLabel(slug)} but does not appear in the topology file`
3778
- });
3669
+ if (state === "block-comment") {
3670
+ if (c === "*" && next === "/") {
3671
+ out += c;
3672
+ out += next;
3673
+ state = "code";
3674
+ i += 2;
3675
+ continue;
3779
3676
  }
3677
+ out += c === `
3678
+ ` ? `
3679
+ ` : c;
3680
+ i++;
3681
+ continue;
3780
3682
  }
3781
- }
3782
- return { check: "T2", status: failures.length > 0 ? "fail" : "pass", failures };
3783
- }
3784
- function scopeT2ToPlanPr(result, isPlanPr) {
3785
- if (isPlanPr || result.status !== "fail")
3786
- return result;
3787
- return {
3788
- ...result,
3789
- status: "info",
3790
- note: result.note ?? "T2 findings are non-blocking outside plan PRs (point-of-power principle) — see aeg-root/enforcement.md."
3791
- };
3792
- }
3793
- function checkT3(entries, ciTrancheSlug, enrichedEntries, forgeUnavailableSlugs) {
3794
- const preEnforcement = new Set;
3795
- if (enrichedEntries) {
3796
- for (const e of enrichedEntries) {
3797
- if (isGrandfathered(e.facts?.closedAt) || isGrandfathered(e.facts?.mergedAt)) {
3798
- preEnforcement.add(e.trancheSlug);
3683
+ const closer = state === "single-quote" ? "'" : state === "double-quote" ? '"' : "`";
3684
+ if (c === "\\") {
3685
+ out += blank(c);
3686
+ i++;
3687
+ if (i < n) {
3688
+ out += blank(content[i]);
3689
+ i++;
3799
3690
  }
3691
+ continue;
3800
3692
  }
3801
- }
3802
- const failures = [];
3803
- for (const e of entries) {
3804
- if (!e.archived && e.task.issue === null) {
3805
- if (ciTrancheSlug && e.trancheSlug !== ciTrancheSlug)
3806
- continue;
3807
- if (forgeUnavailableSlugs?.has(e.trancheSlug)) {
3808
- failures.push({
3809
- code: "tbd-in-active-tranche",
3810
- issue: null,
3811
- tranche: e.trancheSlug,
3812
- task: e.task.id,
3813
- reason: `Task ${e.task.id} in active tranche has no Issue ref (#TBD or empty), but forge data for tranche "${e.trancheSlug}" was unavailable — cannot evaluate grandfather status, not silently failed`,
3814
- grandfathered: true
3815
- });
3816
- continue;
3817
- }
3818
- failures.push({
3819
- code: "tbd-in-active-tranche",
3820
- issue: null,
3821
- tranche: e.trancheSlug,
3822
- task: e.task.id,
3823
- reason: `Task ${e.task.id} in active tranche has no Issue ref (#TBD or empty) — the model requires all active tasks to have Issue numbers`,
3824
- grandfathered: preEnforcement.has(e.trancheSlug)
3825
- });
3693
+ if (c === closer) {
3694
+ state = "code";
3695
+ out += blank(c);
3696
+ i++;
3697
+ continue;
3826
3698
  }
3699
+ out += blank(c);
3700
+ i++;
3827
3701
  }
3828
- const activeFails = failures.filter((f) => !f.grandfathered);
3829
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3830
- return {
3831
- check: "T3",
3832
- status,
3833
- failures,
3834
- note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
3835
- };
3702
+ return out;
3836
3703
  }
3837
- function checkD1(entries, issueToEntry, taskToEntry) {
3838
- const failures = [];
3839
- for (const e of entries) {
3840
- if (!e.facts)
3704
+ function checkSourceComments(files, allowlist = []) {
3705
+ const findings = [];
3706
+ const allowed = new Set(allowlist);
3707
+ const patterns = [
3708
+ { pattern: SOURCE_COMMENT_TRANCHE_SLUG_PATTERN, what: "a tranche-slug citation" },
3709
+ { pattern: SOURCE_COMMENT_FORGE_NUMBER_PATTERN, what: "a forge-number citation" }
3710
+ ];
3711
+ for (const file of files) {
3712
+ if (!file.path.endsWith(".ts"))
3841
3713
  continue;
3842
- if (e.facts.prState !== "open")
3714
+ if (allowed.has(file.path))
3843
3715
  continue;
3844
- for (const dep of e.task.dependsOn) {
3845
- const depEntry = resolveDepEntry(dep, e.trancheSlug, issueToEntry, taskToEntry);
3846
- if (!depEntry)
3847
- continue;
3848
- const sameTask = depEntry.trancheSlug === e.trancheSlug && depEntry.task.id === e.task.id;
3849
- const sameIssue = depEntry.task.issue !== null && e.task.issue !== null && depEntry.task.issue === e.task.issue;
3850
- if (sameTask || sameIssue) {
3851
- failures.push({
3852
- code: "d1-self-dependency",
3853
- issue: e.task.issue,
3854
- tranche: e.trancheSlug,
3855
- task: e.task.id,
3856
- reason: `INTERNAL: parsed a self-dependency (depends-on ${dep}) — this is a parser bug in parseRationaleDeps, not a real dependency. Please report it upstream.`
3857
- });
3858
- continue;
3859
- }
3860
- const depFacts = depEntry.facts;
3861
- const depClosed = depFacts?.issueState === "closed";
3862
- if (!depClosed) {
3863
- failures.push({
3864
- code: "dispatched-on-unmet-deps",
3865
- issue: e.task.issue,
3866
- tranche: e.trancheSlug,
3867
- task: e.task.id,
3868
- reason: `Task has open PR but depends-on ${dep} (issue #${depEntry.task.issue ?? "?"}) is not closed`
3716
+ const comments = extractComments(file.path, file.content);
3717
+ for (const { pattern, what } of patterns) {
3718
+ pattern.lastIndex = 0;
3719
+ let match = pattern.exec(comments);
3720
+ while (match !== null) {
3721
+ findings.push({
3722
+ file: file.path,
3723
+ line: lineAt(comments, match.index),
3724
+ message: `comment cites ${what} ("${match[0]}") a reader outside this repo's tracker cannot resolve`,
3725
+ blocking: false
3869
3726
  });
3727
+ match = pattern.exec(comments);
3870
3728
  }
3871
3729
  }
3872
3730
  }
3873
- return { check: "D1", status: failures.length > 0 ? "fail" : "pass", failures };
3731
+ return findings;
3874
3732
  }
3875
- function resolveDepEntry(dep, trancheSlug, issueToEntry, taskToEntry) {
3876
- const issueMatch = dep.match(/^#(\d+)$/);
3877
- if (issueMatch?.[1])
3878
- return issueToEntry.get(Number(issueMatch[1]));
3879
- return taskToEntry.get(`${trancheSlug}/${dep}`) ?? taskToEntry.get(dep);
3733
+ function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
3734
+ return [
3735
+ ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths),
3736
+ ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix)
3737
+ ];
3880
3738
  }
3881
- function checkR1(issuesBySlug, grandfatheredIssues, registeredNames = [], objectivesSinceIssue) {
3882
- const failures = [];
3883
- for (const [slug, issues] of issuesBySlug) {
3884
- for (const issue of issues) {
3885
- if (!isTaskIssueLabelSet(issue.labels))
3886
- continue;
3887
- const errors = [
3888
- ...checkIssueRationale(issue.body).errors,
3889
- ...checkProjectsRegistered(issue.body, issue.labels, registeredNames).errors,
3890
- ...checkIssueObjectives(issue.body, issue.number, objectivesSinceIssue).errors,
3891
- ...checkPartsCiteDefinedObjectives(issue.body).errors
3892
- ];
3893
- if (errors.length === 0)
3894
- continue;
3895
- failures.push({
3896
- code: "missing-rationale-field",
3897
- issue: issue.number,
3898
- tranche: slug,
3899
- reason: `Issue #${issue.number} fails the rationale gate: ${errors.join(" | ")}`,
3900
- grandfathered: grandfatheredIssues.has(issue.number)
3901
- });
3902
- }
3739
+ function parseGlossaryTerms(glossaryContent) {
3740
+ const terms = [];
3741
+ const re = /^\*\*(.+?)\*\* —/gm;
3742
+ let match = re.exec(glossaryContent);
3743
+ while (match !== null) {
3744
+ if (match[1] !== undefined)
3745
+ terms.push(match[1]);
3746
+ match = re.exec(glossaryContent);
3903
3747
  }
3904
- const activeFails = failures.filter((f) => !f.grandfathered);
3905
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3906
- return {
3907
- check: "R1",
3908
- status,
3909
- failures,
3910
- note: status === "info" ? `${failures.length} grandfathered task Issue(s) predate this check's grammar (rationale fields and/or the project registry)` : undefined
3911
- };
3748
+ return terms;
3912
3749
  }
3913
- function checkL1(files, entriesBySlug) {
3914
- const failures = [];
3915
- for (const f of files) {
3916
- if (f.archived)
3917
- continue;
3918
- const entries = entriesBySlug.get(f.slug) ?? [];
3919
- const withFacts = entries.filter((e) => e.facts !== undefined);
3920
- if (withFacts.length === 0)
3921
- continue;
3922
- const allClosed = withFacts.every((e) => e.facts?.issueState === "closed");
3923
- if (allClosed) {
3924
- failures.push({
3925
- code: "archive-recommended",
3926
- tranche: f.slug,
3927
- reason: "Active tranche has no open task-Issues — consider archiving to completed/"
3928
- });
3929
- }
3930
- }
3931
- return {
3932
- check: "L1",
3933
- status: "info",
3934
- failures,
3935
- note: failures.length > 0 ? `${failures.length} active tranche(s) with no open task-Issues — consider archiving (advisory)` : undefined
3936
- };
3750
+
3751
+ // ../../packages/aeg-core/src/quoted-command.ts
3752
+ var QUOTED_COMMAND_SHIPS_PREFIX = "aeg-root/";
3753
+ var QUOTED_COMMAND_SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
3754
+ var START_PATTERN = /<!--\s*AEG:QUOTES-FILE:START:(\S+?)\s*-->/g;
3755
+ var END_PATTERN = /<!--\s*AEG:QUOTES-FILE:END\s*-->/;
3756
+ function isValidCitedFilePath(path) {
3757
+ if (path.length === 0)
3758
+ return false;
3759
+ if (path.startsWith("/") || path.startsWith("\\"))
3760
+ return false;
3761
+ if (/^[A-Za-z]:[\\/]/.test(path))
3762
+ return false;
3763
+ return !path.split(/[\\/]+/).includes("..");
3937
3764
  }
3938
- function checkL3(files) {
3939
- const active = files.filter((f) => !f.archived);
3940
- return {
3941
- check: "L3",
3942
- status: "info",
3943
- failures: [],
3944
- note: `${active.length} active tranche(s): ${active.map((f) => f.slug).join(", ") || "(none)"}`
3945
- };
3946
- }
3947
- function extractClosesReferences(prBody) {
3948
- const closesPattern = /(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s{0,8}:?\s{0,8}#(\d+)/gi;
3949
- const stripped = stripCode(prBody);
3950
- const searchIn = anchoredRegion(stripped, "CLOSES") ?? stripped;
3951
- const referenced = new Set;
3952
- for (const hit of searchIn.matchAll(closesPattern)) {
3953
- referenced.add(Number(hit[1]));
3765
+ function quotedCommandLineAt(content, index) {
3766
+ let line = 1;
3767
+ for (let i = 0;i < index; i++) {
3768
+ if (content.charCodeAt(i) === 10)
3769
+ line++;
3954
3770
  }
3955
- return referenced;
3771
+ return line;
3956
3772
  }
3957
- function checkClosesNTopology(branch, prBody, trancheFiles, taskIssueRefs) {
3958
- const referenced = extractClosesReferences(prBody);
3959
- if (taskIssueRefs) {
3960
- for (const n of referenced) {
3961
- const ref = taskIssueRefs.get(n);
3962
- if (!ref)
3963
- continue;
3964
- const expectedBranch = `task/${ref.trancheSlug}/${ref.taskId}`;
3965
- if (branch !== expectedBranch) {
3966
- return {
3967
- ok: false,
3968
- message: `closes-n-reverse: branch "${branch}" closes #${n} (task ${ref.taskId} of tranche "${ref.trancheSlug}") but is not named "${expectedBranch}" — rename the branch and re-push, or if this work is intentionally outside AEG's dispatch flow, remove the Closes reference.`
3969
- };
3970
- }
3773
+ function extractQuotedText(raw) {
3774
+ const trimmed = raw.trim();
3775
+ const fenced = /^(?:`{3,}|~{3,})[^\n]*\n([\s\S]*?)\n?(?:`{3,}|~{3,})$/.exec(trimmed);
3776
+ if (fenced)
3777
+ return (fenced[1] ?? "").trim();
3778
+ const inline = /^`([^`]+)`$/.exec(trimmed);
3779
+ if (inline)
3780
+ return (inline[1] ?? "").trim();
3781
+ return trimmed;
3782
+ }
3783
+ function findQuotesInFile(path, content) {
3784
+ const masked = maskCode(content);
3785
+ const quotes = [];
3786
+ START_PATTERN.lastIndex = 0;
3787
+ let start = START_PATTERN.exec(masked);
3788
+ while (start !== null) {
3789
+ const citedFile = start[1];
3790
+ const innerStart = start.index + start[0].length;
3791
+ const end = END_PATTERN.exec(masked.slice(innerStart));
3792
+ if (end === null) {
3793
+ START_PATTERN.lastIndex = innerStart;
3794
+ start = START_PATTERN.exec(masked);
3795
+ continue;
3971
3796
  }
3972
- }
3973
- const ref = parseTaskBranchIdentity(branch);
3974
- if (!ref)
3975
- return { ok: true };
3976
- if (ref.kind === "issue") {
3977
- const expectedIssue = ref.issueNumber;
3978
- if (!referenced.has(expectedIssue)) {
3979
- return {
3980
- ok: false,
3981
- expectedIssue,
3982
- message: `closes-n: PR body does not contain \`Closes #${expectedIssue}\` (required for branch "${branch}"). Add it to the PR body Summary section.`
3983
- };
3797
+ const innerEnd = innerStart + end.index;
3798
+ if (isValidCitedFilePath(citedFile)) {
3799
+ const quotedText = extractQuotedText(content.slice(innerStart, innerEnd));
3800
+ if (quotedText.length > 0) {
3801
+ quotes.push({ file: path, line: quotedCommandLineAt(content, innerStart), quotedText, citedFile });
3802
+ }
3984
3803
  }
3985
- return { ok: true, expectedIssue };
3986
- }
3987
- const trancheSlug = ref.tranche;
3988
- const taskId = ref.taskId;
3989
- const trancheFile = trancheFiles.find((f) => f.slug === trancheSlug);
3990
- if (!trancheFile) {
3991
- return {
3992
- ok: false,
3993
- message: `closes-n: branch "${branch}" references tranche "${trancheSlug}" but no topology file found at aeg-root/tranches/${trancheSlug}.md. Ensure the tranche file exists before opening the PR.`
3994
- };
3995
- }
3996
- const task = trancheFile.tranche.tasks.find((t) => t.id === taskId);
3997
- if (!task) {
3998
- return {
3999
- ok: false,
4000
- message: `closes-n: branch "${branch}" references task "${taskId}" not found in ${trancheSlug} topology. Verify the task ID matches the tranche file.`
4001
- };
3804
+ START_PATTERN.lastIndex = innerEnd + end[0].length;
3805
+ start = START_PATTERN.exec(masked);
4002
3806
  }
4003
- if (task.issue === null) {
4004
- return {
4005
- ok: false,
4006
- message: `closes-n: task "${taskId}" in "${trancheSlug}" has no Issue number (#TBD). The Planner must cut the Issue before this PR can be validated.`
4007
- };
3807
+ return quotes;
3808
+ }
3809
+ function findCitedQuotes(files, readerFacingPrefix, readerFacingSuffix, shipsPrefix = QUOTED_COMMAND_SHIPS_PREFIX) {
3810
+ const quotes = [];
3811
+ for (const file of files) {
3812
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
3813
+ if (!cls || !QUOTED_COMMAND_SWEPT_CLASSES.has(cls))
3814
+ continue;
3815
+ quotes.push(...findQuotesInFile(file.path, file.content));
4008
3816
  }
4009
- const expectedIssue = task.issue;
4010
- if (!referenced.has(expectedIssue)) {
4011
- return {
4012
- ok: false,
4013
- expectedIssue,
4014
- message: `closes-n: PR body does not contain \`Closes #${expectedIssue}\` (required for task "${taskId}" in tranche "${trancheSlug}"). Add it to the PR body Summary section.`
4015
- };
3817
+ return quotes;
3818
+ }
3819
+ function evaluateCitedQuotes(citedQuotes, citedFileContents) {
3820
+ const findings = [];
3821
+ for (const quote of citedQuotes) {
3822
+ const content = citedFileContents.get(quote.citedFile);
3823
+ if (content === undefined) {
3824
+ findings.push({
3825
+ file: quote.file,
3826
+ line: quote.line,
3827
+ citedFile: quote.citedFile,
3828
+ quotedText: quote.quotedText,
3829
+ message: `${quote.file}:${quote.line} quotes "${quote.quotedText}" as citing \`${quote.citedFile}\`, but that file could not be read`
3830
+ });
3831
+ continue;
3832
+ }
3833
+ if (!content.includes(quote.quotedText)) {
3834
+ findings.push({
3835
+ file: quote.file,
3836
+ line: quote.line,
3837
+ citedFile: quote.citedFile,
3838
+ quotedText: quote.quotedText,
3839
+ message: `${quote.file}:${quote.line} quotes "${quote.quotedText}" as citing \`${quote.citedFile}\`, but \`${quote.citedFile}\` no longer contains that text verbatim`
3840
+ });
3841
+ }
4016
3842
  }
4017
- return { ok: true, expectedIssue };
3843
+ return findings;
4018
3844
  }
4019
- // ../../packages/aeg-core/src/archive-task.ts
4020
- function closesRefs(text) {
4021
- return [...new Set([...text.matchAll(/Closes #(\d+)/gi)].map((m) => Number(m[1])))];
3845
+
3846
+ // ../../packages/aeg-core/src/issue-validation.ts
3847
+ function hasRationaleField(body, labelPattern) {
3848
+ const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})`, "im");
3849
+ return re.test(body);
4022
3850
  }
4023
- function extractIssue(body) {
4024
- const stripped = stripCode(body);
4025
- const bodyNums = closesRefs(stripped);
4026
- const anchored = anchoredRegion(stripped, "CLOSES");
4027
- if (anchored !== null) {
4028
- const anchorNums = closesRefs(anchored);
4029
- if (anchorNums.length === 0)
4030
- return { issue: null, extraIssues: bodyNums, outsideHeader: false };
4031
- const issue = anchorNums[0];
4032
- return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: false };
3851
+ var RATIONALE_FIELDS = [
3852
+ { name: "Boundary", pattern: "Boundary" },
3853
+ { name: "Sizing", pattern: "Sizing" },
3854
+ { name: "Project(s) + blast radius", pattern: "Project\\(s\\)|Project(?:s)?\\s*\\+|blast radius" },
3855
+ { name: "Dependency rationale", pattern: "Dependency rationale|Depends[- ]on" },
3856
+ { name: "Traps to avoid", pattern: "Traps" },
3857
+ { name: "Suggested agent-class", pattern: "(?:Suggested\\s+)?agent-class" },
3858
+ { name: "Stop-and-escalate", pattern: "Stop-and-escalate" },
3859
+ { name: "Docs to keep coherent", pattern: "Docs to keep coherent|§7" }
3860
+ ];
3861
+ var DEPENDENCY_RATIONALE_FIELD_NAME = "Dependency rationale";
3862
+ function checkIssueRationale(body) {
3863
+ const errors = [];
3864
+ for (const f of RATIONALE_FIELDS) {
3865
+ if (!hasRationaleField(body, f.pattern)) {
3866
+ 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).`);
3867
+ continue;
3868
+ }
3869
+ if (f.name === DEPENDENCY_RATIONALE_FIELD_NAME && !SECTION_HEADER.test(body)) {
3870
+ 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.");
3871
+ }
4033
3872
  }
4034
- const headerNums = closesRefs(headerRegion(stripped));
4035
- if (bodyNums.length === 0)
4036
- return { issue: null, extraIssues: [], outsideHeader: false };
4037
- const issue = headerNums.length > 0 ? headerNums[0] : bodyNums[0];
4038
- return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: headerNums.length === 0 };
3873
+ return { status: errors.length > 0 ? "fail" : "pass", errors };
4039
3874
  }
4040
- // ../../packages/aeg-core/src/review-input-manifest.ts
4041
- import { createHash as createHash4 } from "node:crypto";
4042
- function briefHash(brief) {
4043
- return createHash4("sha256").update(`${brief}
4044
- `).digest("hex");
3875
+ var OBJECTIVES_SINCE_ISSUE = 404;
3876
+ function checkIssueObjectives(body, issueNumber, sinceIssue = OBJECTIVES_SINCE_ISSUE) {
3877
+ if (sinceIssue !== null && issueNumber !== null && issueNumber < sinceIssue)
3878
+ return { status: "pass", errors: [] };
3879
+ const result = objectivesOf(body);
3880
+ if (result.ok)
3881
+ return { status: "pass", errors: [] };
3882
+ return { status: "fail", errors: result.errors.map((e) => `issue-validation objectives: ${e}`) };
4045
3883
  }
4046
- function policyDigest(policy) {
4047
- return createHash4("sha256").update(JSON.stringify({
4048
- codeReviewThreshold: policy.codeReviewThreshold,
4049
- securityThreshold: policy.securityThreshold,
4050
- maxRounds: policy.maxRounds
4051
- })).digest("hex");
3884
+ function topLevelSectionText(body, headingName) {
3885
+ const headingRe = new RegExp(`^##[ \\t]*${headingName}[ \\t]*$`, "im");
3886
+ const heading = headingRe.exec(body);
3887
+ if (!heading)
3888
+ return null;
3889
+ const afterHeading = body.slice(heading.index + heading[0].length);
3890
+ const next = /^##[ \t]/m.exec(afterHeading);
3891
+ return next ? afterHeading.slice(0, next.index) : afterHeading;
4052
3892
  }
4053
- function isBoundToHead(echoed, headSha) {
4054
- if (!echoed.headSha)
4055
- return false;
4056
- return headSha.toLowerCase().startsWith(echoed.headSha.toLowerCase());
3893
+ function partHasBacktickedPath(text) {
3894
+ let i = 0;
3895
+ while (i < text.length) {
3896
+ const start = text.indexOf("`", i);
3897
+ if (start === -1)
3898
+ return false;
3899
+ const end = text.indexOf("`", start + 1);
3900
+ if (end === -1)
3901
+ return false;
3902
+ if (text.slice(start + 1, end).includes("/"))
3903
+ return true;
3904
+ i = end + 1;
3905
+ }
3906
+ return false;
4057
3907
  }
4058
- function isBoundByPatchIdentity(echoed, headSha, patchIdOf) {
4059
- if (patchIdOf === undefined || !echoed.headSha)
4060
- return false;
4061
- const judged = patchIdOf(echoed.headSha);
4062
- const current = patchIdOf(headSha);
4063
- if (judged === null || current === null)
4064
- return false;
4065
- return judged === current;
3908
+ var PART_MIN_WORDS_OUTSIDE_BACKTICKS = 3;
3909
+ function stripPartBackticks(text) {
3910
+ return text.replace(/`[^`\n]*`/g, " ");
4066
3911
  }
4067
- function isBoundToBase(echoed, currentBase) {
4068
- if (currentBase === null)
4069
- return true;
4070
- if (!echoed.baseSha)
4071
- return false;
4072
- return currentBase.toLowerCase().startsWith(echoed.baseSha.toLowerCase());
3912
+ function partWordCount(text) {
3913
+ return text.split(/\s+/).filter((w) => /[a-z]/i.test(w)).length;
4073
3914
  }
4074
- function isBoundToObjectives(echoed, currentVersion) {
4075
- if (currentVersion === null)
4076
- return true;
4077
- return echoed.objectivesVersion === currentVersion;
3915
+ function looksLikeFilePath(entry) {
3916
+ const stripped = entry.replace(/\/\*\*?$/, "");
3917
+ const lastSegment = stripped.split("/").pop() ?? stripped;
3918
+ const extMatch = /\.[A-Za-z0-9]{1,6}$/.exec(lastSegment);
3919
+ return extMatch !== null && extMatch.index > 0;
4078
3920
  }
4079
- function isBoundToRulings(echoed, currentOrdinal) {
4080
- if (echoed.rulingOrdinal === null)
4081
- return currentOrdinal === 0;
4082
- return echoed.rulingOrdinal === currentOrdinal;
3921
+ function splitGlobList(raw) {
3922
+ return raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
4083
3923
  }
4084
- function isBoundToBriefHash(echoed, currentHash) {
4085
- if (currentHash === null)
4086
- return true;
4087
- return echoed.briefHash === currentHash;
3924
+ function parseIssueSurface(body) {
3925
+ const section = topLevelSectionText(body, "Surface");
3926
+ if (section === null)
3927
+ return { ok: false, errors: ["no `## Surface` heading found in the body."] };
3928
+ const inLine = /^in:\s*(.+)$/im.exec(section);
3929
+ const outLine = /^out:\s*(.+)$/im.exec(section);
3930
+ const errors = [];
3931
+ if (!inLine)
3932
+ errors.push("`## Surface` has no `in:` line.");
3933
+ if (!outLine)
3934
+ errors.push("`## Surface` has no `out:` line.");
3935
+ if (errors.length > 0)
3936
+ return { ok: false, errors };
3937
+ const inGlobs = splitGlobList(inLine[1]);
3938
+ const outGlobs = splitGlobList(outLine[1]);
3939
+ for (const g of [...inGlobs, ...outGlobs]) {
3940
+ if (looksLikeFilePath(g)) {
3941
+ errors.push(`\`${g}\` in \`## Surface\` looks like a file path — Surface entries are directory-level globs, never file paths.`);
3942
+ }
3943
+ }
3944
+ if (inGlobs.length === 0)
3945
+ errors.push("`## Surface`'s `in:` line resolved to zero globs.");
3946
+ if (errors.length > 0)
3947
+ return { ok: false, errors };
3948
+ return { ok: true, value: { in: inGlobs, out: outGlobs } };
4088
3949
  }
4089
- function isBoundToPolicy(echoed, currentDigest) {
4090
- return echoed.policyDigest === currentDigest;
3950
+ function globCoversPath(glob, path) {
3951
+ const g = glob.replace(/\/\*\*?$/, "").replace(/\/+$/, "");
3952
+ const p = path.replace(/\/+$/, "");
3953
+ if (g === "*")
3954
+ return !p.includes("/");
3955
+ return g === p || g.startsWith(`${p}/`) || p.startsWith(`${g}/`);
4091
3956
  }
4092
- function compareManifest(echoed, current, patchIdOf) {
4093
- const exactHead = isBoundToHead(echoed, current.headSha);
4094
- const patchHead = exactHead ? false : isBoundByPatchIdentity(echoed, current.headSha, patchIdOf);
4095
- const head = exactHead || patchHead;
4096
- const echoedShaLen = echoed.baseSha?.length ?? 0;
4097
- const currentShaLen = current.baseSha?.length ?? 0;
4098
- const bothFullShas = echoedShaLen >= 40 && currentShaLen >= 40;
4099
- const base = patchHead || exactHead && bothFullShas ? true : isBoundToBase(echoed, current.baseSha);
4100
- const briefHashBound = isBoundToBriefHash(echoed, current.briefHash);
4101
- const objectivesVersion = isBoundToObjectives(echoed, current.objectivesVersion);
4102
- const rulingOrdinal = isBoundToRulings(echoed, current.rulingOrdinal);
4103
- const policyDigestBound = isBoundToPolicy(echoed, current.policyDigest);
3957
+ function checkSurfaceGlobsResolve(body, resolvesToFile) {
3958
+ const surface = parseIssueSurface(body);
3959
+ if (!surface.ok)
3960
+ return { status: "pass", errors: [] };
3961
+ const errors = [];
3962
+ for (const glob of surface.value.in) {
3963
+ if (!resolvesToFile(glob)) {
3964
+ 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.`);
3965
+ }
3966
+ }
3967
+ return { status: errors.length > 0 ? "fail" : "pass", errors };
3968
+ }
3969
+ function checkSurfaceScope(changedFiles, outGlobs) {
3970
+ if (outGlobs.length === 0)
3971
+ return { ok: true };
3972
+ const violations = [];
3973
+ for (const file of changedFiles) {
3974
+ const glob = outGlobs.find((g) => globCoversPath(g, file));
3975
+ if (glob)
3976
+ violations.push({ file, glob });
3977
+ }
3978
+ return violations.length > 0 ? { ok: false, violations } : { ok: true };
3979
+ }
3980
+ var ISSUE_PART_LINE_RE = /^Part\s+(\d+)\s*\(([^)]*)\)\s*[-—–]\s*(.*)$/i;
3981
+ function parseIssueParts(body) {
3982
+ const section = topLevelSectionText(body, "Parts");
3983
+ if (section === null)
3984
+ return { ok: false, errors: ["no `## Parts` heading found in the body."] };
3985
+ const lines = section.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
3986
+ const parts = [];
3987
+ const errors = [];
3988
+ for (const line of lines) {
3989
+ const m = ISSUE_PART_LINE_RE.exec(line);
3990
+ if (!m) {
3991
+ errors.push(`"${line}" is not a well-formed Parts line — expected \`Part <n> (<refs>) — <outcome>\`.`);
3992
+ continue;
3993
+ }
3994
+ const n = Number.parseInt(m[1], 10);
3995
+ const refs = m[2];
3996
+ const text = m[3].trim();
3997
+ if (text.length === 0) {
3998
+ errors.push(`Part ${n} has no outcome text after the dash — every Part states one observable outcome.`);
3999
+ continue;
4000
+ }
4001
+ if (partHasBacktickedPath(text) && partWordCount(stripPartBackticks(text)) < PART_MIN_WORDS_OUTSIDE_BACKTICKS) {
4002
+ errors.push(`Part ${n} is little more than a file path — a Part names an outcome and symbols, never a bare path.`);
4003
+ continue;
4004
+ }
4005
+ const objectiveIds = [...refs.matchAll(/O(\d+)/g)].map((r) => Number.parseInt(r[1], 10));
4006
+ parts.push({ n, objectiveIds, text });
4007
+ }
4008
+ if (parts.length === 0) {
4009
+ errors.push("the `## Parts` section has no well-formed `Part <n> (<refs>) — <outcome>` lines.");
4010
+ }
4011
+ if (errors.length > 0)
4012
+ return { ok: false, errors };
4013
+ return { ok: true, value: parts };
4014
+ }
4015
+ function checkPartsCiteDefinedObjectives(body) {
4016
+ const parts = parseIssueParts(body);
4017
+ const objectives = objectivesOf(body);
4018
+ if (!parts.ok || !objectives.ok)
4019
+ return { status: "pass", errors: [] };
4020
+ const definedIds = new Set(objectives.objectives.map((o) => Number.parseInt(o.id.slice(1), 10)));
4021
+ const errors = [];
4022
+ for (const part of parts.value) {
4023
+ for (const objectiveId of part.objectiveIds) {
4024
+ if (!definedIds.has(objectiveId)) {
4025
+ errors.push(`issue-validation Parts: Part ${part.n} cites O${objectiveId}, which the Issue's own \`## Objectives\` section does not define.`);
4026
+ }
4027
+ }
4028
+ }
4029
+ return { status: errors.length > 0 ? "fail" : "pass", errors };
4030
+ }
4031
+ function isTaskIssueLabelSet(labels) {
4032
+ return hasLabel("tranche", labels);
4033
+ }
4034
+ function checkTrancheLabelPresence(_body, _labels) {
4035
+ return { status: "pass", errors: [] };
4036
+ }
4037
+ function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTitle) {
4038
+ if (!isTaskIssueLabelSet(labels))
4039
+ return { status: "pass", errors: [] };
4040
+ if (resolvedMilestoneTitle === null)
4041
+ return { status: "pass", errors: [] };
4042
+ if (currentMilestoneTitle === resolvedMilestoneTitle)
4043
+ return { status: "pass", errors: [] };
4104
4044
  return {
4105
- bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && policyDigestBound,
4106
- head,
4107
- base,
4108
- briefHash: briefHashBound,
4109
- objectivesVersion,
4110
- rulingOrdinal,
4111
- policyDigest: policyDigestBound
4045
+ status: "fail",
4046
+ errors: [
4047
+ `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}".`
4048
+ ]
4112
4049
  };
4113
4050
  }
4114
-
4115
- // ../../packages/aeg-core/src/review-gate.ts
4116
- function checkReviewGate(input) {
4117
- const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
4118
- const waived = isWaiverLabelActorVerified({
4119
- label: WAIVER_LABEL_REVIEW,
4120
- labels: input.labels,
4121
- labelActor: input.waiverLabelActor,
4122
- principalAllowlist
4123
- });
4124
- if (waived) {
4125
- return {
4126
- verdict: "pass",
4127
- reason: `\`${WAIVER_LABEL_REVIEW}\` label is actor-verified — review requirement waived for this PR.`,
4128
- waived: true
4129
- };
4051
+ var TYPE_LABEL_IDS = LABELS.filter((l) => l.category === "type").map((l) => l.id);
4052
+ function isControlCodePoint(codePoint) {
4053
+ return codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
4054
+ }
4055
+ function isDisplayControlCodePoint(codePoint) {
4056
+ return codePoint >= 8203 && codePoint <= 8207 || codePoint >= 8234 && codePoint <= 8238 || codePoint >= 8294 && codePoint <= 8297 || codePoint === 65279;
4057
+ }
4058
+ var MESSAGE_VALUE_COUNT_MAX = 5;
4059
+ function residueForMessage(values) {
4060
+ const shown = values.slice(0, MESSAGE_VALUE_COUNT_MAX).map((v) => `\`${forMessage(v)}\``);
4061
+ const rest = values.length - shown.length;
4062
+ return rest > 0 ? `${shown.join(", ")} and ${rest} more` : shown.join(", ");
4063
+ }
4064
+ var MESSAGE_VALUE_MAX = 64;
4065
+ function forMessage(value) {
4066
+ const kept = [];
4067
+ for (const ch of value.replace(/\s+/g, " ")) {
4068
+ const codePoint = ch.codePointAt(0) ?? 0;
4069
+ if (isControlCodePoint(codePoint) || isDisplayControlCodePoint(codePoint))
4070
+ continue;
4071
+ kept.push(ch);
4130
4072
  }
4131
- const verified = input.comments.filter((c) => isPrincipal(c.author, principalAllowlist));
4132
- const ignoredCount = input.comments.filter((c) => !isPrincipal(c.author, principalAllowlist) && c.body.includes("VERDICT")).length;
4133
- const verifiedBodies = verified.map((c) => c.body);
4134
- const codeReview = extractCodeReviewVerdict(verifiedBodies);
4135
- const security = extractSecurityReviewVerdict(verifiedBodies);
4136
- const policy = input.policy ?? DEFAULT_REVIEW_POLICY;
4137
- let codeReviewPolicyEvaluation;
4138
- let securityPolicyEvaluation;
4139
- try {
4140
- codeReviewPolicyEvaluation = evaluateCodeReview(consequentialFindings(codeReview.findingSeverities), policy);
4141
- securityPolicyEvaluation = evaluateSecurityReview(consequentialFindings(security.findingSeverities), policy);
4142
- } catch (err) {
4073
+ const cleaned = kept.join("").trim();
4074
+ if (cleaned.length === 0)
4075
+ return "(unprintable)";
4076
+ const points = Array.from(cleaned);
4077
+ return points.length > MESSAGE_VALUE_MAX ? `${points.slice(0, MESSAGE_VALUE_MAX).join("")}…` : cleaned;
4078
+ }
4079
+ function checkProjectsRegistered(body, _labels, registeredNames) {
4080
+ if (registeredNames.length === 0)
4081
+ return { status: "pass", errors: [] };
4082
+ const field = projectFieldFromBody(body);
4083
+ if (!field.declared)
4084
+ return { status: "pass", errors: [] };
4085
+ const known = new Set(registeredNames.map((n) => n.trim()));
4086
+ const registeredList = [...registeredNames].map(forMessage).join(", ");
4087
+ const errors = [];
4088
+ if (field.unreadable) {
4143
4089
  return {
4144
- verdict: "fail",
4145
- reason: `a verdict comment carries a finding severity this repository's policy does not recognize: ${err instanceof Error ? err.message : String(err)}`,
4146
- waived: false
4090
+ status: "fail",
4091
+ errors: [
4092
+ `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.`
4093
+ ]
4147
4094
  };
4148
4095
  }
4149
- const codeReviewTextClean = codeReview.value === "APPROVE";
4150
- const securityTextClean = security.value === "PASS";
4151
- const codeReviewPolicyClean = codeReviewPolicyEvaluation.outcome === "clean";
4152
- const securityPolicyClean = securityPolicyEvaluation.outcome === "clean";
4153
- const codeReviewClean = codeReviewTextClean && codeReviewPolicyClean;
4154
- const securityClean = securityTextClean && securityPolicyClean;
4155
- const currentManifest = {
4156
- headSha: input.headSha,
4157
- baseSha: input.baseSha ?? null,
4158
- briefHash: input.briefHash ?? null,
4159
- objectivesVersion: input.objectivesVersion,
4160
- rulingOrdinal: input.rulingOrdinal,
4161
- policyDigest: policyDigest(policy)
4162
- };
4163
- const codeReviewEchoed = {
4164
- headSha: codeReview.headSha,
4165
- baseSha: codeReview.baseSha,
4166
- briefHash: codeReview.briefHash,
4167
- objectivesVersion: codeReview.objectivesVersion,
4168
- rulingOrdinal: codeReview.rulingOrdinal,
4169
- policyDigest: codeReview.policyDigest
4170
- };
4171
- const securityEchoed = {
4172
- headSha: security.headSha,
4173
- baseSha: security.baseSha,
4174
- briefHash: security.briefHash,
4175
- objectivesVersion: security.objectivesVersion,
4176
- rulingOrdinal: security.rulingOrdinal,
4177
- policyDigest: security.policyDigest
4178
- };
4179
- const codeReviewBinding = compareManifest(codeReviewEchoed, currentManifest, input.patchIdOf);
4180
- const securityBinding = compareManifest(securityEchoed, currentManifest, input.patchIdOf);
4181
- const codeReviewBound = codeReviewBinding.head;
4182
- const securityBound = securityBinding.head;
4183
- const codeReviewObjectivesBound = codeReviewBinding.objectivesVersion;
4184
- const securityObjectivesBound = securityBinding.objectivesVersion;
4185
- const codeReviewRulingsBound = codeReviewBinding.rulingOrdinal;
4186
- const securityRulingsBound = securityBinding.rulingOrdinal;
4187
- if (codeReviewClean && codeReviewBinding.bound && securityClean && securityBinding.bound) {
4188
- return {
4189
- verdict: "pass",
4190
- reason: `code-reviewer verdict is a clean APPROVE and security-review verdict is a clean PASS, both covering head ${input.headSha}.`,
4191
- waived: false
4192
- };
4096
+ const unregistered = field.names.filter((p) => !known.has(p));
4097
+ if (unregistered.length > 0) {
4098
+ const caseHints = unregistered.map((p) => {
4099
+ const row = [...known].find((k) => k.toLowerCase() === p.toLowerCase());
4100
+ return row ? `\`${forMessage(p)}\` differs from the registered \`${forMessage(row)}\` only in case` : null;
4101
+ }).filter((h) => h !== null);
4102
+ errors.push(`issue-validation project registry: the \`**Project:**\` field declares ${unregistered.map(forMessage).join(", ")} — no such row in \`.vinaya/projects.md\`, which is the authority for valid project names (registered: ${registeredList}). Fix the name, or register the project with \`vinaya init product <name> --path <folder>\` first; an unregistered project has no specs to read and no per-project state to update.${caseHints.length > 0 ? ` Note: ${caseHints.join("; ")} — project names are matched exactly, because every downstream consumer compares them literally.` : ""} This reads the same field \`projectsFromBody\` derives the task's project from, so a name here that is not a row is a task that resolves to a project that does not exist.`);
4193
4103
  }
4194
- const problems = [];
4195
- if (!codeReviewTextClean) {
4196
- problems.push(`code-reviewer verdict is not a clean APPROVE (found: ${codeReview.value})`);
4197
- } else if (!codeReviewPolicyClean) {
4198
- problems.push(`code-reviewer verdict says APPROVE but carries a finding (${codeReviewPolicyEvaluation.blockingFindings.map((f) => f.severity).join(", ")}) at or above this repository's code-review policy threshold (${policy.codeReviewThreshold}) — a reviewer's own APPROVE never overrides policy`);
4199
- } else if (!codeReviewBound) {
4200
- problems.push(`the newest code-review verdict covers ${codeReview.headSha ?? "no recorded commit"}, head is ${input.headSha}`);
4201
- } else if (!codeReviewBinding.base) {
4202
- problems.push(`the newest code-review verdict was cast against base ${codeReview.baseSha ?? "no recorded base"}, the PR's base is now ${currentManifest.baseSha ?? "unresolved"} (a base-only change under an unchanged candidate — same patch text on a new base is not automatically equivalent)`);
4203
- } else if (!codeReviewObjectivesBound) {
4204
- problems.push(`the newest code-review verdict was cast against objectives version ${codeReview.objectivesVersion ?? "none"}, the Issue's list is now ${input.objectivesVersion}`);
4205
- } else if (!codeReviewRulingsBound) {
4206
- problems.push(`the newest code-review verdict was cast against ruling ordinal ${codeReview.rulingOrdinal ?? "none"}, a newer ruling (ruling ${input.rulingOrdinal}) is now posted on this PR`);
4207
- } else if (!codeReviewBinding.briefHash) {
4208
- problems.push(`the newest code-review verdict was cast against brief hash ${codeReview.briefHash ?? "none"}, the frozen brief's current hash is ${currentManifest.briefHash ?? "none"}`);
4209
- } else if (!codeReviewBinding.policyDigest) {
4210
- problems.push(`the newest code-review verdict was cast against review policy digest ${codeReview.policyDigest ?? "none"}, this repository's current policy digest is ${currentManifest.policyDigest}`);
4104
+ if (field.names.length === 0) {
4105
+ const residue = field.unparsed.length > 0 ? ` — ${residueForMessage(field.unparsed)}` : " — the field is empty";
4106
+ 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.`);
4107
+ } else if (field.unparsed.length > 0) {
4108
+ errors.push(`issue-validation project registry: the \`**Project:**\` field declares a value that is not a project name — ${residueForMessage(field.unparsed)} (registered: ${registeredList}). The rest of the field parsed, so this is a name the gate silently could not check rather than a field it could not read at all. A project name is a slug (\`[a-z0-9][a-z0-9-]*\`, matched exactly); write it on its own, or drop it if it names no project.`);
4211
4109
  }
4212
- if (!securityTextClean) {
4213
- problems.push(`security-review verdict is not a clean PASS (found: ${security.value})`);
4214
- } else if (!securityPolicyClean) {
4215
- problems.push(`security-review verdict says PASS but carries a finding (${securityPolicyEvaluation.blockingFindings.map((f) => f.severity).join(", ")}) at or above this repository's security policy threshold (${policy.securityThreshold}) — a reviewer's own PASS never overrides policy`);
4216
- } else if (!securityBound) {
4217
- problems.push(`the newest security-review verdict covers ${security.headSha ?? "no recorded commit"}, head is ${input.headSha}`);
4218
- } else if (!securityBinding.base) {
4219
- problems.push(`the newest security-review verdict was cast against base ${security.baseSha ?? "no recorded base"}, the PR's base is now ${currentManifest.baseSha ?? "unresolved"} (a base-only change under an unchanged candidate — same patch text on a new base is not automatically equivalent)`);
4220
- } else if (!securityObjectivesBound) {
4221
- problems.push(`the newest security-review verdict was cast against objectives version ${security.objectivesVersion ?? "none"}, the Issue's list is now ${input.objectivesVersion}`);
4222
- } else if (!securityRulingsBound) {
4223
- problems.push(`the newest security-review verdict was cast against ruling ordinal ${security.rulingOrdinal ?? "none"}, a newer ruling (ruling ${input.rulingOrdinal}) is now posted on this PR`);
4224
- } else if (!securityBinding.briefHash) {
4225
- problems.push(`the newest security-review verdict was cast against brief hash ${security.briefHash ?? "none"}, the frozen brief's current hash is ${currentManifest.briefHash ?? "none"}`);
4226
- } else if (!securityBinding.policyDigest) {
4227
- problems.push(`the newest security-review verdict was cast against review policy digest ${security.policyDigest ?? "none"}, this repository's current policy digest is ${currentManifest.policyDigest}`);
4110
+ return errors.length > 0 ? { status: "fail", errors } : { status: "pass", errors: [] };
4111
+ }
4112
+ 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;
4113
+ var DOC_PATH_RE_GLOBAL = new RegExp(DOC_PATH_RE.source, "gi");
4114
+ var FILE_EXTENSIONS = new Set([
4115
+ "ts",
4116
+ "tsx",
4117
+ "js",
4118
+ "jsx",
4119
+ "mjs",
4120
+ "cjs",
4121
+ "json",
4122
+ "jsonc",
4123
+ "md",
4124
+ "mdx",
4125
+ "yml",
4126
+ "yaml",
4127
+ "txt",
4128
+ "sh",
4129
+ "lock",
4130
+ "toml",
4131
+ "ndjson",
4132
+ "html",
4133
+ "css"
4134
+ ]);
4135
+
4136
+ // ../../packages/aeg-core/src/task-branch-identity.ts
4137
+ var ISSUE_BRANCH_PATTERN = /^task\/issue-(\d+)$/;
4138
+ var TRANCHE_BRANCH_PATTERN = /^task\/([^/]+)\/([^/]+)$/;
4139
+ function parseTaskBranchIdentity(branch) {
4140
+ const issueMatch = ISSUE_BRANCH_PATTERN.exec(branch);
4141
+ if (issueMatch)
4142
+ return { kind: "issue", issueNumber: Number(issueMatch[1]) };
4143
+ const trancheMatch = TRANCHE_BRANCH_PATTERN.exec(branch);
4144
+ if (trancheMatch)
4145
+ return { kind: "tranche", tranche: trancheMatch[1], taskId: trancheMatch[2] };
4146
+ return null;
4147
+ }
4148
+
4149
+ // ../../packages/aeg-core/src/coherence-checks.ts
4150
+ var COHERENCE_ENFORCED_FROM = "2026-07-01";
4151
+ function isGrandfathered(isoDate) {
4152
+ if (!isoDate)
4153
+ return false;
4154
+ return isoDate.slice(0, 10) < COHERENCE_ENFORCED_FROM;
4155
+ }
4156
+ var R1_GRANDFATHERED_ISSUES = new Set([279, 280, 281, 282]);
4157
+ function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
4158
+ const failures = [];
4159
+ for (const e of entries) {
4160
+ if (!e.facts)
4161
+ continue;
4162
+ if (e.facts.stateReason === "not_planned")
4163
+ continue;
4164
+ if (e.facts.issueState === "closed" && e.facts.prState !== "merged") {
4165
+ const handClosed = e.facts.stateReason === "completed" && isPrincipal(e.facts.closedByActor, principalAllowlist);
4166
+ if (handClosed)
4167
+ continue;
4168
+ failures.push({
4169
+ code: "closed-without-merge",
4170
+ issue: e.task.issue,
4171
+ tranche: e.trancheSlug,
4172
+ task: e.task.id,
4173
+ reason: `Issue closed but closing PR is not merged (prState: ${e.facts.prState})`,
4174
+ grandfathered: isGrandfathered(e.facts.closedAt)
4175
+ });
4176
+ }
4177
+ }
4178
+ const activeFails = failures.filter((f) => !f.grandfathered);
4179
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
4180
+ return {
4181
+ check: "A1",
4182
+ status,
4183
+ failures,
4184
+ note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
4185
+ };
4186
+ }
4187
+ function checkA3(entries) {
4188
+ const failures = [];
4189
+ for (const e of entries) {
4190
+ if (!e.facts)
4191
+ continue;
4192
+ if (e.facts.prState === "merged" && e.facts.issueState !== "closed") {
4193
+ failures.push({
4194
+ code: "auto-close-misfire",
4195
+ issue: e.task.issue,
4196
+ tranche: e.trancheSlug,
4197
+ task: e.task.id,
4198
+ reason: "Closing PR is merged but Issue is still open (GitHub auto-close misfire)",
4199
+ grandfathered: isGrandfathered(e.facts.mergedAt)
4200
+ });
4201
+ }
4228
4202
  }
4229
- const ignoredNote = ignoredCount > 0 ? ` ${ignoredCount} verdict-shaped comment(s) from authors outside the principal allowlist were ignored.` : "";
4203
+ const activeFails = failures.filter((f) => !f.grandfathered);
4204
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
4230
4205
  return {
4231
- verdict: "fail",
4232
- reason: `${problems.join("; ")}. A principal can apply an actor-verified \`${WAIVER_LABEL_REVIEW}\` label to skip this requirement, or post the missing/clean verdict comment(s).${ignoredNote}`,
4233
- waived: false
4206
+ check: "A3",
4207
+ status,
4208
+ failures,
4209
+ note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
4234
4210
  };
4235
4211
  }
4236
- var CHANGESET_RELEASE_BRANCH = "changeset-release/main";
4237
- var DEFAULT_RELEASE_ACTOR = "github-actions[bot]";
4238
- function isChangesetsReleasePr(branch, author, expectedAuthor) {
4239
- return branch === CHANGESET_RELEASE_BRANCH && author === expectedAuthor;
4240
- }
4241
- // ../../packages/aeg-core/src/ruling-ordinal.ts
4242
- var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
4243
- function newestPrincipalRulingOrdinal(comments, allowlist) {
4244
- let best = 0;
4245
- for (const c of comments) {
4246
- if (!isPrincipal(c.author, allowlist))
4247
- continue;
4248
- const firstLine = (c.body.split(`
4249
- `)[0] ?? "").trim();
4250
- const m = RULING_MARKER_ORDINAL.exec(firstLine);
4251
- if (!m)
4212
+ function checkT1(entries) {
4213
+ const failures = [];
4214
+ for (const e of entries) {
4215
+ if (e.task.issue === null)
4252
4216
  continue;
4253
- const k = Number.parseInt(m[1], 10);
4254
- if (k > best)
4255
- best = k;
4217
+ if (e.facts === undefined) {
4218
+ failures.push({
4219
+ code: "phantom-issue-ref",
4220
+ issue: e.task.issue,
4221
+ tranche: e.trancheSlug,
4222
+ task: e.task.id,
4223
+ reason: `Issue #${e.task.issue} in topology does not resolve to a real GitHub Issue`
4224
+ });
4225
+ }
4256
4226
  }
4257
- return best;
4258
- }
4259
- // ../../packages/aeg-core/src/markdown-table.ts
4260
- function splitRow(line) {
4261
- const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
4262
- return trimmed.split("|").map((cell) => cell.trim());
4227
+ return { check: "T1", status: failures.length > 0 ? "fail" : "pass", failures };
4263
4228
  }
4264
- var TABLE_ROW_PATTERN = /^\s*\|.*\|\s*$/;
4265
- var SEPARATOR_ROW_PATTERN = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
4266
- function findTable(lines, fromLine, stopAtHeading = true) {
4267
- let i = fromLine - 1;
4268
- while (i < lines.length) {
4269
- const line = lines[i] ?? "";
4270
- if (stopAtHeading && i > fromLine - 1 && /^##\s/.test(line))
4271
- return null;
4272
- if (TABLE_ROW_PATTERN.test(line)) {
4273
- const headerLine = line;
4274
- const sepLine = lines[i + 1] ?? "";
4275
- if (!SEPARATOR_ROW_PATTERN.test(sepLine)) {
4276
- i++;
4277
- continue;
4278
- }
4279
- const headers = splitRow(headerLine);
4280
- const rows = [];
4281
- let j = i + 2;
4282
- while (j < lines.length && TABLE_ROW_PATTERN.test(lines[j] ?? "")) {
4283
- rows.push({ cells: splitRow(lines[j] ?? ""), line: j + 1 });
4284
- j++;
4229
+ function checkT2(openIssuesBySlug, topologyIssuesBySlug, ciTrancheSlug) {
4230
+ const failures = [];
4231
+ for (const [slug, openNums] of openIssuesBySlug) {
4232
+ if (ciTrancheSlug && slug !== ciTrancheSlug)
4233
+ continue;
4234
+ const topologySet = topologyIssuesBySlug.get(slug) ?? new Set;
4235
+ for (const num of openNums) {
4236
+ if (!topologySet.has(num)) {
4237
+ failures.push({
4238
+ code: "orphan-task",
4239
+ issue: num,
4240
+ tranche: slug,
4241
+ reason: `Issue #${num} is open and labeled ${trancheLabel(slug)} but does not appear in the topology file`
4242
+ });
4285
4243
  }
4286
- return { headers, rows };
4287
4244
  }
4288
- i++;
4289
4245
  }
4290
- return null;
4246
+ return { check: "T2", status: failures.length > 0 ? "fail" : "pass", failures };
4291
4247
  }
4292
- function findHeadingLine(lines, pattern) {
4293
- for (let i = 0;i < lines.length; i++) {
4294
- if (pattern.test(lines[i] ?? ""))
4295
- return i + 1;
4296
- }
4297
- return null;
4248
+ function scopeT2ToPlanPr(result, isPlanPr) {
4249
+ if (isPlanPr || result.status !== "fail")
4250
+ return result;
4251
+ return {
4252
+ ...result,
4253
+ status: "info",
4254
+ note: result.note ?? "T2 findings are non-blocking outside plan PRs (point-of-power principle) — see aeg-root/enforcement.md."
4255
+ };
4298
4256
  }
4299
- // ../../packages/aeg-core/src/diagram-model.ts
4300
- import matter from "gray-matter";
4301
-
4302
- // ../../packages/aeg-core/src/registry-parse.ts
4303
- var RING_HEADINGS = [
4304
- { ring: "ring0", pattern: /^##\s+Ring 0\b/ },
4305
- { ring: "ring1", pattern: /^##\s+Ring 1\b/ },
4306
- { ring: "ring2", pattern: /^##\s+Ring 2\b/ }
4307
- ];
4308
- function stripBackticks2(cell) {
4309
- const trimmed = cell.trim();
4310
- if (trimmed.length >= 2 && trimmed.startsWith("`") && trimmed.endsWith("`")) {
4311
- return trimmed.slice(1, -1);
4257
+ function checkT3(entries, ciTrancheSlug, enrichedEntries, forgeUnavailableSlugs) {
4258
+ const preEnforcement = new Set;
4259
+ if (enrichedEntries) {
4260
+ for (const e of enrichedEntries) {
4261
+ if (isGrandfathered(e.facts?.closedAt) || isGrandfathered(e.facts?.mergedAt)) {
4262
+ preEnforcement.add(e.trancheSlug);
4263
+ }
4264
+ }
4312
4265
  }
4313
- return trimmed;
4314
- }
4315
- function stripBold(cell) {
4316
- return cell.trim().replace(/\*\*/g, "");
4266
+ const failures = [];
4267
+ for (const e of entries) {
4268
+ if (!e.archived && e.task.issue === null) {
4269
+ if (ciTrancheSlug && e.trancheSlug !== ciTrancheSlug)
4270
+ continue;
4271
+ if (forgeUnavailableSlugs?.has(e.trancheSlug)) {
4272
+ failures.push({
4273
+ code: "tbd-in-active-tranche",
4274
+ issue: null,
4275
+ tranche: e.trancheSlug,
4276
+ task: e.task.id,
4277
+ 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`,
4278
+ grandfathered: true
4279
+ });
4280
+ continue;
4281
+ }
4282
+ failures.push({
4283
+ code: "tbd-in-active-tranche",
4284
+ issue: null,
4285
+ tranche: e.trancheSlug,
4286
+ task: e.task.id,
4287
+ 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`,
4288
+ grandfathered: preEnforcement.has(e.trancheSlug)
4289
+ });
4290
+ }
4291
+ }
4292
+ const activeFails = failures.filter((f) => !f.grandfathered);
4293
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
4294
+ return {
4295
+ check: "T3",
4296
+ status,
4297
+ failures,
4298
+ note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
4299
+ };
4317
4300
  }
4318
- function parseEnforcementRegistry(content) {
4319
- const lines = content.split(`
4320
- `);
4321
- const result = [];
4322
- for (const { ring, pattern } of RING_HEADINGS) {
4323
- const headingLine = findHeadingLine(lines, pattern);
4324
- if (headingLine === null)
4301
+ function checkD1(entries, issueToEntry, taskToEntry) {
4302
+ const failures = [];
4303
+ for (const e of entries) {
4304
+ if (!e.facts)
4325
4305
  continue;
4326
- const table = findTable(lines, headingLine + 1);
4327
- if (!table)
4306
+ if (e.facts.prState !== "open")
4328
4307
  continue;
4329
- const descriptionIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "description");
4330
- const implementationIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "implementation");
4331
- const audienceIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "audience");
4332
- for (const row of table.rows) {
4333
- const cells = row.cells;
4334
- if (cells.length < 3)
4308
+ for (const dep of e.task.dependsOn) {
4309
+ const depEntry = resolveDepEntry(dep, e.trancheSlug, issueToEntry, taskToEntry);
4310
+ if (!depEntry)
4335
4311
  continue;
4336
- const action = stripBold(cells[0] ?? "");
4337
- const summary = stripBackticks2(cells[1] ?? "");
4338
- const category = stripBackticks2(cells[2] ?? "");
4339
- const implementation = stripBackticks2((implementationIndex === -1 ? cells[cells.length - 1] : cells[implementationIndex]) ?? "");
4340
- const description = descriptionIndex === -1 ? undefined : stripBackticks2(cells[descriptionIndex] ?? "") || undefined;
4341
- const specIndex = (audienceIndex === -1 ? cells.length - 1 : audienceIndex) - 1;
4342
- const spec = specIndex >= 3 ? stripBackticks2(cells[specIndex] ?? "") || undefined : undefined;
4343
- const audience = audienceIndex === -1 ? "repo-own" : stripBackticks2(cells[audienceIndex] ?? "") === "product" ? "product" : "repo-own";
4344
- result.push({ ring, action, summary, category, description, spec, implementation, audience, line: row.line });
4312
+ const sameTask = depEntry.trancheSlug === e.trancheSlug && depEntry.task.id === e.task.id;
4313
+ const sameIssue = depEntry.task.issue !== null && e.task.issue !== null && depEntry.task.issue === e.task.issue;
4314
+ if (sameTask || sameIssue) {
4315
+ failures.push({
4316
+ code: "d1-self-dependency",
4317
+ issue: e.task.issue,
4318
+ tranche: e.trancheSlug,
4319
+ task: e.task.id,
4320
+ reason: `INTERNAL: parsed a self-dependency (depends-on ${dep}) — this is a parser bug in parseRationaleDeps, not a real dependency. Please report it upstream.`
4321
+ });
4322
+ continue;
4323
+ }
4324
+ const depFacts = depEntry.facts;
4325
+ const depClosed = depFacts?.issueState === "closed";
4326
+ if (!depClosed) {
4327
+ failures.push({
4328
+ code: "dispatched-on-unmet-deps",
4329
+ issue: e.task.issue,
4330
+ tranche: e.trancheSlug,
4331
+ task: e.task.id,
4332
+ reason: `Task has open PR but depends-on ${dep} (issue #${depEntry.task.issue ?? "?"}) is not closed`
4333
+ });
4334
+ }
4345
4335
  }
4346
4336
  }
4347
- return result;
4337
+ return { check: "D1", status: failures.length > 0 ? "fail" : "pass", failures };
4348
4338
  }
4349
- // ../../packages/aeg-core/src/registry-checks.ts
4350
- function checkG1(rows, existsFn) {
4351
- const findings = [];
4352
- for (const row of rows) {
4353
- if (row.implementation === "")
4354
- continue;
4355
- if (!existsFn(row.implementation)) {
4356
- findings.push({
4357
- row: row.action,
4358
- path: row.implementation,
4359
- reason: `${row.ring} row "${row.action}" names implementation "${row.implementation}", which does not exist on disk`
4339
+ function resolveDepEntry(dep, trancheSlug, issueToEntry, taskToEntry) {
4340
+ const issueMatch = dep.match(/^#(\d+)$/);
4341
+ if (issueMatch?.[1])
4342
+ return issueToEntry.get(Number(issueMatch[1]));
4343
+ return taskToEntry.get(`${trancheSlug}/${dep}`) ?? taskToEntry.get(dep);
4344
+ }
4345
+ function checkR1(issuesBySlug, grandfatheredIssues, registeredNames = [], objectivesSinceIssue) {
4346
+ const failures = [];
4347
+ for (const [slug, issues] of issuesBySlug) {
4348
+ for (const issue of issues) {
4349
+ if (!isTaskIssueLabelSet(issue.labels))
4350
+ continue;
4351
+ const errors = [
4352
+ ...checkIssueRationale(issue.body).errors,
4353
+ ...checkProjectsRegistered(issue.body, issue.labels, registeredNames).errors,
4354
+ ...checkIssueObjectives(issue.body, issue.number, objectivesSinceIssue).errors,
4355
+ ...checkPartsCiteDefinedObjectives(issue.body).errors
4356
+ ];
4357
+ if (errors.length === 0)
4358
+ continue;
4359
+ failures.push({
4360
+ code: "missing-rationale-field",
4361
+ issue: issue.number,
4362
+ tranche: slug,
4363
+ reason: `Issue #${issue.number} fails the rationale gate: ${errors.join(" | ")}`,
4364
+ grandfathered: grandfatheredIssues.has(issue.number)
4360
4365
  });
4361
4366
  }
4362
4367
  }
4363
- return { check: "G1", status: findings.length > 0 ? "fail" : "pass", findings };
4368
+ const activeFails = failures.filter((f) => !f.grandfathered);
4369
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
4370
+ return {
4371
+ check: "R1",
4372
+ status,
4373
+ failures,
4374
+ note: status === "info" ? `${failures.length} grandfathered task Issue(s) predate this check's grammar (rationale fields and/or the project registry)` : undefined
4375
+ };
4364
4376
  }
4365
- var SCAFFOLD_PLACEHOLDER = "[undocumented — fill in why]";
4366
- var NON_GATE_BIN_NAMES = NON_GATE_BINS;
4367
- var TWIN_CANDIDATE_EXCEPTIONS = {
4368
- "apps/cli/src/checks/bin/check-dead-branch-push.ts": 'Ring 0 "Pushing to a branch whose pull request already resolved" (implementation: check-push-target.ts)',
4369
- "apps/cli/src/checks/bin/check-issue-assignment.ts": `Ring 0 "A task branch's first push (Issue self-assignment)" (implementation: assign-task-issue.ts)`,
4370
- "apps/cli/src/checks/bin/check-closes-n.ts": 'Ring 1 "Closes linkage" (implementation: verify-coherence.ts)'
4371
- };
4372
- var NON_GATE_HOOK_SCRIPTS = [".claude/hooks/track-transcript.sh"];
4373
- function checkG2(rows, candidateFiles) {
4374
- const implementations = new Set(rows.map((r) => r.implementation).filter((p) => p !== ""));
4375
- const claimedNames = new Set(rows.flatMap((r) => claimedCheckNames(r.implementation)));
4376
- const findings = [];
4377
- for (const path of candidateFiles) {
4378
- if (implementations.has(path))
4379
- continue;
4380
- if (path.startsWith(AEG_CORE_BIN_PATH_PREFIX) && NON_GATE_BIN_NAMES.includes(basenameNoExt(path)))
4381
- continue;
4382
- if (NON_GATE_HOOK_SCRIPTS.includes(path))
4383
- continue;
4384
- if (path in TWIN_CANDIDATE_EXCEPTIONS)
4377
+ function checkL1(files, entriesBySlug) {
4378
+ const failures = [];
4379
+ for (const f of files) {
4380
+ if (f.archived)
4385
4381
  continue;
4386
- const candidateNames = claimedCheckNames(path);
4387
- if (candidateNames.length > 0 && candidateNames.some((n) => claimedNames.has(n)))
4382
+ const entries = entriesBySlug.get(f.slug) ?? [];
4383
+ const withFacts = entries.filter((e) => e.facts !== undefined);
4384
+ if (withFacts.length === 0)
4388
4385
  continue;
4389
- findings.push({
4390
- path,
4391
- reason: `"${path}" is not named as the implementation of any row in enforcement.md's ring tables`
4392
- });
4393
- }
4394
- for (const row of rows) {
4395
- const carriesPlaceholder = [row.summary, row.description, row.spec].some((cell) => cell === SCAFFOLD_PLACEHOLDER);
4396
- if (carriesPlaceholder) {
4397
- findings.push({
4398
- row: row.action,
4399
- path: row.implementation,
4400
- reason: `${row.ring} row "${row.action}" still carries the scaffold placeholder marker — the why is owed`
4386
+ const allClosed = withFacts.every((e) => e.facts?.issueState === "closed");
4387
+ if (allClosed) {
4388
+ failures.push({
4389
+ code: "archive-recommended",
4390
+ tranche: f.slug,
4391
+ reason: "Active tranche has no open task-Issues — consider archiving to completed/"
4401
4392
  });
4402
4393
  }
4403
4394
  }
4404
- return { check: "G2", status: findings.length > 0 ? "fail" : "pass", findings };
4395
+ return {
4396
+ check: "L1",
4397
+ status: "info",
4398
+ failures,
4399
+ note: failures.length > 0 ? `${failures.length} active tranche(s) with no open task-Issues — consider archiving (advisory)` : undefined
4400
+ };
4405
4401
  }
4406
- function checkG3(ring0Rows, crossingFiles) {
4407
- const ring0Implementations = new Set(ring0Rows.map((r) => r.implementation));
4408
- const findings = [];
4409
- for (const path of crossingFiles) {
4410
- if (!ring0Implementations.has(path)) {
4411
- findings.push({
4412
- path,
4413
- reason: `"${path}" makes a GitHub-crossing call but is not named by any Ring-0 row's implementation — a seventh, unlisted way into GitHub`
4414
- });
4415
- }
4416
- }
4417
- return { check: "G3", status: findings.length > 0 ? "fail" : "pass", findings };
4402
+ function checkL3(files) {
4403
+ const active = files.filter((f) => !f.archived);
4404
+ return {
4405
+ check: "L3",
4406
+ status: "info",
4407
+ failures: [],
4408
+ note: `${active.length} active tranche(s): ${active.map((f) => f.slug).join(", ") || "(none)"}`
4409
+ };
4418
4410
  }
4419
- function checkG4(content, resolveFn) {
4420
- const cited = new Set;
4421
- for (const hit of content.matchAll(/#(\d{3,})\b/g)) {
4422
- cited.add(Number(hit[1]));
4423
- }
4424
- const findings = [];
4425
- for (const n of cited) {
4426
- if (!resolveFn(n)) {
4427
- findings.push({
4428
- reason: `#${n} is cited in enforcement.md but does not resolve to a real Issue or PR in the forge`
4429
- });
4430
- }
4411
+ function extractClosesReferences(prBody) {
4412
+ const closesPattern = /(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s{0,8}:?\s{0,8}#(\d+)/gi;
4413
+ const stripped = stripCode(prBody);
4414
+ const searchIn = anchoredRegion(stripped, "CLOSES") ?? stripped;
4415
+ const referenced = new Set;
4416
+ for (const hit of searchIn.matchAll(closesPattern)) {
4417
+ referenced.add(Number(hit[1]));
4431
4418
  }
4432
- return { check: "G4", status: findings.length > 0 ? "fail" : "pass", findings };
4419
+ return referenced;
4433
4420
  }
4434
- function checkG5(roles, contracts) {
4435
- const roleIds = new Set(roles.map((r) => r.role_id));
4436
- const findings = [];
4437
- for (const contract of contracts) {
4438
- if (!roleIds.has(contract.producer)) {
4439
- findings.push({
4440
- path: contract.file,
4441
- reason: `contract "${contract.file}" names producer "${contract.producer}", which is not a real role_id`
4442
- });
4443
- }
4444
- if (!roleIds.has(contract.consumer)) {
4445
- findings.push({
4446
- path: contract.file,
4447
- reason: `contract "${contract.file}" names consumer "${contract.consumer}", which is not a real role_id`
4448
- });
4421
+ function checkClosesNTopology(branch, prBody, trancheFiles, taskIssueRefs) {
4422
+ const referenced = extractClosesReferences(prBody);
4423
+ if (taskIssueRefs) {
4424
+ for (const n of referenced) {
4425
+ const ref = taskIssueRefs.get(n);
4426
+ if (!ref)
4427
+ continue;
4428
+ const expectedBranch = `task/${ref.trancheSlug}/${ref.taskId}`;
4429
+ if (branch !== expectedBranch) {
4430
+ return {
4431
+ ok: false,
4432
+ 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.`
4433
+ };
4434
+ }
4449
4435
  }
4450
4436
  }
4451
- for (const role of roles) {
4452
- if (role.performs.length === 0) {
4453
- findings.push({ path: role.file, reason: `role "${role.role_id}" has an empty performs array` });
4454
- }
4455
- if (role.refuses_when.trim() === "") {
4456
- findings.push({ path: role.file, reason: `role "${role.role_id}" has an empty refuses_when` });
4437
+ const ref = parseTaskBranchIdentity(branch);
4438
+ if (!ref)
4439
+ return { ok: true };
4440
+ if (ref.kind === "issue") {
4441
+ const expectedIssue = ref.issueNumber;
4442
+ if (!referenced.has(expectedIssue)) {
4443
+ return {
4444
+ ok: false,
4445
+ expectedIssue,
4446
+ message: `closes-n: PR body does not contain \`Closes #${expectedIssue}\` (required for branch "${branch}"). Add it to the PR body Summary section.`
4447
+ };
4457
4448
  }
4449
+ return { ok: true, expectedIssue };
4458
4450
  }
4459
- return { check: "G5", status: findings.length > 0 ? "fail" : "pass", findings };
4460
- }
4461
- var SHIPPED_BIN_PATH_PREFIX = "apps/cli/src/checks/bin/check-";
4462
- var AEG_CORE_BIN_PATH_PREFIX = "packages/aeg-core/bin/";
4463
- function basenameNoExt(path) {
4464
- const base = path.slice(path.lastIndexOf("/") + 1);
4465
- return base.replace(/\.ts$/, "");
4466
- }
4467
- function claimedCheckNames(implementation) {
4468
- if (implementation.startsWith(SHIPPED_BIN_PATH_PREFIX) && implementation.endsWith(".ts")) {
4469
- return [implementation.slice(SHIPPED_BIN_PATH_PREFIX.length, -".ts".length)];
4451
+ const trancheSlug = ref.tranche;
4452
+ const taskId = ref.taskId;
4453
+ const trancheFile = trancheFiles.find((f) => f.slug === trancheSlug);
4454
+ if (!trancheFile) {
4455
+ return {
4456
+ ok: false,
4457
+ 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.`
4458
+ };
4470
4459
  }
4471
- if (implementation.startsWith(AEG_CORE_BIN_PATH_PREFIX)) {
4472
- const audience = GATE_AUDIENCE[basenameNoExt(implementation)];
4473
- if (audience && isShipped(audience)) {
4474
- return Array.isArray(audience.shippedAs) ? audience.shippedAs : [audience.shippedAs];
4475
- }
4460
+ const task = trancheFile.tranche.tasks.find((t) => t.id === taskId);
4461
+ if (!task) {
4462
+ return {
4463
+ ok: false,
4464
+ message: `closes-n: branch "${branch}" references task "${taskId}" not found in ${trancheSlug} topology. Verify the task ID matches the tranche file.`
4465
+ };
4476
4466
  }
4477
- return [];
4467
+ if (task.issue === null) {
4468
+ return {
4469
+ ok: false,
4470
+ message: `closes-n: task "${taskId}" in "${trancheSlug}" has no Issue number (#TBD). The Planner must cut the Issue before this PR can be validated.`
4471
+ };
4472
+ }
4473
+ const expectedIssue = task.issue;
4474
+ if (!referenced.has(expectedIssue)) {
4475
+ return {
4476
+ ok: false,
4477
+ expectedIssue,
4478
+ 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.`
4479
+ };
4480
+ }
4481
+ return { ok: true, expectedIssue };
4478
4482
  }
4479
- function checkG6(rows, registeredCheckNames) {
4480
- const findings = [];
4481
- for (const row of rows) {
4482
- if (row.audience !== "product")
4483
- continue;
4484
- const candidates = claimedCheckNames(row.implementation);
4485
- if (!candidates.some((name) => registeredCheckNames.has(name))) {
4486
- findings.push({
4487
- row: row.action,
4488
- path: row.implementation,
4489
- reason: `${row.ring} row "${row.action}" is marked \`product\` but its implementation "${row.implementation}" does not resolve to a coreCheckRegistry() entry`
4490
- });
4491
- }
4483
+ // ../../packages/aeg-core/src/archive-task.ts
4484
+ function closesRefs(text) {
4485
+ return [...new Set([...text.matchAll(/Closes #(\d+)/gi)].map((m) => Number(m[1])))];
4486
+ }
4487
+ function extractIssue(body) {
4488
+ const stripped = stripCode(body);
4489
+ const bodyNums = closesRefs(stripped);
4490
+ const anchored = anchoredRegion(stripped, "CLOSES");
4491
+ if (anchored !== null) {
4492
+ const anchorNums = closesRefs(anchored);
4493
+ if (anchorNums.length === 0)
4494
+ return { issue: null, extraIssues: bodyNums, outsideHeader: false };
4495
+ const issue = anchorNums[0];
4496
+ return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: false };
4492
4497
  }
4493
- return { check: "G6", status: findings.length > 0 ? "fail" : "pass", findings };
4498
+ const headerNums = closesRefs(headerRegion(stripped));
4499
+ if (bodyNums.length === 0)
4500
+ return { issue: null, extraIssues: [], outsideHeader: false };
4501
+ const issue = headerNums.length > 0 ? headerNums[0] : bodyNums[0];
4502
+ return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: headerNums.length === 0 };
4494
4503
  }
4495
- // ../../packages/aeg-core/src/reader-resolvable-prose.ts
4496
- var PRODUCT_SLUG_SCOPE = [
4497
- "apps/cli/src",
4498
- ".github/workflows",
4499
- ".vinaya",
4500
- "apps/cli/README.md",
4501
- "packages/sources/README.md"
4502
- ];
4503
- function isUnderOrEqual(path, prefix) {
4504
- return path === prefix || path.startsWith(`${prefix}/`);
4504
+ // ../../packages/aeg-core/src/review-input-manifest.ts
4505
+ import { createHash as createHash4 } from "node:crypto";
4506
+ function briefHash(brief) {
4507
+ return createHash4("sha256").update(`${brief}
4508
+ `).digest("hex");
4505
4509
  }
4506
- function isProductScopeFile(path) {
4507
- return PRODUCT_SLUG_SCOPE.some((prefix) => isUnderOrEqual(path, prefix));
4510
+ function policyDigest(policy) {
4511
+ return createHash4("sha256").update(JSON.stringify({
4512
+ codeReviewThreshold: policy.codeReviewThreshold,
4513
+ securityThreshold: policy.securityThreshold,
4514
+ maxRounds: policy.maxRounds
4515
+ })).digest("hex");
4508
4516
  }
4509
- var SHIPS_PREFIX = "aeg-root/";
4510
- function shipsArchivePrefix(shipsPrefix) {
4511
- return `${shipsPrefix}tranches/completed/`;
4517
+ function isBoundToHead(echoed, headSha) {
4518
+ if (!echoed.headSha)
4519
+ return false;
4520
+ return headSha.toLowerCase().startsWith(echoed.headSha.toLowerCase());
4512
4521
  }
4513
- var DEFAULT_SPEC_PATHS = ["SPEC.md", "CONTEXT.md", "docs/adr"];
4514
- function normalizeSpecPath(entry) {
4515
- let out = entry.replace(/\\/g, "/");
4516
- while (out.startsWith("./"))
4517
- out = out.slice(2);
4518
- out = out.replace(/\/{2,}/g, "/");
4519
- while (out.endsWith("/"))
4520
- out = out.slice(0, -1);
4521
- return out;
4522
+ function isBoundByPatchIdentity(echoed, headSha, patchIdOf) {
4523
+ if (patchIdOf === undefined || !echoed.headSha)
4524
+ return false;
4525
+ const judged = patchIdOf(echoed.headSha);
4526
+ const current = patchIdOf(headSha);
4527
+ if (judged === null || current === null)
4528
+ return false;
4529
+ return judged === current;
4522
4530
  }
4523
- function isSpecFile2(path, specPaths) {
4524
- if (path.startsWith("apps/") && path.includes("/specs/") && path.endsWith(".md"))
4531
+ function isBoundToBase(echoed, currentBase) {
4532
+ if (currentBase === null)
4525
4533
  return true;
4526
- if (!path.endsWith(".md"))
4534
+ if (!echoed.baseSha)
4527
4535
  return false;
4528
- return specPaths.some((entry) => isUnderOrEqual(path, normalizeSpecPath(entry)));
4536
+ return currentBase.toLowerCase().startsWith(echoed.baseSha.toLowerCase());
4529
4537
  }
4530
- function isClaudeMdFile(path) {
4531
- return path === "CLAUDE.md" || path.endsWith("/CLAUDE.md");
4538
+ function isBoundToObjectives(echoed, currentVersion) {
4539
+ if (currentVersion === null)
4540
+ return true;
4541
+ return echoed.objectivesVersion === currentVersion;
4532
4542
  }
4533
- function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS) {
4534
- if (path.startsWith(shipsPrefix)) {
4535
- return path.startsWith(shipsArchivePrefix(shipsPrefix)) ? "internal" : "ships";
4543
+ function isBoundToRulings(echoed, currentOrdinal) {
4544
+ if (echoed.rulingOrdinal === null)
4545
+ return currentOrdinal === 0;
4546
+ return echoed.rulingOrdinal === currentOrdinal;
4547
+ }
4548
+ function isBoundToBriefHash(echoed, currentHash) {
4549
+ if (currentHash === null)
4550
+ return true;
4551
+ return echoed.briefHash === currentHash;
4552
+ }
4553
+ function isBoundToPolicy(echoed, currentDigest) {
4554
+ return echoed.policyDigest === currentDigest;
4555
+ }
4556
+ function compareManifest(echoed, current, patchIdOf) {
4557
+ const exactHead = isBoundToHead(echoed, current.headSha);
4558
+ const patchHead = exactHead ? false : isBoundByPatchIdentity(echoed, current.headSha, patchIdOf);
4559
+ const head = exactHead || patchHead;
4560
+ const echoedShaLen = echoed.baseSha?.length ?? 0;
4561
+ const currentShaLen = current.baseSha?.length ?? 0;
4562
+ const bothFullShas = echoedShaLen >= 40 && currentShaLen >= 40;
4563
+ const base = patchHead || exactHead && bothFullShas ? true : isBoundToBase(echoed, current.baseSha);
4564
+ const briefHashBound = isBoundToBriefHash(echoed, current.briefHash);
4565
+ const objectivesVersion = isBoundToObjectives(echoed, current.objectivesVersion);
4566
+ const rulingOrdinal = isBoundToRulings(echoed, current.rulingOrdinal);
4567
+ const policyDigestBound = isBoundToPolicy(echoed, current.policyDigest);
4568
+ return {
4569
+ bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && policyDigestBound,
4570
+ head,
4571
+ base,
4572
+ briefHash: briefHashBound,
4573
+ objectivesVersion,
4574
+ rulingOrdinal,
4575
+ policyDigest: policyDigestBound
4576
+ };
4577
+ }
4578
+
4579
+ // ../../packages/aeg-core/src/review-gate.ts
4580
+ function renderGateDeferred(deferred) {
4581
+ if (deferred.length === 0)
4582
+ return "";
4583
+ const items = deferred.map((d) => {
4584
+ const where = d.finding.location && d.finding.location.length > 0 ? d.finding.location : "(no location)";
4585
+ return `${d.finding.severity} ${where} (${DEFERRAL_REASON_TEXT[d.reason]})`;
4586
+ }).join("; ");
4587
+ return ` ${deferred.length} finding(s) deferred, not blocking this round: ${items}.`;
4588
+ }
4589
+ function checkReviewGate(input) {
4590
+ const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
4591
+ const waived = isWaiverLabelActorVerified({
4592
+ label: WAIVER_LABEL_REVIEW,
4593
+ labels: input.labels,
4594
+ labelActor: input.waiverLabelActor,
4595
+ principalAllowlist
4596
+ });
4597
+ if (waived) {
4598
+ return {
4599
+ verdict: "pass",
4600
+ reason: `\`${WAIVER_LABEL_REVIEW}\` label is actor-verified — review requirement waived for this PR.`,
4601
+ waived: true
4602
+ };
4536
4603
  }
4537
- if (path.startsWith(readerFacingPrefix) && path.endsWith(readerFacingSuffix)) {
4538
- return "reader-facing";
4604
+ const verified = input.comments.filter((c) => isPrincipal(c.author, principalAllowlist));
4605
+ const ignoredCount = input.comments.filter((c) => !isPrincipal(c.author, principalAllowlist) && c.body.includes("VERDICT")).length;
4606
+ const verifiedBodies = verified.map((c) => c.body);
4607
+ const codeReview = extractCodeReviewVerdict(verifiedBodies);
4608
+ const security = extractSecurityReviewVerdict(verifiedBodies);
4609
+ const policy = input.policy ?? DEFAULT_REVIEW_POLICY;
4610
+ let codeReviewPolicyEvaluation;
4611
+ let securityPolicyEvaluation;
4612
+ try {
4613
+ codeReviewPolicyEvaluation = evaluateCodeReview(consequentialFindings(codeReview.findingSeverities), policy, input.deferralContext);
4614
+ securityPolicyEvaluation = evaluateSecurityReview(consequentialFindings(security.findingSeverities), policy, input.deferralContext);
4615
+ } catch (err) {
4616
+ return {
4617
+ verdict: "fail",
4618
+ reason: `a verdict comment carries a finding severity this repository's policy does not recognize: ${err instanceof Error ? err.message : String(err)}`,
4619
+ waived: false
4620
+ };
4539
4621
  }
4540
- if (isClaudeMdFile(path))
4541
- return "internal";
4542
- if (isSpecFile2(path, specPaths))
4543
- return "spec";
4544
- if (isProductScopeFile(path))
4545
- return "product";
4546
- return null;
4547
- }
4548
- var SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
4549
- function stripNonProse(path, content) {
4550
- if (path.endsWith(".md")) {
4551
- return content.replace(/```.*?```/gs, (m) => m.replace(/[^\n]/g, "")).replace(/`[^`\n]*`/g, (m) => m.replace(/[^\n]/g, ""));
4622
+ const codeReviewTextClean = codeReview.value === "APPROVE";
4623
+ const securityTextClean = security.value === "PASS";
4624
+ const codeReviewPolicyClean = codeReviewPolicyEvaluation.outcome === "clean";
4625
+ const securityPolicyClean = securityPolicyEvaluation.outcome === "clean";
4626
+ const codeReviewClean = codeReviewTextClean && codeReviewPolicyClean;
4627
+ const securityClean = securityTextClean && securityPolicyClean;
4628
+ const currentManifest = {
4629
+ headSha: input.headSha,
4630
+ baseSha: input.baseSha ?? null,
4631
+ briefHash: input.briefHash ?? null,
4632
+ objectivesVersion: input.objectivesVersion,
4633
+ rulingOrdinal: input.rulingOrdinal,
4634
+ policyDigest: policyDigest(policy)
4635
+ };
4636
+ const codeReviewEchoed = {
4637
+ headSha: codeReview.headSha,
4638
+ baseSha: codeReview.baseSha,
4639
+ briefHash: codeReview.briefHash,
4640
+ objectivesVersion: codeReview.objectivesVersion,
4641
+ rulingOrdinal: codeReview.rulingOrdinal,
4642
+ policyDigest: codeReview.policyDigest
4643
+ };
4644
+ const securityEchoed = {
4645
+ headSha: security.headSha,
4646
+ baseSha: security.baseSha,
4647
+ briefHash: security.briefHash,
4648
+ objectivesVersion: security.objectivesVersion,
4649
+ rulingOrdinal: security.rulingOrdinal,
4650
+ policyDigest: security.policyDigest
4651
+ };
4652
+ const codeReviewBinding = compareManifest(codeReviewEchoed, currentManifest, input.patchIdOf);
4653
+ const securityBinding = compareManifest(securityEchoed, currentManifest, input.patchIdOf);
4654
+ const codeReviewBound = codeReviewBinding.head;
4655
+ const securityBound = securityBinding.head;
4656
+ const codeReviewObjectivesBound = codeReviewBinding.objectivesVersion;
4657
+ const securityObjectivesBound = securityBinding.objectivesVersion;
4658
+ const codeReviewRulingsBound = codeReviewBinding.rulingOrdinal;
4659
+ const securityRulingsBound = securityBinding.rulingOrdinal;
4660
+ const deferredNote = renderGateDeferred([
4661
+ ...codeReviewPolicyEvaluation.deferredFindings,
4662
+ ...securityPolicyEvaluation.deferredFindings
4663
+ ]);
4664
+ if (codeReviewClean && codeReviewBinding.bound && securityClean && securityBinding.bound) {
4665
+ return {
4666
+ verdict: "pass",
4667
+ reason: `code-reviewer verdict is a clean APPROVE and security-review verdict is a clean PASS, both covering head ${input.headSha}.${deferredNote}`,
4668
+ waived: false
4669
+ };
4552
4670
  }
4553
- if (path.endsWith(".tsx") || path.endsWith(".ts")) {
4554
- return content.replace(/\/\*.*?\*\//gs, (m) => m.replace(/[^\n]/g, "")).replace(/(^|[^:])\/\/[^\n]*/g, (m) => m.replace(/[^\n]/g, ""));
4671
+ const problems = [];
4672
+ if (!codeReviewTextClean) {
4673
+ problems.push(`code-reviewer verdict is not a clean APPROVE (found: ${codeReview.value})`);
4674
+ } else if (!codeReviewPolicyClean) {
4675
+ 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`);
4676
+ } else if (!codeReviewBound) {
4677
+ problems.push(`the newest code-review verdict covers ${codeReview.headSha ?? "no recorded commit"}, head is ${input.headSha}`);
4678
+ } else if (!codeReviewBinding.base) {
4679
+ 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)`);
4680
+ } else if (!codeReviewObjectivesBound) {
4681
+ problems.push(`the newest code-review verdict was cast against objectives version ${codeReview.objectivesVersion ?? "none"}, the Issue's list is now ${input.objectivesVersion}`);
4682
+ } else if (!codeReviewRulingsBound) {
4683
+ 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`);
4684
+ } else if (!codeReviewBinding.briefHash) {
4685
+ 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"}`);
4686
+ } else if (!codeReviewBinding.policyDigest) {
4687
+ problems.push(`the newest code-review verdict was cast against review policy digest ${codeReview.policyDigest ?? "none"}, this repository's current policy digest is ${currentManifest.policyDigest}`);
4555
4688
  }
4556
- return content;
4557
- }
4558
- function stripNonProseForProduct(path, content) {
4559
- return path.endsWith(".md") ? stripNonProse(path, content) : content;
4560
- }
4561
- function lineAt(content, index) {
4562
- let line = 1;
4563
- for (let i = 0;i < index; i++) {
4564
- if (content.charCodeAt(i) === 10)
4565
- line++;
4689
+ if (!securityTextClean) {
4690
+ problems.push(`security-review verdict is not a clean PASS (found: ${security.value})`);
4691
+ } else if (!securityPolicyClean) {
4692
+ 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`);
4693
+ } else if (!securityBound) {
4694
+ problems.push(`the newest security-review verdict covers ${security.headSha ?? "no recorded commit"}, head is ${input.headSha}`);
4695
+ } else if (!securityBinding.base) {
4696
+ 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)`);
4697
+ } else if (!securityObjectivesBound) {
4698
+ problems.push(`the newest security-review verdict was cast against objectives version ${security.objectivesVersion ?? "none"}, the Issue's list is now ${input.objectivesVersion}`);
4699
+ } else if (!securityRulingsBound) {
4700
+ 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`);
4701
+ } else if (!securityBinding.briefHash) {
4702
+ 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"}`);
4703
+ } else if (!securityBinding.policyDigest) {
4704
+ problems.push(`the newest security-review verdict was cast against review policy digest ${security.policyDigest ?? "none"}, this repository's current policy digest is ${currentManifest.policyDigest}`);
4566
4705
  }
4567
- return line;
4568
- }
4569
- var FORGE_NUMBER_PATTERN = /#[0-9]{2,4}/g;
4570
- var TRANCHE_SLUG_VN_PATTERN = /[a-z][a-z-]+-v[0-9]/g;
4571
- var TASK_NUMBER_PATTERN = /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi;
4572
- function legacySlugPattern(legacySlugs) {
4573
- if (legacySlugs.length === 0)
4574
- return null;
4575
- const alternation = legacySlugs.map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
4576
- return new RegExp(`(^|[^a-zA-Z0-9\\n-])(${alternation})([^a-zA-Z0-9\\n-]|$)`, "g");
4706
+ const ignoredNote = ignoredCount > 0 ? ` ${ignoredCount} verdict-shaped comment(s) from authors outside the principal allowlist were ignored.` : "";
4707
+ return {
4708
+ verdict: "fail",
4709
+ 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}`,
4710
+ waived: false
4711
+ };
4577
4712
  }
4578
- function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4579
- const findings = [];
4580
- const legacyPattern = legacySlugPattern(legacySlugs);
4581
- const grandfathered = new Set(specGrandfather);
4582
- const patterns = [
4583
- { pattern: FORGE_NUMBER_PATTERN, what: "a forge number" },
4584
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug" },
4585
- ...legacyPattern ? [{ pattern: legacyPattern, what: "an internal tranche slug", group: 2 }] : []
4586
- ];
4587
- const productPatterns = [
4588
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug in product code" }
4589
- ];
4590
- const specPatterns = [
4591
- ...patterns,
4592
- { pattern: TASK_NUMBER_PATTERN, what: "a task number", group: 2 }
4593
- ];
4594
- for (const file of files) {
4595
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths);
4596
- if (!cls || cls === "internal")
4597
- continue;
4598
- if (cls !== "product" && cls !== "spec" && !SWEPT_CLASSES.has(cls))
4713
+ var CHANGESET_RELEASE_BRANCH = "changeset-release/main";
4714
+ var DEFAULT_RELEASE_ACTOR = "github-actions[bot]";
4715
+ function isChangesetsReleasePr(branch, author, expectedAuthor) {
4716
+ return branch === CHANGESET_RELEASE_BRANCH && author === expectedAuthor;
4717
+ }
4718
+ // ../../packages/aeg-core/src/ruling-ordinal.ts
4719
+ var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
4720
+ function newestPrincipalRulingOrdinal(comments, allowlist) {
4721
+ let best = 0;
4722
+ for (const c of comments) {
4723
+ if (!isPrincipal(c.author, allowlist))
4599
4724
  continue;
4600
- if (cls === "spec" && grandfathered.has(file.path))
4725
+ const firstLine = (c.body.split(`
4726
+ `)[0] ?? "").trim();
4727
+ const m = RULING_MARKER_ORDINAL.exec(firstLine);
4728
+ if (!m)
4601
4729
  continue;
4602
- const blocking = cls === "product" || cls === "spec";
4603
- const scrubbed = cls === "product" ? stripNonProseForProduct(file.path, file.content) : stripNonProse(file.path, file.content);
4604
- const patternsToRun = cls === "product" ? productPatterns : cls === "spec" ? specPatterns : patterns;
4605
- for (const { pattern, what, group } of patternsToRun) {
4606
- pattern.lastIndex = 0;
4607
- let match = pattern.exec(scrubbed);
4608
- while (match !== null) {
4609
- const cited = group !== undefined ? match[group] ?? match[0] : match[0];
4610
- const citedIndex = match.index + match[0].indexOf(cited);
4611
- findings.push({
4612
- file: file.path,
4613
- line: lineAt(scrubbed, citedIndex),
4614
- message: `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
4615
- blocking
4616
- });
4617
- match = pattern.exec(scrubbed);
4618
- }
4619
- }
4730
+ const k = Number.parseInt(m[1], 10);
4731
+ if (k > best)
4732
+ best = k;
4620
4733
  }
4621
- return findings;
4622
- }
4623
- function escapeTerm(term) {
4624
- return term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4734
+ return best;
4625
4735
  }
4626
- function containsWholeWord(text, term) {
4627
- const escaped = escapeTerm(term);
4628
- const re = new RegExp(`(^|[^a-zA-Z])${escaped}([^a-zA-Z]|$)`, "i");
4629
- return re.test(text);
4736
+ // ../../packages/aeg-core/src/markdown-table.ts
4737
+ function splitRow(line) {
4738
+ const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
4739
+ return trimmed.split("|").map((cell) => cell.trim());
4630
4740
  }
4631
- function findWholeWordLine(content, term) {
4632
- const lines = content.split(`
4633
- `);
4634
- let lineNo = 0;
4635
- for (const line of lines) {
4636
- lineNo++;
4637
- if (containsWholeWord(line, term))
4638
- return lineNo;
4741
+ var TABLE_ROW_PATTERN = /^\s*\|.*\|\s*$/;
4742
+ var SEPARATOR_ROW_PATTERN = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
4743
+ function findTable(lines, fromLine, stopAtHeading = true) {
4744
+ let i = fromLine - 1;
4745
+ while (i < lines.length) {
4746
+ const line = lines[i] ?? "";
4747
+ if (stopAtHeading && i > fromLine - 1 && /^##\s/.test(line))
4748
+ return null;
4749
+ if (TABLE_ROW_PATTERN.test(line)) {
4750
+ const headerLine = line;
4751
+ const sepLine = lines[i + 1] ?? "";
4752
+ if (!SEPARATOR_ROW_PATTERN.test(sepLine)) {
4753
+ i++;
4754
+ continue;
4755
+ }
4756
+ const headers = splitRow(headerLine);
4757
+ const rows = [];
4758
+ let j = i + 2;
4759
+ while (j < lines.length && TABLE_ROW_PATTERN.test(lines[j] ?? "")) {
4760
+ rows.push({ cells: splitRow(lines[j] ?? ""), line: j + 1 });
4761
+ j++;
4762
+ }
4763
+ return { headers, rows };
4764
+ }
4765
+ i++;
4639
4766
  }
4640
4767
  return null;
4641
4768
  }
4642
- function definesOrLinksGlossary(content, term) {
4643
- const escaped = escapeTerm(term);
4644
- const definesInline = new RegExp(`(^|[^a-zA-Z])${escaped}([^a-zA-Z]|$)[^\\n]{0,3}—`, "i").test(content);
4645
- if (definesInline)
4646
- return true;
4647
- return /docs\/glossary|glossary\.md/i.test(content);
4769
+ function findHeadingLine(lines, pattern) {
4770
+ for (let i = 0;i < lines.length; i++) {
4771
+ if (pattern.test(lines[i] ?? ""))
4772
+ return i + 1;
4773
+ }
4774
+ return null;
4648
4775
  }
4649
- function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX) {
4650
- const findings = [];
4651
- for (const file of files) {
4652
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
4653
- if (!cls || !SWEPT_CLASSES.has(cls))
4654
- continue;
4655
- const scrubbed = stripNonProse(file.path, file.content);
4656
- for (const term of glossaryTerms) {
4657
- const line = findWholeWordLine(scrubbed, term);
4658
- if (line === null)
4659
- continue;
4660
- if (definesOrLinksGlossary(scrubbed, term))
4661
- continue;
4662
- findings.push({
4663
- file: file.path,
4664
- line,
4665
- message: `uses coined term "${term}" without defining it inline or linking the glossary`,
4666
- blocking: false
4667
- });
4668
- }
4776
+ // ../../packages/aeg-core/src/diagram-model.ts
4777
+ import matter from "gray-matter";
4778
+
4779
+ // ../../packages/aeg-core/src/registry-parse.ts
4780
+ var RING_HEADINGS = [
4781
+ { ring: "ring0", pattern: /^##\s+Ring 0\b/ },
4782
+ { ring: "ring1", pattern: /^##\s+Ring 1\b/ },
4783
+ { ring: "ring2", pattern: /^##\s+Ring 2\b/ }
4784
+ ];
4785
+ function stripBackticks2(cell) {
4786
+ const trimmed = cell.trim();
4787
+ if (trimmed.length >= 2 && trimmed.startsWith("`") && trimmed.endsWith("`")) {
4788
+ return trimmed.slice(1, -1);
4669
4789
  }
4670
- return findings;
4790
+ return trimmed;
4671
4791
  }
4672
- var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g;
4673
- var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = /#[0-9]{2,}/g;
4674
- function extractComments(path, content) {
4675
- if (!path.endsWith(".ts") && !path.endsWith(".tsx"))
4676
- return content.replace(/[^\n]/g, "");
4677
- let state = "code";
4678
- let out = "";
4679
- const n = content.length;
4680
- let i = 0;
4681
- const blank = (ch) => ch === `
4682
- ` ? `
4683
- ` : " ";
4684
- while (i < n) {
4685
- const c = content[i];
4686
- const next = i + 1 < n ? content[i + 1] : "";
4687
- if (state === "code") {
4688
- if (c === "/" && next === "/") {
4689
- state = "line-comment";
4690
- out += c;
4691
- i++;
4692
- continue;
4693
- }
4694
- if (c === "/" && next === "*") {
4695
- state = "block-comment";
4696
- out += c;
4697
- i++;
4698
- continue;
4699
- }
4700
- if (c === "'") {
4701
- state = "single-quote";
4702
- out += blank(c);
4703
- i++;
4704
- continue;
4705
- }
4706
- if (c === '"') {
4707
- state = "double-quote";
4708
- out += blank(c);
4709
- i++;
4710
- continue;
4711
- }
4712
- if (c === "`") {
4713
- state = "template";
4714
- out += blank(c);
4715
- i++;
4716
- continue;
4717
- }
4718
- out += blank(c);
4719
- i++;
4792
+ function stripBold(cell) {
4793
+ return cell.trim().replace(/\*\*/g, "");
4794
+ }
4795
+ function parseEnforcementRegistry(content) {
4796
+ const lines = content.split(`
4797
+ `);
4798
+ const result = [];
4799
+ for (const { ring, pattern } of RING_HEADINGS) {
4800
+ const headingLine = findHeadingLine(lines, pattern);
4801
+ if (headingLine === null)
4720
4802
  continue;
4721
- }
4722
- if (state === "line-comment") {
4723
- if (c === `
4724
- `) {
4725
- state = "code";
4726
- out += `
4727
- `;
4728
- i++;
4729
- continue;
4730
- }
4731
- out += c;
4732
- i++;
4803
+ const table = findTable(lines, headingLine + 1);
4804
+ if (!table)
4733
4805
  continue;
4734
- }
4735
- if (state === "block-comment") {
4736
- if (c === "*" && next === "/") {
4737
- out += c;
4738
- out += next;
4739
- state = "code";
4740
- i += 2;
4806
+ const descriptionIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "description");
4807
+ const implementationIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "implementation");
4808
+ const audienceIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "audience");
4809
+ for (const row of table.rows) {
4810
+ const cells = row.cells;
4811
+ if (cells.length < 3)
4741
4812
  continue;
4742
- }
4743
- out += c === `
4744
- ` ? `
4745
- ` : c;
4746
- i++;
4747
- continue;
4748
- }
4749
- const closer = state === "single-quote" ? "'" : state === "double-quote" ? '"' : "`";
4750
- if (c === "\\") {
4751
- out += blank(c);
4752
- i++;
4753
- if (i < n) {
4754
- out += blank(content[i]);
4755
- i++;
4756
- }
4757
- continue;
4813
+ const action = stripBold(cells[0] ?? "");
4814
+ const summary = stripBackticks2(cells[1] ?? "");
4815
+ const category = stripBackticks2(cells[2] ?? "");
4816
+ const implementation = stripBackticks2((implementationIndex === -1 ? cells[cells.length - 1] : cells[implementationIndex]) ?? "");
4817
+ const description = descriptionIndex === -1 ? undefined : stripBackticks2(cells[descriptionIndex] ?? "") || undefined;
4818
+ const specIndex = (audienceIndex === -1 ? cells.length - 1 : audienceIndex) - 1;
4819
+ const spec = specIndex >= 3 ? stripBackticks2(cells[specIndex] ?? "") || undefined : undefined;
4820
+ const audience = audienceIndex === -1 ? "repo-own" : stripBackticks2(cells[audienceIndex] ?? "") === "product" ? "product" : "repo-own";
4821
+ result.push({ ring, action, summary, category, description, spec, implementation, audience, line: row.line });
4758
4822
  }
4759
- if (c === closer) {
4760
- state = "code";
4761
- out += blank(c);
4762
- i++;
4823
+ }
4824
+ return result;
4825
+ }
4826
+ // ../../packages/aeg-core/src/registry-checks.ts
4827
+ function checkG1(rows, existsFn) {
4828
+ const findings = [];
4829
+ for (const row of rows) {
4830
+ if (row.implementation === "")
4763
4831
  continue;
4832
+ if (!existsFn(row.implementation)) {
4833
+ findings.push({
4834
+ row: row.action,
4835
+ path: row.implementation,
4836
+ reason: `${row.ring} row "${row.action}" names implementation "${row.implementation}", which does not exist on disk`
4837
+ });
4764
4838
  }
4765
- out += blank(c);
4766
- i++;
4767
4839
  }
4768
- return out;
4840
+ return { check: "G1", status: findings.length > 0 ? "fail" : "pass", findings };
4769
4841
  }
4770
- function checkSourceComments(files, allowlist = []) {
4842
+ var SCAFFOLD_PLACEHOLDER = "[undocumented — fill in why]";
4843
+ var NON_GATE_BIN_NAMES = NON_GATE_BINS;
4844
+ var TWIN_CANDIDATE_EXCEPTIONS = {
4845
+ "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)',
4846
+ "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)`,
4847
+ "apps/cli/src/checks/bin/check-closes-n.ts": 'Ring 1 "Closes linkage" (implementation: verify-coherence.ts)'
4848
+ };
4849
+ var NON_GATE_HOOK_SCRIPTS = [".claude/hooks/track-transcript.sh"];
4850
+ function checkG2(rows, candidateFiles) {
4851
+ const implementations = new Set(rows.map((r) => r.implementation).filter((p) => p !== ""));
4852
+ const claimedNames = new Set(rows.flatMap((r) => claimedCheckNames(r.implementation)));
4771
4853
  const findings = [];
4772
- const allowed = new Set(allowlist);
4773
- const patterns = [
4774
- { pattern: SOURCE_COMMENT_TRANCHE_SLUG_PATTERN, what: "a tranche-slug citation" },
4775
- { pattern: SOURCE_COMMENT_FORGE_NUMBER_PATTERN, what: "a forge-number citation" }
4776
- ];
4777
- for (const file of files) {
4778
- if (!file.path.endsWith(".ts"))
4854
+ for (const path of candidateFiles) {
4855
+ if (implementations.has(path))
4779
4856
  continue;
4780
- if (allowed.has(file.path))
4857
+ if (path.startsWith(AEG_CORE_BIN_PATH_PREFIX) && NON_GATE_BIN_NAMES.includes(basenameNoExt(path)))
4781
4858
  continue;
4782
- const comments = extractComments(file.path, file.content);
4783
- for (const { pattern, what } of patterns) {
4784
- pattern.lastIndex = 0;
4785
- let match = pattern.exec(comments);
4786
- while (match !== null) {
4787
- findings.push({
4788
- file: file.path,
4789
- line: lineAt(comments, match.index),
4790
- message: `comment cites ${what} ("${match[0]}") a reader outside this repo's tracker cannot resolve`,
4791
- blocking: false
4792
- });
4793
- match = pattern.exec(comments);
4794
- }
4859
+ if (NON_GATE_HOOK_SCRIPTS.includes(path))
4860
+ continue;
4861
+ if (path in TWIN_CANDIDATE_EXCEPTIONS)
4862
+ continue;
4863
+ const candidateNames = claimedCheckNames(path);
4864
+ if (candidateNames.length > 0 && candidateNames.some((n) => claimedNames.has(n)))
4865
+ continue;
4866
+ findings.push({
4867
+ path,
4868
+ reason: `"${path}" is not named as the implementation of any row in enforcement.md's ring tables`
4869
+ });
4870
+ }
4871
+ for (const row of rows) {
4872
+ const carriesPlaceholder = [row.summary, row.description, row.spec].some((cell) => cell === SCAFFOLD_PLACEHOLDER);
4873
+ if (carriesPlaceholder) {
4874
+ findings.push({
4875
+ row: row.action,
4876
+ path: row.implementation,
4877
+ reason: `${row.ring} row "${row.action}" still carries the scaffold placeholder marker — the why is owed`
4878
+ });
4795
4879
  }
4796
4880
  }
4797
- return findings;
4798
- }
4799
- function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4800
- return [
4801
- ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths),
4802
- ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix)
4803
- ];
4881
+ return { check: "G2", status: findings.length > 0 ? "fail" : "pass", findings };
4804
4882
  }
4805
- function parseGlossaryTerms(glossaryContent) {
4806
- const terms = [];
4807
- const re = /^\*\*(.+?)\*\* —/gm;
4808
- let match = re.exec(glossaryContent);
4809
- while (match !== null) {
4810
- if (match[1] !== undefined)
4811
- terms.push(match[1]);
4812
- match = re.exec(glossaryContent);
4883
+ function checkG3(ring0Rows, crossingFiles) {
4884
+ const ring0Implementations = new Set(ring0Rows.map((r) => r.implementation));
4885
+ const findings = [];
4886
+ for (const path of crossingFiles) {
4887
+ if (!ring0Implementations.has(path)) {
4888
+ findings.push({
4889
+ path,
4890
+ reason: `"${path}" makes a GitHub-crossing call but is not named by any Ring-0 row's implementation — a seventh, unlisted way into GitHub`
4891
+ });
4892
+ }
4813
4893
  }
4814
- return terms;
4815
- }
4816
-
4817
- // ../../packages/aeg-core/src/quoted-command.ts
4818
- var QUOTED_COMMAND_SHIPS_PREFIX = "aeg-root/";
4819
- var QUOTED_COMMAND_SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
4820
- var START_PATTERN = /<!--\s*AEG:QUOTES-FILE:START:(\S+?)\s*-->/g;
4821
- var END_PATTERN = /<!--\s*AEG:QUOTES-FILE:END\s*-->/;
4822
- function isValidCitedFilePath(path) {
4823
- if (path.length === 0)
4824
- return false;
4825
- if (path.startsWith("/") || path.startsWith("\\"))
4826
- return false;
4827
- if (/^[A-Za-z]:[\\/]/.test(path))
4828
- return false;
4829
- return !path.split(/[\\/]+/).includes("..");
4894
+ return { check: "G3", status: findings.length > 0 ? "fail" : "pass", findings };
4830
4895
  }
4831
- function quotedCommandLineAt(content, index) {
4832
- let line = 1;
4833
- for (let i = 0;i < index; i++) {
4834
- if (content.charCodeAt(i) === 10)
4835
- line++;
4896
+ function checkG4(content, resolveFn) {
4897
+ const cited = new Set;
4898
+ for (const hit of content.matchAll(/#(\d{3,})\b/g)) {
4899
+ cited.add(Number(hit[1]));
4836
4900
  }
4837
- return line;
4838
- }
4839
- function extractQuotedText(raw) {
4840
- const trimmed = raw.trim();
4841
- const fenced = /^(?:`{3,}|~{3,})[^\n]*\n([\s\S]*?)\n?(?:`{3,}|~{3,})$/.exec(trimmed);
4842
- if (fenced)
4843
- return (fenced[1] ?? "").trim();
4844
- const inline = /^`([^`]+)`$/.exec(trimmed);
4845
- if (inline)
4846
- return (inline[1] ?? "").trim();
4847
- return trimmed;
4901
+ const findings = [];
4902
+ for (const n of cited) {
4903
+ if (!resolveFn(n)) {
4904
+ findings.push({
4905
+ reason: `#${n} is cited in enforcement.md but does not resolve to a real Issue or PR in the forge`
4906
+ });
4907
+ }
4908
+ }
4909
+ return { check: "G4", status: findings.length > 0 ? "fail" : "pass", findings };
4848
4910
  }
4849
- function findQuotesInFile(path, content) {
4850
- const masked = maskCode(content);
4851
- const quotes = [];
4852
- START_PATTERN.lastIndex = 0;
4853
- let start = START_PATTERN.exec(masked);
4854
- while (start !== null) {
4855
- const citedFile = start[1];
4856
- const innerStart = start.index + start[0].length;
4857
- const end = END_PATTERN.exec(masked.slice(innerStart));
4858
- if (end === null) {
4859
- START_PATTERN.lastIndex = innerStart;
4860
- start = START_PATTERN.exec(masked);
4861
- continue;
4911
+ function checkG5(roles, contracts) {
4912
+ const roleIds = new Set(roles.map((r) => r.role_id));
4913
+ const findings = [];
4914
+ for (const contract of contracts) {
4915
+ if (!roleIds.has(contract.producer)) {
4916
+ findings.push({
4917
+ path: contract.file,
4918
+ reason: `contract "${contract.file}" names producer "${contract.producer}", which is not a real role_id`
4919
+ });
4862
4920
  }
4863
- const innerEnd = innerStart + end.index;
4864
- if (isValidCitedFilePath(citedFile)) {
4865
- const quotedText = extractQuotedText(content.slice(innerStart, innerEnd));
4866
- if (quotedText.length > 0) {
4867
- quotes.push({ file: path, line: quotedCommandLineAt(content, innerStart), quotedText, citedFile });
4868
- }
4921
+ if (!roleIds.has(contract.consumer)) {
4922
+ findings.push({
4923
+ path: contract.file,
4924
+ reason: `contract "${contract.file}" names consumer "${contract.consumer}", which is not a real role_id`
4925
+ });
4869
4926
  }
4870
- START_PATTERN.lastIndex = innerEnd + end[0].length;
4871
- start = START_PATTERN.exec(masked);
4872
4927
  }
4873
- return quotes;
4928
+ for (const role of roles) {
4929
+ if (role.performs.length === 0) {
4930
+ findings.push({ path: role.file, reason: `role "${role.role_id}" has an empty performs array` });
4931
+ }
4932
+ if (role.refuses_when.trim() === "") {
4933
+ findings.push({ path: role.file, reason: `role "${role.role_id}" has an empty refuses_when` });
4934
+ }
4935
+ }
4936
+ return { check: "G5", status: findings.length > 0 ? "fail" : "pass", findings };
4874
4937
  }
4875
- function findCitedQuotes(files, readerFacingPrefix, readerFacingSuffix, shipsPrefix = QUOTED_COMMAND_SHIPS_PREFIX) {
4876
- const quotes = [];
4877
- for (const file of files) {
4878
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
4879
- if (!cls || !QUOTED_COMMAND_SWEPT_CLASSES.has(cls))
4880
- continue;
4881
- quotes.push(...findQuotesInFile(file.path, file.content));
4938
+ var SHIPPED_BIN_PATH_PREFIX = "apps/cli/src/checks/bin/check-";
4939
+ var AEG_CORE_BIN_PATH_PREFIX = "packages/aeg-core/bin/";
4940
+ function basenameNoExt(path) {
4941
+ const base = path.slice(path.lastIndexOf("/") + 1);
4942
+ return base.replace(/\.ts$/, "");
4943
+ }
4944
+ function claimedCheckNames(implementation) {
4945
+ if (implementation.startsWith(SHIPPED_BIN_PATH_PREFIX) && implementation.endsWith(".ts")) {
4946
+ return [implementation.slice(SHIPPED_BIN_PATH_PREFIX.length, -".ts".length)];
4882
4947
  }
4883
- return quotes;
4948
+ if (implementation.startsWith(AEG_CORE_BIN_PATH_PREFIX)) {
4949
+ const audience = GATE_AUDIENCE[basenameNoExt(implementation)];
4950
+ if (audience && isShipped(audience)) {
4951
+ return Array.isArray(audience.shippedAs) ? audience.shippedAs : [audience.shippedAs];
4952
+ }
4953
+ }
4954
+ return [];
4884
4955
  }
4885
- function evaluateCitedQuotes(citedQuotes, citedFileContents) {
4956
+ function checkG6(rows, registeredCheckNames) {
4886
4957
  const findings = [];
4887
- for (const quote of citedQuotes) {
4888
- const content = citedFileContents.get(quote.citedFile);
4889
- if (content === undefined) {
4890
- findings.push({
4891
- file: quote.file,
4892
- line: quote.line,
4893
- citedFile: quote.citedFile,
4894
- quotedText: quote.quotedText,
4895
- message: `${quote.file}:${quote.line} quotes "${quote.quotedText}" as citing \`${quote.citedFile}\`, but that file could not be read`
4896
- });
4958
+ for (const row of rows) {
4959
+ if (row.audience !== "product")
4897
4960
  continue;
4898
- }
4899
- if (!content.includes(quote.quotedText)) {
4961
+ const candidates = claimedCheckNames(row.implementation);
4962
+ if (!candidates.some((name) => registeredCheckNames.has(name))) {
4900
4963
  findings.push({
4901
- file: quote.file,
4902
- line: quote.line,
4903
- citedFile: quote.citedFile,
4904
- quotedText: quote.quotedText,
4905
- message: `${quote.file}:${quote.line} quotes "${quote.quotedText}" as citing \`${quote.citedFile}\`, but \`${quote.citedFile}\` no longer contains that text verbatim`
4964
+ row: row.action,
4965
+ path: row.implementation,
4966
+ reason: `${row.ring} row "${row.action}" is marked \`product\` but its implementation "${row.implementation}" does not resolve to a coreCheckRegistry() entry`
4906
4967
  });
4907
4968
  }
4908
4969
  }
4909
- return findings;
4970
+ return { check: "G6", status: findings.length > 0 ? "fail" : "pass", findings };
4910
4971
  }
4911
4972
  // ../../packages/aeg-core/src/dead-branch-push-guard.ts
4912
4973
  function checkDeadBranchPush(input) {
@@ -5813,7 +5874,9 @@ var DevReviewLoopEventSchema = z2.discriminatedUnion("event", [
5813
5874
  "escalated",
5814
5875
  "principal_stop",
5815
5876
  "confidence",
5816
- "reappearance"
5877
+ "reappearance",
5878
+ "repeat_finding",
5879
+ "repeat_failure"
5817
5880
  ])
5818
5881
  }).strict(),
5819
5882
  z2.object({
@@ -6317,6 +6380,10 @@ var LoopStateRecordSchema = z3.object({
6317
6380
  budgets: LoopBudgetsSchema,
6318
6381
  heldResult: roundHeadIdentity.nullable(),
6319
6382
  deliveredFindings: roundHeadIdentity.nullable(),
6383
+ repeatMemory: z3.object({
6384
+ blockingFindings: z3.array(z3.string()),
6385
+ lastFailure: z3.object({ signature: z3.string(), message: z3.string() }).nullable()
6386
+ }).strict().optional(),
6320
6387
  recordedAt: isoTimestamp
6321
6388
  }).strict();
6322
6389
  var EffectRecordSchema = z3.object({
@@ -6975,7 +7042,7 @@ import { dirname as dirname5, join as join6 } from "node:path";
6975
7042
  import { promisify as promisify5 } from "node:util";
6976
7043
 
6977
7044
  // src/lib/config.ts
6978
- import { execFile as execFile4, execFileSync as execFileSync2 } from "node:child_process";
7045
+ import { execFile as execFile4, execFileSync as execFileSync3 } from "node:child_process";
6979
7046
  import { promisify as promisify4 } from "node:util";
6980
7047
  import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync2, realpathSync, writeFileSync } from "node:fs";
6981
7048
  import { homedir } from "node:os";
@@ -6985,6 +7052,28 @@ import { z as z4 } from "zod";
6985
7052
  // src/lib/agent-vendors.ts
6986
7053
  var AGENT_VENDORS = ["skills", "claude", "gemini"];
6987
7054
 
7055
+ // src/lib/worker-boundary.ts
7056
+ import { execFileSync as execFileSync2 } from "node:child_process";
7057
+ var LOG_HEADER_KEYCHAIN_SERVICE = "Vinaya Log";
7058
+ var logHeaderKeychainCache = new Map;
7059
+ function readRealLogHeaderKeychainCredential(variable) {
7060
+ if (process.platform !== "darwin")
7061
+ return null;
7062
+ try {
7063
+ return execFileSync2("/usr/bin/security", ["find-generic-password", "-s", LOG_HEADER_KEYCHAIN_SERVICE, "-a", variable, "-w"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5000, maxBuffer: 1024 * 1024 }).replace(/\n$/, "");
7064
+ } catch {
7065
+ return null;
7066
+ }
7067
+ }
7068
+ function readLogHeaderKeychainCredential(variable) {
7069
+ const cached = logHeaderKeychainCache.get(variable);
7070
+ if (cached !== undefined)
7071
+ return cached;
7072
+ const value = readRealLogHeaderKeychainCredential(variable);
7073
+ logHeaderKeychainCache.set(variable, value);
7074
+ return value;
7075
+ }
7076
+
6988
7077
  // src/lib/config.ts
6989
7078
  var EnvEntrySchema = z4.union([
6990
7079
  z4.literal(true),
@@ -7160,6 +7249,9 @@ var VinayaConfigSchema = z4.object({
7160
7249
  briefRulesSincePr: z4.number().int().nonnegative().optional(),
7161
7250
  agentBoxesRefusedSincePr: z4.number().int().nonnegative().optional()
7162
7251
  }).optional(),
7252
+ planning: z4.object({
7253
+ collisionThreshold: z4.number().int().nonnegative().optional()
7254
+ }).optional(),
7163
7255
  prePush: z4.object({
7164
7256
  alwaysRun: z4.array(z4.string()).optional()
7165
7257
  }).optional(),
@@ -7334,12 +7426,17 @@ function resolveTrustAnchorLogsDestination(local, trustAnchorConfig) {
7334
7426
  return "url" in anchored && anchored.url === local.url ? anchored : null;
7335
7427
  return "folder" in anchored && anchored.folder === local.folder ? anchored : null;
7336
7428
  }
7337
- function resolveLogsHeaderValues(headers, env) {
7429
+ function resolveLogsHeaderValues(headers, env, readKeychain = readLogHeaderKeychainCredential) {
7338
7430
  if (!headers)
7339
7431
  return;
7340
7432
  const resolved = {};
7341
7433
  for (const [key, value] of Object.entries(headers)) {
7342
- resolved[key] = value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_match, name) => env[name] ?? "");
7434
+ resolved[key] = value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_match, name) => {
7435
+ const fromEnv = env[name];
7436
+ if (fromEnv !== undefined)
7437
+ return fromEnv;
7438
+ return readKeychain(name) ?? "";
7439
+ });
7343
7440
  }
7344
7441
  return resolved;
7345
7442
  }
@@ -7348,7 +7445,7 @@ function trustAnchorRepo() {
7348
7445
  if (fromRunner)
7349
7446
  return fromRunner;
7350
7447
  try {
7351
- const url = execFileSync2("git", ["remote", "get-url", "origin"], {
7448
+ const url = execFileSync3("git", ["remote", "get-url", "origin"], {
7352
7449
  encoding: "utf-8",
7353
7450
  stdio: ["ignore", "pipe", "pipe"]
7354
7451
  });
@@ -7395,7 +7492,7 @@ function resolveCiTrustAnchorProbeRef(env = process.env) {
7395
7492
  return ref;
7396
7493
  }
7397
7494
  function readTrustAnchorConfigAtRef(ref) {
7398
- const raw = execFileSync2("git", ["show", `${ref}:${LOCAL_CONFIG_FILENAME}`], {
7495
+ const raw = execFileSync3("git", ["show", `${ref}:${LOCAL_CONFIG_FILENAME}`], {
7399
7496
  encoding: "utf-8",
7400
7497
  stdio: ["ignore", "pipe", "pipe"],
7401
7498
  timeout: 1e4
@@ -7409,7 +7506,7 @@ function ghFetchTrustAnchorConfig() {
7409
7506
  const repo = trustAnchorRepo();
7410
7507
  if (!repo)
7411
7508
  throw new Error("could not resolve repo identity for the trust-anchor read");
7412
- return execFileSync2("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], {
7509
+ return execFileSync3("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], {
7413
7510
  encoding: "utf-8",
7414
7511
  stdio: ["ignore", "pipe", "pipe"]
7415
7512
  });
@@ -8535,11 +8632,11 @@ function summaryLineIndex(maskedRegion) {
8535
8632
  var LOOP_LOG_MAX_BYTES = 8 * 1024 * 1024;
8536
8633
 
8537
8634
  // src/lib/diff-evidence.ts
8538
- import { execFileSync as execFileSync6 } from "node:child_process";
8635
+ import { execFileSync as execFileSync7 } from "node:child_process";
8539
8636
  import { join as join9, relative, resolve as resolve2 } from "node:path";
8540
8637
 
8541
8638
  // src/lib/brief-assembly.ts
8542
- import { execFileSync as execFileSync5 } from "node:child_process";
8639
+ import { execFileSync as execFileSync6 } from "node:child_process";
8543
8640
  import { existsSync as existsSync7, readFileSync as readFileSync6, readdirSync as readdirSync2 } from "node:fs";
8544
8641
  import { join as join8 } from "node:path";
8545
8642
 
@@ -9246,6 +9343,16 @@ var COMMANDS = [
9246
9343
  "Safe to run more than once: the server stores events by `event_id` and ignores one it already holds, so a re-sent chunk creates no duplicate, and a second run finds the folder emptied and the queue drained."
9247
9344
  ],
9248
9345
  status: "shipped"
9346
+ },
9347
+ {
9348
+ name: "log set-credential",
9349
+ description: "Store a `logs.headers` delivery credential in the macOS login Keychain, read from standard input",
9350
+ details: [
9351
+ 'For a `logs.url` server whose `headers` reference a credential by variable name (`{ "authorization": "Bearer ${VINAYA_LOG_TOKEN}" }`) on a host where that variable is not in the process environment — the case an Operator the Claude desktop app starts on macOS hits, since the token lives in an interactive shell file the app never reads. It stores the value so header resolution finds it in the Keychain when the environment does not, with no token copied into any settings file.',
9352
+ 'The value is read from STANDARD INPUT, never a command-line argument a `ps` listing could show — `printf %s "$TOKEN" | vinaya log set-credential VINAYA_LOG_TOKEN`. Only the variable NAME, which is not a secret, sits on the command line; the value is stored under the Keychain service `Vinaya Log` keyed by that name. The command prints a confirmation naming the variable and never echoes, returns, or logs the value.',
9353
+ "macOS only (Linux keyrings are out of scope); it refuses with a clear message elsewhere. The environment still wins over the Keychain wherever the variable is set, so this changes nothing for a host that already exports it."
9354
+ ],
9355
+ status: "shipped"
9249
9356
  }
9250
9357
  ];
9251
9358
  // ../../packages/sources/src/forge-adapter.ts
@@ -9263,7 +9370,7 @@ var StateSourceConfigSchema = z5.discriminatedUnion("kind", [
9263
9370
  z5.object({ kind: z5.literal("file"), root: z5.string().optional() })
9264
9371
  ]);
9265
9372
  // src/checks/edge-resolve.ts
9266
- import { execFileSync as execFileSync3 } from "node:child_process";
9373
+ import { execFileSync as execFileSync4 } from "node:child_process";
9267
9374
  var DIRECT_ISSUE_REF = /#(\d+)/;
9268
9375
  var issueCache = new Map;
9269
9376
  function fetchIssueState(num, repo) {
@@ -9272,7 +9379,7 @@ function fetchIssueState(num, repo) {
9272
9379
  return issueCache.get(key) ?? null;
9273
9380
  let out = null;
9274
9381
  try {
9275
- const raw = execFileSync3("gh", [
9382
+ const raw = execFileSync4("gh", [
9276
9383
  "issue",
9277
9384
  "view",
9278
9385
  String(num),
@@ -9381,7 +9488,7 @@ async function resolveEdge(id, taskById, factsByTaskId, repo, resolveSibling = d
9381
9488
  }
9382
9489
 
9383
9490
  // src/commands/doctrine.ts
9384
- import { execFileSync as execFileSync4 } from "node:child_process";
9491
+ import { execFileSync as execFileSync5 } from "node:child_process";
9385
9492
  import { existsSync as existsSync6, readdirSync, readFileSync as readFileSync5 } from "node:fs";
9386
9493
  import { dirname as dirname6, join as join7, sep } from "node:path";
9387
9494
  import matter2 from "gray-matter";
@@ -9391,7 +9498,7 @@ function resolveDoctrineRoot(pkg = packageRoot(import.meta.url), cwd = process.c
9391
9498
  }
9392
9499
  function gitToplevel(cwd) {
9393
9500
  try {
9394
- return execFileSync4("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
9501
+ return execFileSync5("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
9395
9502
  encoding: "utf8",
9396
9503
  stdio: ["ignore", "pipe", "pipe"]
9397
9504
  }).trim();
@@ -9420,7 +9527,7 @@ var PACKAGED_TEMPLATE_PATH = join8(PACKAGE_ROOT, "aeg-root", "templates", "brief
9420
9527
  var TEMPLATE_PATH = existsSync7(PACKAGED_TEMPLATE_PATH) ? PACKAGED_TEMPLATE_PATH : join8(PACKAGE_ROOT, "..", "..", "aeg-root", "templates", "brief-template.md");
9421
9528
  function git(args) {
9422
9529
  try {
9423
- return execFileSync5("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
9530
+ return execFileSync6("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
9424
9531
  } catch {
9425
9532
  return "";
9426
9533
  }
@@ -9433,6 +9540,8 @@ function expandGlob(glob) {
9433
9540
  var DRAFT_ISSUE_SENTINEL = Number.MAX_SAFE_INTEGER;
9434
9541
 
9435
9542
  // src/lib/forge-write.ts
9543
+ var IMPORTABLE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
9544
+ var IMPORT_SEARCH_PATHSPEC = IMPORTABLE_EXTENSIONS.map((e) => `*${e}`);
9436
9545
  var INFORMATIONAL_DISPATCH_BLOCKER_CLASSES = new Set([
9437
9546
  "depends-on-not-merged",
9438
9547
  "conflicts-with"
@@ -9469,7 +9578,7 @@ function parseChangedLineRanges(diffOutput) {
9469
9578
  function fileDiffAgainst(ref, path) {
9470
9579
  let out;
9471
9580
  try {
9472
- out = execFileSync6("git", ["diff", `${ref}...HEAD`, "--", path], {
9581
+ out = execFileSync7("git", ["diff", `${ref}...HEAD`, "--", path], {
9473
9582
  encoding: "utf8",
9474
9583
  stdio: ["ignore", "pipe", "pipe"]
9475
9584
  }).trim();
@@ -9480,7 +9589,7 @@ function fileDiffAgainst(ref, path) {
9480
9589
  }
9481
9590
  function revParse(ref) {
9482
9591
  try {
9483
- return execFileSync6("git", ["rev-parse", "--verify", ref], {
9592
+ return execFileSync7("git", ["rev-parse", "--verify", ref], {
9484
9593
  encoding: "utf8",
9485
9594
  stdio: ["ignore", "pipe", "pipe"]
9486
9595
  }).trim();
@@ -9490,7 +9599,7 @@ function revParse(ref) {
9490
9599
  }
9491
9600
  function repoRoot() {
9492
9601
  try {
9493
- return execFileSync6("git", ["rev-parse", "--show-toplevel"], {
9602
+ return execFileSync7("git", ["rev-parse", "--show-toplevel"], {
9494
9603
  encoding: "utf8",
9495
9604
  stdio: ["ignore", "pipe", "pipe"]
9496
9605
  }).trim();
@@ -9501,7 +9610,7 @@ function repoRoot() {
9501
9610
  function changedFiles(base) {
9502
9611
  let out;
9503
9612
  try {
9504
- out = execFileSync6("git", ["diff", "--name-only", `${base}...HEAD`], {
9613
+ out = execFileSync7("git", ["diff", "--name-only", `${base}...HEAD`], {
9505
9614
  encoding: "utf8",
9506
9615
  stdio: ["ignore", "pipe", "pipe"]
9507
9616
  }).trim();
@@ -9627,20 +9736,20 @@ var TOKEN_ROW_REMEDY = [
9627
9736
  var USAGE2 = "Usage: vinaya pr report [--write <body-file> | --push <pr> [--body-file <path>]] [--phase <phase>] " + "[--role <role>] [--model <id>] [--transcript <path>]";
9628
9737
 
9629
9738
  // src/lib/patch-id.ts
9630
- import { execFileSync as execFileSync7 } from "node:child_process";
9739
+ import { execFileSync as execFileSync8 } from "node:child_process";
9631
9740
  function patchIdAt(base, sha) {
9632
9741
  try {
9633
- execFileSync7("git", ["fetch", "--quiet", "origin", sha], { stdio: ["ignore", "ignore", "ignore"] });
9742
+ execFileSync8("git", ["fetch", "--quiet", "origin", sha], { stdio: ["ignore", "ignore", "ignore"] });
9634
9743
  } catch {}
9635
9744
  try {
9636
- const diff = execFileSync7("git", ["diff", `origin/${base}...${sha}`], {
9745
+ const diff = execFileSync8("git", ["diff", `origin/${base}...${sha}`], {
9637
9746
  encoding: "utf8",
9638
9747
  maxBuffer: 64 * 1024 * 1024,
9639
9748
  stdio: ["ignore", "pipe", "pipe"]
9640
9749
  });
9641
9750
  if (diff === "")
9642
9751
  return null;
9643
- const out = execFileSync7("git", ["patch-id", "--stable"], {
9752
+ const out = execFileSync8("git", ["patch-id", "--stable"], {
9644
9753
  input: diff,
9645
9754
  encoding: "utf8",
9646
9755
  stdio: ["pipe", "pipe", "pipe"]
@@ -9752,7 +9861,7 @@ function compareEvidenceBlock(resolved, resolvedHead, actualNumstat, expectedGro
9752
9861
  var DEVELOPER_ROUND_MARKER = /<!--\s*aeg:developer:round-\d+\s*-->/i;
9753
9862
  function fetchHasPriorDeveloperRound(prNumber) {
9754
9863
  try {
9755
- const out = execFileSync8("gh", ["pr", "view", String(prNumber), "--json", "comments"], {
9864
+ const out = execFileSync9("gh", ["pr", "view", String(prNumber), "--json", "comments"], {
9756
9865
  encoding: "utf8",
9757
9866
  stdio: ["ignore", "pipe", "pipe"]
9758
9867
  });
@@ -9766,7 +9875,7 @@ function fetchHasPriorDeveloperRound(prNumber) {
9766
9875
  var CHECK_NAME = "evidence-fresh";
9767
9876
  function git2(args) {
9768
9877
  try {
9769
- return execFileSync8("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
9878
+ return execFileSync9("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
9770
9879
  } catch {
9771
9880
  return "";
9772
9881
  }
@@ -9785,7 +9894,7 @@ class GitCommandError2 extends Error {
9785
9894
  }
9786
9895
  function gitStrict(args) {
9787
9896
  try {
9788
- return execFileSync8("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
9897
+ return execFileSync9("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
9789
9898
  } catch (err) {
9790
9899
  const stderr = err.stderr;
9791
9900
  throw new GitCommandError2(args, String(stderr ?? err.message).trim() || "non-zero exit");
@@ -9803,7 +9912,7 @@ function resolveMergeBase(head) {
9803
9912
  }
9804
9913
  function fetchPrRefs(prNumber) {
9805
9914
  try {
9806
- const out = execFileSync8("gh", ["pr", "view", String(prNumber), "--json", "headRefOid,baseRefName"], {
9915
+ const out = execFileSync9("gh", ["pr", "view", String(prNumber), "--json", "headRefOid,baseRefName"], {
9807
9916
  encoding: "utf8",
9808
9917
  stdio: ["ignore", "pipe", "pipe"]
9809
9918
  });