@attalabs/vinaya 0.34.0 → 0.36.0

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