forgedock 1.54.1 → 1.55.1

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 (115) hide show
  1. package/bin/config-schema.mjs +12 -0
  2. package/bin/engine/events.mjs +1 -0
  3. package/bin/engine/events.test.mjs +5 -1
  4. package/bin/engine/outcome-codes.mjs +3 -0
  5. package/bin/engine-cli.mjs +126 -34
  6. package/bin/forge-utils.mjs +37 -5
  7. package/bin/forgedock.mjs +54 -2
  8. package/bin/gc-schedule.mjs +83 -0
  9. package/bin/gc.mjs +66 -10
  10. package/bin/help-text.mjs +1 -1
  11. package/bin/hooks/pre-tool-use.mjs +1 -0
  12. package/bin/init-detect.mjs +73 -2
  13. package/bin/labels.json +5 -0
  14. package/bin/lean/admission.mjs +21 -1
  15. package/bin/lean/baselines.mjs +43 -0
  16. package/bin/lean/baselines.test.mjs +33 -0
  17. package/bin/lean/batch-health.mjs +43 -6
  18. package/bin/lean/batch-health.test.mjs +41 -1
  19. package/bin/lean/batch.mjs +41 -4
  20. package/bin/lean/batch.test.mjs +106 -3
  21. package/bin/lean/conformance.mjs +131 -12
  22. package/bin/lean/conformance.test.mjs +172 -3
  23. package/bin/lean/depcache.mjs +23 -2
  24. package/bin/lean/depcache.test.mjs +22 -0
  25. package/bin/lean/docsgate.mjs +137 -0
  26. package/bin/lean/docsgate.test.mjs +78 -0
  27. package/bin/lean/effects.mjs +31 -2
  28. package/bin/lean/enumerating.mjs +39 -13
  29. package/bin/lean/enumerating.test.mjs +20 -0
  30. package/bin/lean/execution.test.mjs +3 -3
  31. package/bin/lean/fastforward.mjs +93 -0
  32. package/bin/lean/fastforward.test.mjs +73 -0
  33. package/bin/lean/guardgate.mjs +38 -7
  34. package/bin/lean/guardgate.test.mjs +39 -0
  35. package/bin/lean/issuewatch-install.mjs +92 -0
  36. package/bin/lean/issuewatch-install.test.mjs +31 -0
  37. package/bin/lean/issuewatch-parity.mjs +33 -3
  38. package/bin/lean/issuewatch-parity.test.mjs +30 -5
  39. package/bin/lean/issuewatch-reconcile.mjs +123 -0
  40. package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
  41. package/bin/lean/issuewatch-verify.mjs +51 -9
  42. package/bin/lean/issuewatch.mjs +153 -33
  43. package/bin/lean/issuewatch.test.mjs +243 -22
  44. package/bin/lean/lean.mjs +381 -75
  45. package/bin/lean/lean.test.mjs +437 -20
  46. package/bin/lean/light.mjs +11 -3
  47. package/bin/lean/light.test.mjs +27 -0
  48. package/bin/lean/lightlane.mjs +8 -3
  49. package/bin/lean/lightlane.test.mjs +20 -0
  50. package/bin/lean/mechfix.mjs +21 -2
  51. package/bin/lean/mechfix.test.mjs +28 -1
  52. package/bin/lean/orchestrate-children.test.mjs +10 -0
  53. package/bin/lean/orchestrate-owned.test.mjs +73 -0
  54. package/bin/lean/orchestrate.mjs +28 -4
  55. package/bin/lean/overlap.mjs +20 -0
  56. package/bin/lean/overlap.test.mjs +49 -0
  57. package/bin/lean/pagegate.mjs +152 -0
  58. package/bin/lean/pagegate.test.mjs +77 -0
  59. package/bin/lean/parked-relabel.mjs +32 -0
  60. package/bin/lean/parked-relabel.test.mjs +45 -0
  61. package/bin/lean/phaseledger.mjs +17 -2
  62. package/bin/lean/postdeploy-check.mjs +27 -0
  63. package/bin/lean/postdeploy-check.test.mjs +13 -1
  64. package/bin/lean/postrun.mjs +32 -0
  65. package/bin/lean/postrun.test.mjs +41 -0
  66. package/bin/lean/preflight.mjs +46 -0
  67. package/bin/lean/preflight.test.mjs +30 -1
  68. package/bin/lean/prompts.mjs +36 -6
  69. package/bin/lean/recovery.test.mjs +16 -0
  70. package/bin/lean/release-review.mjs +12 -1
  71. package/bin/lean/release-review.test.mjs +14 -0
  72. package/bin/lean/release.mjs +23 -2
  73. package/bin/lean/release.test.mjs +28 -1
  74. package/bin/lean/render.mjs +17 -6
  75. package/bin/lean/reproquality.mjs +116 -0
  76. package/bin/lean/reproquality.test.mjs +85 -0
  77. package/bin/lean/review-trigger.mjs +8 -3
  78. package/bin/lean/sandbox-budget.test.mjs +27 -0
  79. package/bin/lean/schedd.mjs +40 -11
  80. package/bin/lean/schedd.test.mjs +12 -1
  81. package/bin/lean/testadequacy.mjs +97 -0
  82. package/bin/lean/testadequacy.test.mjs +92 -0
  83. package/bin/lean/testsandbox.mjs +202 -0
  84. package/bin/lean/testsandbox.test.mjs +157 -0
  85. package/bin/lean/toolplace.mjs +5 -2
  86. package/bin/lean/toolplace.test.mjs +6 -0
  87. package/bin/lean/verify.mjs +6 -1
  88. package/bin/lean/verify.test.mjs +18 -2
  89. package/bin/lean/warmtree.mjs +77 -0
  90. package/bin/lean/warmtree.test.mjs +81 -0
  91. package/bin/review-staging.mjs +51 -9
  92. package/bin/stats/conformance-outcomes.mjs +12 -2
  93. package/bin/stats/depth.mjs +24 -1
  94. package/bin/stats/depth.test.mjs +21 -1
  95. package/bin/stats/index.mjs +5 -2
  96. package/bin/stats/query.mjs +2 -1
  97. package/commands/cleanup.md +18 -0
  98. package/commands/fd-introspect.md +19 -0
  99. package/commands/milestone.md +5 -1
  100. package/commands/pipeline-health/phase-2-metrics.md +4 -0
  101. package/commands/recover-orphans.md +31 -1
  102. package/commands/review-pr-staging.md +9 -0
  103. package/commands/review-pr.md +2 -0
  104. package/docs/CONFIG.md +26 -1
  105. package/docs/EVENTS.md +1 -0
  106. package/docs/ISSUE-WATCH.md +12 -3
  107. package/docs/eval/adversarial-bench.md +1 -1
  108. package/docs/eval/published/adversarial-2026-11-11.md +58 -0
  109. package/package.json +1 -1
  110. package/scripts/bench-lightlane.mjs +3 -2
  111. package/scripts/hotspots.sh +7 -4
  112. package/scripts/hotspots.test.sh +12 -0
  113. package/scripts/recover-orphans-stateless.test.sh +79 -0
  114. package/scripts/transition-label.sh +2 -0
  115. package/templates/workflows/forgedock-reopen-clean.yml +33 -0
@@ -10,6 +10,7 @@
10
10
  import { spawnSync } from "node:child_process";
11
11
  import { OUTCOME_CODES, ENV_VALIDATE_TIMEOUT } from "../engine/outcome-codes.mjs";
12
12
  import { noComments } from "./context.mjs";
13
+ import { seqNumber } from "./sequence.mjs";
13
14
  import { activationFailures } from "./activation.mjs";
14
15
  import * as nodeFs from "node:fs";
15
16
  import { tmpdir } from "node:os";
