opencode-agent-harness 0.0.0-stage → 0.3.14

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 (171) hide show
  1. package/CHANGELOG.md +217 -0
  2. package/LICENSE +21 -0
  3. package/README.md +636 -2
  4. package/bin/agent-harness.js +3182 -0
  5. package/contrib/global-plugins/README.md +49 -0
  6. package/contrib/global-plugins/harness-freshness.ts +355 -0
  7. package/package.json +86 -4
  8. package/templates/.agents/AGENTS.md +148 -0
  9. package/templates/.agents/features/INDEX.md +10 -0
  10. package/templates/.agents/handoffs/README.md +87 -0
  11. package/templates/.agents/memory/dev-loop.md +59 -0
  12. package/templates/.agents/memory/domain-map.md +29 -0
  13. package/templates/.agents/memory/environments.md +35 -0
  14. package/templates/.agents/memory/flow-map.md +23 -0
  15. package/templates/.agents/memory/history.md +7 -0
  16. package/templates/.agents/memory/locations.md +14 -0
  17. package/templates/.agents/memory/model-routing.md +261 -0
  18. package/templates/.agents/memory/orchestration.md +183 -0
  19. package/templates/.agents/memory/owned-files.md +19 -0
  20. package/templates/.agents/memory/product-principles.md +37 -0
  21. package/templates/.agents/memory/quality-parameters.md +37 -0
  22. package/templates/.agents/memory/stack-versions.md +35 -0
  23. package/templates/.agents/memory/test-design-parameters.md +36 -0
  24. package/templates/.agents/nightly.json +17 -0
  25. package/templates/.agents/qa-plans/README.md +70 -0
  26. package/templates/.agents/qa-runs/README.md +21 -0
  27. package/templates/.agents/reviews/README.md +47 -0
  28. package/templates/.agents/rules/00-operating.md +199 -0
  29. package/templates/.agents/skills/data-engineer/SKILL.md +31 -0
  30. package/templates/.agents/skills/devops-engineer/SKILL.md +50 -0
  31. package/templates/.agents/skills/diagnostics-expert/SKILL.md +44 -0
  32. package/templates/.agents/skills/docs/SKILL.md +140 -0
  33. package/templates/.agents/skills/features/SKILL.md +187 -0
  34. package/templates/.agents/skills/frontend-engineer/SKILL.md +81 -0
  35. package/templates/.agents/skills/handoff/SKILL.md +85 -0
  36. package/templates/.agents/skills/mobile-engineer/SKILL.md +101 -0
  37. package/templates/.agents/skills/planner/SKILL.md +112 -0
  38. package/templates/.agents/skills/product-manager/SKILL.md +115 -0
  39. package/templates/.agents/skills/qa-architect/SKILL.md +224 -0
  40. package/templates/.agents/skills/qa-runner/SKILL.md +64 -0
  41. package/templates/.agents/skills/security-engineer/SKILL.md +53 -0
  42. package/templates/.agents/skills/system-architect/SKILL.md +42 -0
  43. package/templates/.agents/skills/ui-designer/SKILL.md +71 -0
  44. package/templates/.github/workflows/ci.yml +148 -0
  45. package/templates/.github/workflows/deploy-uat.yml +95 -0
  46. package/templates/.github/workflows/nightly.yml +83 -0
  47. package/templates/.github/workflows/uat-health.yml +41 -0
  48. package/templates/.husky/pre-push +23 -0
  49. package/templates/.ignore +28 -0
  50. package/templates/.opencode/agents/data-engineer.md +37 -0
  51. package/templates/.opencode/agents/devops-engineer.md +37 -0
  52. package/templates/.opencode/agents/diagnostics-expert.md +37 -0
  53. package/templates/.opencode/agents/docs.md +37 -0
  54. package/templates/.opencode/agents/features.md +21 -0
  55. package/templates/.opencode/agents/frontend-engineer.md +37 -0
  56. package/templates/.opencode/agents/handoff.md +21 -0
  57. package/templates/.opencode/agents/mobile-engineer.md +37 -0
  58. package/templates/.opencode/agents/planner.md +34 -0
  59. package/templates/.opencode/agents/product-manager.md +29 -0
  60. package/templates/.opencode/agents/qa-architect.md +27 -0
  61. package/templates/.opencode/agents/qa-runner.md +17 -0
  62. package/templates/.opencode/agents/security-engineer.md +37 -0
  63. package/templates/.opencode/agents/system-architect.md +37 -0
  64. package/templates/.opencode/agents/ui-designer.md +37 -0
  65. package/templates/.opencode/commands/board.md +15 -0
  66. package/templates/.opencode/commands/checkpoint.md +25 -0
  67. package/templates/.opencode/commands/feature.md +56 -0
  68. package/templates/.opencode/commands/finish.md +36 -0
  69. package/templates/.opencode/commands/next.md +49 -0
  70. package/templates/.opencode/commands/report.md +55 -0
  71. package/templates/.opencode/commands/resume.md +39 -0
  72. package/templates/.opencode/commands/switch-model.md +34 -0
  73. package/templates/.opencode/commands/tidy.md +49 -0
  74. package/templates/.opencode/plugins/backlog-notify.ts +57 -0
  75. package/templates/.opencode/plugins/backlog.ts +272 -0
  76. package/templates/.opencode/plugins/checkpoint.ts +160 -0
  77. package/templates/.opencode/plugins/context-guard.ts +1164 -0
  78. package/templates/.opencode/plugins/diff.ts +85 -0
  79. package/templates/.opencode/plugins/gates.ts +71 -0
  80. package/templates/.opencode/plugins/job-notify.ts +241 -0
  81. package/templates/.opencode/plugins/orient.ts +67 -0
  82. package/templates/.opencode/plugins/session.ts +89 -0
  83. package/templates/.opencode/plugins/wait.ts +101 -0
  84. package/templates/.opencode/plugins/where.ts +70 -0
  85. package/templates/.opencode/skills/bounded-explore/SKILL.md +38 -0
  86. package/templates/.opencode/skills/dev-loop/SKILL.md +87 -0
  87. package/templates/.vercelignore +16 -0
  88. package/templates/AGENTS.md +27 -0
  89. package/templates/BACKLOG.md +95 -0
  90. package/templates/docs/ci-cd-pipeline.md +81 -0
  91. package/templates/docs/gates.md +128 -0
  92. package/templates/docs/mcp-integrations.md +97 -0
  93. package/templates/docs/mobile-testing.md +555 -0
  94. package/templates/docs/nightly-testing.md +106 -0
  95. package/templates/docs/wsl-optimizations.md +290 -0
  96. package/templates/opencode.json +188 -0
  97. package/templates/scripts/agent-report.js +541 -0
  98. package/templates/scripts/agent-search.sh +117 -0
  99. package/templates/scripts/backlog.js +1924 -0
  100. package/templates/scripts/board-service.sh +214 -0
  101. package/templates/scripts/checkpoint.js +290 -0
  102. package/templates/scripts/finalize.js +416 -0
  103. package/templates/scripts/nightly.js +913 -0
  104. package/templates/scripts/orient.js +514 -0
  105. package/templates/scripts/qa/board-client.js +323 -0
  106. package/templates/scripts/qa/board-lib.js +96 -0
  107. package/templates/scripts/qa/board-sync.js +499 -0
  108. package/templates/scripts/qa/capacity-lib.js +916 -0
  109. package/templates/scripts/qa/check-backlog.js +434 -0
  110. package/templates/scripts/qa/check-capacity.js +85 -0
  111. package/templates/scripts/qa/check-ci-policy.js +164 -0
  112. package/templates/scripts/qa/check-concurrency.js +344 -0
  113. package/templates/scripts/qa/check-dispatch-config.js +296 -0
  114. package/templates/scripts/qa/check-docs.js +288 -0
  115. package/templates/scripts/qa/check-integrate.js +98 -0
  116. package/templates/scripts/qa/check-linger.js +160 -0
  117. package/templates/scripts/qa/check-prefix-stability.js +187 -0
  118. package/templates/scripts/qa/check-product.js +177 -0
  119. package/templates/scripts/qa/check-qa-plan.js +378 -0
  120. package/templates/scripts/qa/check-qa-scripts.js +85 -0
  121. package/templates/scripts/qa/check-quality.js +249 -0
  122. package/templates/scripts/qa/check-test-wiring.js +253 -0
  123. package/templates/scripts/qa/check-worktrees.js +93 -0
  124. package/templates/scripts/qa/ci-triage.js +346 -0
  125. package/templates/scripts/qa/ci-usage-lib.js +185 -0
  126. package/templates/scripts/qa/ci-wait-lib.js +294 -0
  127. package/templates/scripts/qa/command-classifier.js +552 -0
  128. package/templates/scripts/qa/context-guard-core.js +1618 -0
  129. package/templates/scripts/qa/diff.js +174 -0
  130. package/templates/scripts/qa/feature-scaffold.js +224 -0
  131. package/templates/scripts/qa/fixtures/backlog.md +104 -0
  132. package/templates/scripts/qa/governance.js +174 -0
  133. package/templates/scripts/qa/hash-file.js +32 -0
  134. package/templates/scripts/qa/lease-lib.js +263 -0
  135. package/templates/scripts/qa/merge-backlog.js +324 -0
  136. package/templates/scripts/qa/mobile-e2e/analyze-timings.js +300 -0
  137. package/templates/scripts/qa/mobile-e2e/apk-cache.js +420 -0
  138. package/templates/scripts/qa/mobile-e2e/backend-build-cache.js +203 -0
  139. package/templates/scripts/qa/mobile-e2e/boot-emulator.sh +432 -0
  140. package/templates/scripts/qa/mobile-e2e/build-apk.sh +210 -0
  141. package/templates/scripts/qa/mobile-e2e/check-flows.js +568 -0
  142. package/templates/scripts/qa/mobile-e2e/config.yaml +18 -0
  143. package/templates/scripts/qa/mobile-e2e/device-down.sh +88 -0
  144. package/templates/scripts/qa/mobile-e2e/device-up.sh +258 -0
  145. package/templates/scripts/qa/mobile-e2e/ios-simulator-down.sh +72 -0
  146. package/templates/scripts/qa/mobile-e2e/ios-simulator-up.sh +153 -0
  147. package/templates/scripts/qa/mobile-e2e/job-events.js +181 -0
  148. package/templates/scripts/qa/mobile-e2e/prewarm.sh +56 -0
  149. package/templates/scripts/qa/mobile-e2e/run-detached.sh +222 -0
  150. package/templates/scripts/qa/mobile-e2e/run-maestro.js +1543 -0
  151. package/templates/scripts/qa/mobile-e2e/ui-dump.js +327 -0
  152. package/templates/scripts/qa/models.allowlist.txt +32 -0
  153. package/templates/scripts/qa/provider-stats.js +878 -0
  154. package/templates/scripts/qa/run-clean.js +83 -0
  155. package/templates/scripts/qa/run-gates.js +213 -0
  156. package/templates/scripts/qa/run-loop.js +220 -0
  157. package/templates/scripts/qa/session-recon.js +512 -0
  158. package/templates/scripts/qa/store-lib.js +324 -0
  159. package/templates/scripts/qa/tool-lib.js +134 -0
  160. package/templates/scripts/qa/where.js +214 -0
  161. package/templates/scripts/qa/worktree-hygiene.js +217 -0
  162. package/templates/scripts/qa/wslconfig-merge.js +157 -0
  163. package/templates/scripts/serve.js +1328 -0
  164. package/templates/scripts/setup-nightly.sh +185 -0
  165. package/templates/scripts/setup-tmpfs.sh +374 -0
  166. package/templates/scripts/ship.js +586 -0
  167. package/templates/scripts/switch-reasoning-model.ps1 +101 -0
  168. package/templates/scripts/switch-reasoning-model.sh +104 -0
  169. package/templates/scripts/wait-for.js +342 -0
  170. package/templates/scripts/wsl-gpu.sh +180 -0
  171. package/templates/scripts/wsl-tune.sh +319 -0
