superpowers-mcp 6.4.6 → 6.4.8

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 (62) hide show
  1. package/README.es.md +30 -3
  2. package/README.hi.md +30 -3
  3. package/README.ja.md +30 -3
  4. package/README.ko.md +30 -3
  5. package/README.md +31 -4
  6. package/README.pt-BR.md +30 -3
  7. package/README.zh-TW.md +30 -3
  8. package/docs/maintainers/upstream-sync.md +4 -0
  9. package/docs/skill-compositions.es.md +1 -1
  10. package/docs/skill-compositions.hi.md +1 -1
  11. package/docs/skill-compositions.ja.md +1 -1
  12. package/docs/skill-compositions.ko.md +1 -1
  13. package/docs/skill-compositions.md +1 -1
  14. package/docs/skill-compositions.pt-BR.md +1 -1
  15. package/docs/skill-compositions.zh-TW.md +1 -1
  16. package/out/server.js +148 -104
  17. package/out/setup-runner.js +51 -36
  18. package/out/setup.js +51 -36
  19. package/package.json +7 -6
  20. package/scripts/copy-skills.js +65 -6
  21. package/scripts/install.ps1 +11 -2
  22. package/scripts/install.sh +7 -1
  23. package/scripts/run-tests.js +164 -0
  24. package/scripts/setup.js +100 -11
  25. package/scripts/upstream-drift.js +31 -8
  26. package/skills/brainstorming/SKILL.md +24 -2
  27. package/skills/brainstorming/builder-check-prompt.md +23 -0
  28. package/skills/brainstorming/scripts/helper.js +2 -1
  29. package/skills/brainstorming/scripts/server.cjs +38 -10
  30. package/skills/brainstorming/scripts/start-server.ps1 +7 -3
  31. package/skills/brainstorming/scripts/start-server.sh +30 -6
  32. package/skills/brainstorming/scripts/stop-server.ps1 +10 -4
  33. package/skills/brainstorming/scripts/stop-server.sh +16 -10
  34. package/skills/diagnosing-superpowers/SKILL.md +6 -3
  35. package/skills/diagnosing-superpowers/references/github-issues.md +3 -3
  36. package/skills/diagnosing-superpowers/templates/issue.md +23 -4
  37. package/skills/executing-plans/SKILL.md +18 -12
  38. package/skills/executing-plans/scripts/task-done +14 -5
  39. package/skills/executing-plans/scripts/task-done.ps1 +34 -12
  40. package/skills/executing-plans/scripts/task-start +16 -4
  41. package/skills/executing-plans/scripts/task-start.ps1 +9 -4
  42. package/skills/requesting-code-review/SKILL.md +1 -1
  43. package/skills/subagent-driven-development/SKILL.md +24 -15
  44. package/skills/subagent-driven-development/implementer-prompt.md +6 -5
  45. package/skills/subagent-driven-development/re-review-prompt.md +4 -3
  46. package/skills/subagent-driven-development/scripts/review-package +23 -17
  47. package/skills/subagent-driven-development/scripts/review-package.ps1 +41 -27
  48. package/skills/subagent-driven-development/scripts/sdd-repo +44 -0
  49. package/skills/subagent-driven-development/scripts/sdd-repo.ps1 +74 -0
  50. package/skills/subagent-driven-development/scripts/sdd-workspace +20 -11
  51. package/skills/subagent-driven-development/scripts/sdd-workspace.ps1 +38 -27
  52. package/skills/subagent-driven-development/scripts/task-brief +74 -11
  53. package/skills/subagent-driven-development/scripts/task-brief.ps1 +89 -17
  54. package/skills/subagent-driven-development/task-reviewer-prompt.md +5 -6
  55. package/skills/systematic-debugging/SKILL.md +2 -2
  56. package/skills/writing-skills/render-graphs.js +4 -3
  57. package/skills/brainstorming/spec-document-reviewer-prompt.md +0 -50
  58. package/skills/systematic-debugging/CREATION-LOG.md +0 -119
  59. package/skills/systematic-debugging/test-academic.md +0 -14
  60. package/skills/systematic-debugging/test-pressure-1.md +0 -58
  61. package/skills/systematic-debugging/test-pressure-2.md +0 -68
  62. package/skills/systematic-debugging/test-pressure-3.md +0 -69