@@ -31,8 +32,10 @@ const INCIDENTAL_RE = /(^|\/)(CHANGELOG|CHANGES|HISTORY)(\.[a-z]+)?$|(^|\/)(pack
31
32
  export const MIN_QUOTE_CHARS = 12;
32
33
  /** A contract larger than this cannot be posted whole in one comment (the comment cap is 60k). */
33
34
  export const MAX_CONTRACT_CHARS = 40000;
34
- import { CHECK_ID_RE } from "./postdeploy-check.mjs";
35
+ import { CHECK_ID_RE, e2eCheckFor } from "./postdeploy-check.mjs";
35
36
  import { normaliseDecision, deadAnchors, anchorMatches } from "./decisions.mjs";
37
+ import { globToRegex } from "../../scripts/ci-local/lib.mjs";
38
+ import { contractBriefProblems } from "./pagegate.mjs"; // #5428
36
39
  const C = OUTCOME_CODES;
37
40
 
38
41
  /** #4789: folds what a builder retyping a quote changes: unicode punctuation, markdown links/markup, escapes, invisible chars. */
@@ -180,13 +183,28 @@ export const isTestPath = (p) => TEST_RE.test(String(p));
180
183
  export const isIncidentalPath = (p) => INCIDENTAL_RE.test(String(p));
181
184
  const cleanPath = (p) => String(p ?? "").trim().replace(/^\.\//, "");
182
185
  const globRe = (g) => new RegExp(`^${g.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*\/?/g, "\u0000").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]").replace(/\u0000/g, ".*")}$`);
183
- /** True when deliverable `d` (a file, a dir ending in "/", or a glob) covers changed file `f`. */
186
+ const dirOf = (p) => p.slice(0, p.lastIndexOf("/") + 1);
187
+ /**
188
+ * #5440: `file` with its sequence number replaced by the one in deliverable `p`, when both sit in one directory and both
189
+ * names start with a (different) sequence number: an in-lane renumber (0637_x -> 0639_x) is an add from the base, so git
190
+ * rename detection cannot see it. null otherwise.
191
+ */
192
+ function renumberedAs(p, file) {
193
+ const was = seqNumber(p.slice(dirOf(p).length)), now = seqNumber(file.slice(dirOf(file).length));
194
+ if (!was || !now || was === now || dirOf(p) !== dirOf(file)) return null;
195
+ return `${dirOf(file)}${was}${file.slice(dirOf(file).length + now.length)}`;
196
+ }
197
+ /** True when deliverable `d` (a file, a directory with or without a trailing "/", or a glob) covers changed file `f`. */
184
198
  export function pathCovers(d, f) {
185
199
  const p = cleanPath(d), file = cleanPath(f);
186
200
  if (!p) return false;
187
201
  if (p.endsWith("/")) return file.startsWith(p);
188
- if (/[*?]/.test(p)) return globRe(p).test(file);
189
- return p === file;
202
+ const hit = (x) => (/[*?]/.test(p) ? globRe(p).test(x) : p === x);
203
+ // a file and a directory cannot share a path, so a slash-less deliverable that prefixes `file/` is a directory
204
+ if (!/[*?]/.test(p) && file.startsWith(`${p}/`)) return true;
205
+ if (hit(file)) return true;
206
+ const as = renumberedAs(p, file);
207
+ return as !== null && hit(as);
190
208
  }
191
209
  /** #5365: explicit coupling map: editing `when` (a deliverable) also puts `also` in scope (a test asserts parity between them). */
192
210
  const COUPLED_PATHS = [{ when: "bin/engine/outcome-codes.mjs", also: ["docs/OUTCOME-CODES.md"] }];
@@ -453,7 +471,49 @@ export function weakenedE2eDecisions(c) {
453
471
  }).map((k) => k.id).filter(Boolean);
454
472
  }
455
473
 
