forgedock 1.52.0 → 1.54.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 (233) hide show
  1. package/.claude-plugin/marketplace.json +51 -0
  2. package/README.md +8 -2
  3. package/bin/auth/app-manifest.mjs +89 -0
  4. package/bin/auth/app-manifest.test.mjs +75 -0
  5. package/bin/auth/app-token.mjs +256 -0
  6. package/bin/auth/app-token.test.mjs +232 -0
  7. package/bin/brand.mjs +7 -0
  8. package/bin/config-history.mjs +151 -0
  9. package/bin/config-schema.mjs +115 -0
  10. package/bin/demo.mjs +65 -11
  11. package/bin/engine/outcome-codes.mjs +9 -3
  12. package/bin/engine/telemetry-seam.mjs +11 -3
  13. package/bin/engine/telemetry-seam.test.mjs +17 -0
  14. package/bin/engine-cli.mjs +110 -36
  15. package/bin/experiment.mjs +58 -6
  16. package/bin/first-run.mjs +122 -0
  17. package/bin/forge-utils.mjs +6 -2
  18. package/bin/forgedock.mjs +138 -142
  19. package/bin/help-text.mjs +144 -0
  20. package/bin/hooks/pre-tool-use.mjs +7 -0
  21. package/bin/journey.mjs +82 -83
  22. package/bin/lean/acceptance.mjs +313 -0
  23. package/bin/lean/acceptance.test.mjs +215 -0
  24. package/bin/lean/account-watch.mjs +28 -0
  25. package/bin/lean/account-watch.test.mjs +30 -0
  26. package/bin/lean/activation.mjs +38 -0
  27. package/bin/lean/activation.test.mjs +36 -1
  28. package/bin/lean/basered.mjs +115 -0
  29. package/bin/lean/basered.test.mjs +66 -0
  30. package/bin/lean/batch-health.mjs +114 -7
  31. package/bin/lean/batch-health.test.mjs +87 -1
  32. package/bin/lean/batch.mjs +41 -2
  33. package/bin/lean/batch.test.mjs +115 -11
  34. package/bin/lean/branchlock.mjs +54 -0
  35. package/bin/lean/branchlock.test.mjs +49 -0
  36. package/bin/lean/ceiling.mjs +72 -0
  37. package/bin/lean/ceiling.test.mjs +54 -0
  38. package/bin/lean/checkpoint-reconcile.mjs +43 -0
  39. package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
  40. package/bin/lean/ci-budget.mjs +366 -0
  41. package/bin/lean/ci-budget.test.mjs +167 -0
  42. package/bin/lean/conformance.e2e.test.mjs +8 -1
  43. package/bin/lean/conformance.mjs +269 -38
  44. package/bin/lean/conformance.test.mjs +280 -7
  45. package/bin/lean/context.mjs +35 -6
  46. package/bin/lean/context.test.mjs +27 -1
  47. package/bin/lean/depcache.mjs +25 -1
  48. package/bin/lean/depcache.test.mjs +26 -0
  49. package/bin/lean/e2e.mjs +18 -2
  50. package/bin/lean/e2e.test.mjs +26 -1
  51. package/bin/lean/effects.mjs +47 -14
  52. package/bin/lean/execution.mjs +19 -3
  53. package/bin/lean/execution.test.mjs +63 -0
  54. package/bin/lean/facts.mjs +3 -3
  55. package/bin/lean/facts.test.mjs +5 -0
  56. package/bin/lean/findinglabel.mjs +16 -0
  57. package/bin/lean/findinglabel.test.mjs +39 -0
  58. package/bin/lean/fixround.mjs +14 -0
  59. package/bin/lean/fixround.test.mjs +25 -2
  60. package/bin/lean/gh-assoc.test.mjs +2 -1
  61. package/bin/lean/integration.mjs +100 -9
  62. package/bin/lean/integration.test.mjs +98 -0
  63. package/bin/lean/issuewatch-parity.mjs +64 -0
  64. package/bin/lean/issuewatch-parity.test.mjs +127 -0
  65. package/bin/lean/issuewatch-release.mjs +6 -2
  66. package/bin/lean/issuewatch-release.test.mjs +17 -1
  67. package/bin/lean/issuewatch.mjs +45 -6
  68. package/bin/lean/issuewatch.test.mjs +3 -2
  69. package/bin/lean/lanelock.mjs +14 -0
  70. package/bin/lean/lean.mjs +473 -100
  71. package/bin/lean/lean.test.mjs +686 -33
  72. package/bin/lean/light.mjs +48 -7
  73. package/bin/lean/light.test.mjs +37 -3
  74. package/bin/lean/limits.test.mjs +142 -9
  75. package/bin/lean/mechfix.mjs +124 -0
  76. package/bin/lean/mechfix.test.mjs +75 -0
  77. package/bin/lean/orchestrate-cancel.test.mjs +143 -0
  78. package/bin/lean/orchestrate.mjs +116 -28
  79. package/bin/lean/phaseledger.mjs +47 -5
  80. package/bin/lean/phaseledger.test.mjs +30 -1
  81. package/bin/lean/postdeploy-check.test.mjs +39 -0
  82. package/bin/lean/precheck.mjs +23 -4
  83. package/bin/lean/precheck.test.mjs +14 -1
  84. package/bin/lean/prereq.mjs +28 -0
  85. package/bin/lean/prereq.test.mjs +20 -0
  86. package/bin/lean/probe.mjs +4 -2
  87. package/bin/lean/prodparity.mjs +52 -0
  88. package/bin/lean/prodparity.test.mjs +67 -0
  89. package/bin/lean/prompts.mjs +77 -19
  90. package/bin/lean/quota.mjs +39 -0
  91. package/bin/lean/recovery.test.mjs +11 -1
  92. package/bin/lean/relaxation.mjs +73 -0
  93. package/bin/lean/relaxation.test.mjs +54 -0
  94. package/bin/lean/release-io.test.mjs +42 -0
  95. package/bin/lean/release-postmerge.mjs +125 -0
  96. package/bin/lean/release-preflight.mjs +58 -0
  97. package/bin/lean/release-preflight.test.mjs +114 -0
  98. package/bin/lean/release-rehearsal.mjs +64 -0
  99. package/bin/lean/release-rehearsal.test.mjs +93 -0
  100. package/bin/lean/release-review.e2e.test.mjs +77 -0
  101. package/bin/lean/release-review.mjs +254 -0
  102. package/bin/lean/release-review.test.mjs +307 -0
  103. package/bin/lean/release-snapshot.mjs +188 -0
  104. package/bin/lean/release-snapshot.test.mjs +190 -0
  105. package/bin/lean/release.mjs +296 -0
  106. package/bin/lean/release.test.mjs +387 -0
  107. package/bin/lean/render.mjs +1 -1
  108. package/bin/lean/replan.mjs +184 -0
  109. package/bin/lean/replan.test.mjs +110 -0
  110. package/bin/lean/resume.mjs +9 -7
  111. package/bin/lean/resume.test.mjs +16 -0
  112. package/bin/lean/rotator.mjs +150 -31
  113. package/bin/lean/rotator.test.mjs +105 -2
  114. package/bin/lean/sandbox-remote.mjs +9 -2
  115. package/bin/lean/schedd.mjs +83 -5
  116. package/bin/lean/schedd.test.mjs +108 -7
  117. package/bin/lean/selfreview.mjs +94 -0
  118. package/bin/lean/selfreview.test.mjs +58 -1
  119. package/bin/lean/selftest-gate.mjs +22 -0
  120. package/bin/lean/selftest-gate.test.mjs +18 -1
  121. package/bin/lean/selftest-journey.mjs +234 -0
  122. package/bin/lean/selftest-journey.test.mjs +130 -0
  123. package/bin/lean/selftest-live.mjs +2 -1
  124. package/bin/lean/seqlease.mjs +35 -1
  125. package/bin/lean/seqlease.test.mjs +15 -0
  126. package/bin/lean/seqreserve.e2e.test.mjs +135 -0
  127. package/bin/lean/seqreserve.mjs +73 -0
  128. package/bin/lean/seqreserve.test.mjs +134 -0
  129. package/bin/lean/sequence.mjs +35 -6
  130. package/bin/lean/seqversioned.mjs +147 -0
  131. package/bin/lean/stagestamp.mjs +28 -0
  132. package/bin/lean/stagestamp.test.mjs +32 -0
  133. package/bin/lean/surfaces.mjs +75 -0
  134. package/bin/lean/surfaces.test.mjs +59 -0
  135. package/bin/lean/toolplace.mjs +28 -0
  136. package/bin/lean/toolplace.test.mjs +24 -0
  137. package/bin/lean/toolstats.mjs +3 -1
  138. package/bin/lean/toolstats.test.mjs +11 -0
  139. package/bin/lean/validatebest.mjs +28 -0
  140. package/bin/lean/validatebest.test.mjs +27 -0
  141. package/bin/lean/verifier.mjs +3 -2
  142. package/bin/lean/verify.mjs +2 -1
  143. package/bin/lean/verify.test.mjs +6 -0
  144. package/bin/pool/agent.mjs +27 -4
  145. package/bin/pool/docker.mjs +5 -0
  146. package/bin/pool/router.mjs +74 -28
  147. package/bin/prereqs.mjs +111 -0
  148. package/bin/replay-timelapse.mjs +149 -0
  149. package/bin/review-staging.mjs +123 -16
  150. package/bin/review-staging.test.mjs +18 -0
  151. package/bin/runner.mjs +43 -6
  152. package/bin/splash-install.mjs +157 -0
  153. package/bin/stats/aggregate.mjs +8 -1
  154. package/bin/stats/conformance-outcomes.mjs +289 -0
  155. package/bin/stats/conformance-outcomes.test.mjs +274 -0
  156. package/bin/stats/depth.mjs +275 -0
  157. package/bin/stats/depth.test.mjs +158 -0
  158. package/bin/stats/efficiency.mjs +26 -5
  159. package/bin/stats/efficiency.test.mjs +45 -1
  160. package/bin/stats/experiment.mjs +7 -5
  161. package/bin/stats/first-review.mjs +77 -0
  162. package/bin/stats/first-review.test.mjs +36 -0
  163. package/bin/stats/firstmerge.mjs +40 -0
  164. package/bin/stats/firstmerge.test.mjs +41 -0
  165. package/bin/stats/github-source.mjs +53 -15
  166. package/bin/stats/index.mjs +147 -9
  167. package/bin/stats/local-source.mjs +12 -0
  168. package/bin/stats/origin.mjs +80 -0
  169. package/bin/stats/origin.test.mjs +58 -0
  170. package/bin/stats/query.mjs +69 -0
  171. package/bin/stats/render.mjs +3 -1
  172. package/bin/stats/scoreboard.mjs +137 -0
  173. package/bin/stats/scoreboard.test.mjs +87 -0
  174. package/bin/stats/selffiled.mjs +52 -0
  175. package/bin/stats/selffiled.test.mjs +71 -0
  176. package/bin/stats/stats.test.mjs +80 -0
  177. package/bin/tui.mjs +3 -2
  178. package/commands/bootstrap.md +15 -14
  179. package/commands/deploy-pr.md +18 -3
  180. package/commands/forge-stats.md +1 -1
  181. package/commands/forgedock-ci-setup.md +28 -0
  182. package/commands/forgedock-init.md +4 -5
  183. package/commands/issue.md +2 -0
  184. package/commands/milestone.md +9 -1
  185. package/commands/orchestrate.md +1 -1
  186. package/commands/replay.md +2 -0
  187. package/commands/review-pr-agents/security.md +4 -0
  188. package/commands/review-pr-staging.md +6 -1
  189. package/commands/work-on/build.md +4 -6
  190. package/commands/work-on/close.md +8 -0
  191. package/docs/CONFIG.md +170 -18
  192. package/docs/ISSUE-WATCH.md +25 -0
  193. package/docs/OUTCOME-CODES.md +4 -0
  194. package/docs/REPLAY.md +9 -0
  195. package/docs/SELFTEST.md +11 -0
  196. package/docs/STATS.md +61 -0
  197. package/docs/TELEMETRY.md +1 -1
  198. package/docs/eval/README.md +6 -0
  199. package/docs/eval/adversarial-bench.md +68 -0
  200. package/docs/eval/corpus/adversarial-v1.json +285 -0
  201. package/docs/eval/feature-bench.md +42 -0
  202. package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
  203. package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
  204. package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
  205. package/docs/site/start-a-new-project.md +2 -1
  206. package/package.json +5 -2
  207. package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
  208. package/plugins/forgedock-splash/README.md +27 -0
  209. package/plugins/forgedock-splash/hooks/hooks.json +1 -0
  210. package/plugins/forgedock-splash/hooks/register.tsx +74 -0
  211. package/plugins/forgedock-splash/hooks/scene.ts +222 -0
  212. package/plugins/forgedock-splash/types/index.d.ts +10 -0
  213. package/pool/README.md +1 -1
  214. package/pool/image/cs-cred +14 -1
  215. package/scripts/backfill-finding-labels.mjs +50 -0
  216. package/scripts/backfill-finding-labels.test.mjs +36 -0
  217. package/scripts/bench-adversarial.mjs +216 -0
  218. package/scripts/bench-feature.mjs +170 -0
  219. package/scripts/bench-lightlane.mjs +2 -2
  220. package/scripts/bootstrap-create.mjs +2 -2
  221. package/scripts/bootstrap-validate.mjs +35 -2
  222. package/scripts/check-spec-size.sh +4 -3
  223. package/scripts/check-spec-size.test.sh +3 -0
  224. package/scripts/doctor-pipeline-state.sh +21 -6
  225. package/scripts/file-deferred-followups.sh +59 -251
  226. package/scripts/file-deferred-followups.test.sh +85 -206
  227. package/scripts/followup-route.mjs +12 -0
  228. package/scripts/owner-route-parity.test.sh +17 -1
  229. package/scripts/plan-validate-live.mjs +40 -6
  230. package/scripts/review-pr-side-effects.test.sh +40 -0
  231. package/scripts/review-pr-staging-scope.test.sh +1 -1
  232. package/scripts/review-staging-post.sh +23 -0
  233. package/scripts/review-staging-post.test.sh +8 -0