@@ -0,0 +1,164 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Runs every test suite and reports all failures, not just the first.
4
+ *
5
+ * The previous `test` script chained the suites with `&&`, so a failure in an early
6
+ * suite skipped every later one — a green-to-red signal depended on which suite
7
+ * broke first, and a single regression could hide most of the suite.
8
+ */
9
+
10
+ const { spawnSync } = require("child_process");
11
+ const fs = require("fs");
12
+ const path = require("path");
13
+
14
+ const REPO_ROOT = path.join(__dirname, "..");
15
+
16
+ const FAIL_ON_SKIP = process.argv.includes("--fail-on-skip");
17
+
18
+ // Resolve a bash binary so .sh suites also run on Windows (Git for Windows
19
+ // ships bash outside PATH). Returns null when no bash exists — .sh suites are
20
+ // then reported as SKIP, never as passed.
21
+ function resolveBash() {
22
+ const candidates = ["bash"];
23
+ if (process.platform === "win32") {
24
+ candidates.push(
25
+ "C:\\Program Files\\Git\\bin\\bash.exe",
26
+ "C:\\Program Files (x86)\\Git\\bin\\bash.exe",
27
+ "C:\\Program Files\\Git\\usr\\bin\\bash.exe"
28
+ );
29
+ }
30
+ for (const bin of candidates) {
31
+ try {
32
+ const probe = spawnSync(bin, ["--version"], { stdio: "ignore", timeout: 30000 });
33
+ if (!probe.error && probe.status === 0) return bin;
34
+ } catch {
35
+ // Try the next candidate.
36
+ }
37
+ }
38
+ return null;
39
+ }
40
+
41
+ function havePwsh() {
42
+ try {
43
+ const probe = spawnSync("pwsh", ["--version"], { stdio: "ignore", timeout: 30000 });
44
+ return !probe.error && probe.status === 0;
45
+ } catch {
46
+ return false;
47
+ }
48
+ }
49
+
50
+ const BASH_BIN = resolveBash();
51
+ const HAVE_PWSH = havePwsh();
52
+
53
+ const SUITES = [
54
+ "tests/edge_cases_test.js",
55
+ "tests/run_test.js",
56
+ "tests/client_truncation_test.js",
57
+ "tests/brainstorm_server_test.js",
58
+ "tests/prompts_compositions_test.js",
59
+ "tests/upstream_sync_test.js",
60
+ "tests/mcp_coverage_test.js",
61
+ "tests/drift_test.js",
62
+ "tests/setup_test.js",
63
+ "tests/executing-plans/test-task-start.sh",
64
+ "tests/executing-plans/test-task-done.sh",
65
+ "tests/sdd/test-sdd-workspace.sh",
66
+ "tests/sdd/test-sdd-helper-paths.sh",
67
+ "tests/sdd/test-no-dev-files-in-skills.sh",
68
+ "tests/writing-skills/test-render-graphs.sh",
69
+ "tests/brainstorming/test-start-server-env-hosts.sh",
70
+ // Intentionally excluded: tests/perf_benchmark.js (timing benchmark, not a
71
+ // pass/fail suite), tests/block_network.cjs (helper required by drift_test,
72
+ // not standalone).
73
+ ];
74
+
75
+ // PowerShell suites run under pwsh when it exists; when pwsh is missing they
76
+ // are reported as SKIP (not a pass, not a failure) so a green run on a
77
+ // pwsh-less machine never claims Windows coverage it did not run.
78
+ let psSuites = [];
79
+ try {
80
+ psSuites = fs.readdirSync(path.join(REPO_ROOT, "tests", "powershell"))
81
+ .filter((f) => f.startsWith("test-") && f.endsWith(".ps1"))
82
+ .sort()
83
+ .map((f) => `tests/powershell/${f}`);
84
+ } catch {
85
+ psSuites = [];
86
+ }
87
+
88
+ const results = [];
89
+
90
+ function runSuite(suite) {
91
+ const started = process.hrtime.bigint();
92
+ let run;
93
+ if (suite.endsWith(".sh")) {
94
+ if (!BASH_BIN) {
95
+ const ms = Number(process.hrtime.bigint() - started) / 1e6;
96
+ results.push({ suite, status: "SKIP", ms, note: "no bash available" });
97
+ console.error(`\n⊘ ${suite} SKIPPED: no bash available\n`);
98
+ return;
99
+ }
100
+ run = spawnSync(BASH_BIN, [suite], { cwd: REPO_ROOT, stdio: "inherit", timeout: 180000 });
101
+ } else if (suite.endsWith(".ps1")) {
102
+ // Caller guarantees HAVE_PWSH; kept explicit so the SKIP path above
103
+ // stays the only way a ps1 suite is not executed.
104
+ run = spawnSync("pwsh", ["-NoProfile", "-File", suite], { cwd: REPO_ROOT, stdio: "inherit", timeout: 180000 });
105
+ } else {
106
+ run = spawnSync(process.execPath, [suite], { cwd: REPO_ROOT, stdio: "inherit", timeout: 180000 });
107
+ }
108
+ const ms = Number(process.hrtime.bigint() - started) / 1e6;
109
+ // Differentiate the three failure modes: spawn failure (binary missing),
110
+ // signal death (killed/timeout), and non-zero exit. A null status from a
111
+ // signal kill previously collapsed into `1`, hiding the cause.
112
+ if (run.error) {
113
+ results.push({ suite, status: "FAIL", code: null, signal: null, error: run.error.message, ms });
114
+ console.error(`\n✗ ${suite} failed to spawn: ${run.error.message}\n`);
115
+ } else if (run.signal) {
116
+ results.push({ suite, status: "FAIL", code: run.status, signal: run.signal, error: null, ms });
117
+ console.error(`\n✗ ${suite} killed by signal ${run.signal} — continuing so every suite still runs\n`);
118
+ } else {
119
+ const code = run.status === null ? 1 : run.status;
120
+ results.push({ suite, status: code === 0 ? "PASS" : "FAIL", code, signal: null, error: null, ms });
121
+ if (code !== 0) {
122
+ console.error(`\n✗ ${suite} exited ${code} — continuing so every suite still runs\n`);
123
+ }
124
+ }
125
+ }
126
+
127
+ for (const suite of SUITES) {
128
+ runSuite(suite);
129
+ }
130
+ if (HAVE_PWSH) {
131
+ for (const suite of psSuites) {
132
+ runSuite(suite);
133
+ }
134
+ } else {
135
+ for (const suite of psSuites) {
136
+ results.push({ suite, status: "SKIP", ms: 0, note: "pwsh not available" });
137
+ console.error(`\n⊘ ${suite} SKIPPED: pwsh not available (not a pass)\n`);
138
+ }
139
+ }
140
+
141
+ console.log("\n================ test summary ================");
142
+ for (const { suite, status, ms } of results) {
143
+ const mark = status === "PASS" ? "PASS" : status === "SKIP" ? "SKIP" : "FAIL";
144
+ console.log(` ${mark} ${suite.padEnd(48)} ${ms.toFixed(0)}ms`);
145
+ }
146
+ const failed = results.filter((r) => r.status === "FAIL");
147
+ const skipped = results.filter((r) => r.status === "SKIP");
148
+ console.log(`==============================================`);
149
+ console.log(` ${results.length - failed.length - skipped.length}/${results.length} suites passed${skipped.length > 0 ? ` (${skipped.length} skipped)` : ""}`);
150
+ if (skipped.length > 0) {
151
+ console.log(` skipped: ${skipped.map((s) => s.suite).join(", ")}`);
152
+ }
153
+ if (failed.length > 0) {
154
+ console.error(` failing: ${failed.map((f) => {
155
+ if (f.error) return `${f.suite} (spawn: ${f.error})`;
156
+ if (f.signal) return `${f.suite} (signal ${f.signal})`;
157
+ return `${f.suite} (exit ${f.code})`;
158
+ }).join(", ")}`);
159
+ process.exit(1);
160
+ }
161
+ if (FAIL_ON_SKIP && skipped.length > 0) {
162
+ console.error(` skipped (fail-on-skip): ${skipped.map((s) => s.suite).join(", ")}`);
163
+ process.exit(1);
164
+ }
package/scripts/setup.js CHANGED
@@ -42,12 +42,37 @@ function needsBuild() {
42
42
  return true;
43
43
  }