456
- export function validateContract(c, issueText, { repro = false } = {}) {
474
+ const TEST_LEVELS = ["unit", "integration", "e2e", "live"];
475
+ const planWords = (t) => new Set(String(t ?? "").toLowerCase().match(/[a-z0-9]{3,}/g)?.map((w) => w.slice(0, 5)) ?? []);
476
+ const MOCK_RE = /\b(?:mock|stub|fake)\w*/i, NEG_MOCK_PLAN_RE = /\b(?:no|not|never|without|non|avoid\w*)[ -]+(?:\w+[ -]+)?(?:mock|stub|fake)\w*/gi;
477
+ /** #5445: a proof whose words are (almost) all in the deliverable text of its requirement only restates the fix. Pure. */
478
+ export function proofEchoesDeliverable(proof, deliverables) {
479
+ const pw = planWords(proof);
480
+ if (!pw.size) return false;
481
+ return deliverables.some((d) => { const dw = planWords(`${d?.change ?? ""} ${d?.path ?? ""}`); let n = 0; for (const w of pw) if (dw.has(w)) n++; return n / pw.size >= 0.7; });
482
+ }
483
+ /**
484
+ * #5445: problems with the frozen test plan `test_plan: [{requirement, proof, level, level_reason, repro, reason, regression, env, command}]`.
485
+ * Shape is checked whenever present; `required` (a bug lane with repro on) also needs one row per deliver requirement.
486
+ */
487
+ export function testPlanProblems(c, { required = false } = {}) {
488
+ const plan = c?.test_plan, problems = [];
489
+ if (plan == null) { if (!required) return problems; }
490
+ else if (!Array.isArray(plan)) return ["test_plan must be an array of rows"];
491
+ const rows = Array.isArray(plan) ? plan : [], dels = Array.isArray(c?.deliverables) ? c.deliverables : [];
492
+ if (required) for (const r of (Array.isArray(c?.requirements) ? c.requirements : []).filter((x) => x?.disposition === "deliver")) if (!rows.some((t) => t?.requirement === r.id)) problems.push(`${r.id}: test_plan needs a row for this bug requirement (proof, level, level_reason, repro or no-repro with reason, command)`);
493
+ for (const t of rows) {
494
+ const id = t?.requirement ?? "test_plan row";
495
+ if (!t || typeof t !== "object" || !t.requirement) { problems.push("test_plan row without a requirement id"); continue; }
496
+ if (blank(t.proof)) problems.push(`${id}: test_plan proof must name the root-cause observable that shows the cause is fixed`);
497
+ else if (proofEchoesDeliverable(t.proof, dels.filter((d) => (d?.requirements ?? []).includes(t.requirement)))) problems.push(`${id}: test_plan proof only restates a deliverable; describe the observable that was wrong (the symptom or root cause), not the presence of the fix`);
498
+ if (!TEST_LEVELS.includes(t.level)) problems.push(`${id}: test_plan level must be one of ${TEST_LEVELS.join("|")}`);
499
+ if (blank(t.level_reason)) problems.push(`${id}: test_plan level needs a level_reason (why the cheapest level that observes the cause)`);
500
+ else if (MOCK_RE.test(String(t.level_reason).replace(NEG_MOCK_PLAN_RE, " "))) problems.push(`${id}: test_plan may not prove the cause fixed by mocking the component the bug lives in; pick a level that exercises it`);
501
+ if (blank(t.repro)) problems.push(`${id}: test_plan repro must be a test id (red on base, green on head) or "no-repro" with a reason`);
502
+ else if (/^no-repro$/i.test(String(t.repro).trim()) && blank(t.reason)) problems.push(`${id}: test_plan no-repro needs a reason the reviewer can reject`);
503
+ if (blank(t.command)) problems.push(`${id}: test_plan needs the exact command validate runs`);
504
+ else {
505
+ for (const p of tmpdirInputs(t.command)) problems.push(tmpInputProblem(id, p));
506
+ if (vitestQuietFlag(t.command)) problems.push(`${id}: test_plan command: vitest 3 rejects -q/--quiet; use --reporter=dot`);
507
+ const syn = shellSyntaxError(t.command);
508
+ if (syn) problems.push(`${id}: test_plan command is not valid shell (bash -n: ${syn})`);
509
+ }
510
+ }
511
+ return problems;
512
+ }
513
+
514
+ /** #5448: a requirement that starts as an imperative build verb is development work, not a prod-only measurement. */
515
+ const DEV_WORK_RE = /^\W*(?:\w+\s+){0,2}?(?:find|fix|implement|develop|build|write|patch|add|change)\b/i;
516
+ export function validateContract(c, issueText, { repro = false, pages = null, testPlan = false } = {}) {
457
517
  const problems = [];
458
518
  if (!c || typeof c !== "object" || Array.isArray(c)) return { ok: false, problems: ["contract.json is missing or not a JSON object"] };
459
519
  const reqs = Array.isArray(c.requirements) ? c.requirements : [];
@@ -467,6 +527,8 @@ export function validateContract(c, issueText, { repro = false } = {}) {
467
527
  if (!inIssue(r?.quote, issueText)) problems.push(quoteMiss(id, r?.quote, issueText));
468
528
  if (TRACKED.includes(r?.disposition) && blank(r?.why)) problems.push(`${id}: ${r.disposition} needs a why`);
469
529
  if (r?.disposition === "post-deploy" && !CHECK_ID_RE.test(String(r?.check ?? ""))) problems.push(`${id}: post-deploy needs a check id (\`check\`, e.g. "login-smoke") naming an entry of .forge/post-deploy-checks.json on the default branch`);
530
+ if (r?.disposition === "post-deploy" && blank(r?.local_infeasible_why)) problems.push(`${id}: post-deploy needs local_infeasible_why: why a fixture or recorded response cannot check this locally (#5448)`);
531
+ if (r?.disposition === "post-deploy" && (inLaneDeferral(r) || (bucketKind(r?.bucket) !== "owner" && bucketKind(r?.bucket) !== "host" && DEV_WORK_RE.test(String(r?.quote ?? ""))))) problems.push(`${id}: development work (finding or fixing the signal) is delivered in-lane, never deferred as prod-only; deliver it and keep only the measurement post-deploy (#5448)`);
470
532
  if (r?.disposition === "not-applicable" && blank(r?.evidence)) problems.push(`${id}: not-applicable needs file:line evidence`);
471
533
  for (const m of bucketProblems(r)) problems.push(`${id}: ${m}`);
472
534
  if (r?.class != null && !FOLLOWUP_CLASSES.includes(r.class)) problems.push(`${id}: class must be one of ${FOLLOWUP_CLASSES.join("|")}`);
@@ -474,6 +536,13 @@ export function validateContract(c, issueText, { repro = false } = {}) {
474
536
  if (isOutOfBand(r) && r?.disposition !== "deliver") problems.push(`${id}: verify out_of_band applies only to a deliver requirement`);
475
537
  else if (isOutOfBand(r) && blank(r?.evidence)) problems.push(`${id}: verify out_of_band needs evidence naming the job or workflow that measures it (or set verify "in_lane" if this change can check it)`);
476
538
  }
539
+ if (c.regression != null && !Array.isArray(c.regression)) problems.push("regression must be an array of {id, command, covers}");
540
+ for (const g of Array.isArray(c.regression) ? c.regression : []) {
541
+ if (!g?.id || blank(g?.command)) { problems.push(`regression entry without id or command: ${JSON.stringify(g ?? null).slice(0, 80)}`); continue; }
542
+ for (const p of tmpdirInputs(g.command)) problems.push(tmpInputProblem(g.id, p));
543
+ const syn = shellSyntaxError(g.command);
544
+ if (syn) problems.push(`${g.id}: the command is not valid shell (bash -n: ${syn})`);
545
+ }
477
546
  const dels = Array.isArray(c.deliverables) ? c.deliverables : [];
478
547
  if (reqs.some((r) => r?.disposition === "deliver") && !dels.length) problems.push("deliver requirements but no deliverables");
479
548
  for (const d of dels) if (!d?.id || !d?.path) problems.push(`deliverable without id or path: ${JSON.stringify(d).slice(0, 80)}`);
@@ -512,7 +581,9 @@ export function validateContract(c, issueText, { repro = false } = {}) {
512
581
  if (syn) problems.push(`repro_test: the command is not valid shell (bash -n: ${syn})`);
513
582
  }
514
583
  }
584
+ problems.push(...testPlanProblems(c, { required: testPlan }));
515
585
  if (JSON.stringify(c).length > MAX_CONTRACT_CHARS) problems.push(`the contract is over ${MAX_CONTRACT_CHARS} characters; keep quotes to the requirement sentence and descriptions short`);
586
+ if (pages) problems.push(...contractBriefProblems(c, pages)); // #5428: page deliverables need page_gate briefs
516
587
  return { ok: problems.length === 0, problems };
517
588
  }
518
589
 
@@ -769,6 +840,8 @@ export function deferChecklessPostDeploy(contract) {
769
840
  const converted = [];
770
841
  const requirements = (Array.isArray(contract?.requirements) ? contract.requirements : []).map((r) => {
771
842
  if (r?.disposition !== "post-deploy" || CHECK_ID_RE.test(String(r?.check ?? ""))) return r;
843
+ // #5448: only a row that truly needs an owner or read-only prod data is converted; any other check-less prod-only claim stays post-deploy so freeze rejects it
844
+ if (!EXTERNAL_NEED_RE.test(`${r.bucket ?? ""} ${r.why ?? ""}`) && !READONLY_PROD_RE.test(`${r.bucket ?? ""} ${r.why ?? ""}`)) return r;
772
845
  converted.push(r.id);
773
846
  return { ...r, disposition: "defer", bucket: String(r.bucket ?? "").startsWith("owner:") ? r.bucket : ORCHESTRATOR_BUCKET, why: r.why ?? "post-deploy action with no registered check: deferred to the orchestrator" };
774
847
  });
@@ -791,6 +864,7 @@ export function applyValidateRecipes(contract, recipes) {
791
864
  if (Array.isArray(contract.validate)) out.validate = contract.validate.map((v) => (v && typeof v === "object" ? { ...v, command: rewrite(v.id, v.command) } : v));
792
865
  const t = contract.repro_test;
793
866
  if (t && typeof t === "object" && !Array.isArray(t)) out.repro_test = { ...t, command: rewrite("repro_test", t.command) };
867
+ if (Array.isArray(contract.test_plan)) out.test_plan = contract.test_plan.map((r) => (r && typeof r === "object" ? { ...r, command: rewrite(`test_plan ${r.requirement}`, r.command) } : r)); // #5445
794
868
  return { contract: applied.length ? out : contract, applied };
795
869
  }
796
870
  /** #5020: the env.* verdict for a repro command that failed on head because a tool is missing (e.g. an uninstalled Poetry env); null when the failure is the test's own. */
@@ -958,7 +1032,7 @@ export function repoTracks(paths) {
958
1032
  * `ciCovered` (#4527): the validate ids accepted only because the head is CI-verified (no local result, or a missing host
959
1033
  * tool), for the trajectory; always an array.
960
1034
  */
961
- export function precheck({ contract, result, changedFiles, ignore = [], ciVerified = false, hotspots = null, repro = null, validateRuns = null, repoHas = () => false, frozen = null, checkIds = null, guardFailures = null, coupledFailures = null, relaxationFailures = null, routeFailures = null, prodParityFailures = null, newOffKeys = null, substitutedRuns = null, removedPaths = [], baseFiles = [], uiBrowser = null }) {
1035
+ export function precheck({ contract, result, changedFiles, ignore = [], ciVerified = false, hotspots = null, repro = null, validateRuns = null, repoHas = () => false, frozen = null, checkIds = null, baselineFailures = null, guardFailures = null, coupledFailures = null, relaxationFailures = null, routeFailures = null, docsFailures = null, pageFailures = null, docsPaths = null, prodParityFailures = null, newOffKeys = null, substitutedRuns = null, removedPaths = [], baseFiles = [], uiBrowser = null }) {
962
1036
  const failures = [], superseded = [], ciCovered = [];
963
1037
  // #4626: a post-deploy check id must be on the default branch or added by this PR (`checkIds`: ids of both checks files; null = not resolved)
964
1038
  if (checkIds) for (const r of contract.requirements ?? []) {
@@ -968,7 +1042,7 @@ export function precheck({ contract, result, changedFiles, ignore = [], ciVerifi
968
1042
  if (newOffKeys?.length) for (const f of activationFailures(contract, newOffKeys)) failures.push({ code: C.CONFORMANCE_UNIMPLEMENTED, ...f });
969
1043
  // #5285: interactive UI changed on a high-risk surface with no real-browser check configured: a recorded skip that blocks
970
1044
  if (uiBrowser?.files?.length && uiBrowser.highRisk && !uiBrowser.ran) failures.push({ code: C.CONFORMANCE_E2E_UNVERIFIED, kind: "ui_browser_unverified", detail: `interactive UI changed (${uiBrowser.files.slice(0, 5).join(", ")}) on a high-risk surface but no real-browser check runs (${uiBrowser.reason}); configure verify.e2e_label/e2e_workflow or add a Playwright spec` });
971
- const outside = (k) => changedFiles.filter((f) => !ignore.some((p) => f.startsWith(p)) && !authorizationOf(k, f));
1045
+ const outside = (k) => changedFiles.filter((f) => !ignore.some((p) => f.startsWith(p)) && !authorizationOf(k, f) && !(docsPaths?.length && docsPaths.some((g) => globToRegex(g).test(f)))); // #5419: configured docs.paths/registries are authorized
972
1046
  const creep = outside(contract);
973
1047
  const amendedOnly = frozenAmendedFiles(frozen, contract, outside, creep);
974
1048
  if (creep.length) failures.push({ code: C.CONFORMANCE_SCOPE_CREEP, kind: "scope_creep", detail: `changed outside the contract's deliverables: ${creep.join(", ")}` });
@@ -1004,7 +1078,7 @@ export function precheck({ contract, result, changedFiles, ignore = [], ciVerifi
1004
1078
  continue;
1005
1079
  }
1006
1080
  const miss = rerun ? missingTool(rerun, { repoHas, command: v.command }) : null;
1007
- if (miss && ciVerified) { ciCovered.push(v.id); continue; }
1081
+ // #5447: CI may not run this test, so a missing tool on the rerun is never covered by a CI-verified head
1008
1082
  if (miss) failures.push({ code: C.ENV_TOOL_MISSING, kind: "validate_env", tool: miss.tool, detail: `validate ${v.id} (\`${v.command}\`) could not run: the host is missing ${KIND_NAME[miss.kind]} '${miss.tool}' (environment, not the change)${outputTail(rerun.output)}` });
1009
1083
  else if (amendedOnly && isScopeCheck(v.command)) superseded.push({ id: v.id, files: amendedOnly });
1010
1084
  else failures.push({ code: C.CONFORMANCE_UNIMPLEMENTED, kind: "validate_failed", detail: `validate ${v.id} (\`${v.command}\`) failed (exit ${r.exit})${outputTail(rerun?.output)}` });
@@ -1023,8 +1097,9 @@ export function precheck({ contract, result, changedFiles, ignore = [], ciVerifi
1023
1097
  else if (s !== "implemented") failures.push({ code: C.CONFORMANCE_UNIMPLEMENTED, kind: "requirement_unimplemented", detail: `${r.id} reported "${s ?? "no status"}"` });
1024
1098
  }
1025
1099
  }
1100
+ for (const f of baselineFailures ?? []) failures.push({ code: C.CONFORMANCE_REGRESSION, ...f }); // #5448
1026
1101
  failures.push(...hotspotGrowth({ contract, result, hotspots, changedFiles }));
1027
- if (repro) failures.push(...reproFailures(contract, repro));
1102
+ if (repro) failures.push(...reproFailures(contract, repro), ...reproQualityFailures(repro));
1028
1103
  failures.push(...sourceDeliverableFailures(contract, changedFiles, ignore));
1029
1104
  // #4693: a broken guard fails unless the contract carries a supersedes amendment for it
1030
1105
  const retired = new Set((contract.supersedes ?? []).map((s) => s.guard));
@@ -1032,6 +1107,8 @@ export function precheck({ contract, result, changedFiles, ignore = [], ciVerifi
1032
1107
  for (const f of coupledFailures ?? []) failures.push(f); // #5079
1033
1108
  for (const f of relaxationFailures ?? []) failures.push(f); // #5237
1034
1109
  failures.push(...(routeFailures ?? [])); // #5087: topology.route_reachability, blocking when declared
1110
+ failures.push(...(docsFailures ?? [])); // #5419: forge.yaml docs
1111
+ failures.push(...(pageFailures ?? [])); // #5428: forge.yaml pages
1035
1112
  failures.push(...(prodParityFailures ?? [])); // #5284: topology.prod_parity
1036
1113
  return { ok: failures.length === 0, failures, superseded, ciCovered };
1037
1114
  }
@@ -1071,6 +1148,13 @@ export function reproFailures(contract, { base, head } = {}) {
1071
1148
  detail: `repro test ${name} (\`${t.command ?? ""}\`) must fail on the base and pass on head; got BASE=${base ?? "UNRUNNABLE"} HEAD=${head}${skipped}` }];
1072
1149
  }
1073
1150
 
1151
+ /** #5446: a repro_test every targeted mutation of the fix survived. Only under lean.repro_quality: enforce; patch_echo is the reviewer's call. */
1152
+ export function reproQualityFailures({ quality, enforce } = {}) {
1153
+ if (!enforce || quality !== "mutation_survivor") return [];
1154
+ return [{ code: MUTATION_SURVIVED, kind: "repro_mutation_survivor",
1155
+ detail: "repro_test still passes with the fix's changed lines mutated (flipped condition, early return, dropped call): it does not exercise the fix" }];
1156
+ }
1157
+
1074
1158
  const DOC_ONLY_RE = /\.(?:md|mdx|txt|rst|adoc)$/i;
1075
1159
  const SOURCE_EXT_RE = /\.(?:m?[jt]sx?|cjs|py|go|rs|rb|java|kt|swift|php|cs|c|cc|cpp|h|hpp|sh)$/i;
1076
1160
  /**
@@ -1285,7 +1369,8 @@ export function checkCompleteness(rv, { contract, changedFiles, issueText, pathE
1285
1369
  /** #4726, #5339: a requirement quote that carries a `[type:e2e]` or `[type:manual]` criterion. */
1286
1370
  const wantsE2e = (r) => /\[type:(?:e2e|manual)\]/i.test(String(r?.quote ?? ""));
1287
1371
  /** #5339: failure kinds enforced without an `engine.conformance_kinds` entry (the entry still overrides). */
1288
- const DEFAULT_ENFORCED_KINDS = ["e2e_row"];
1372
+ // #5449: test_missing/test_weak are only generated for bug lanes (testadequacy.mjs), so enforcing the kinds is bug-only.
1373
+ const DEFAULT_ENFORCED_KINDS = ["e2e_row", "test_missing", "test_weak"];
1289
1374
  const E2E_CMD_RE = /\b(?:playwright|cypress|e2e|live[- ]stack|wdio)\b/i;
1290
1375
  /**
1291
1376
  * #4726: whether a validate command runs a real end-to-end check: an entry of `verify.e2e_checks`, a file of the e2e spec set
@@ -1298,11 +1383,45 @@ export function isE2eCommand(command, e2e = null) {
1298
1383
  if (typeof e2e?.isSpec === "function" && cmd.split(/\s+/).some((t) => t && e2e.isSpec(t.replace(/^["']+|["']+$/g, "")))) return true;
1299
1384
  return E2E_CMD_RE.test(cmd);
1300
1385
  }
1386
+ /** #5468: a `[type:e2e]`/`[type:manual]` quote whose observable only exists in production (live URL, deploy, prod probe); local stack, browser and sandbox wording is runnable pre-merge. */
1387
+ export function prodOnlyE2e(quote) {
1388
+ const q = String(quote ?? "");
1389
+ if (/\b(?:localhost|127\.0\.0\.1|local stack|playwright|browser|sandbox|staging)\b/i.test(q)) return false;
1390
+ return /https?:\/\//i.test(q) || /\b(?:after (?:the )?deploy|production|prod probe|live (?:domain|site)|prod)\b/i.test(q);
1391
+ }
1392
+ /**
1393
+ * #5468: rewrite production-only e2e/manual rows (deliver or defer; only `only` ids when given) to `post-deploy` with a generated
1394
+ * check id. Pure; returns {contract, converted:[{id, check, entry}]}. A row whose quote names no probeable URL is left alone.
1395
+ */
1396
+ export function autoPostDeployE2e(contract, only = null) {
1397
+ const converted = [];
1398
+ const requirements = (Array.isArray(contract?.requirements) ? contract.requirements : []).map((r) => {
1399
+ if (!["deliver", "defer"].includes(r?.disposition) || !wantsE2e(r) || (only && !only.includes(r.id)) || isOutOfBand(r) || !prodOnlyE2e(r.quote)) return r;
1400
+ const g = e2eCheckFor(r.id, r.quote);
1401
+ if (!g) return r;
1402
+ converted.push({ id: r.id, check: g.id, entry: g.entry });
1403
+ return { ...r, disposition: "post-deploy", bucket: "post-deploy", check: g.id, local_infeasible_why: "the observable exists only in production (live domain or deploy), so no local fixture can check it", why: "production-only e2e/manual criterion: converted by the engine to a post-deploy check (#5468)" };
1404
+ });
1405
+ return { contract: converted.length ? { ...contract, requirements } : contract, converted };
1406
+ }
1407
+ /** #5468: the row ids named by `e2e_row` failures when every failure is one; null otherwise (anything else blocks as before). */
1408
+ export function loneE2eRows(failures) {
1409
+ const fs = failures ?? [];
1410
+ if (!fs.length || !fs.every((f) => f?.code === C.CONFORMANCE_E2E_UNVERIFIED && f.kind === "e2e_row")) return null;
1411
+ const ids = fs.map((f) => /^(\S+) is a /.exec(String(f.detail ?? ""))?.[1]);
1412
+ return ids.every(Boolean) ? [...new Set(ids)] : null;
1413
+ }
1414
+ /** #5468 (#5450): a validate that declares `env` names of configured test sandboxes (forge.yaml `sandboxes`) runs against a provisioned live service: the route for an e2e check that can run pre-merge. */
1415
+ export function sandboxedRun(v, e2e = null) {
1416
+ const known = e2e?.sandboxes ?? [];
1417
+ const names = Array.isArray(v?.env) ? v.env : typeof v?.env === "string" ? v.env.split(",") : [];
1418
+ return names.some((n) => known.includes(String(n).trim()));
1419
+ }
1301
1420
  /** #4726: true when a V-ref named in the row's `validated_by` resolves to a contract validate command that is a real e2e check. */
1302
1421
  export function e2eVerified(row, contract, e2e = null) {
1303
1422
  const by = String(row?.validated_by ?? "");
1304
1423
  const refs = (contract?.validate ?? []).filter((v) => v?.id && new RegExp(`(?:^|[^A-Za-z0-9_])${v.id}(?![A-Za-z0-9_])`).test(by));
1305
- return refs.some((v) => isE2eCommand(v.command, e2e)) || (!refs.length && isE2eCommand(by, e2e));
1424
+ return refs.some((v) => isE2eCommand(v.command, e2e) || sandboxedRun(v, e2e)) || (!refs.length && isE2eCommand(by, e2e));
1306
1425
  }
1307
1426
  /**
1308
1427
  * The engine's decision from the reviewer's rows. state: conforms | nonconforming | review.unparseable | review.incomplete
@@ -1327,7 +1446,7 @@ export function decide(raw, ctx) {
1327
1446
  f.push({ code: ["deferred", "post-deploy"].includes(row.status) ? C.CONFORMANCE_UNTRACKED_DEFERRAL : C.CONFORMANCE_UNIMPLEMENTED, detail: `${r.amendment?.text ? `${r.id} amendment not accepted (amended to "${String(r.amendment.text).slice(0, 200)}"): ` : `${r.id} `}${row.status}${row.note ? `: ${row.note}` : ""}${row.evidence ? ` (${row.evidence})` : ""}` });
1328
1447
  } else if (r.disposition === "deliver" && wantsE2e(r) && !e2eVerified(row, ctx.contract, ctx.e2e)) {
1329
1448
  const faked = (ctx.e2e?.faked ?? []).length ? `; faked or mocked components in ${ctx.e2e.faked.slice(0, 3).join(", ")}` : "";
1330
- f.push({ code: C.CONFORMANCE_E2E_UNVERIFIED, kind: "e2e_row", detail: `${r.id} is a [type:e2e]/[type:manual] criterion but ${row.validated_by || "its validated_by"} is not a real end-to-end check (the repo's e2e set, Playwright/browser/live stack${faked}); run one, or mark ${r.id} post-deploy so it is transferred to the epic's acceptance` });
1449
+ f.push({ code: C.CONFORMANCE_E2E_UNVERIFIED, kind: "e2e_row", detail: `${r.id} is a [type:e2e]/[type:manual] criterion but ${row.validated_by || "its validated_by"} is not a real end-to-end check (the repo's e2e set, Playwright/browser/live stack${faked}); run one, or mark ${r.id} post-deploy so it is transferred to the epic's acceptance${ctx.e2e?.sandboxes?.length ? `; it can run pre-merge: declare env: [${ctx.e2e.sandboxes.slice(0, 3).join(", ")}] on its validate to use the test sandbox (#5450), do not defer it` : ""}` });
1331
1450
  } else if (r.disposition === "defer" && wantsE2e(r)) {
1332
1451
  // #5339: a deferred e2e/manual requirement is not met; only a post-deploy one is transferred to the epic (the lane closes partial)
1333
1452
  f.push({ code: C.CONFORMANCE_E2E_UNVERIFIED, kind: "e2e_row", detail: `${r.id} is a [type:e2e]/[type:manual] criterion deferred without a run; run the real path, or mark ${r.id} post-deploy so it is transferred to the epic's acceptance` });
@@ -3,7 +3,7 @@
3
3
  import { readFileSync } from "node:fs";
4
4
  import { describe, it } from "node:test";
5
5
  import assert from "node:assert/strict";
6
- import { outputTail, removedNamedPaths, removedPathsOf, shellSyntaxError, unrunnableValidate, noopCommand, substituteVerdict, describesUnrunnableCommand, vitestQuietFlag, normalizeRunnerCommand, cliUsageError, validateContract, applyAmendments, amendmentKindProblems, precheck, hotspotGrowth, reproFailures, isBugIssue, parseReview, checkCompleteness, decide, closePlan, isInvestigation, formatShadowSummary, followupItems, inIssue, snapQuote, snapQuotes, isTestPath, normalizeEvidencePath, mergeReviewRows, reviewSkeleton, missingIds, resolveEvidencePath, movingBaseDiff, scopeText, evidencePathLine, evidencePathOnly, reaskable, matchCriterion, criterionLines, fillEngineRows, explainFailures, resolveForgedockPaths, missingTool, repoTracks, tmpdirInputs, isScopeCheck, isPureScopeCheck, dropScopeValidates, tagOutOfBand, outOfBandRequirements, isOutOfBand, followupMap, renderPendingFollowups, VERIFY_MODES, OUT_OF_BAND_RE, FOLLOWUP_CLASSES, followupClass, inLaneDeferral, pendingTracking, BUCKETS, bucketKind, bucketProblems, bucketTally, isE2eCommand, e2eVerified, impliedDocDeliverables, applyValidateRecipes, deferChecklessPostDeploy, substituteShellProblem, reproEnvMiss, ORCHESTRATOR_BUCKET, ownerRoute, weakenedE2eDecisions, guessedUvEnv, projectDirPathMiss, rewriteProjectDirCommand, convertDelivered } from "./conformance.mjs";
6
+ import { testPlanProblems, proofEchoesDeliverable, outputTail, removedNamedPaths, removedPathsOf, shellSyntaxError, unrunnableValidate, noopCommand, substituteVerdict, describesUnrunnableCommand, vitestQuietFlag, normalizeRunnerCommand, cliUsageError, validateContract, applyAmendments, amendmentKindProblems, precheck, hotspotGrowth, reproFailures, reproQualityFailures, isBugIssue, parseReview, checkCompleteness, decide, closePlan, isInvestigation, formatShadowSummary, followupItems, inIssue, snapQuote, snapQuotes, isTestPath, normalizeEvidencePath, mergeReviewRows, reviewSkeleton, missingIds, resolveEvidencePath, movingBaseDiff, scopeText, evidencePathLine, evidencePathOnly, reaskable, matchCriterion, criterionLines, fillEngineRows, explainFailures, resolveForgedockPaths, missingTool, repoTracks, tmpdirInputs, isScopeCheck, isPureScopeCheck, dropScopeValidates, tagOutOfBand, outOfBandRequirements, isOutOfBand, followupMap, renderPendingFollowups, VERIFY_MODES, OUT_OF_BAND_RE, FOLLOWUP_CLASSES, followupClass, inLaneDeferral, pendingTracking, BUCKETS, bucketKind, bucketProblems, bucketTally, isE2eCommand, e2eVerified, impliedDocDeliverables, applyValidateRecipes, deferChecklessPostDeploy, substituteShellProblem, reproEnvMiss, ORCHESTRATOR_BUCKET, ownerRoute, weakenedE2eDecisions, guessedUvEnv, projectDirPathMiss, rewriteProjectDirCommand, convertDelivered } from "./conformance.mjs";
7
7
 
8
8
  const ISSUE = "## Requirements\n1. The scrape route must release the spend reservation on 429.\n2. The search route must release the spend reservation on 429.\n\n- [ ] Billing pricing is unchanged.";
9
9
  const Q1 = "The scrape route must release the spend reservation on 429.";
@@ -278,8 +278,10 @@ describe("precheck (deterministic, no reviewer)", () => {
278
278
  assert.equal(pc.failures[0].kind, "validate_env"); assert.equal(pc.failures[0].tool, "yaml");
279
279
  assert.match(pc.failures[0].detail, /could not run: the host is missing Python module 'yaml'/);
280
280
  assert.deepEqual(codes(precheck({ contract: C, result: failed, changedFiles: files, validateRuns: { V1: { rc: 127, output: "bash: line 1: pytest: command not found" } } })), ["env.tool_missing"]);
281
- assert.deepEqual(codes(precheck({ contract: C, result: failed, changedFiles: files, ciVerified: true, validateRuns: { V1: { rc: 127, output: "bash: pytest: command not found" } } })), [], "CI-verified head: like a validate left to CI");
281
+ assert.deepEqual(codes(precheck({ contract: C, result: failed, changedFiles: files, ciVerified: true, validateRuns: { V1: { rc: 127, output: "bash: pytest: command not found" } } })), ["env.tool_missing"], "#5447: a CI-verified head never covers a test the host could not run");
282
282
  assert.deepEqual(codes(precheck({ contract: C, result: failed, changedFiles: files, validateRuns: { V1: { rc: 0, output: "" } } })), [], "a passing rerun counts as passed");
283
+ { const pc5447 = precheck({ contract: C, result: failed, changedFiles: files, ciVerified: true, validateRuns: { V1: { rc: 127, output: "bash: pytest: command not found" } } }); assert.deepEqual(pc5447.ciCovered, [], "#5447: validate_env is never ciCovered"); assert.equal(pc5447.failures[0].kind, "validate_env"); }
284
+ { const un = precheck({ contract: C, result: { ...res, validation: [] }, changedFiles: files }); assert.ok(un.failures.length > 0 && un.ciCovered.length === 0, "#5447: a declared test with no executed result blocks"); }
283
285
  assert.deepEqual(codes(precheck({ contract: C, result: failed, changedFiles: files, validateRuns: { V1: { rc: 1, output: "AssertionError: 1 !== 2" } } })), ["conformance.unimplemented"]);
284
286
  // #4906: a rerun that timed out (rc 124) is infrastructure, never conformance.unimplemented
285
287
  assert.deepEqual(codes(precheck({ contract: C, result: failed, changedFiles: files, validateRuns: { V1: { rc: 124, output: "(timed out)" } } })), ["env.validate_timeout"]);
@@ -301,6 +303,11 @@ describe("precheck (deterministic, no reviewer)", () => {
301
303
  assert.deepEqual(codes(carried), []);
302
304
  assert.deepEqual(precheck({ contract: C, result: { ...res, validation: [] }, changedFiles: files }).failures.map((f) => f.kind), ["validate_missing"]);
303
305
  });
306
+ it("#5446 reproQualityFailures: a mutation survivor fails only when enforced; patch_echo and behavioural never do", () => {
307
+ assert.equal(reproQualityFailures({ quality: "mutation_survivor", enforce: true })[0].kind, "repro_mutation_survivor");
308
+ assert.deepEqual(reproQualityFailures({ quality: "mutation_survivor", enforce: false }), []);
309
+ assert.deepEqual(reproQualityFailures({ quality: "patch_echo", enforce: true }), []);
310
+ });
304
311
  it("#4323 missingTool: commands, python and node modules; paths, relative and repo-tracked names are not the environment", () => {
305
312
  assert.deepEqual(missingTool({ rc: 127, output: "sh: 1: jq: not found" }), { tool: "jq", kind: "command" });
306
313
  assert.deepEqual(missingTool({ rc: 127, output: "" }, { command: "uv run pytest -q" }), { tool: "uv", kind: "command" });
@@ -784,6 +791,10 @@ describe("hotspot growth precheck (forge#4195)", () => {
784
791
  assert.equal(run(hs([big])).ok, false);
785
792
  assert.equal(run(hs([{ ...big, generated: true }])).ok, true);
786
793
  assert.equal(run(hs([{ ...big, generated: true, excluded: true }])).ok, true);
794
+ // #5470: a generated/ segment row (generated:true from hotspots.sh) grown by 6k lines passes; hand-written still flags
795
+ const seg = H({ path: "src/scrape.js", lines: 6607, base_lines: 0, growth: 6607 });
796
+ assert.equal(run(hs([{ ...seg, generated: true, excluded: true }])).ok, true);
797
+ assert.equal(run(hs([{ ...seg, generated: false }])).ok, false);
787
798
  });
788
799
 
789
800
  it("within the limit, under the threshold, excluded, unchanged, disabled or no facts: no failure", () => {
@@ -1485,7 +1496,7 @@ describe("#5020 freeze-time environment defects", () => {
1485
1496
  assert.equal(reproEnvMiss({ rc: 0, output: "" }), null);
1486
1497
  });
1487
1498
  it("a post-deploy requirement with no check id is deferred to the orchestrator; one with a check is untouched", () => {
1488
- const c = { requirements: [{ id: "R1", quote: "q", disposition: "post-deploy", why: "needs prod creds" }, { id: "R2", quote: "q", disposition: "post-deploy", check: "login-smoke", why: "w" }] };
1499
+ const c = { requirements: [{ id: "R1", quote: "q", disposition: "post-deploy", why: "needs prod credentials" }, { id: "R2", quote: "q", disposition: "post-deploy", check: "login-smoke", why: "w" }] };
1489
1500
  const { contract, converted } = deferChecklessPostDeploy(c);
1490
1501
  assert.deepEqual(converted, ["R1"]);
1491
1502
  assert.equal(contract.requirements[0].disposition, "defer");
@@ -1493,6 +1504,26 @@ describe("#5020 freeze-time environment defects", () => {
1493
1504
  assert.equal(contract.requirements[1].disposition, "post-deploy");
1494
1505
  assert.deepEqual(bucketProblems(contract.requirements[0]), []);
1495
1506
  });
1507
+ it("#5448: a check-less prod-only claim is not converted and freeze rejects it; local_infeasible_why is required", () => {
1508
+ const c = { requirements: [{ id: "R1", quote: "Listing returns results on prod.", disposition: "post-deploy", bucket: "post-deploy", why: "only measurable on prod after release" }], deliverables: [], validate: [{ id: "V1", command: "true" }] };
1509
+ const d = deferChecklessPostDeploy(c);
1510
+ assert.deepEqual(d.converted, []);
1511
+ const v = validateContract(d.contract, "Listing returns results on prod.");
1512
+ assert.ok(v.problems.some((p) => /needs a check id/.test(p)));
1513
+ assert.ok(v.problems.some((p) => /local_infeasible_why/.test(p)));
1514
+ const ok = validateContract({ ...c, requirements: [{ ...c.requirements[0], check: "listing-prod", local_infeasible_why: "needs live vendor traffic" }] }, "Listing returns results on prod.");
1515
+ assert.deepEqual(ok.problems, []);
1516
+ });
1517
+ it("#5448 replay of #40539: development work cannot be deferred as prod-only", () => {
1518
+ const q = "Find and fix the 403 signal for reddit listings.";
1519
+ const r = { id: "R3", quote: q, disposition: "post-deploy", bucket: "post-deploy", check: "reddit-403", why: "w", local_infeasible_why: "live" };
1520
+ const v = validateContract({ requirements: [r], deliverables: [], validate: [{ id: "V1", command: "true" }] }, q);
1521
+ assert.ok(v.problems.some((p) => /development work/.test(p)));
1522
+ });
1523
+ it("#5448: a malformed regression set is a contract problem", () => {
1524
+ const c = { requirements: [{ id: "R1", quote: "q q q q q q q q q q q q", disposition: "deliver" }], deliverables: [{ id: "D1", path: "a", change: "c" }], validate: [{ id: "V1", command: "true" }], regression: [{ id: "G1" }] };
1525
+ assert.ok(validateContract(c, "q q q q q q q q q q q q").problems.some((p) => /regression entry/.test(p)));
1526
+ });
1496
1527
  it("a post-deploy amendment with no check becomes a tracked defer instead of a problem", () => {
1497
1528
  const c = { requirements: [{ id: "R1", quote: "q", disposition: "deliver" }], deliverables: [], validate: [] };
1498
1529
  const r = applyAmendments(c, [{ kind: "post-deploy", requirement: "R1", why: "manual prod action" }], "q");
@@ -1759,3 +1790,141 @@ describe("#5339 a faked or deferred e2e/manual requirement is not met", () => {
1759
1790
  assert.deepEqual(codes(decide(rv({ status: "deferred", deferral_ok: false }), c2)), ["conformance.unjustified_deferral"]);
1760
1791
  });
1761
1792
  });
1793
+
1794
+ import { contractBriefProblems as pageBriefProblems, parsePagesConfig as parsePagesCfg } from "./pagegate.mjs";
1795
+ describe("page gate wiring (#5428)", () => {
1796
+ it("validateContract reports missing page_gate briefs and precheck carries pageFailures", () => {
1797
+ const pages = parsePagesCfg(undefined, { hasAppPages: true });
1798
+ const c = { requirements: [{ id: "R1", quote: "q", disposition: "deliver" }], deliverables: [{ id: "D1", path: "web/app/x/page.tsx", change: "c", requirements: ["R1"] }], validate: [] };
1799
+ assert.equal(pageBriefProblems(c, pages).length, 1);
1800
+ assert.ok(validateContract(c, "q", { pages }).problems.some((p) => /page_gate/.test(p)));
1801
+ assert.ok(!validateContract(c, "q").problems.some((p) => /page_gate/.test(p)));
1802
+ const pc = precheck({ contract: c, result: {}, changedFiles: [], pageFailures: [{ code: "x", kind: "page_sitemap_missing", detail: "d" }] });
1803
+ assert.ok(pc.failures.some((f) => f.kind === "page_sitemap_missing"));
1804
+ });
1805
+ });
1806
+
1807
+ describe("test plan frozen with the contract (#5445)", () => {
1808
+ const D = [{ id: "D1", path: "src/scrape.js", change: "rewrite the listing .json URL to old.reddit.com", requirements: ["R1"] }, { id: "D2", path: "src/search.js", requirements: ["R2"] }];
1809
+ const row = (r, o = {}) => ({ requirement: r, proof: "www.reddit.com listing .json returns 200 JSON instead of 403", level: "integration", level_reason: "a real HTTP fixture observes the status", repro: "test/x.test.js#403", regression: ["old.reddit.com listings"], env: ["http fixture"], command: "node --test test/x.test.js", ...o });
1810
+ const K = (plan) => ({ ...C, deliverables: D, test_plan: plan });
1811
+ const bug = (c) => validateContract(c, ISSUE, { testPlan: true }).problems.join("\n");
1812
+ it("a complete plan is valid; without the option an old contract stays valid", () => {
1813
+ assert.deepEqual(validateContract(K([row("R1"), row("R2")]), ISSUE, { testPlan: true }), { ok: true, problems: [] });
1814
+ assert.deepEqual(validateContract(C, ISSUE), { ok: true, problems: [] });
1815
+ });
1816
+ it("a bug requirement without a row, or without a repro, is rejected", () => {
1817
+ assert.match(bug(K([row("R1")])), /R2: test_plan needs a row/);
1818
+ assert.match(bug(C), /R1: test_plan needs a row/);
1819
+ assert.match(bug(K([row("R1", { repro: "" }), row("R2")])), /R1: test_plan repro must be a test id/);
1820
+ assert.match(bug(K([row("R1", { repro: "no-repro" }), row("R2")])), /R1: test_plan no-repro needs a reason/);
1821
+ assert.equal(bug(K([row("R1", { repro: "no-repro", reason: "spec-only change" }), row("R2")])), "");
1822
+ });
1823
+ it("a proof that echoes a deliverable is rejected; one about the 403 is accepted", () => {
1824
+ assert.match(bug(K([row("R1", { proof: "the listing .json URL is rewritten to old.reddit.com" }), row("R2")])), /R1: test_plan proof only restates a deliverable/);
1825
+ assert.equal(proofEchoesDeliverable("the listing json URL is rewritten", D.slice(0, 1)), true);
1826
+ assert.equal(proofEchoesDeliverable("returns 200 JSON instead of 403", D.slice(0, 1)), false);
1827
+ });
1828
+ it("level, its reason and the command are checked; mocking the bug's component is rejected", () => {
1829
+ assert.match(testPlanProblems(K([row("R1", { level: "manual" })])).join(), /level must be one of/);
1830
+ assert.match(testPlanProblems(K([row("R1", { level_reason: "" })])).join(), /level_reason/);
1831
+ assert.match(testPlanProblems(K([row("R1", { level_reason: "mock the fetcher" })])).join(), /mocking the component/);
1832
+ assert.equal(testPlanProblems(K([row("R1", { level_reason: "no mocks needed, real fixture" })])).length, 0);
1833
+ assert.match(testPlanProblems(K([row("R1", { command: "" })])).join(), /exact command/);
1834
+ assert.match(testPlanProblems({ ...C, test_plan: "x" }).join(), /must be an array/);
1835
+ });
1836
+ it("applyValidateRecipes rewrites test_plan commands", () => {
1837
+ const r = applyValidateRecipes(K([row("R1")]), [{ match: "^node --test", replace: "npx node --test" }]);
1838
+ assert.equal(r.contract.test_plan[0].command, "npx node --test test/x.test.js");
1839
+ });
1840
+ });
1841
+
1842
+ import { pathCovers as cover5440 } from "./conformance.mjs";
1843
+ describe("#5440 pathCovers: directory without slash, renumbered sequence file", () => {
1844
+ it("#5440 directory deliverable without slash covers files beneath it", () => {
1845
+ assert.ok(cover5440("listings/official/travel", "listings/official/travel/agent.md"));
1846
+ assert.ok(cover5440("listings/official/travel", "listings/official/travel/a/b/page.md"));
1847
+ assert.ok(cover5440("listings/official/travel", "listings/official/travel"));
1848
+ });
1849
+ it("#5440 a sibling directory sharing the prefix is not covered", () => {
1850
+ assert.ok(!cover5440("listings/official/travel", "listings/official/travel2/agent.md"));
1851
+ assert.ok(!cover5440("listings/official/travel", "listings/official/jobs/agent.md"));
1852
+ });
1853
+ it("#5440 a renumbered migration is covered (exact and glob); other dirs and names are not", () => {
1854
+ assert.ok(cover5440("db/migrations/0637_add_x.sql", "db/migrations/0639_add_x.sql"));
1855
+ assert.ok(cover5440("db/migrations/0637_*", "db/migrations/0639_add_x.sql"));
1856
+ assert.ok(!cover5440("db/migrations/0637_add_x.sql", "db/migrations/0639_other.sql"));
1857
+ assert.ok(!cover5440("db/migrations/0637_*", "other/0639_add_x.sql"));
1858
+ assert.ok(!cover5440("src/a.js", "src/b.js"));
1859
+ });
1860
+ });
1861
+
1862
+ describe("#5449 test adequacy kinds are enforced by default", () => {
1863
+ it("test_missing and test_weak block in a shadow lane; other kinds still follow the lane", async () => {
1864
+ const { blockingFailures } = await import("./conformance.mjs");
1865
+ const f = [{ code: "x.a", kind: "test_missing" }, { code: "x.b", kind: "test_weak" }, { code: "x.c", kind: "other" }];
1866
+ const r = blockingFailures(f, { shadow: true });
1867
+ assert.deepEqual(r.block.map((x) => x.code), ["x.a", "x.b"]); assert.deepEqual(r.record.map((x) => x.code), ["x.c"]);
1868
+ });
1869
+ });
1870
+
1871
+ import { prodOnlyE2e, autoPostDeployE2e, loneE2eRows, sandboxedRun } from "./conformance.mjs";
1872
+ import { e2eCheckFor, mergeCheckEntries, parseChecks } from "./postdeploy-check.mjs";
1873
+
1874
+ describe("#5468 production-only e2e/manual criteria become post-deploy checks", () => {
1875
+ const PQ = "`https://store.alterlab.io/{slug}/agent.md` returns 200 for every published listing [type:e2e]";
1876
+ const LQ = "The signup page works against the local stack in a browser [type:e2e]";
1877
+ const mk = (quote) => {
1878
+ const contract = { ...C, requirements: [{ id: "R1", quote, disposition: "deliver" }, C.requirements[1]], validate: [{ id: "V1", command: "pytest tests/test_x.py" }] };
1879
+ return { contract, ctx: { ...ctx, contract, issueText: `${ISSUE}\n${quote}` } };
1880
+ };
1881
+ const decideRow = (quote) => { const m = mk(quote); const r = { ...good, issue_coverage: [{ quote, status: "covered" }, ...good.issue_coverage.slice(1)] }; return { m, d: decide(r, m.ctx) }; };
1882
+ it("classifies production-only versus pre-merge-runnable quotes", () => {
1883
+ assert.equal(prodOnlyE2e(PQ), true);
1884
+ assert.equal(prodOnlyE2e("Re-run the probe after deploy [type:manual]"), true);
1885
+ assert.equal(prodOnlyE2e(LQ), false);
1886
+ });
1887
+ it("freeze converts a prod-only row to post-deploy with a generated check that parses", () => {
1888
+ const { contract } = mk(PQ);
1889
+ const out = autoPostDeployE2e(contract);
1890
+ const r = out.contract.requirements[0];
1891
+ assert.equal(r.disposition, "post-deploy");
1892
+ assert.match(r.check, /^e2e-r1-[0-9a-f]+$/);
1893
+ assert.equal(out.contract.requirements[1].disposition, "deliver");
1894
+ assert.ok(parseChecks(mergeCheckEntries("", { [r.check]: out.converted[0].entry }))[r.check]);
1895
+ assert.equal(autoPostDeployE2e(mk(LQ).contract).converted.length, 0);
1896
+ });
1897
+ it("prod-only e2e_unverified converts instead of blocking", () => {
1898
+ const { m, d } = decideRow(PQ);
1899
+ assert.equal(d.state, "nonconforming");
1900
+ const ids = loneE2eRows(d.failures);
1901
+ assert.deepEqual(ids, ["R1"]);
1902
+ const cv = autoPostDeployE2e(m.contract, ids);
1903
+ assert.equal(cv.converted.length, ids.length);
1904
+ assert.equal(cv.contract.requirements[0].disposition, "post-deploy");
1905
+ });
1906
+ it("mixed failures, rows without a probeable URL and pre-merge rows still block", () => {
1907
+ assert.equal(loneE2eRows([{ code: "conformance.e2e_unverified", kind: "e2e_row", detail: "R1 is a x" }, { code: "conformance.unimplemented", detail: "R2 x" }]), null);
1908
+ assert.equal(loneE2eRows([{ code: "conformance.e2e_unverified", kind: "ui_browser_unverified", detail: "x" }]), null);
1909
+ assert.equal(e2eCheckFor("R1", "Operators restore after deploy [type:manual]"), null);
1910
+ const { m, d } = decideRow(LQ);
1911
+ assert.equal(autoPostDeployE2e(m.contract, loneE2eRows(d.failures)).converted.length, 0);
1912
+ });
1913
+ it("a pre-merge e2e row is verified by a validate declaring a configured test sandbox, never deferred (#5450 route)", () => {
1914
+ const m = mk(LQ);
1915
+ m.contract.validate = [{ id: "V1", command: "pytest tests/test_x.py", env: ["web"] }];
1916
+ const r = { ...good, issue_coverage: [{ quote: LQ, status: "covered" }, ...good.issue_coverage.slice(1)] };
1917
+ assert.equal(sandboxedRun(m.contract.validate[0], { sandboxes: ["web"] }), true);
1918
+ assert.equal(sandboxedRun(m.contract.validate[0], { sandboxes: [] }), false);
1919
+ assert.equal(decide(r, { ...m.ctx, contract: m.contract, e2e: { sandboxes: ["web"] } }).state, "conforms");
1920
+ const d = decide(r, { ...m.ctx, contract: m.contract, e2e: { sandboxes: ["db"] } });
1921
+ assert.match(d.failures[0].detail, /declare env: \[db\] on its validate to use the test sandbox/);
1922
+ const rd = { ...r, requirements: [{ ...r.requirements[0], status: "deferred", deferral_ok: true }, ...r.requirements.slice(1)] };
1923
+ const dd = decide(rd, { ...m.ctx, contract: { ...m.contract, requirements: [{ ...m.contract.requirements[0], disposition: "defer", bucket: "post-deploy" }, m.contract.requirements[1]] }, e2e: { sandboxes: ["web"] } });
1924
+ assert.ok(dd.failures.some((f) => f.code === "conformance.e2e_unverified"), "a deferred pre-merge e2e row still fails");
1925
+ });
1926
+ it("mergeCheckEntries keeps existing entries", () => {
1927
+ const o = JSON.parse(mergeCheckEntries(JSON.stringify({ a: { run: "x" } }), { a: { run: "y" }, b: { run: "z" } }));
1928
+ assert.equal(o.a.run, "x"); assert.equal(o.b.run, "z");
1929
+ });
1930
+ });
@@ -58,6 +58,27 @@ function detect(fs, wt) {
58
58
  if (has("uv.lock")) out.push({ eco: "uv", lock: "uv.lock" });
59
59
  else if (has("poetry.lock")) out.push({ eco: "poetry", lock: "poetry.lock" });
60
60
  else out.push(...serviceLocks(fs, wt));
61
+ out.push(...nestedJsLocks(fs, wt));
62
+ return out;
63
+ }
64
+
65
+ const JS_LOCKS = [["pnpm", "pnpm-lock.yaml"], ["npm", "package-lock.json"], ["yarn", "yarn.lock"]];
66
+ const JS_DIRS = ["web", "frontend", "client", "ui"];
67
+ /** #5423: JS lockfiles one level down (web/, frontend/, services|packages|apps/<name>/) with their own package.json; each is prepared in its own dir, so a sandbox has the vitest/vite a validate command calls. */
68
+ function nestedJsLocks(fs, wt) {
69
+ const dirs = [...JS_DIRS];
70
+ for (const root of SERVICE_ROOTS) {
71
+ try { for (const n of fs.readdirSync(join(wt, root)).sort()) dirs.push(`${root}/${n}`); } catch { /* absent */ }
72
+ }
73
+ const out = [];
74
+ for (const dir of dirs) {
75
+ if (out.length >= SERVICE_CAP) break;
76
+ try {
77
+ if (!fs.existsSync(join(wt, dir, "package.json"))) continue;
78
+ const hit = JS_LOCKS.find(([, lock]) => fs.existsSync(join(wt, dir, lock)));
79
+ if (hit) out.push({ eco: hit[0], lock: hit[1], dir, ...(hit[0] === "yarn" ? { berry: fs.existsSync(join(wt, dir, ".yarnrc.yml")) } : {}) });
80
+ } catch { /* unreadable: skip */ }
81
+ }
61
82
  return out;
62
83
  }
63
84
 
@@ -304,8 +325,8 @@ export function makeDepCache({ root = depcacheRoot(), exec, fs = nodeFs, now = (
304
325
  for (const d of found) {
305
326
  try {
306
327
  const r = await prepareOne(d.dir ? join(wt, d.dir) : wt, keyRoot, d, laneEnv && typeof laneEnv === "object" ? laneEnv : undefined);
307
- out.push(d.dir ? { ...r, dir: d.dir } : r);
308
- } catch (e) { out.push({ status: "failed", eco: d.eco, key: null, ms: 0, reason: msg(e) }); }
328
+ out.push({ ...r, dir: d.dir ?? "." });
329
+ } catch (e) { out.push({ status: "failed", eco: d.eco, key: null, ms: 0, reason: msg(e), dir: d.dir ?? "." }); }
309
330
  }
310
331
  return out;
311
332
  }
@@ -137,6 +137,7 @@ describe("depcache (#4220): shared dependency installs keyed by lock hash", () =
137
137
  assert.equal(ra.status, "miss-installed", JSON.stringify(ra));
138
138
  assert.equal(ra.published, true);
139
139
  assert.equal(ra.eco, eco);
140
+ assert.equal(ra.dir, ".", "#5447: every result row carries its project dir");
140
141
  const [snap] = snapDirs(root, eco);
141
142
  assert.ok(snap && existsSync(join(snap, "manifest.json")));
142
143
  const fullInstalls = f.installs().length;
@@ -449,3 +450,24 @@ describe("depcache (#5331): per-service Python lockfiles", () => {
449
450
  assert.equal(r.reason, "no lockfile");
450
451
  });
451
452
  });
453
+
454
+ describe("depcache (#5423): nested JS lockfiles", () => {
455
+ it("web/package-lock.json is prepared in web/ next to a root without a lockfile", async () => {
456
+ const { cache, base } = setup("npm");
457
+ const wt = join(base, "wt", "web");
458
+ mkdirSync(wt, { recursive: true });
459
+ FIXTURES.npm(join(wt, "web"));
460
+ const res = await cache.prepare({ wt, repoKey: "repo-web" });
461
+ assert.equal(res.length, 1, JSON.stringify(res));
462
+ assert.equal(res[0].eco, "npm");
463
+ assert.equal(res[0].dir, "web");
464
+ assert.ok(["miss-installed", "hit"].includes(res[0].status), JSON.stringify(res[0]));
465
+ });
466
+ it("a web/ without its own package.json is not prepared", async () => {
467
+ const { cache, base } = setup("npm");
468
+ const wt = join(base, "wt", "web2");
469
+ put(join(wt, "web/package-lock.json"), "{}");
470
+ const [r] = await cache.prepare({ wt, repoKey: "repo-web2" });
471
+ assert.equal(r.reason, "no lockfile");
472
+ });
473
+ });