@@ -8,7 +8,10 @@
8
8
  * trigger (oversized diff, repro not red on base, two test failures, risk path, public-API-shape change from #4449)
9
9
  * moves the lane to the full pipeline. forge.yaml `lean.light` {mode: off|shadow (default)|on, max_lines: 40,
10
10
  * max_files: 2}: off is never eligible, shadow reports the verdict without changing the lane shape, on lets an eligible
11
- * issue run light (lane wiring: #4450). Pure: no I/O, no model call.
11
+ * issue run light (lane wiring: #4450). #5209: a named non-test file over maintenance.hotspot.file_lines (scripts/hotspots.sh
12
+ * `over`) is a hard `hotspot` reason, and every evaluated signal (repro, named files, churn, hotspot, risk path, docs/config/
13
+ * chore labels, size) is recorded in `signals`, which never changes the verdict: `forgedock stats --depth` attributes lane
14
+ * outcomes to them. Pure: no I/O, no model call.
12
15
  */
13
16
  import { riskClassOf, riskPathHits } from "./review-trigger.mjs";
14
17
  import { classifyPath } from "./routing.mjs";
@@ -18,6 +21,8 @@ import { postDeployOnly } from "./prefilter.mjs";
18
21
 
19
22
  export const LIGHT_MODES = Object.freeze(["off", "shadow", "on"]);
20
23
  export const LIGHT_DEFAULTS = Object.freeze({ mode: "shadow", maxLines: 40, maxFiles: 2 });
24
+ /** #5209: commits in 90 days (scripts/hotspots.sh commits_90d) at or above which a named file records a `churn_high` signal. */
25
+ export const CHURN_HIGH = 20;
21
26
 
22
27
  const posInt = (v) => { const s = String(v ?? "").trim(); return /^\d+$/.test(s) && Number(s) > 0 ? Number(s) : null; };
23
28
 
@@ -55,6 +60,17 @@ const FENCE_RE = /^\s*(```|~~~)/m;
55
60
  const DECISION_LABEL_RE = /^(type[:/]\s*)?(decision|needs-decision|product-decision|rfc|adr)$/i;
56
61
  const DECISION_TITLE_RE = /^\s*(decision|rfc|adr)[(:]/i;
57
62
  const POST_DEPLOY_LABELS = new Set(["post-deploy", "awaiting-promotion", "awaiting-due"]);
63
+ const KIND_LABELS = [["label_docs", /^(type[:/]\s*)?(docs|documentation)$/i], ["label_config", /^(type[:/]\s*)?(config|configuration)$/i], ["label_chore", /^(type[:/]\s*)?chore$/i]];
64
+
65
+ /** #5209: hotspots.sh rows by path ({path, lines, commits_90d, over}); anything malformed is skipped. */
66
+ function hotIndex(hotspots) {
67
+ const m = new Map();
68
+ for (const h of Array.isArray(hotspots) ? hotspots : []) {
69
+ const p = h && typeof h === "object" ? String(h.path ?? "").trim().replace(/^\.\//, "") : "";
70
+ if (p) m.set(p, h);
71
+ }
72
+ return m;
73
+ }
58
74
 
59
75
  /** Risk details for `files`: a built-in risk word or a declared review.risk_paths glob. */
60
76
  function riskDetails(files, riskPaths) {
@@ -72,24 +88,49 @@ function riskDetails(files, riskPaths) {
72
88
  * Light-lane eligibility of one issue: {mode, verdict, eligible, light, reasons:[{code, detail}]}.
73
89
  * verdict: off | eligible | ineligible (a hard reason: files, size, risk_path, investigate, post_deploy, decision) |
74
90
  * ambiguous (only soft reasons: no_repro, files_unknown). `light` is the lane shape: true only in mode on when eligible.
91
+ * #5209: `hotspots` are scripts/hotspots.sh `files` rows; a predicted non-test file with `over` adds the hard `hotspot`
92
+ * reason. `signals` lists every evaluated signal (codes: repro|no_repro, files_named, churn_high, hotspot, risk_path,
93
+ * label_docs|label_config|label_chore, size_S|size_M|size_L|size_none) and never changes the verdict.
75
94
  */
76
- export function lightEligibility({ title = "", body = "", labels = [], predictedFiles = [], riskPaths = [], cfg = {} } = {}) {
95
+ export function lightEligibility({ title = "", body = "", labels = [], predictedFiles = [], riskPaths = [], hotspots = [], cfg = {} } = {}) {
77
96
  const c = cfgOf(cfg);
78
- if (c.mode === "off") return { mode: "off", verdict: "off", eligible: false, light: false, reasons: [] };
79
- const hard = [], soft = [];
97
+ if (c.mode === "off") return { mode: "off", verdict: "off", eligible: false, light: false, reasons: [], signals: [] };
98
+ const hard = [], soft = [], signals = [];
80
99
  const text = String(body ?? "").replace(/<!--[\s\S]*?-->/g, " ");
81
- if (!FENCE_RE.test(text) && !REPRO_RE.test(text)) soft.push({ code: "no_repro", detail: "no repro, expected behaviour or code block in the body" });
100
+ if (!FENCE_RE.test(text) && !REPRO_RE.test(text)) {
101
+ soft.push({ code: "no_repro", detail: "no repro, expected behaviour or code block in the body" });
102
+ signals.push({ code: "no_repro", detail: "no repro, expected behaviour or code block in the body" });
103
+ } else signals.push({ code: "repro", detail: "repro, expected behaviour or code block in the body" });
82
104
 
83
105
  const files = uniquePaths(predictedFiles);
84
106
  const nonTest = files.filter((f) => classifyPath(f) !== "test");
85
107
  if (nonTest.length > c.maxFiles) hard.push({ code: "files", detail: `${nonTest.length} predicted non-test files (max ${c.maxFiles})` });
86
108
  else if (!nonTest.length) soft.push({ code: "files_unknown", detail: "no predicted non-test files" });
109
+ signals.push({ code: "files_named", detail: String(nonTest.length) });
110
+
111
+ const hot = hotIndex(hotspots);
112
+ for (const f of nonTest) {
113
+ const h = hot.get(f);
114
+ if (!h) continue;
115
+ const commits = Number(h.commits_90d);
116
+ if (Number.isFinite(commits) && commits >= CHURN_HIGH) signals.push({ code: "churn_high", detail: `${f} (${commits} commits/90d)` });
117
+ if (h.over === true) {
118
+ const d = `${f} (${Number(h.lines) || 0} lines)`;
119
+ hard.push({ code: "hotspot", detail: d });
120
+ signals.push({ code: "hotspot", detail: d });
121
+ }
122
+ }
87
123
 
88
124
  const names = labelNames(labels);
89
125
  const size = laneSize({ labels: names });
90
126
  if (size && size !== "S") hard.push({ code: "size", detail: `size:${size}` });
127
+ signals.push({ code: size ? `size_${size}` : "size_none", detail: size ? `size:${size}` : "no size label" });
128
+ for (const [code, re] of KIND_LABELS) {
129
+ const n = names.find((x) => re.test(x));
130
+ if (n) signals.push({ code, detail: `label ${n}` });
131
+ }
91
132
 
92
- for (const d of riskDetails(files, riskPaths)) hard.push({ code: "risk_path", detail: d });
133
+ for (const d of riskDetails(files, riskPaths)) { hard.push({ code: "risk_path", detail: d }); signals.push({ code: "risk_path", detail: d }); }
93
134
 
94
135
  if (isInvestigation(title)) hard.push({ code: "investigate", detail: "investigate( issue" });
95
136
  const pdLabel = names.find((n) => POST_DEPLOY_LABELS.has(n.toLowerCase()));
@@ -101,7 +142,7 @@ export function lightEligibility({ title = "", body = "", labels = [], predicted
101
142
 
102
143
  const verdict = hard.length ? "ineligible" : soft.length ? "ambiguous" : "eligible";
103
144
  const eligible = verdict === "eligible";
104
- return { mode: c.mode, verdict, eligible, light: c.mode === "on" && eligible, reasons: sortReasons([...hard, ...soft]) };
145
+ return { mode: c.mode, verdict, eligible, light: c.mode === "on" && eligible, reasons: sortReasons([...hard, ...soft]), signals: sortReasons(signals) };
105
146
  }
106
147
 
107
148
  const lineCount = (v) => { const n = Number(v); return Number.isFinite(n) && n > 0 ? n : 0; };
@@ -5,7 +5,7 @@ import assert from "node:assert/strict";
5
5
  import { readFileSync, writeFileSync } from "node:fs";
6
6
  import { join } from "node:path";
7
7
  import { tmpDir } from "../tests/_tmp.mjs";
8
- import { LIGHT_MODES, LIGHT_DEFAULTS, parseLightConfig, lightEligibility, upgradeTriggers } from "./light.mjs";
8
+ import { CHURN_HIGH, LIGHT_MODES, LIGHT_DEFAULTS, parseLightConfig, lightEligibility, upgradeTriggers } from "./light.mjs";
9
9
  import { readLight } from "../engine-cli.mjs";
10
10
 
11
11
  const ON = { mode: "on", maxLines: 40, maxFiles: 2 };
@@ -40,8 +40,9 @@ describe("parseLightConfig (#4448)", () => {
40
40
 
41
41
  describe("lightEligibility rules (#4448)", () => {
42
42
  it("accepts a well-specified size:S issue with 1-2 predicted files", () => {
43
- const r = lightEligibility(issue());
43
+ const { signals, ...r } = lightEligibility(issue());
44
44
  assert.deepEqual(r, { mode: "on", verdict: "eligible", eligible: true, light: true, reasons: [] });
45
+ assert.ok(Array.isArray(signals), "#5209 signals are recorded alongside");
45
46
  });
46
47
  it("repro or expected behaviour: present accepts, absent is ambiguous (never a model call)", () => {
47
48
  for (const body of ["Repro: `x()` throws", "Expected result: 3", "```\nboom\n```", "actual output differs"]) assert.equal(lightEligibility(issue({ body })).verdict, "eligible", body);
@@ -104,7 +105,7 @@ describe("lightEligibility rules (#4448)", () => {
104
105
 
105
106
  describe("lightEligibility modes (#4448)", () => {
106
107
  it("off never returns eligible, even for a fully eligible issue", () => {
107
- assert.deepEqual(lightEligibility(issue({ cfg: { mode: "off" } })), { mode: "off", verdict: "off", eligible: false, light: false, reasons: [] });
108
+ assert.deepEqual(lightEligibility(issue({ cfg: { mode: "off" } })), { mode: "off", verdict: "off", eligible: false, light: false, reasons: [], signals: [] });
108
109
  });
109
110
  it("shadow returns the verdict without changing the lane shape", () => {
110
111
  const r = lightEligibility(issue({ cfg: { mode: "shadow" } }));
@@ -121,6 +122,39 @@ describe("lightEligibility modes (#4448)", () => {
121
122
  });
122
123
  });
123
124
 
125
+ describe("lightEligibility signals and the hotspot reason (#5209)", () => {
126
+ const sig = (r) => r.signals.map((x) => x.code);
127
+ const hot = (o = {}) => ({ path: "src/chunk.py", lines: 2400, commits_90d: 1, over: false, ...o });
128
+ it("a predicted non-test file over the hotspot limit is a hard hotspot reason; a test file or an under-limit file is not", () => {
129
+ const r = lightEligibility(issue({ hotspots: [hot({ over: true })] }));
130
+ assert.equal(r.verdict, "ineligible");
131
+ assert.deepEqual(codes(r), ["hotspot"]);
132
+ assert.equal(r.reasons[0].detail, "src/chunk.py (2400 lines)");
133
+ assert.ok(sig(r).includes("hotspot"));
134
+ assert.equal(lightEligibility(issue({ hotspots: [hot()] })).verdict, "eligible");
135
+ assert.equal(lightEligibility(issue({ hotspots: [hot({ path: "tests/test_chunk.py", over: true })] })).verdict, "eligible");
136
+ assert.equal(lightEligibility(issue({ hotspots: [null, "x", { over: true }] })).verdict, "eligible", "malformed rows are skipped");
137
+ });
138
+ it("records repro/no_repro, files_named, churn_high at CHURN_HIGH, labels and size", () => {
139
+ const r = lightEligibility(issue({ labels: ["Docs", "type:config", "chore", "size:S"], hotspots: [hot({ commits_90d: CHURN_HIGH })] }));
140
+ assert.deepEqual(sig(r).sort(), ["churn_high", "files_named", "label_chore", "label_config", "label_docs", "repro", "size_S"]);
141
+ assert.equal(r.signals.find((x) => x.code === "files_named").detail, "1");
142
+ assert.ok(!sig(lightEligibility(issue({ hotspots: [hot({ commits_90d: CHURN_HIGH - 1 })] }))).includes("churn_high"));
143
+ const n = lightEligibility(issue({ body: "broken", labels: ["bug"] }));
144
+ assert.ok(sig(n).includes("no_repro") && sig(n).includes("size_none") && !sig(n).includes("repro"));
145
+ assert.ok(sig(lightEligibility(issue({ labels: ["size:M"] }))).includes("size_M"));
146
+ assert.ok(sig(lightEligibility(issue({ predictedFiles: ["src/auth/token.py"] }))).includes("risk_path"));
147
+ });
148
+ it("signals never change the verdict, eligible or light", () => {
149
+ const base = lightEligibility(issue());
150
+ for (const o of [{ labels: ["bug", "size:S", "docs"] }, { hotspots: [hot({ commits_90d: 99 })] }]) {
151
+ const r = lightEligibility(issue(o));
152
+ assert.deepEqual([r.verdict, r.eligible, r.light, r.reasons], [base.verdict, base.eligible, base.light, base.reasons], JSON.stringify(o));
153
+ }
154
+ assert.deepEqual(lightEligibility(issue({ cfg: { mode: "off" }, hotspots: [hot({ over: true })] })).signals, []);
155
+ });
156
+ });
157
+
124
158
  describe("upgradeTriggers (#4448)", () => {
125
159
  const quiet = { diff: numstat(["src/chunk.py", 30, 10], ["tests/test_chunk.py", 200]), repro: RED, testFailures: 1, cfg: ON };
126
160
  it("no trigger on a small red-green diff", () => {
@@ -248,24 +248,157 @@ describe("account rotator and usage-limit holds (#5094)", () => {
248
248
  assert.deepEqual(starts, [t0]);
249
249
  });
250
250
 
251
- it("#5094 #5095 a limited pool account keeps its own hold under a rotator with headroom; the host account is never held", async () => {
251
+ it("#5094 #5095 #5203 a limited pool account rotates under a rotator with headroom (no pool hold); once every account was tried it keeps its own hold", async () => {
252
252
  const { c, now, sleep } = fakeClock();
253
253
  const t0 = c.t;
254
254
  const limits = openLimits(storeFile(), { now });
255
255
  const rotator = { accounts: [{ n: 1 }], headroom: () => true, resumeAt: () => now(), isAccount: (id) => id === "acct-1", currentIdentity: () => "acct-1" };
256
256
  const remote = { max: 2, fallbackLocal: true, isRemote: () => true, place: () => ({ where: "remote", reason: "heavy" }), identity: () => "remote:pool" };
257
- const runs = [];
257
+ const runs = [], pausedHolds = [];
258
258
  const rows = await orchestrate({ issues: [1, 2], parallel: 1, now, sleep, readBody: async () => "", limits, rotator, remote, identity: () => laneBackendId({}, rotator),
259
+ onUpdate: (u) => { if (u.outcome === "paused") pausedHolds.push(limits.holdUntil("remote:pool")); },
259
260
  runOne: async (n, _l, ctx) => {
260
261
  runs.push({ n, at: now(), where: ctx.placement?.where, poolHeld: limits.holdUntil("remote:pool"), hostHeld: limits.holdUntil("acct-1") });
261
- return n === 1 && runs.length === 1 ? limited("remote:pool", t0 + 600_000) : { terminalReason: "merged" };
262
+ return n === 1 && runs.filter((x) => x.n === 1).length <= 2 ? limited("remote:pool", t0 + 600_000) : { terminalReason: "merged" };
262
263
  } });
263
264
  assert.deepEqual(rows.map((r) => r.outcome), ["merged", "merged"]);
264
- const second = runs.find((x) => x.n === 2);
265
- assert.equal(runs[0].where, "remote");
266
- assert.equal(second.at, t0, "the host account is not held: admissions continue");
267
- assert.equal(second.poolHeld, t0 + 600_000, "the pool's own hold is recorded (#5095)");
268
- assert.ok(!(second.hostHeld > now()), "no host-wide hold while the rotator has headroom");
269
- assert.equal(second.where, "local", "hybrid falls back local while the pool is held");
265
+ const ones = runs.filter((x) => x.n === 1);
266
+ assert.equal(ones[0].where, "remote");
267
+ assert.equal(ones[1].at, t0, "the pool limit reruns at once (the router hands out another login, #5165)");
268
+ assert.equal(ones[1].poolHeld, null, "no pool hold while an account has headroom (#5203)");
269
+ assert.equal(ones[1].where, "remote");
270
+ assert.ok(runs.every((x) => !(x.hostHeld > x.at)), "no host-wide hold while the rotator has headroom");
271
+ // the second limit exhausted the one-account rotation budget: the pool's own hold applies again (#5095)
272
+ assert.deepEqual(pausedHolds, [null, t0 + 600_000], "only the second limit records the pool hold (#5095)");
273
+ });
274
+
275
+ it("#5203 a rate-limited pool lane with another usable account rotates and sets no batch-wide notBefore", async () => {
276
+ const { c, now, sleep } = fakeClock();
277
+ const t0 = c.t;
278
+ const limits = openLimits(storeFile(), { now });
279
+ const rotator = { accounts: [{ n: 1 }, { n: 3 }, { n: 5 }], headroom: () => true, resumeAt: () => now(), isAccount: (id) => /^acct-/.test(id), currentIdentity: () => "acct-1" };
280
+ const remote = { max: 2, fallbackLocal: false, isRemote: () => true, place: () => ({ where: "remote", reason: "heavy" }), identity: () => "remote:pool" };
281
+ let state = null;
282
+ const store = { load: () => state, save: (s) => { state = JSON.parse(JSON.stringify(s)); } };
283
+ const runs = [];
284
+ const rows = await orchestrate({ issues: [1, 2, 3], parallel: 1, now, sleep, readBody: async () => "", limits, rotator, remote, store, identity: () => laneBackendId({}, rotator),
285
+ runOne: async (n) => {
286
+ runs.push({ n, at: now(), poolHeld: limits.holdUntil("remote:pool"), notBefore: { ...(state?.notBefore ?? {}) }, quota: state?.quota?.[1] ?? null });
287
+ return n === 1 && runs.length === 1 ? limited("remote:pool", t0 + 2 * 3_600_000) : { terminalReason: "merged" };
288
+ } });
289
+ assert.deepEqual(rows.map((r) => r.outcome), ["merged", "merged", "merged"]);
290
+ assert.ok(runs.every((x) => x.at === t0), "every lane starts at once: nothing waits for the limited account's reset");
291
+ const rerun = runs.filter((x) => x.n === 1)[1];
292
+ assert.equal(rerun.quota.rotations, 1, "rotations >= 1");
293
+ assert.equal(rerun.poolHeld, null, "no pool hold");
294
+ assert.ok(runs.every((x) => Object.values(x.notBefore).every((v) => !(v > t0))), "no batch-wide notBefore");
295
+ });
296
+
297
+ it("#5203 when every account is limited, the pool hold and notBefore are the earliest reset across accounts", async () => {
298
+ const { c, now, sleep } = fakeClock();
299
+ const t0 = c.t;
300
+ let everyLimited = false; // the rotator has headroom until the lane reports the limit
301
+ const earliest = t0 + 1_800_000, laneReset = t0 + 3 * 3_600_000;
302
+ const limits = openLimits(storeFile(), { now });
303
+ const rotator = { accounts: [{ n: 1 }, { n: 2 }], headroom: () => !everyLimited || now() >= earliest, resumeAt: () => Math.max(earliest, now()), isAccount: (id) => /^acct-/.test(id), currentIdentity: () => "acct-1" };
304
+ const remote = { max: 2, fallbackLocal: false, isRemote: () => true, place: () => ({ where: "remote", reason: "heavy" }), identity: () => "remote:pool" };
305
+ let poolHold = null;
306
+ const runs = [], log = [];
307
+ const rows = await orchestrate({ issues: [1, 2], parallel: 1, now, sleep, readBody: async () => "", limits, rotator, remote, identity: () => laneBackendId({}, rotator),
308
+ onUpdate: (u) => { log.push(u); if (u.outcome === "paused") poolHold = limits.holdUntil("remote:pool"); },
309
+ runOne: async (n) => {
310
+ runs.push({ n, at: now() });
311
+ if (n === 1 && runs.length === 1) { everyLimited = true; return limited("remote:pool", laneReset); }
312
+ return { terminalReason: "merged" };
313
+ } });
314
+ assert.deepEqual(rows.map((r) => r.outcome), ["merged", "merged"]);
315
+ assert.equal(poolHold, earliest, "the pool hold (the notBefore of every remote-placed issue) is the earliest reset across accounts, not the lane's own");
316
+ assert.equal(runs.find((x) => x.n === 2).at, earliest, "the next lane starts at the earliest reset");
317
+ assert.match(log.find((u) => u.outcome === "paused").detail, new RegExp(`until ${new Date(earliest).toISOString()}`));
318
+ });
319
+
320
+ it("#5203 --requeue of a quota-paused pending issue clears its notBefore and the pool hold", async () => {
321
+ const { c, now, sleep } = fakeClock();
322
+ const t0 = c.t;
323
+ const limits = openLimits(storeFile(), { now });
324
+ const remote = { max: 2, fallbackLocal: false, isRemote: () => true, place: () => ({ where: "remote", reason: "heavy" }), identity: () => "remote:pool" };
325
+ let paused = false;
326
+ const runs = [], log = [];
327
+ const rows = await orchestrate({ issues: [1], parallel: 1, now, sleep, pollMs: 5000, readBody: async () => "", limits, remote, identity: () => "local", onUpdate: (u) => log.push(u),
328
+ getRequeued: () => (paused ? [{ issue: 1, reason: "accounts 1, 3, 5 usable", by: "operator", at: "2026-11-07T08:05:00Z" }] : []),
329
+ runOne: async (n) => {
330
+ runs.push({ n, at: now() });
331
+ if (runs.length === 1) { paused = true; return limited("remote:pool", t0 + 2 * 3_600_000); }
332
+ return { terminalReason: "merged" };
333
+ } });
334
+ assert.equal(rows[0].outcome, "merged");
335
+ assert.equal(runs.length, 2);
336
+ assert.ok(runs[1].at < t0 + 60_000, `the released issue runs on the next poll, not at the reset (ran at +${runs[1].at - t0}ms)`);
337
+ assert.equal(limits.holdUntil("remote:pool"), null, "the pool hold is cleared");
338
+ assert.ok(log.some((u) => u.issue === 1 && u.outcome === "requeued" && /quota pause released/.test(u.detail)));
339
+ });
340
+ });
341
+
342
+ describe("tokenbaton rotation holds (#5205)", () => {
343
+ const H = 3_600_000;
344
+ const memStore = () => { const states = []; return { states, load: () => null, save: (s) => states.push(JSON.parse(JSON.stringify(s))) }; };
345
+
346
+ it("#5205 all accounts limited: the hold lasts until tokenbaton's earliest reset, not the limited account's own; rotations summed", async () => {
347
+ const { c, now, sleep } = fakeClock();
348
+ const t0 = c.t, earliest = t0 + 2 * H, own = t0 + 5 * H;
349
+ const picks = [];
350
+ let exhausted = false; // every account limited once the first run returns
351
+ const rot = { accounts: [{ n: 1 }, { n: 2 }, { n: 3 }], headroom: () => !exhausted || now() >= earliest, resumeAt: () => t0 + 4 * H, isAccount: (id) => id === "acct-1", currentIdentity: () => "acct-1",
352
+ pick: ({ exclude }) => { picks.push([...exclude.keys()]); return now() >= earliest ? { account: 2, stale: false } : { account: null, earliestReset: earliest }; } };
353
+ const limits = openLimits(storeFile(), { now }), store = memStore(), updates = [], starts = [];
354
+ const rows = await orchestrate({ issues: [1], now, sleep, readBody: async () => "", rotator: rot, limits, identity: () => "acct-1", store, onUpdate: (u) => updates.push(u),
355
+ runOne: async () => { starts.push(now()); exhausted = true; return starts.length === 1 ? { ...limited("acct-1", own), rotations: 2, limited: [{ account: 1, until: own }, { account: 3, until: t0 + 3 * H }] } : { terminalReason: "merged" }; } });
356
+ assert.equal(rows[0].outcome, "merged");
357
+ assert.equal(limits.holdUntil("acct-1") ?? earliest, earliest, "the hold is tokenbaton's earliest reset");
358
+ const paused = updates.find((u) => u.outcome === "paused");
359
+ assert.equal(paused.quota.resumeAt, new Date(earliest).toISOString());
360
+ assert.equal(starts[1], earliest, "rerun at the earliest reset, not the account's own reset");
361
+ assert.deepEqual(picks[0]?.sort(), [1, 3], `lane-reported limited accounts are excluded: ${JSON.stringify({ picks, starts, u: updates.map((u) => u.outcome) })}`);
362
+ const st = store.states.find((s) => s.quota?.["1"]);
363
+ assert.equal(st.quota["1"].rotations, 2, "lane-reported rotations add to quota.rotations");
364
+ assert.deepEqual(Object.keys(st.limitedAccounts).sort(), ["1", "3"], "limited accounts persist with the batch");
365
+ });
366
+
367
+ it("#5236 a quota.exhausted lane result is held until the earliest reset and the batch log row names the code and reset", async () => {
368
+ const { c, now, sleep } = fakeClock();
369
+ const t0 = c.t, earliest = t0 + 3 * H;
370
+ const rot = { accounts: [{ n: 1 }, { n: 2 }], headroom: () => now() >= earliest, resumeAt: () => earliest, isAccount: (id) => id === "acct-1", currentIdentity: () => "acct-1",
371
+ pick: () => (now() >= earliest ? { account: 2, stale: false } : { account: null, earliestReset: earliest }) };
372
+ const limits = openLimits(storeFile(), { now }), updates = [], starts = [];
373
+ const rows = await orchestrate({ issues: [1], now, sleep, readBody: async () => "", rotator: rot, limits, identity: () => "acct-1", store: memStore(), onUpdate: (u) => updates.push(u),
374
+ runOne: async () => { starts.push(now()); return starts.length === 1 ? { terminalReason: "deferred", code: "quota.exhausted", backendId: "acct-1", resetAtEpochMs: earliest, detail: "quota exhausted: no account has capacity" } : { terminalReason: "merged" }; } });
375
+ assert.equal(rows[0].outcome, "merged");
376
+ assert.equal(starts[1], earliest, "rerun at the earliest reset");
377
+ const paused = updates.find((u) => u.outcome === "paused");
378
+ assert.equal(paused.quota.resumeAt, new Date(earliest).toISOString());
379
+ assert.match(paused.detail, /quota\.exhausted/);
380
+ const evt = updates.find((u) => u.event === "quota.exhausted");
381
+ assert.ok(evt, "batch-level quota.exhausted event");
382
+ assert.equal(evt.resumeAt, new Date(earliest).toISOString());
383
+ });
384
+
385
+ it("#5205 a lane-reported limited account is excluded from headroom until its reset", async () => {
386
+ const { c, now, sleep } = fakeClock();
387
+ const t0 = c.t, seen = [];
388
+ const rot = { accounts: [{ n: 1 }, { n: 2 }], headroom: (ex) => { seen.push(ex ? [...ex.keys()] : []); return !(ex?.has(1) && ex?.has(2)); }, resumeAt: () => t0 + H, isAccount: () => true, currentIdentity: () => "acct-1", pick: () => ({ account: null, earliestReset: t0 + H }) };
389
+ let runs = 0;
390
+ await orchestrate({ issues: [1, 2], parallel: 1, now, sleep, readBody: async () => "", rotator: rot, limits: openLimits(storeFile(), { now }), identity: () => "acct-1",
391
+ runOne: async (n) => { runs++; return n === 1 ? { terminalReason: "merged", rotations: 1, limited: [{ account: 1, until: t0 + H }] } : { terminalReason: "merged" }; } });
392
+ assert.equal(runs, 2);
393
+ assert.ok(seen.some((x) => x.includes(1)), `headroom saw the limited account excluded: ${JSON.stringify(seen)}`);
394
+ });
395
+
396
+ it("#5205 no rotator: the hold is now + the reset delay, as before", async () => {
397
+ const { c, now, sleep } = fakeClock();
398
+ const limits = openLimits(storeFile(), { now });
399
+ const until = c.t + H;
400
+ await orchestrate({ issues: [1], now, sleep, readBody: async () => "", limits, identity: () => "A",
401
+ runOne: async () => { if (now() < until) { const r = limited("A", until); setImmediate(() => {}); return r; } return { terminalReason: "merged" }; },
402
+ onUpdate: (u) => { if (u.outcome === "paused") assert.equal(limits.holdUntil("A"), until); } });
270
403
  });
271
404
  });
@@ -0,0 +1,124 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Mechanical fixes (#5348): the enumerating-test and duplicate-export gates already name the exact change, so the engine
5
+ * applies it itself and re-runs the detector; a model session starts only for what is left. No model, never throws.
6
+ * Both functions return {applied, remaining} over the findings they were given; `remaining` keeps the unproven ones.
7
+ */
8
+ import fs from "node:fs";
9
+ import { join, posix } from "node:path";
10
+
11
+ const STR = /(["'`])(?:(?!\1)[^\\\n]|\\.)*\1/g;
12
+ const ALL_STRINGS = /^\s*(?:(["'`])(?:(?!\1)[^\\\n]|\\.)*\1\s*(?:,\s*|$))+$/;
13
+
14
+ /** Spans of every `[...]` in `text` (string literals skipped): [{start, end}] with `end` the index of the `]`. */
15
+ function arraySpans(text) {
16
+ const spans = [], stack = [];
17
+ for (let i = 0; i < text.length; i++) {
18
+ const c = text[i];
19
+ if (c === '"' || c === "'" || c === "`") { // skip a string literal
20
+ for (i++; i < text.length && text[i] !== c && text[i] !== "\n"; i++) if (text[i] === "\\") i++;
21
+ } else if (c === "[") stack.push(i);
22
+ else if (c === "]" && stack.length) spans.push({ start: stack.pop(), end: i });
23
+ }
24
+ return spans;
25
+ }
26
+
27
+ const lineOf = (text, idx) => text.slice(0, idx).split("\n").length;
28
+
29
+ /**
30
+ * Add `symbols` to the array literal of string literals that covers 1-based `line` of `text`. Only an unambiguous list
31
+ * (2+ elements, strings only) is edited; the new entry copies the neighbours' quote and layout.
32
+ * @returns {{text: string, inserted: string[]}} `inserted` is empty when the list was not recognised.
33
+ */
34
+ export function insertIntoList(text, line, symbols) {
35
+ const span = arraySpans(text)
36
+ .filter((s) => lineOf(text, s.start) <= line && line <= lineOf(text, s.end))
37
+ .sort((a, b) => (a.end - a.start) - (b.end - b.start))
38
+ .find((s) => ALL_STRINGS.test(text.slice(s.start + 1, s.end)) && [...text.slice(s.start + 1, s.end).matchAll(STR)].length >= 2);
39
+ if (!span) return { text, inserted: [] };
40
+ const body = text.slice(span.start + 1, span.end);
41
+ const items = [...body.matchAll(STR)];
42
+ const have = new Set(items.map((m) => m[0].slice(1, -1)));
43
+ const quote = items[0][0][0];
44
+ const fresh = [...new Set(symbols)].filter((s) => !have.has(s) && !/[\\"'`\n]/.test(s));
45
+ if (!fresh.length) return { text, inserted: [] };
46
+ const lit = (s) => `${quote}${s}${quote}`;
47
+ const last = items[items.length - 1], lastEnd = span.start + 1 + last.index + last[0].length;
48
+ const trailing = /^\s*,/.exec(text.slice(lastEnd)); // a comma after the last element
49
+ const at = trailing ? lastEnd + trailing[0].length : lastEnd;
50
+ let add;
51
+ if (body.includes("\n")) {
52
+ const ls = text.lastIndexOf("\n", lastEnd) + 1, indent = /^\s*/.exec(text.slice(ls, lastEnd))[0];
53
+ add = trailing ? fresh.map((s) => `\n${indent}${lit(s)},`).join("") : fresh.map((s) => `,\n${indent}${lit(s)}`).join("");
54
+ } else add = trailing ? fresh.map((s) => ` ${lit(s)},`).join("") : fresh.map((s) => `, ${lit(s)}`).join("");
55
+ return { text: text.slice(0, at) + add + text.slice(at), inserted: fresh };
56
+ }
57
+
58
+ /**
59
+ * Enumerating tests: write every missing symbol into the list its test keeps. @param missing [{symbol, module, test, line}]
60
+ * @returns {{applied: object[], remaining: object[]}}
61
+ */
62
+ export function applyEnumerating({ missing = [], cwd, fsx = fs } = {}) {
63
+ const applied = [], remaining = [];
64
+ const byTest = new Map();
65
+ for (const m of missing) { if (!byTest.has(m.test)) byTest.set(m.test, []); byTest.get(m.test).push(m); }
66
+ for (const [test, rows] of byTest) {
67
+ let text;
68
+ try { text = fsx.readFileSync(join(cwd, test), "utf8"); } catch { remaining.push(...rows); continue; }
69
+ const groups = new Map();
70
+ for (const m of rows) { const k = `${m.line}\0${m.module}`; if (!groups.has(k)) groups.set(k, []); groups.get(k).push(m); }
71
+ let changed = false;
72
+ // bottom-up: an insertion only shifts the lines below it, so the detector's line numbers stay valid
73
+ for (const g of [...groups.values()].sort((a, b) => b[0].line - a[0].line)) {
74
+ const r = insertIntoList(text, g[0].line, g.map((m) => m.symbol));
75
+ const done = new Set(r.inserted);
76
+ for (const m of g) (done.has(m.symbol) ? applied : remaining).push(m);
77
+ if (r.inserted.length) { text = r.text; changed = true; }
78
+ }
79
+ if (changed) { try { fsx.writeFileSync(join(cwd, test), text); } catch { for (const m of applied.splice(applied.length - rows.length)) remaining.push(m); } }
80
+ }
81
+ return { applied, remaining };
82
+ }
83
+
84
+ const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
85
+ const pascal = (s) => String(s).split(/[^A-Za-z0-9]+/).filter(Boolean).map(cap).join("");
86
+
87
+ /** `<AppPrefix><Symbol>`: the prefix is the declaring file's directory (its stem for an index file), cased like the symbol. */
88
+ export function renamedExport(symbol, path) {
89
+ const stem = posix.basename(path).replace(/\.[^.]+$/, "");
90
+ const dir = posix.basename(posix.dirname(path));
91
+ const prefix = pascal(stem === "index" || stem === "mod" ? dir : stem) || pascal(dir);
92
+ if (!prefix) return null;
93
+ const lower = /^[a-z]/.test(symbol);
94
+ return lower ? `${prefix.charAt(0).toLowerCase()}${prefix.slice(1)}${cap(symbol)}` : `${prefix}${cap(symbol)}`;
95
+ }
96
+
97
+ const word = (s) => new RegExp(`(?<![\\w$])${s.replace(/[\\$]/g, "\\$&")}(?![\\w$])`, "g");
98
+
99
+ /**
100
+ * Duplicate exports: rename the lane's new export to `<AppPrefix><Symbol>` when the name occurs only in its declaring file and the
101
+ * other files that declare it themselves (`others`; so no importer, registry or test keyed by the name can be left behind) and never as a property, string or label.
102
+ * @param dups [{symbol, path, others}]; `git(args)` returns stdout
103
+ * @returns {Promise<{applied: object[], remaining: object[]}>}
104
+ */
105
+ export async function renameDuplicates({ dups = [], cwd, git, fsx = fs } = {}) {
106
+ const applied = [], remaining = [];
107
+ const grep = async (name) => { try { return String(await git(["-c", "core.quotepath=off", "grep", "-l", "-w", "-e", name])).split("\n").map((l) => l.trim()).filter(Boolean); } catch { return []; } };
108
+ for (const d of dups) {
109
+ try {
110
+ const next = renamedExport(d.symbol, d.path);
111
+ if (!next || next === d.symbol || (await grep(next)).length) { remaining.push(d); continue; }
112
+ const files = await grep(d.symbol);
113
+ const ours = new Set([d.path, ...(d.others ?? [])]); // the detector's others declare the name themselves, so they cannot import ours
114
+ if (!files.includes(d.path) || files.some((f) => !ours.has(f))) { remaining.push(d); continue; }
115
+ const text = fsx.readFileSync(join(cwd, d.path), "utf8");
116
+ const re = word(d.symbol);
117
+ const bad = [...text.matchAll(re)].some((m) => /[.'"`]$/.test(text.slice(Math.max(0, m.index - 1), m.index)) || /^\s*[:'"`]/.test(text.slice(m.index + d.symbol.length, m.index + d.symbol.length + 2)));
118
+ if (bad) { remaining.push(d); continue; }
119
+ fsx.writeFileSync(join(cwd, d.path), text.replace(re, next));
120
+ applied.push({ ...d, renamedTo: next });
121
+ } catch { remaining.push(d); }
122
+ }
123
+ return { applied, remaining };
124
+ }
@@ -0,0 +1,75 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import fs from "node:fs";
6
+ import { join } from "node:path";
7
+ import { insertIntoList, applyEnumerating, renamedExport, renameDuplicates } from "./mechfix.mjs";
8
+ import { tmpDir } from "../tests/_tmp.mjs";
9
+
10
+ const tmp = () => tmpDir("mechfix-");
11
+
12
+ describe("#5348 enumerating list insertion", () => {
13
+ it("appends to a one-per-line list, copying quote, indent and the trailing comma", () => {
14
+ const src = `const names = [\n "alpha",\n "beta",\n "gamma",\n];\n`;
15
+ const r = insertIntoList(src, 3, ["delta"]);
16
+ assert.deepEqual(r.inserted, ["delta"]);
17
+ assert.equal(r.text, `const names = [\n "alpha",\n "beta",\n "gamma",\n "delta",\n];\n`);
18
+ });
19
+ it("appends to a one-line list without a trailing comma", () => {
20
+ const r = insertIntoList(`assert.deepEqual(keys, ['a1', 'b2', 'c3']);\n`, 1, ["d4", "e5"]);
21
+ assert.equal(r.text, `assert.deepEqual(keys, ['a1', 'b2', 'c3', 'd4', 'e5']);\n`);
22
+ });
23
+ it("leaves a name already listed, and a list that is not all string literals, alone", () => {
24
+ assert.deepEqual(insertIntoList(`x(["aa", "bb", "cc"]);\n`, 1, ["bb"]).inserted, []);
25
+ assert.deepEqual(insertIntoList(`x(["aa", bb, "cc"]);\n`, 1, ["dd"]).inserted, []);
26
+ assert.deepEqual(insertIntoList(`x(["aa"]);\n`, 1, ["dd"]).inserted, [], "one element is not a sibling list");
27
+ });
28
+ it("applyEnumerating edits the test file and reports what it could not place", () => {
29
+ const cwd = tmp();
30
+ fs.writeFileSync(join(cwd, "a.test.mjs"), `const L = ["one", "two", "three"];\nconst M = ["x1", "x2", "x3"];\n`);
31
+ const missing = [
32
+ { symbol: "four", module: "m", test: "a.test.mjs", line: 1 },
33
+ { symbol: "x4", module: "n", test: "a.test.mjs", line: 2 },
34
+ { symbol: "gone", module: "m", test: "missing.test.mjs", line: 1 },
35
+ ];
36
+ const r = applyEnumerating({ missing, cwd });
37
+ assert.deepEqual(r.applied.map((m) => m.symbol).sort(), ["four", "x4"]);
38
+ assert.deepEqual(r.remaining.map((m) => m.symbol), ["gone"]);
39
+ assert.equal(fs.readFileSync(join(cwd, "a.test.mjs"), "utf8"), `const L = ["one", "two", "three", "four"];\nconst M = ["x1", "x2", "x3", "x4"];\n`);
40
+ });
41
+ });
42
+
43
+ describe("#5348 duplicate export rename", () => {
44
+ it("names the export after its app, cased like the symbol", () => {
45
+ assert.equal(renamedExport("Button", "apps/web/ui.ts"), "UiButton");
46
+ assert.equal(renamedExport("loadAll", "apps/web/index.ts"), "webLoadAll");
47
+ });
48
+ const world = (files) => {
49
+ const cwd = tmp();
50
+ for (const [f, text] of Object.entries(files)) { fs.mkdirSync(join(cwd, f, ".."), { recursive: true }); fs.writeFileSync(join(cwd, f), text); }
51
+ const git = async (a) => {
52
+ const name = a[a.indexOf("-e") + 1];
53
+ const hit = Object.entries(files).filter(([, t]) => new RegExp(`(?<![\\w$])${name}(?![\\w$])`).test(fs.readFileSync(join(cwd, ...[Object.keys(files).find((k) => files[k] === t)]), "utf8"))).map(([f]) => f);
54
+ if (!hit.length) throw new Error("exit 1");
55
+ return hit.join("\n");
56
+ };
57
+ return { cwd, git };
58
+ };
59
+ it("renames an export only its declaring file mentions", async () => {
60
+ const { cwd, git } = world({ "app/ui.ts": `export const Button = 1;\nexport const y = Button + 1;\n`, "app/other.ts": `export const Button = 2;\n` });
61
+ const r = await renameDuplicates({ dups: [{ symbol: "Button", path: "app/ui.ts", others: ["app/other.ts"] }], cwd, git });
62
+ assert.equal(r.applied.length, 1); assert.equal(r.remaining.length, 0);
63
+ assert.equal(fs.readFileSync(join(cwd, "app/ui.ts"), "utf8"), `export const UiButton = 1;\nexport const y = UiButton + 1;\n`);
64
+ assert.equal(fs.readFileSync(join(cwd, "app/other.ts"), "utf8"), `export const Button = 2;\n`);
65
+ });
66
+ it("leaves it for a session when another file references the name, or it is used as a property", async () => {
67
+ let w = world({ "app/ui.ts": `export const Button = 1;\n`, "app/use.ts": `import { Button } from "./ui";\n` });
68
+ let r = await renameDuplicates({ dups: [{ symbol: "Button", path: "app/ui.ts", others: ["app/other.ts"] }], cwd: w.cwd, git: w.git });
69
+ assert.equal(r.applied.length, 0); assert.equal(r.remaining.length, 1);
70
+ w = world({ "app/ui.ts": `export const Button = 1;\nexport const map = { Button: 2 };\n` });
71
+ r = await renameDuplicates({ dups: [{ symbol: "Button", path: "app/ui.ts", others: ["x.ts"] }], cwd: w.cwd, git: w.git });
72
+ assert.equal(r.remaining.length, 1);
73
+ assert.match(fs.readFileSync(join(w.cwd, "app/ui.ts"), "utf8"), /export const Button = 1/);
74
+ });
75
+ });