44
44
  try {
45
- return fs.statSync(compiledRunner).mtimeMs < newestInputMtime();
45
+ return fs.statSync(compiledRunner).mtimeMs <= newestInputMtime();
46
46
  } catch {
47
47
  return true;
48
48
  }
49
49
  }
50
50
 
51
+ // PID of the process holding the build lock, or null when unreadable.
52
+ function lockOwnerPid() {
53
+ try {
54
+ const pid = Number.parseInt(fs.readFileSync(lockPath, "utf8").trim(), 10);
55
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ // True when the lock holder might still be running. Fail closed: an unreadable
62
+ // owner counts as alive so its lock is never stolen.
63
+ function lockOwnerAlive() {
64
+ const pid = lockOwnerPid();
65
+ if (pid === null) return true;
66
+ if (pid === process.pid) return false; // Our own leftover lock: reclaim it.
67
+ try {
68
+ process.kill(pid, 0);
69
+ return true;
70
+ } catch (err) {
71
+ // ESRCH means no such process; anything else (e.g. EPERM) assumes alive.
72
+ return err && err.code !== "ESRCH";
73
+ }
74
+ }
75
+
51
76
  function acquireLock() {
52
77
  fs.mkdirSync(path.dirname(lockPath), { recursive: true });
53
78
  try {
@@ -55,7 +80,21 @@ function acquireLock() {
55
80
  return true;
56
81
  } catch (err) {
57
82
  if (err && err.code === "EEXIST") {
58
- return false; // another build holds the lock
83
+ // Only steal the lock when its holder is dead; a live holder keeps it.
84
+ if (!lockOwnerAlive()) {
85
+ try {
86
+ fs.unlinkSync(lockPath);
87
+ } catch {
88
+ return false;
89
+ }
90
+ try {
91
+ fs.writeFileSync(lockPath, String(process.pid), { flag: "wx" });
92
+ return true;
93
+ } catch {
94
+ return false;
95
+ }
96
+ }
97
+ return false; // another (live) build holds the lock
59
98
  }
60
99
  // Unexpected lock error (e.g. permissions) — proceed without exclusion; the
61
100
  // build itself will surface any real failure.
@@ -65,22 +104,33 @@ function acquireLock() {
65
104
 
66
105
  function releaseLock() {
67
106
  try {
107
+ // Only remove the lock when we still own it; another builder may have
108
+ // taken over since (e.g. after stealing our dead-holder lock).
109
+ if (fs.readFileSync(lockPath, "utf8").trim() !== String(process.pid)) {
110
+ return;
111
+ }
68
112
  fs.unlinkSync(lockPath);
69
113
  } catch {
70
- // Ignore: we may not own it.
114
+ // Ignore: already gone or unreadable.
71
115
  }
72
116
  }
73
117
 
74
118
  function lockIsStale() {
75
119
  try {
76
- return Date.now() - fs.statSync(lockPath).mtimeMs > 120000;
120
+ // Stale threshold (30s) stays well under the 60s wait deadline below, so a
121
+ // dead holder's lock is reclaimed instead of timing out the waiter.
122
+ return Date.now() - fs.statSync(lockPath).mtimeMs > 30000;
77
123
  } catch {
78
124
  return false; // already gone
79
125
  }
80
126
  }
81
127
 
82
- if (needsBuild()) {
83
- const { execSync } = require("child_process");
128
+ // Help and dry-run never execute the runner, so they must not trigger a build.
129
+ const cliArgs = process.argv.slice(2);
130
+ const skipBuild = cliArgs.includes("--help") || cliArgs.includes("-h") || cliArgs.includes("--dry-run");
131
+
132
+ if (!skipBuild && needsBuild()) {
133
+ const { execFileSync } = require("child_process");
84
134
 
85
135
  const deadline = Date.now() + 60000;
86
136
  let owned = acquireLock();
@@ -88,21 +138,33 @@ if (needsBuild()) {
88
138
  // Wait for a concurrent build to finish (and release the lock) before building,
89
139
  // so two invocations never run esbuild at once and interleave writes to out/*.
90
140
  while (!owned && needsBuild() && Date.now() < deadline) {
91
- if (lockIsStale()) {
92
- releaseLock();
141
+ if (!fs.existsSync(lockPath) || lockIsStale()) {
142
+ // acquireLock steals only a dead holder's lock; a live holder keeps
143
+ // it and we keep waiting for it to finish. A missing lock means the
144
+ // holder released cleanly, so it is acquirable.
93
145
  owned = acquireLock();
94
- break;
146
+ if (owned) break;
95
147
  }
96
148
  sleepSync(250);
97
149
  }
98
150
 
99
151
  if (owned) {
152
+ // Heartbeat: periodically refresh the lock mtime so concurrent waiters
153
+ // (30s stale threshold) do not steal it mid-build on slow machines.
154
+ const heartbeat = setInterval(() => {
155
+ try {
156
+ fs.utimesSync(lockPath, new Date(), new Date());
157
+ } catch {
158
+ // Best-effort; the build proceeds regardless.
159
+ }
160
+ }, 10000);
100
161
  try {
101
- execSync("node esbuild.js", { cwd: repoRoot, stdio: "inherit" });
162
+ execFileSync(process.execPath, ["esbuild.js"], { cwd: repoRoot, stdio: "inherit" });
102
163
  } catch (e) {
103
164
  console.error("Failed to build out/setup-runner.js automatically:", e.message);
104
165
  process.exit(1);
105
166
  } finally {
167
+ clearInterval(heartbeat);
106
168
  releaseLock();
107
169
  }
108
170
  } else if (needsBuild()) {
@@ -112,7 +174,34 @@ if (needsBuild()) {
112
174
  // If !owned but !needsBuild(), another process finished the build — reuse it.
113
175
  }
114
176
 
115
- const runner = require(compiledRunner);
177
+ let runner;
178
+ try {
179
+ runner = require(compiledRunner);
180
+ } catch (loadErr) {
181
+ // Help and dry-run skip the build above, so the bundle may legitimately be
182
+ // missing here (fresh checkout). Serve those without the bundle — reading
183
+ // the version straight from package.json — instead of crashing on require.
184
+ // Any other case (a build was expected, or the bundle exists but is broken)
185
+ // rethrows: that is a genuine failure, not a skippable one.
186
+ if (require.main !== module || !skipBuild || fs.existsSync(compiledRunner)) {
187
+ throw loadErr;
188
+ }
189
+ let pkgVersion = "unknown";
190
+ try {
191
+ pkgVersion = JSON.parse(fs.readFileSync(path.join(repoRoot, "package.json"), "utf8")).version || "unknown";
192
+ } catch {
193
+ // Keep "unknown".
194
+ }
195
+ if (cliArgs.includes("--help") || cliArgs.includes("-h")) {
196
+ console.log(`\nSuperpowers MCP v${pkgVersion} - Targeted Global Setup`);
197
+ console.log("\nUsage:\n superpowers-mcp setup --target <name> [options]\n");
198
+ console.log("The setup bundle (out/setup-runner.js) is not built yet;");
199
+ console.log("re-run without --help/--dry-run to build it, then use --help for full usage.\n");
200
+ process.exit(0);
201
+ }
202
+ console.log(`Superpowers MCP v${pkgVersion}: setup bundle is not built; re-run without --dry-run to build it first.`);
203
+ process.exit(0);
204
+ }
116
205
 
117
206
  module.exports = runner;
118
207
 
@@ -17,6 +17,10 @@
17
17
  * node scripts/upstream-drift.js --fetch # compare the baseline against upstream
18
18
  * node scripts/upstream-drift.js --record # refresh the baseline from upstream
19
19
  *
20
+ * Auth: unauthenticated GitHub API calls are rate-limited (60/hr). Set GH_TOKEN
21
+ * (or GITHUB_TOKEN) to a personal access token to raise the limit; `gh api`
22
+ * uses its own auth when the GitHub CLI is logged in.
23
+ *
20
24
  * Options:
21
25
  * --ref <ref> upstream ref to read (default: the baseline ref, else "dev")
22
26
  * --repo <owner/name> upstream repository (default: obra/superpowers)
@@ -36,6 +40,7 @@
36
40
 
37
41
  const fs = require("fs");
38
42
  const path = require("path");
43
+ const crypto = require("crypto");
39
44
  const { execFileSync } = require("child_process");
40
45
 
41
46
  const REPO_ROOT = path.join(__dirname, "..");
@@ -66,6 +71,9 @@ function parseArgs(argv) {
66
71
  throw new Error(`Unknown argument: ${arg}`);
67
72
  }
68
73
  }
74
+ if (opts.repo && !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(opts.repo)) {
75
+ throw new Error(`Invalid --repo "${opts.repo}" (expected owner/name)`);
76
+ }
69
77
  return opts;
70
78
  }
71
79
 
@@ -190,8 +198,14 @@ async function fetchUpstreamTree(repo, ref) {
190
198
  }
191
199
  if (!raw) {
192
200
  source = "api.github.com";
201
+ // Authenticated requests get a far higher rate limit; without a token
202
+ // an unauthenticated fetch can 403/429 on shared CI IPs. `gh api`
203
+ // above already uses the CLI's own auth when available.
204
+ const headers = { accept: "application/vnd.github+json", "user-agent": "superpowers-mcp-drift" };
205
+ const token = process.env.GH_TOKEN || process.env.GITHUB_TOKEN;
206
+ if (token) headers.authorization = `Bearer ${token}`;
193
207
  const response = await fetch(`https://api.github.com/${endpoint}`, {
194
- headers: { accept: "application/vnd.github+json", "user-agent": "superpowers-mcp-drift" },
208
+ headers,
195
209
  signal: AbortSignal.timeout(NETWORK_TIMEOUT_MS),
196
210
  });
197
211
  if (!response.ok) {
@@ -240,6 +254,9 @@ function requireCompleteTreeForRecord(tree) {
240
254
  if (tree.truncated) {
241
255
  throw new Error("Refusing to record a truncated upstream tree; the existing baseline was left unchanged");
242
256
  }
257
+ if (!tree.commit || Object.keys(tree.files || {}).length === 0) {
258
+ throw new Error("Refusing to record an empty upstream tree; the existing baseline was left unchanged");
259
+ }
243
260
  }
244
261
 
245
262
  async function main() {
@@ -279,9 +296,12 @@ async function main() {
279
296
  const recorded = { repo, ref, commit: tree.commit, capturedAt: new Date().toISOString().slice(0, 10), files, upstreamSkills, ignoredUpstreamSkills: ignored };
280
297
  // Atomic write: temp file + rename so an interrupted --record can never
281
298
  // truncate/corrupt the baseline (which a later run would then silently rebuild).
282
- const tmpPath = `${BASELINE_PATH}.${process.pid}.tmp`;
299
+ // The suffix mixes pid and crypto randomness so concurrent --record runs
300
+ // never share a tmp path, and the wx flag makes a (near-impossible)
301
+ // collision fail instead of silently overwriting the other writer.
302
+ const tmpPath = `${BASELINE_PATH}.${process.pid}.${crypto.randomBytes(8).toString("hex")}.tmp`;
283
303
  try {
284
- fs.writeFileSync(tmpPath, JSON.stringify(recorded, null, 2) + "\n", "utf-8");
304
+ fs.writeFileSync(tmpPath, JSON.stringify(recorded, null, 2) + "\n", { encoding: "utf-8", flag: "wx" });
285
305
  fs.renameSync(tmpPath, BASELINE_PATH);
286
306
  } catch (writeErr) {
287
307
  try { fs.unlinkSync(tmpPath); } catch { /* ignore */ }
@@ -340,12 +360,15 @@ async function main() {
340
360
 
341
361
  const tree = await fetchUpstreamTree(repo, ref);
342
362
  const drift = classifyDrift(baseline.files, tree.files, ignored);
343
- // A truncated upstream tree has files missing from the listing; those baseline
344
- // files would be misclassified as "removed". Suppress the unreliable removals so
345
- // the report does not invent drift (changed/added only cover files that ARE listed
346
- // and remain trustworthy).
363
+ // A truncated upstream tree has files missing from the listing; the added
364
+ // and changed entries below cover only the files that ARE listed, so they
365
+ // are a partial view, and missing baseline files would be misclassified
366
+ // as "removed". Suppress the unreliable removals so the report does not
367
+ // invent drift, and warn loudly that added/changed are partial too — they
368
+ // must never be recorded as a complete review of upstream movement.
347
369
  if (tree.truncated) {
348
370
  drift.removed = [];
371
+ console.warn("warning: the upstream listing was truncated — added/changed below are PARTIAL and removals were suppressed.");
349
372
  }
350
373
  const driftCount = drift.changed.length + drift.added.length + drift.removed.length;
351
374
  if (opts.json) {
@@ -370,7 +393,7 @@ async function main() {
370
393
  console.log(`${drift.unadoptedFiles.length} upstream file(s) belong to skills this fork does not adopt — adopt or record them with --ignore.`);
371
394
  }
372
395
  if (tree.truncated) {
373
- console.log("warning: the upstream listing was truncated, so this comparison may be partial.");
396
+ console.log("warning: the upstream listing was truncated, so this comparison is partial: added/changed may be incomplete and removals were suppressed — re-run with GH_TOKEN set or a narrower ref.");
374
397
  }
375
398
  }
376
399
  if (opts.failOnDrift && driftCount > 0 && !tree.truncated) {
@@ -135,7 +135,8 @@ your path and complete them in order.
135
135
  6. **Write design doc** — save to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md` and commit
136
136
  7. **Planning-handoff review** — simulate the next planning stage, rate and inventory its burdens, and take the required bounded branch (see below)
137
137
  8. **User reviews written spec** — ask user to review the spec file before proceeding
138
- 9. **Transition to implementation** — invoke writing-plans skill to create implementation plan
138
+ 9. **Builder check** — a fresh subagent reads the design as its builder and lists what they'd still need to ask; answer what's answered, decide the minor calls, bring the user only what changes the build (see below)
139
+ 10. **Transition to implementation** — invoke writing-plans skill to create implementation plan
139
140
 
140
141
  ## Process Flow
141
142
 
@@ -156,6 +157,7 @@ digraph brainstorming {
156
157
  "Write design doc" [shape=box];
157
158
  "Planning-handoff review\n(rate; burden ledger; bounded branch)" [shape=box];
158
159
  "User reviews spec?" [shape=diamond];
160
+ "Builder check\n(fresh subagent; one round)" [shape=box];
159
161
  "Invoke writing-plans skill" [shape=doublecircle];
160
162
  "Hidden complexity? Upgrade path" [shape=box];
161
163
 
@@ -177,7 +179,8 @@ digraph brainstorming {
177
179
  "Write design doc" -> "Planning-handoff review\n(rate; burden ledger; bounded branch)";
178
180
  "Planning-handoff review\n(rate; burden ledger; bounded branch)" -> "User reviews spec?";
179
181
  "User reviews spec?" -> "Write design doc" [label="changes requested"];
180
- "User reviews spec?" -> "Invoke writing-plans skill" [label="approved"];
182
+ "User reviews spec?" -> "Builder check\n(fresh subagent; one round)" [label="approved"];
183
+ "Builder check\n(fresh subagent; one round)" -> "Invoke writing-plans skill";
181
184
  }
182
185
  ```
183
186
 
@@ -326,6 +329,25 @@ After the spec review loop passes, ask the user to review the written spec befor
326
329
 
327
330
  Wait for the user's response. If they request changes, make them and re-run the spec review loop. Only proceed once the user approves.
328
331
 
332
+ **Builder Check:**
333
+ After the user approves the spec, dispatch a fresh subagent with
334
+ `builder-check-prompt.md` in this directory (fill in the domain and the
335
+ design document path) before handing anything to planning. When telling
336
+ the user the design is written up, say a reviewer will read it first and
337
+ you may come back once with a few questions. Sort what the builder asks
338
+ into three piles:
339
+
340
+ - **Answered already** by the conversation or the repository: put the answer in the document.
341
+ - **Minor:** a sensible builder could settle it without changing what gets built. Settle it yourself and mark it in the document as your call.
342
+ - **Theirs:** only the human partner can answer it, and the answer changes what gets built.
343
+
344
+ Bring the "theirs" pile in one message, most important first. Update the
345
+ document with the answers, then hand it over with a short list of the
346
+ calls you made so they can check those while reading. That's the only
347
+ round of questions the check produces. Without a subagent tool, read the
348
+ document as that builder yourself. Do not begin planning until this round
349
+ closes.
350
+
329
351
  **Implementation:**
330
352
 
331
353
  - Invoke the writing-plans skill to create a detailed implementation plan
@@ -0,0 +1,23 @@
1
+ # Builder Check Prompt
2
+
3
+ Dispatch a fresh general-purpose subagent with this prompt once the
4
+ written design exists. Fill in the domain and the document path.
5
+
6
+ ```
7
+ You are a talented [DOMAIN, e.g. "software engineer", "event planner",
8
+ "bakery consultant"]. You've been handed a design document and asked to
9
+ put together a plan to build what it describes. You will not be able to
10
+ talk to the person who wrote it.
11
+
12
+ Read [DOCUMENT_PATH].
13
+
14
+ Report only the questions you'd still need answered before you could plan
15
+ this well: places where you'd have to guess and a wrong guess would
16
+ matter. For each, give the question and why the answer changes the plan.
17
+ Rank them by importance.
18
+
19
+ Skip anything the document explicitly leaves to the builder, and anything
20
+ you could reasonably decide yourself. Skip nitpicks about wording.
21
+
22
+ If nothing important is left, say "nothing important left".
23
+ ```
@@ -27,7 +27,8 @@
27
27
  }
28
28
 
29
29
  function reloadAfterRecovery() {
30
- window.location.replace('/');
30
+ const href = window.location.href;
31
+ window.location.replace(href && href.indexOf('key=') !== -1 ? href : '/');
31
32
  }
32
33
 
33
34
  // Reflect connection state in the frame's status pill (absent on full-doc screens).
@@ -610,9 +610,10 @@ function parseCookies(header) {
610
610
  // A request is authorized if it carries the session key as ?key= or as the
611
611
  // session cookie. Both are compared in constant time.
612
612
  function isAuthorized(req) {
613
- const q = req.url.indexOf('?');
613
+ const url = req.url || '/';
614
+ const q = url.indexOf('?');
614
615
  if (q >= 0) {
615
- const params = new URLSearchParams(req.url.slice(q + 1));
616
+ const params = new URLSearchParams(url.slice(q + 1));
616
617
  if (params.has('key')) {
617
618
  const key = params.get('key');
618
619
  return Boolean(key && timingSafeEqualStr(key, TOKEN));
@@ -658,6 +659,7 @@ function isAllowedWebSocketOrigin(req) {
658
659
  // ========== HTTP Request Handler ==========
659
660
 
660
661
  function handleRequest(req, res) {
662
+ const url = req.url || '/';
661
663
  if (!isAuthorized(req)) {
662
664
  res.writeHead(403, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }));
663
665
  res.end(FORBIDDEN_PAGE);
@@ -671,8 +673,8 @@ function handleRequest(req, res) {
671
673
  res.setHeader('Set-Cookie',
672
674
  COOKIE_NAME + '=' + TOKEN + '; HttpOnly; SameSite=Strict; Path=/');
673
675
 
674
- const pathname = pathnameOf(req.url);
675
- const keyFromQuery = queryKey(req.url);
676
+ const pathname = pathnameOf(url);
677
+ const keyFromQuery = queryKey(url);
676
678
  if (req.method === 'GET' && pathname === '/' && keyFromQuery && timingSafeEqualStr(keyFromQuery, TOKEN)) {
677
679
  res.writeHead(303, securityHeaders({ Location: '/' }));
678
680
  res.end();
@@ -747,10 +749,11 @@ function isWebSocketUpgradeRequest(req) {
747
749
  }
748
750
 
749
751
  function handleUpgrade(req, socket) {
752
+ const url = req.url || '/';
750
753
  if (!isAuthorized(req) || !isAllowedWebSocketOrigin(req)) { socket.destroy(); return; }
751
754
  if (!isWebSocketUpgradeRequest(req)) { socket.destroy(); return; }
752
755
  // The companion's WebSocket lives at '/' only (helper.js connects there).
753
- if (pathnameOf(req.url) !== '/') { socket.destroy(); return; }
756
+ if (pathnameOf(url) !== '/') { socket.destroy(); return; }
754
757
 
755
758
  const key = req.headers['sec-websocket-key'];
756
759
  if (!key) { socket.destroy(); return; }
@@ -905,7 +908,7 @@ function appendEvent(event) {
905
908
  return;
906
909
  }
907
910
 
908
- const fd = openPrivateAppendFile(eventsFile);
911
+ let fd = openPrivateAppendFile(eventsFile);
909
912
  if (fd === null) {
910
913
  console.error('Failed to append user event: events path is not a private regular file');
911
914
  return;
@@ -921,8 +924,25 @@ function appendEvent(event) {
921
924
  const firstNewline = retained.indexOf(0x0a);
922
925
  retained = firstNewline >= 0 ? retained.subarray(firstNewline + 1) : Buffer.alloc(0);
923
926
  }
924
- fs.ftruncateSync(fd, 0);
925
- if (retained.length > 0) fs.writeSync(fd, retained);
927
+ try {
928
+ fs.ftruncateSync(fd, 0);
929
+ if (retained.length > 0) fs.writeSync(fd, retained);
930
+ } catch (truncateErr) {
931
+ // Windows refuses ftruncate on an O_APPEND descriptor (EPERM), so
932
+ // rewrite the compacted tail through a fresh truncate-open instead.
933
+ // The new line is still appended below; the size cap still holds.
934
+ if (truncateErr.code !== 'EPERM' && truncateErr.code !== 'EACCES') throw truncateErr;
935
+ try { fs.closeSync(fd); } catch (e) { /* already closed */ }
936
+ let compacted = false;
937
+ if (writePrivateFile(eventsFile, retained)) {
938
+ const reopened = openPrivateAppendFile(eventsFile);
939
+ if (reopened !== null) {
940
+ fd = reopened;
941
+ compacted = true;
942
+ }
943
+ }
944
+ if (!compacted) throw truncateErr;
945
+ }
926
946
  }
927
947
  fs.writeSync(fd, line);
928
948
  } catch (e) {
@@ -951,7 +971,7 @@ function handleMessage(text) {
951
971
  : JSON.stringify({ source: 'user-event', truncated: true });
952
972
  console.log(logOutput);
953
973
  if (event && typeof event === 'object') {
954
- if (event.choice) {
974
+ if (event && typeof event === 'object' && ('choice' in event) && event.choice != null) {
955
975
  appendEvent(event);
956
976
  } else if (event.type === 'choice' && event.value) {
957
977
  appendEvent({ ...event, choice: event.value });
@@ -979,8 +999,16 @@ function maybeOpenBrowser() {
979
999
  const url = companionUrl(); // must carry the key or the gate 403s it
980
1000
  const cp = require('child_process');
981
1001
  // Operator-provided launcher: run via execFile (no shell) so a malicious env var
982
- // cannot inject commands through shell metacharacters.
1002
+ // cannot inject commands through shell metacharacters. Only an absolute path
1003
+ // is honored — the operator is expected to allowlist a fixed browser binary
1004
+ // (e.g. export BRAINSTORM_OPEN_CMD=/usr/bin/xdg-open); a relative value is
1005
+ // refused with a warning because it would resolve via PATH and could be
1006
+ // hijacked by a planted executable earlier on the search path.
983
1007
  if (process.env.BRAINSTORM_OPEN_CMD) {
1008
+ if (!path.isAbsolute(process.env.BRAINSTORM_OPEN_CMD)) {
1009
+ console.error('Refusing relative BRAINSTORM_OPEN_CMD (must be an absolute path):', process.env.BRAINSTORM_OPEN_CMD);
1010
+ return;
1011
+ }
984
1012
  try { cp.execFile(process.env.BRAINSTORM_OPEN_CMD, [url], () => {}); } catch (e) { /* best effort */ }
985
1013
  return;
986
1014
  }
@@ -34,8 +34,12 @@ function Protect-PathForCurrentUser {
34
34
  $item = Get-Item -LiteralPath $Path -ErrorAction Stop
35
35
  if (-not $isWindowsPlatform) {
36
36
  $mode = if ($item.PSIsContainer) { "700" } else { "600" }
37
- & chmod $mode $item.FullName
38
- if ($LASTEXITCODE -ne 0) { throw "chmod failed" }
37
+ # chmod may be absent (e.g. bare Windows pwsh without Git-bash);
38
+ # skip best-effort instead of failing — Windows uses ACLs below.
39
+ if (Get-Command chmod -ErrorAction SilentlyContinue) {
40
+ & chmod $mode $item.FullName
41
+ if ($LASTEXITCODE -ne 0) { throw "chmod failed" }
42
+ }
39
43
  return
40
44
  }
41
45
  $acl = Get-Acl -LiteralPath $item.FullName
@@ -121,7 +125,7 @@ if ($urlHost -eq "") {
121
125
  function Test-LoopbackHost {
122
126
  param([string]$HostValue)
123
127
  $normalized = $HostValue.Trim().TrimStart('[').TrimEnd(']').ToLowerInvariant()
124
- if ($normalized -eq "localhost" -or $normalized -eq "::1" -or $normalized.StartsWith("127.")) {
128
+ if ($normalized -eq "localhost" -or $normalized -eq "::1") {
125
129
  return $true
126
130
  }
127
131
  $address = $null