@@ -0,0 +1,217 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /*
4
+ * worktree-hygiene — one source of truth for "is this checkout closed out?".
5
+ *
6
+ * The failure this prevents: a session lands its feature worktree, then ends
7
+ * with "main is N commits behind and dirty" and "worktree <id> is still in
8
+ * place — prune it later". Both are invisible to every gate, so they
9
+ * accumulate: merged worktrees pile up, the main checkout drifts, and the next
10
+ * session works on top of unrelated uncommitted edits (which is exactly how
11
+ * two sessions collide in CHANGELOG.md / package.json / AGENTS.md).
12
+ *
13
+ * Everything here is read-only and cheap: `git worktree list --porcelain` plus
14
+ * one `git status` / `git rev-list` per worktree. Callers decide the policy:
15
+ *
16
+ * - finalize/ship: warn + converge the main checkout after a landing
17
+ * - check-worktrees: fail when a merged worktree is left behind or main is stale
18
+ * - orient: show the summary at session start
19
+ *
20
+ * Usage:
21
+ * node scripts/qa/worktree-hygiene.js [--root <dir>] [--base main] [--json]
22
+ */
23
+ const { spawnSync } = require("child_process");
24
+ const path = require("path");
25
+
26
+ function git(dir, args) {
27
+ const res = spawnSync("git", ["-C", dir, ...args], { encoding: "utf8" });
28
+ return {
29
+ ok: res.status === 0,
30
+ out: String(res.stdout || "").trim(),
31
+ err: String(res.stderr || "").trim(),
32
+ };
33
+ }
34
+
35
+ /* Parse `git worktree list --porcelain` into records. The first record is the
36
+ * main checkout (the only one without `worktree` pointing under .worktrees). */
37
+ function listWorktrees(root) {
38
+ const res = git(root, ["worktree", "list", "--porcelain"]);
39
+ if (!res.ok) return [];
40
+ const records = [];
41
+ let current = null;
42
+ for (const line of res.out.split(/\r?\n/)) {
43
+ if (line.startsWith("worktree ")) {
44
+ current = { path: line.slice("worktree ".length).trim(), head: null, branch: null, bare: false, detached: false, locked: false, prunable: false };
45
+ records.push(current);
46
+ } else if (!current) {
47
+ continue;
48
+ } else if (line.startsWith("HEAD ")) {
49
+ current.head = line.slice("HEAD ".length).trim();
50
+ } else if (line.startsWith("branch ")) {
51
+ const ref = line.slice("branch ".length).trim();
52
+ current.branch = ref.replace(/^refs\/heads\//, "");
53
+ } else if (line === "detached") {
54
+ current.detached = true;
55
+ } else if (line === "bare") {
56
+ current.bare = true;
57
+ } else if (line.startsWith("locked")) {
58
+ current.locked = true;
59
+ } else if (line.startsWith("prunable")) {
60
+ current.prunable = true;
61
+ }
62
+ }
63
+ return records;
64
+ }
65
+
66
+ /* Dirty entries, excluding ignored files. */
67
+ function statusEntries(dir) {
68
+ const res = git(dir, ["status", "--porcelain"]);
69
+ if (!res.ok) return [];
70
+ return res.out.split(/\r?\n/).filter((l) => l && !l.startsWith("!!"));
71
+ }
72
+
73
+ function revListCount(dir, range) {
74
+ const res = git(dir, ["rev-list", "--count", range]);
75
+ const n = Number(res.out);
76
+ return Number.isFinite(n) ? n : 0;
77
+ }
78
+
79
+ /* Is `ref` contained in `baseRef`? Callers fetch beforehand when they want a
80
+ * network-fresh answer; this function never touches the network. */
81
+ function isMerged(dir, ref, baseRef) {
82
+ if (!ref || !baseRef) return false;
83
+ return git(dir, ["merge-base", "--is-ancestor", ref, baseRef]).ok;
84
+ }
85
+
86
+ /**
87
+ * Summarise the repo's worktree hygiene.
88
+ *
89
+ * @param {string} root any path inside the repo (main or linked worktree)
90
+ * @param {string} base integration branch name (default "main")
91
+ * @param {string} [cwd] the caller's checkout, marked `current: true`
92
+ * @returns {object|null} null when `root` is not a git repo
93
+ */
94
+ function hygiene(root, base = "main", cwd = process.cwd()) {
95
+ const worktrees = listWorktrees(root);
96
+ if (!worktrees.length) return null;
97
+ const main = worktrees[0];
98
+ const currentPath = (() => {
99
+ const res = git(cwd, ["rev-parse", "--show-toplevel"]);
100
+ return res.ok ? res.out : path.resolve(cwd);
101
+ })();
102
+ const baseRef = `origin/${base}`;
103
+ const hasBase = git(root, ["rev-parse", "--verify", "--quiet", baseRef]).ok;
104
+ const mainBranch = main.branch || base;
105
+ const mainHead = main.head || git(main.path, ["rev-parse", "HEAD"]).out;
106
+
107
+ const records = worktrees.map((wt) => {
108
+ const dirty = statusEntries(wt.path);
109
+ const merged = wt.path === main.path ? false : hasBase && isMerged(wt.path, wt.head, baseRef);
110
+ return {
111
+ ...wt,
112
+ current: path.resolve(wt.path) === path.resolve(currentPath),
113
+ main: wt.path === main.path,
114
+ dirty: dirty.length,
115
+ dirtyEntries: dirty.slice(0, 20),
116
+ merged,
117
+ };
118
+ });
119
+
120
+ const linked = records.filter((r) => !r.main);
121
+ const mainDirty = records[0].dirtyEntries;
122
+ const mainAhead = hasBase ? revListCount(main.path, `${baseRef}..${mainHead}`) : 0;
123
+ const mainBehind = hasBase ? revListCount(main.path, `${mainHead}..${baseRef}`) : 0;
124
+
125
+ return {
126
+ base,
127
+ baseRef,
128
+ hasBase,
129
+ main: {
130
+ path: main.path,
131
+ branch: mainBranch,
132
+ head: mainHead,
133
+ dirty: mainDirty.length,
134
+ dirtyEntries: mainDirty,
135
+ ahead: mainAhead,
136
+ behind: mainBehind,
137
+ current: records[0].current,
138
+ },
139
+ worktrees: records,
140
+ linked,
141
+ // A linked worktree that is fully merged and clean is pure leftovers.
142
+ stale: linked.filter((w) => w.merged && w.dirty === 0),
143
+ // A merged worktree with uncommitted work cannot be pruned and will
144
+ // collide with whichever session edits the same files next.
145
+ mergedDirty: linked.filter((w) => w.merged && w.dirty > 0),
146
+ };
147
+ }
148
+
149
+ /* One-paragraph human summary, reused by finalize/ship/orient. */
150
+ function describe(h) {
151
+ if (!h) return "worktree hygiene: not a git repository";
152
+ const lines = [];
153
+ if (!h.hasBase) lines.push(`(no ${h.baseRef} yet — merge/behind counts skipped)`);
154
+ else if (h.main.behind > 0) lines.push(`main checkout is ${h.main.behind} commit(s) BEHIND ${h.baseRef}`);
155
+ else if (h.main.ahead > 0) lines.push(`main checkout is ${h.main.ahead} commit(s) AHEAD of ${h.baseRef} (unpushed)`);
156
+ else lines.push(`main checkout is in sync with ${h.baseRef}`);
157
+ if (h.main.dirty) lines.push(`main checkout has ${h.main.dirty} uncommitted entr${h.main.dirty === 1 ? "y" : "ies"}`);
158
+ if (h.stale.length) lines.push(`${h.stale.length} merged worktree(s) left on disk: ${h.stale.map((w) => w.branch || w.path).join(", ")}`);
159
+ if (h.mergedDirty.length)
160
+ lines.push(`${h.mergedDirty.length} merged worktree(s) still dirty (cannot prune): ${h.mergedDirty.map((w) => w.branch || w.path).join(", ")}`);
161
+ return lines.join("; ");
162
+ }
163
+
164
+ /* Close-out advice for a session that just landed a feature. */
165
+ function closeOutAdvice(h) {
166
+ const advice = [];
167
+ if (!h) return advice;
168
+ if (h.main.behind > 0) {
169
+ advice.push(
170
+ h.main.dirty
171
+ ? `main checkout is ${h.main.behind} behind and has uncommitted work — commit/stash it, then: git -C ${h.main.path} merge --ff-only ${h.baseRef}`
172
+ : `converge the main checkout: git -C ${h.main.path} merge --ff-only ${h.baseRef}`
173
+ );
174
+ }
175
+ if (h.stale.length) {
176
+ advice.push(`remove merged worktrees: node scripts/backlog.js worktree-prune`);
177
+ }
178
+ if (h.mergedDirty.length) {
179
+ advice.push(
180
+ `merged worktree(s) still dirty — commit or discard before pruning: ${h.mergedDirty
181
+ .map((w) => `${w.path} (${w.dirty} entries)`)
182
+ .join(", ")}`
183
+ );
184
+ }
185
+ return advice;
186
+ }
187
+
188
+ function main() {
189
+ const argv = process.argv.slice(2);
190
+ const args = { base: "main", json: false, root: process.cwd() };
191
+ for (let i = 0; i < argv.length; i++) {
192
+ const a = argv[i];
193
+ if (a === "--root") args.root = path.resolve(argv[++i]);
194
+ else if (a === "--base") args.base = argv[++i];
195
+ else if (a === "--json") args.json = true;
196
+ else if (a === "--help" || a === "-h") {
197
+ console.log("worktree-hygiene — report main-checkout drift and leftover merged worktrees\n\n node scripts/qa/worktree-hygiene.js [--root <dir>] [--base main] [--json]");
198
+ return;
199
+ }
200
+ }
201
+ const h = hygiene(args.root, args.base);
202
+ if (args.json) {
203
+ console.log(JSON.stringify(h, null, 2));
204
+ return;
205
+ }
206
+ console.log(`worktree hygiene (${h ? h.base : "n/a"})\n ${describe(h)}`);
207
+ for (const w of h ? h.linked : []) {
208
+ const flags = [w.merged ? "merged" : "unmerged", w.dirty ? `${w.dirty} dirty` : "clean", w.current ? "current" : null].filter(Boolean);
209
+ console.log(` - ${w.branch || "(detached)"} ${w.path} [${flags.join(", ")}]`);
210
+ }
211
+ const advice = closeOutAdvice(h);
212
+ if (advice.length) console.log("\nClose-out:\n" + advice.map((a) => ` - ${a}`).join("\n"));
213
+ }
214
+
215
+ if (require.main === module) main();
216
+
217
+ module.exports = { listWorktrees, statusEntries, isMerged, hygiene, describe, closeOutAdvice };
@@ -0,0 +1,157 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /*
4
+ * wslconfig-merge — set/overwrite keys in a `[section]` INI file (a Windows
5
+ * `.wslconfig`) WITHOUT clobbering the user's other settings. `scripts/wsl-tune.sh`
6
+ * uses it to apply the recommended `[wsl2]`/`[experimental]` tuning idempotently.
7
+ *
8
+ * Why a merged file, not a managed block: `.wslconfig` is INI, so a second
9
+ * `[wsl2]` section would be invalid. This updates keys in place, inserts a
10
+ * missing key at the end of its section, and appends a whole section only when
11
+ * it is absent — comments, blank lines, ordering, and unknown keys survive.
12
+ *
13
+ * Usage:
14
+ * node scripts/qa/wslconfig-merge.js --file <path> --set wsl2.processors=8 \
15
+ * --set wsl2.swap=4GB [--set experimental.autoMemoryReclaim=gradual] \
16
+ * [--write] [--backup] [--dry-run]
17
+ *
18
+ * Without --write it prints the merged content to stdout (nothing is changed).
19
+ * Exit 1 on an invalid key / unreadable file.
20
+ */
21
+ const fs = require("fs");
22
+
23
+ const KEY_RE = /^[A-Za-z0-9_.-]+$/;
24
+
25
+ function validate(section, key) {
26
+ if (!KEY_RE.test(section) || !KEY_RE.test(key)) {
27
+ throw new Error(`invalid section/key: [${section}] ${key}`);
28
+ }
29
+ }
30
+
31
+ function detectEol(text) {
32
+ return /\r\n/.test(text) ? "\r\n" : "\n";
33
+ }
34
+
35
+ /* Pure merge: returns the new content. `sets` is [{section,key,value}]. */
36
+ function mergeConfig(text, sets) {
37
+ const eol = detectEol(text);
38
+ // Normalize to \n for processing, restore at the end.
39
+ const lines = String(text == null ? "" : text).replace(/\r\n/g, "\n").split("\n");
40
+ const pending = new Map(); // section(lower) -> [{key,value}]
41
+ for (const s of sets) {
42
+ validate(s.section, s.key);
43
+ const sec = s.section.toLowerCase();
44
+ if (!pending.has(sec)) pending.set(sec, []);
45
+ // Last write wins within a section.
46
+ const list = pending.get(sec);
47
+ const idx = list.findIndex((x) => x.key.toLowerCase() === s.key.toLowerCase());
48
+ if (idx === -1) list.push({ key: s.key, value: s.value });
49
+ else list[idx] = { key: s.key, value: s.value };
50
+ }
51
+
52
+ const out = [];
53
+ let current = null;
54
+ const flush = () => {
55
+ if (current && pending.has(current)) {
56
+ for (const { key, value } of pending.get(current)) out.push(`${key}=${value}`);
57
+ pending.delete(current);
58
+ }
59
+ };
60
+ for (const line of lines) {
61
+ const header = line.match(/^\s*\[([^\]]+)\]\s*$/);
62
+ if (header) {
63
+ flush();
64
+ current = header[1].trim().toLowerCase();
65
+ out.push(line);
66
+ continue;
67
+ }
68
+ const kv = line.match(/^([ \t]*)([A-Za-z0-9_.-]+)([ \t]*)=([ \t]*)(.*)$/);
69
+ if (kv && current && pending.has(current)) {
70
+ const list = pending.get(current);
71
+ const idx = list.findIndex((x) => x.key.toLowerCase() === kv[2].toLowerCase());
72
+ if (idx !== -1) {
73
+ out.push(`${kv[1]}${list[idx].key}=${list[idx].value}`);
74
+ list.splice(idx, 1);
75
+ continue;
76
+ }
77
+ }
78
+ out.push(line);
79
+ }
80
+ flush();
81
+ for (const [section, list] of pending) {
82
+ if (!list.length) continue;
83
+ out.push("", `[${section}]`, ...list.map((x) => `${x.key}=${x.value}`));
84
+ }
85
+ // Collapse an accidental leading blank when the file started empty.
86
+ let result = out.join("\n");
87
+ if (!result.endsWith("\n")) result += "\n";
88
+ return result.replace(/\n/g, eol);
89
+ }
90
+
91
+ function parseArgs(argv) {
92
+ const out = { sets: [] };
93
+ for (let i = 0; i < argv.length; i++) {
94
+ const a = argv[i];
95
+ if (a === "--file") out.file = argv[++i];
96
+ else if (a === "--set") out.sets.push(argv[++i]);
97
+ else if (a === "--write") out.write = true;
98
+ else if (a === "--backup") out.backup = true;
99
+ else if (a === "--dry-run") out.dryRun = true;
100
+ else if (a.startsWith("--set=")) out.sets.push(a.slice(6));
101
+ else if (a.startsWith("--file=")) out.file = a.slice(7);
102
+ }
103
+ return out;
104
+ }
105
+
106
+ function parseSet(spec) {
107
+ const m = String(spec).match(/^([A-Za-z0-9_.-]+)\.([A-Za-z0-9_.-]+)=(.*)$/);
108
+ if (!m) throw new Error(`--set must be <section>.<key>=<value>, got "${spec}"`);
109
+ return { section: m[1], key: m[2], value: m[3] };
110
+ }
111
+
112
+ function run(argv) {
113
+ const args = parseArgs(argv);
114
+ if (!args.file) {
115
+ console.error("usage: node scripts/qa/wslconfig-merge.js --file <path> --set section.key=value [--set ...] [--write] [--backup] [--dry-run]");
116
+ return 2;
117
+ }
118
+ let sets;
119
+ try {
120
+ sets = args.sets.map(parseSet);
121
+ } catch (e) {
122
+ console.error("wslconfig-merge: " + e.message);
123
+ return 1;
124
+ }
125
+ if (!sets.length) {
126
+ console.error("wslconfig-merge: at least one --set is required");
127
+ return 1;
128
+ }
129
+ let current = "";
130
+ try {
131
+ current = fs.readFileSync(args.file, "utf8");
132
+ } catch (_) {
133
+ current = ""; // create the file
134
+ }
135
+ const merged = mergeConfig(current, sets);
136
+ if (args.dryRun || !args.write) {
137
+ process.stdout.write(merged);
138
+ return 0;
139
+ }
140
+ if (merged === current) {
141
+ console.log(`wslconfig-merge: ${args.file} already up to date`);
142
+ return 0;
143
+ }
144
+ if (args.backup && current) {
145
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
146
+ fs.writeFileSync(`${args.file}.bak-${stamp}`, current, "utf8");
147
+ }
148
+ fs.writeFileSync(args.file, merged, "utf8");
149
+ console.log(`wslconfig-merge: updated ${args.file}`);
150
+ return 0;
151
+ }
152
+
153
+ if (require.main === module) {
154
+ process.exitCode = run(process.argv.slice(2));
155
+ }
156
+
157
+ module.exports = { mergeConfig, parseSet, parseArgs, detectEol };