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