claude-everything-workflow 0.1.8 → 0.2.2

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 (132) hide show
  1. package/AGENTS.md +19 -20
  2. package/README.md +112 -104
  3. package/agents/code-reviewer.md +15 -44
  4. package/agents/harness-optimizer.md +3 -2
  5. package/agents/planner.md +23 -107
  6. package/commands/code-review.md +25 -9
  7. package/commands/learn.md +97 -0
  8. package/commands/pr.md +4 -0
  9. package/commands/to-spec.md +11 -0
  10. package/hooks/check-code-size.js +33 -12
  11. package/hooks/check-console-log.js +72 -24
  12. package/package.json +5 -2
  13. package/rules/01-base.md +19 -42
  14. package/rules/02-code-size.md +6 -17
  15. package/rules/03-architecture.md +16 -54
  16. package/rules/04-error-handling.md +4 -25
  17. package/rules/05-git-workflow.md +9 -37
  18. package/rules/06-comments.md +3 -37
  19. package/rules/07-forbidden.md +6 -30
  20. package/rules/08-specialty-rules-index.md +18 -0
  21. package/rules/09-first-principles-adversarial-testing.md +6 -18
  22. package/rules/common/agent-orchestration.md +10 -47
  23. package/rules/common/context-hygiene.md +9 -72
  24. package/rules/common/harness-engineering.md +11 -38
  25. package/rules/common/hooks.md +11 -82
  26. package/rules/common/performance.md +8 -71
  27. package/rules/common/pr-automation.md +7 -68
  28. package/rules/common/skills-learning.md +12 -36
  29. package/rules/common/testing.md +15 -59
  30. package/scripts/cleanup-retired-skills.js +214 -0
  31. package/scripts/install.ps1 +73 -85
  32. package/scripts/install.sh +54 -77
  33. package/scripts/learning/review-confidence.js +1 -4
  34. package/scripts/merge-claude-settings.cjs +75 -0
  35. package/scripts/retired-skill-files.json +37 -0
  36. package/scripts/upstream-capability-baseline.json +27 -0
  37. package/scripts/upstream-capability-map.json +150 -0
  38. package/scripts/verify/core.js +91 -0
  39. package/scripts/verify/grilling-spec-gate-checks.js +260 -0
  40. package/scripts/verify/metadata-checks.js +724 -0
  41. package/scripts/verify/repository-checks.js +435 -0
  42. package/scripts/verify/runtime-checks.js +593 -0
  43. package/scripts/verify/workflow-checks.js +741 -0
  44. package/scripts/verify/workflow-ownership-fixtures.js +371 -0
  45. package/scripts/verify/workflow-ownership.js +780 -0
  46. package/scripts/verify-harness.js +16 -1075
  47. package/scripts/verify-upstream-capability-map.js +117 -0
  48. package/skills/README.md +24 -10
  49. package/skills/code-review/SKILL.md +50 -0
  50. package/skills/code-review/references/spec-reviewer-prompt.md +24 -0
  51. package/skills/code-review/references/standards-reviewer-prompt.md +35 -0
  52. package/skills/codebase-design/SKILL.md +63 -0
  53. package/skills/codebase-design/references/deepening.md +27 -0
  54. package/skills/codebase-design/references/design-it-twice.md +17 -0
  55. package/skills/continuous-learning-v2/SKILL.md +7 -7
  56. package/skills/continuous-learning-v2/config.json +0 -4
  57. package/skills/domain-modeling/SKILL.md +100 -0
  58. package/skills/feature-acceptance/SKILL.md +89 -0
  59. package/skills/grilling/SKILL.md +83 -0
  60. package/skills/handoff/SKILL.md +56 -0
  61. package/skills/implement/SKILL.md +97 -0
  62. package/skills/improve-codebase-architecture/SKILL.md +48 -0
  63. package/skills/iterative-retrieval/SKILL.md +10 -1
  64. package/skills/learn/README.md +2 -2
  65. package/skills/project-context/SKILL.md +94 -0
  66. package/skills/project-context/agents/openai.yaml +6 -0
  67. package/skills/project-context/references/project-context-template.md +61 -0
  68. package/skills/prototype/SKILL.md +50 -0
  69. package/skills/prototype/references/logic.md +28 -0
  70. package/skills/prototype/references/ui.md +30 -0
  71. package/skills/research/SKILL.md +48 -0
  72. package/skills/resolving-merge-conflicts/SKILL.md +27 -0
  73. package/skills/spec-gate/SKILL.md +149 -0
  74. package/skills/spec-gate/agents/openai.yaml +4 -0
  75. package/skills/spec-gate/references/spec-document-reviewer-prompt.md +31 -0
  76. package/skills/subagent-driven-development/SKILL.md +95 -414
  77. package/skills/systematic-debugging/SKILL.md +7 -51
  78. package/skills/systematic-debugging/references/diagnosing-bugs.upstream.md +129 -0
  79. package/skills/systematic-debugging/scripts/hitl-loop.template.js +75 -0
  80. package/skills/systematic-debugging/scripts/hitl-loop.template.sh +41 -0
  81. package/skills/test-driven-development/SKILL.md +18 -2
  82. package/skills/to-tickets/SKILL.md +94 -0
  83. package/skills/triage/SKILL.md +53 -0
  84. package/skills/triage/references/agent-brief.md +32 -0
  85. package/skills/triage/references/out-of-scope.md +14 -0
  86. package/skills/using-superpowers/SKILL.md +140 -40
  87. package/skills/visual-companion/SKILL.md +62 -0
  88. package/skills/visual-companion/agents/openai.yaml +4 -0
  89. package/skills/{brainstorming/visual-companion.md → visual-companion/references/guide.md} +1 -1
  90. package/skills/{brainstorming → visual-companion}/scripts/frame-template.html +42 -12
  91. package/skills/visual-companion/scripts/pages.cjs +28 -0
  92. package/skills/visual-companion/scripts/server-utils.cjs +82 -0
  93. package/skills/{brainstorming → visual-companion}/scripts/server.cjs +108 -248
  94. package/skills/{brainstorming → visual-companion}/scripts/start-server.sh +18 -4
  95. package/skills/visual-companion/scripts/websocket.cjs +86 -0
  96. package/skills/wayfinder/SKILL.md +57 -0
  97. package/commands/e2e.md +0 -28
  98. package/commands/evolve.md +0 -42
  99. package/commands/harness-audit.md +0 -27
  100. package/commands/instinct-status.md +0 -38
  101. package/commands/learn-eval.md +0 -91
  102. package/commands/projects.md +0 -27
  103. package/commands/promote.md +0 -29
  104. package/commands/prune.md +0 -46
  105. package/commands/tdd.md +0 -27
  106. package/homunculus/instincts/personal/always-test-first.md +0 -28
  107. package/homunculus/instincts/personal/pr-ci-quality-gate.md +0 -30
  108. package/rules/08-ecc-integration.md +0 -46
  109. package/rules/common/implementation.md +0 -25
  110. package/rules/common/security.md +0 -19
  111. package/skills/brainstorming/SKILL.md +0 -185
  112. package/skills/brainstorming/agents/openai.yaml +0 -3
  113. package/skills/brainstorming/spec-document-reviewer-prompt.md +0 -49
  114. package/skills/context-budget/SKILL.md +0 -59
  115. package/skills/documentation-lookup/SKILL.md +0 -90
  116. package/skills/executing-plans/SKILL.md +0 -66
  117. package/skills/skill-creator/LICENSE.txt +0 -202
  118. package/skills/skill-creator/SKILL.md +0 -356
  119. package/skills/skill-creator/references/output-patterns.md +0 -82
  120. package/skills/skill-creator/references/workflows.md +0 -28
  121. package/skills/skill-creator/scripts/init_skill.py +0 -303
  122. package/skills/skill-creator/scripts/package_skill.py +0 -110
  123. package/skills/skill-creator/scripts/quick_validate.py +0 -95
  124. package/skills/subagent-driven-development/implementer-prompt.md +0 -139
  125. package/skills/subagent-driven-development/scripts/review-package +0 -44
  126. package/skills/subagent-driven-development/scripts/sdd-workspace +0 -22
  127. package/skills/subagent-driven-development/scripts/task-brief +0 -40
  128. package/skills/subagent-driven-development/task-reviewer-prompt.md +0 -188
  129. package/skills/writing-plans/SKILL.md +0 -206
  130. package/skills/writing-plans/plan-document-reviewer-prompt.md +0 -49
  131. /package/skills/{brainstorming → visual-companion}/scripts/helper.js +0 -0
  132. /package/skills/{brainstorming → visual-companion}/scripts/stop-server.sh +0 -0
@@ -2,83 +2,24 @@ const crypto = require('crypto');
2
2
  const http = require('http');
3
3
  const fs = require('fs');
4
4
  const path = require('path');
5
-
6
- // ========== WebSocket Protocol (RFC 6455) ==========
7
-
8
- const OPCODES = { TEXT: 0x01, CLOSE: 0x08, PING: 0x09, PONG: 0x0A };
9
- const WS_MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
10
- const MAX_FRAME_PAYLOAD_BYTES = 10 * 1024 * 1024;
11
-
12
- function computeAcceptKey(clientKey) {
13
- return crypto.createHash('sha1').update(clientKey + WS_MAGIC).digest('base64');
14
- }
15
-
16
- function encodeFrame(opcode, payload) {
17
- const fin = 0x80;
18
- const len = payload.length;
19
- let header;
20
-
21
- if (len < 126) {
22
- header = Buffer.alloc(2);
23
- header[0] = fin | opcode;
24
- header[1] = len;
25
- } else if (len < 65536) {
26
- header = Buffer.alloc(4);
27
- header[0] = fin | opcode;
28
- header[1] = 126;
29
- header.writeUInt16BE(len, 2);
30
- } else {
31
- header = Buffer.alloc(10);
32
- header[0] = fin | opcode;
33
- header[1] = 127;
34
- header.writeBigUInt64BE(BigInt(len), 2);
35
- }
36
-
37
- return Buffer.concat([header, payload]);
38
- }
39
-
40
- function decodeFrame(buffer) {
41
- if (buffer.length < 2) return null;
42
-
43
- const secondByte = buffer[1];
44
- const opcode = buffer[0] & 0x0F;
45
- const masked = (secondByte & 0x80) !== 0;
46
- let payloadLen = secondByte & 0x7F;
47
- let offset = 2;
48
-
49
- if (!masked) throw new Error('Client frames must be masked');
50
-
51
- if (payloadLen === 126) {
52
- if (buffer.length < 4) return null;
53
- payloadLen = buffer.readUInt16BE(2);
54
- offset = 4;
55
- } else if (payloadLen === 127) {
56
- if (buffer.length < 10) return null;
57
- const extendedLen = buffer.readBigUInt64BE(2);
58
- if (extendedLen > BigInt(MAX_FRAME_PAYLOAD_BYTES)) {
59
- throw new Error('WebSocket frame payload exceeds maximum allowed size');
60
- }
61
- payloadLen = Number(extendedLen);
62
- offset = 10;
63
- }
64
-
65
- if (payloadLen > MAX_FRAME_PAYLOAD_BYTES) {
66
- throw new Error('WebSocket frame payload exceeds maximum allowed size');
67
- }
68
-
69
- const maskOffset = offset;
70
- const dataOffset = offset + 4;
71
- const totalLen = dataOffset + payloadLen;
72
- if (buffer.length < totalLen) return null;
73
-
74
- const mask = buffer.slice(maskOffset, dataOffset);
75
- const data = Buffer.alloc(payloadLen);
76
- for (let i = 0; i < payloadLen; i++) {
77
- data[i] = buffer[dataOffset + i] ^ mask[i % 4];
78
- }
79
-
80
- return { opcode, payload: data, bytesConsumed: totalLen };
81
- }
5
+ const {
6
+ computeAcceptKey,
7
+ encodeFrame,
8
+ decodeFrame,
9
+ OPCODES,
10
+ MAX_FRAME_PAYLOAD_BYTES,
11
+ } = require('./websocket.cjs');
12
+ const {
13
+ urlHostForHttp,
14
+ browserLauncherForPlatform,
15
+ timingSafeEqualStr,
16
+ parseCookies,
17
+ pathnameOf,
18
+ queryKey,
19
+ securityHeaders,
20
+ isAllowedWebSocketOrigin,
21
+ } = require('./server-utils.cjs');
22
+ const { FORBIDDEN_PAGE, bootstrapPage } = require('./pages.cjs');
82
23
 
83
24
  // ========== Configuration ==========
84
25
 
@@ -161,44 +102,23 @@ const MIME_TYPES = {
161
102
  function waitingPage() {
162
103
  return renderBranding(`<!DOCTYPE html>
163
104
  <html>
164
- <head><meta charset="utf-8"><title>Brainstorm Companion</title>
105
+ <head><meta charset="utf-8"><title>Visual Companion</title>
165
106
  <style>
166
107
  body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
167
108
  h1 { color: #333; } p { color: #666; }
168
- .brand { display: flex; align-items: center; min-width: 0; overflow: hidden; margin-bottom: 1.5rem; color: #666; font-size: 0.9rem; line-height: 1; }
169
- .brand a { color: inherit; text-decoration: none; display: flex; align-items: center; gap: 0.5rem; min-width: 0; max-width: 100%; line-height: 1; }
170
- .brand-copy { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 1; transform: translateY(-1px); }
109
+ .brand { display: flex; align-items: center; min-width: 0; overflow: hidden;
110
+ margin-bottom: 1.5rem; color: #666; font-size: 0.9rem; line-height: 1; }
111
+ .brand a { color: inherit; text-decoration: none; display: flex; align-items: center;
112
+ gap: 0.5rem; min-width: 0; max-width: 100%; line-height: 1; }
113
+ .brand-copy { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis;
114
+ white-space: nowrap; line-height: 1; transform: translateY(-1px); }
171
115
  .brand-logo { display: block; height: 1em; width: auto; max-width: 180px; filter: invert(1); }
172
116
  </style>
173
117
  </head>
174
- <body><!-- BRANDING --><h1>Brainstorm Companion</h1>
118
+ <body><!-- BRANDING --><h1>Visual Companion</h1>
175
119
  <p>Waiting for the agent to push a screen...</p></body></html>`);
176
120
  }
177
121
 
178
- const FORBIDDEN_PAGE = `<!DOCTYPE html>
179
- <html>
180
- <head><meta charset="utf-8"><title>Session key required</title>
181
- <style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
182
- h1 { color: #333; } p { color: #666; } code { background: #f0f0f0; padding: 0.1em 0.3em; border-radius: 4px; }</style>
183
- </head>
184
- <body><h1>Session key required</h1>
185
- <p>This page needs the full URL your coding agent gave you, including the
186
- <code>?key=&hellip;</code> part. Copy the complete URL and open it again.</p></body></html>`;
187
-
188
- function bootstrapPage(key) {
189
- const jsonKey = JSON.stringify(String(key));
190
- return `<!DOCTYPE html>
191
- <html>
192
- <head><meta charset="utf-8"><title>Opening Brainstorm Companion</title></head>
193
- <body>
194
- <script>
195
- try { sessionStorage.setItem('brainstorm-session-key', ${jsonKey}); } catch (e) {}
196
- location.replace('/');
197
- </script>
198
- </body>
199
- </html>`;
200
- }
201
-
202
122
  const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8');
203
123
  const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');
204
124
  const helperInjection = '<script>\n' + helperScript + '\n</script>';
@@ -246,9 +166,12 @@ function brandMarkup() {
246
166
  : 'Superpowers v' + version;
247
167
  const logo = SUPERPOWERS_TELEMETRY_DISABLED
248
168
  ? ''
249
- : '<img class="brand-logo" src="' + SUPERPOWERS_BRAND_IMAGE_URL + '?v=' + encodeURIComponent(SUPERPOWERS_VERSION) + '" alt="Prime Radiant" referrerpolicy="no-referrer" decoding="async">';
169
+ : '<img class="brand-logo" src="' + SUPERPOWERS_BRAND_IMAGE_URL +
170
+ '?v=' + encodeURIComponent(SUPERPOWERS_VERSION) +
171
+ '" alt="Prime Radiant" referrerpolicy="no-referrer" decoding="async">';
250
172
 
251
- return '<div class="brand"><a href="https://github.com/obra/superpowers">' + logo + '<span class="brand-copy">' + text + '</span></a></div>';
173
+ return '<div class="brand"><a href="https://github.com/obra/superpowers">' +
174
+ logo + '<span class="brand-copy">' + text + '</span></a></div>';
252
175
  }
253
176
 
254
177
  function renderBranding(html) {
@@ -277,30 +200,10 @@ function getNewestScreen() {
277
200
  return files.length > 0 ? files[0].path : null;
278
201
  }
279
202
 
280
- function urlHostForHttp(host) {
281
- const h = String(host);
282
- if (h.startsWith('[') && h.endsWith(']')) return h;
283
- return h.includes(':') ? '[' + h + ']' : h;
284
- }
285
-
286
203
  function companionUrl() {
287
204
  return 'http://' + urlHostForHttp(URL_HOST) + ':' + PORT + '/?key=' + TOKEN;
288
205
  }
289
206
 
290
- function browserLauncherForPlatform(url, {
291
- platform = process.platform,
292
- osRelease = require('os').release(),
293
- env = process.env
294
- } = {}) {
295
- const isWSL = platform === 'linux' && /microsoft/i.test(osRelease);
296
- if (platform === 'darwin') return { bin: 'open', args: [url] };
297
- if (platform === 'win32' || isWSL) {
298
- return { bin: 'rundll32.exe', args: ['url.dll,FileProtocolHandler', url] };
299
- }
300
- if (env.DISPLAY || env.WAYLAND_DISPLAY) return { bin: 'xdg-open', args: [url] };
301
- return null;
302
- }
303
-
304
207
  function isRegularFileInsideContentDir(filePath) {
305
208
  let stat, realContentDir, realFilePath;
306
209
  try {
@@ -318,24 +221,6 @@ function isRegularFileInsideContentDir(filePath) {
318
221
 
319
222
  // ========== Authentication ==========
320
223
 
321
- function timingSafeEqualStr(a, b) {
322
- const ab = Buffer.from(String(a));
323
- const bb = Buffer.from(String(b));
324
- if (ab.length !== bb.length) return false;
325
- return crypto.timingSafeEqual(ab, bb);
326
- }
327
-
328
- function parseCookies(header) {
329
- const out = {};
330
- if (!header) return out;
331
- for (const part of header.split(';')) {
332
- const eq = part.indexOf('=');
333
- if (eq < 0) continue;
334
- out[part.slice(0, eq).trim()] = part.slice(eq + 1).trim();
335
- }
336
- return out;
337
- }
338
-
339
224
  // A request is authorized if it carries the session key as ?key= or as the
340
225
  // session cookie. Both are compared in constant time.
341
226
  function isAuthorized(req) {
@@ -352,36 +237,6 @@ function isAuthorized(req) {
352
237
  return false;
353
238
  }
354
239
 
355
- function pathnameOf(url) {
356
- const q = url.indexOf('?');
357
- return q >= 0 ? url.slice(0, q) : url;
358
- }
359
-
360
- function queryKey(url) {
361
- const q = url.indexOf('?');
362
- if (q < 0) return null;
363
- return new URLSearchParams(url.slice(q + 1)).get('key');
364
- }
365
-
366
- function securityHeaders(headers = {}) {
367
- return {
368
- 'Referrer-Policy': 'no-referrer',
369
- 'Cache-Control': 'no-store',
370
- 'X-Frame-Options': 'DENY',
371
- 'Content-Security-Policy': "frame-ancestors 'none'",
372
- 'Cross-Origin-Resource-Policy': 'same-origin',
373
- ...headers
374
- };
375
- }
376
-
377
- function isAllowedWebSocketOrigin(req) {
378
- const origin = req.headers.origin;
379
- if (!origin) return true;
380
- const host = req.headers.host;
381
- if (!host) return false;
382
- return origin === 'http://' + host;
383
- }
384
-
385
240
  // ========== HTTP Request Handler ==========
386
241
 
387
242
  function handleRequest(req, res) {
@@ -537,7 +392,9 @@ function maybeOpenBrowser() {
537
392
  const cp = require('child_process');
538
393
  // Operator-provided launcher: run as given (this env var is trusted operator input).
539
394
  if (process.env.BRAINSTORM_OPEN_CMD) {
540
- try { cp.exec(process.env.BRAINSTORM_OPEN_CMD + ' ' + JSON.stringify(url), () => {}); } catch (e) { /* best effort */ }
395
+ try {
396
+ cp.exec(process.env.BRAINSTORM_OPEN_CMD + ' ' + JSON.stringify(url), () => {});
397
+ } catch (e) { /* best effort */ }
541
398
  return;
542
399
  }
543
400
  // Platform launchers: pass the URL as an argv element via execFile (no shell),
@@ -573,31 +430,23 @@ const debounceTimers = new Map();
573
430
 
574
431
  // ========== Server Startup ==========
575
432
 
576
- function startServer() {
433
+ function ensureSessionDirectories() {
577
434
  if (!fs.existsSync(CONTENT_DIR)) fs.mkdirSync(CONTENT_DIR, { recursive: true });
578
435
  if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true });
436
+ }
579
437
 
580
- // Track known files to distinguish new screens from updates.
581
- // macOS fs.watch reports 'rename' for both new files and overwrites,
582
- // so we can't rely on eventType alone.
438
+ function createContentWatcher() {
583
439
  const knownFiles = new Set(
584
440
  fs.readdirSync(CONTENT_DIR).filter(f => !f.startsWith('.') && f.endsWith('.html'))
585
441
  );
586
-
587
- const server = http.createServer(handleRequest);
588
- server.on('upgrade', handleUpgrade);
589
-
590
442
  const watcher = fs.watch(CONTENT_DIR, (eventType, filename) => {
591
443
  if (!filename || filename.startsWith('.') || !filename.endsWith('.html')) return;
592
-
593
444
  if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename));
594
445
  debounceTimers.set(filename, setTimeout(() => {
595
446
  debounceTimers.delete(filename);
596
447
  const filePath = path.join(CONTENT_DIR, filename);
597
-
598
448
  if (!fs.existsSync(filePath)) return; // file was deleted
599
449
  touchActivity();
600
-
601
450
  if (!knownFiles.has(filename)) {
602
451
  knownFiles.add(filename);
603
452
  const eventsFile = path.join(STATE_DIR, 'events');
@@ -607,91 +456,88 @@ function startServer() {
607
456
  } else {
608
457
  console.log(JSON.stringify({ type: 'screen-updated', file: filePath }));
609
458
  }
610
-
611
459
  broadcast({ type: 'reload' });
612
460
  }, 100));
613
461
  });
614
462
  watcher.on('error', (err) => console.error('fs.watch error:', err.message));
463
+ return watcher;
464
+ }
615
465
 
616
- function shutdown(reason) {
617
- console.log(JSON.stringify({ type: 'server-stopped', reason }));
618
- const infoFile = path.join(STATE_DIR, 'server-info');
619
- if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile);
620
- fs.writeFileSync(
621
- path.join(STATE_DIR, 'server-stopped'),
622
- JSON.stringify({ reason, timestamp: Date.now() }) + '\n'
623
- );
624
- watcher.close();
625
- clearInterval(lifecycleCheck);
626
- // Close any upgraded WebSocket sockets so server.close() can complete and
627
- // the process actually exits instead of lingering on an open connection.
628
- for (const socket of clients) {
629
- try { socket.destroy(); } catch (e) { /* already gone */ }
630
- }
631
- server.close(() => process.exit(0));
466
+ function shutdown(runtime, reason) {
467
+ console.log(JSON.stringify({ type: 'server-stopped', reason }));
468
+ const infoFile = path.join(STATE_DIR, 'server-info');
469
+ if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile);
470
+ fs.writeFileSync(
471
+ path.join(STATE_DIR, 'server-stopped'),
472
+ JSON.stringify({ reason, timestamp: Date.now() }) + '\n'
473
+ );
474
+ runtime.watcher.close();
475
+ clearInterval(runtime.lifecycleCheck);
476
+ for (const socket of clients) {
477
+ try { socket.destroy(); } catch (e) { /* already gone */ }
632
478
  }
479
+ runtime.server.close(() => process.exit(0));
480
+ }
633
481
 
634
- function ownerAlive() {
635
- if (!ownerPid) return true;
636
- try { process.kill(ownerPid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
637
- }
482
+ function ownerAlive() {
483
+ if (!ownerPid) return true;
484
+ try { process.kill(ownerPid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
485
+ }
638
486
 
639
- // Periodically exit if the owner process died or we've been idle too long.
640
- const lifecycleCheck = setInterval(() => {
641
- if (!ownerAlive()) shutdown('owner process exited');
642
- else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout');
487
+ function startLifecycleCheck(runtime) {
488
+ runtime.lifecycleCheck = setInterval(() => {
489
+ if (!ownerAlive()) shutdown(runtime, 'owner process exited');
490
+ else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown(runtime, 'idle timeout');
643
491
  }, LIFECYCLE_CHECK_MS);
644
- lifecycleCheck.unref();
492
+ runtime.lifecycleCheck.unref();
493
+ }
645
494
 
646
- // Validate owner PID at startup. If it's already dead, the PID resolution
647
- // was wrong (common on WSL, Tailscale SSH, and cross-user scenarios).
648
- // Disable monitoring and rely on the idle timeout instead.
495
+ function validateOwnerPid() {
649
496
  if (ownerPid) {
650
497
  try { process.kill(ownerPid, 0); }
651
498
  catch (e) {
652
499
  if (e.code !== 'EPERM') {
653
- console.log(JSON.stringify({ type: 'owner-pid-invalid', pid: ownerPid, reason: 'dead at startup' }));
500
+ console.log(JSON.stringify({
501
+ type: 'owner-pid-invalid',
502
+ pid: ownerPid,
503
+ reason: 'dead at startup'
504
+ }));
654
505
  ownerPid = null;
655
506
  }
656
507
  }
657
508
  }
509
+ }
658
510
 
659
- // If the preferred port is already taken (e.g. a previous server is still
660
- // alive), fall back to a random port once instead of failing.
661
- let triedFallback = false;
662
-
663
- function onListen() {
664
- // Cookie name keys on the ACTUAL bound port (may differ from the preferred
665
- // one after an EADDRINUSE fallback) so it can't collide with another server's
666
- // cookie in the shared localhost jar.
667
- COOKIE_NAME = 'brainstorm-key-' + PORT;
668
- // Record the bound port AND token so the next restart of this session reuses
669
- // them — but ONLY when we got our preferred port. On a fallback we bound a
670
- // *different* port because someone else holds the preferred one; persisting
671
- // would overwrite the shared files and strand that other session's open tab.
672
- if (PORT_FILE && !triedFallback) {
673
- try { fs.writeFileSync(PORT_FILE, String(PORT)); } catch (e) { /* best effort */ }
674
- if (TOKEN_FILE) {
675
- try {
676
- fs.writeFileSync(TOKEN_FILE, TOKEN, { mode: 0o600 });
677
- chmodOwnerOnly(TOKEN_FILE);
678
- } catch (e) { /* best effort */ }
679
- }
511
+ function writeServerInfo(triedFallback) {
512
+ COOKIE_NAME = 'brainstorm-key-' + PORT;
513
+ if (PORT_FILE && !triedFallback) {
514
+ try { fs.writeFileSync(PORT_FILE, String(PORT)); } catch (e) { /* best effort */ }
515
+ if (TOKEN_FILE) {
516
+ try {
517
+ fs.writeFileSync(TOKEN_FILE, TOKEN, { mode: 0o600 });
518
+ chmodOwnerOnly(TOKEN_FILE);
519
+ } catch (e) { /* best effort */ }
680
520
  }
681
- const info = JSON.stringify({
682
- type: 'server-started', port: Number(PORT), host: HOST,
683
- url_host: URL_HOST, url: companionUrl(),
684
- screen_dir: CONTENT_DIR, state_dir: STATE_DIR, idle_timeout_ms: IDLE_TIMEOUT_MS
685
- });
686
- console.log(info);
687
- // server-info embeds the key — keep it owner-only.
688
- fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\n', { mode: 0o600 });
689
521
  }
522
+ const info = JSON.stringify({
523
+ type: 'server-started', port: Number(PORT), host: HOST,
524
+ url_host: URL_HOST, url: companionUrl(),
525
+ screen_dir: CONTENT_DIR, state_dir: STATE_DIR, idle_timeout_ms: IDLE_TIMEOUT_MS
526
+ });
527
+ console.log(info);
528
+ fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\n', { mode: 0o600 });
529
+ }
690
530
 
531
+ function listenWithFallback(server) {
532
+ let triedFallback = false;
533
+ const onListen = () => writeServerInfo(triedFallback);
691
534
  server.on('error', (err) => {
692
535
  if (err.code === 'EADDRINUSE' && !triedFallback) {
693
536
  if (tokenSource === 'env') {
694
- console.error('Server failed to bind: preferred port is in use and BRAINSTORM_TOKEN is set; refusing fallback with explicit token');
537
+ console.error(
538
+ 'Server failed to bind: preferred port is in use and BRAINSTORM_TOKEN is set; ' +
539
+ 'refusing fallback with explicit token'
540
+ );
695
541
  process.exit(1);
696
542
  }
697
543
  triedFallback = true;
@@ -709,6 +555,20 @@ function startServer() {
709
555
  server.listen(PORT, HOST, onListen);
710
556
  }
711
557
 
558
+ function startServer() {
559
+ ensureSessionDirectories();
560
+ const server = http.createServer(handleRequest);
561
+ server.on('upgrade', handleUpgrade);
562
+ const runtime = {
563
+ server,
564
+ watcher: createContentWatcher(),
565
+ lifecycleCheck: null,
566
+ };
567
+ startLifecycleCheck(runtime);
568
+ validateOwnerPid();
569
+ listenWithFallback(server);
570
+ }
571
+
712
572
  if (require.main === module) {
713
573
  startServer();
714
574
  }
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env bash
2
2
  # Start the brainstorm server and output connection info
3
- # Usage: start-server.sh [--project-dir <path>] [--host <bind-host>] [--url-host <display-host>] [--foreground] [--background]
3
+ # Usage: start-server.sh [--project-dir <path>] [--host <bind-host>]
4
+ # [--url-host <display-host>] [--foreground] [--background]
4
5
  #
5
6
  # Starts server on a random high port, outputs JSON with URL.
6
7
  # Each session gets its own directory to avoid conflicts.
@@ -168,7 +169,12 @@ fi
168
169
 
169
170
  # Foreground mode for environments that reap detached/background processes.
170
171
  if [[ "$FOREGROUND" == "true" ]]; then
171
- env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs "--brainstorm-server-id=$SERVER_ID" &
172
+ env \
173
+ BRAINSTORM_DIR="$SESSION_DIR" \
174
+ BRAINSTORM_HOST="$BIND_HOST" \
175
+ BRAINSTORM_URL_HOST="$URL_HOST" \
176
+ BRAINSTORM_OWNER_PID="$OWNER_PID" \
177
+ node server.cjs "--brainstorm-server-id=$SERVER_ID" &
172
178
  SERVER_PID=$!
173
179
  echo "$SERVER_PID" > "$PID_FILE"
174
180
  wait "$SERVER_PID"
@@ -177,7 +183,12 @@ fi
177
183
 
178
184
  # Start server, capturing output to log file
179
185
  # Use nohup to survive shell exit; disown to remove from job table
180
- nohup env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs "--brainstorm-server-id=$SERVER_ID" > "$LOG_FILE" 2>&1 &
186
+ nohup env \
187
+ BRAINSTORM_DIR="$SESSION_DIR" \
188
+ BRAINSTORM_HOST="$BIND_HOST" \
189
+ BRAINSTORM_URL_HOST="$URL_HOST" \
190
+ BRAINSTORM_OWNER_PID="$OWNER_PID" \
191
+ node server.cjs "--brainstorm-server-id=$SERVER_ID" > "$LOG_FILE" 2>&1 &
181
192
  SERVER_PID=$!
182
193
  disown "$SERVER_PID" 2>/dev/null
183
194
  echo "$SERVER_PID" > "$PID_FILE"
@@ -195,7 +206,10 @@ for _ in {1..50}; do
195
206
  sleep 0.1
196
207
  done
197
208
  if [[ "$alive" != "true" ]]; then
198
- echo "{\"error\": \"Server started but was killed. Retry in a persistent terminal with: $SCRIPT_DIR/start-server.sh${PROJECT_DIR:+ --project-dir $PROJECT_DIR} --host $BIND_HOST --url-host $URL_HOST --foreground\"}"
209
+ persistent_command="$SCRIPT_DIR/start-server.sh"
210
+ persistent_command+="${PROJECT_DIR:+ --project-dir $PROJECT_DIR}"
211
+ persistent_command+=" --host $BIND_HOST --url-host $URL_HOST --foreground"
212
+ echo "{\"error\": \"Server started but was killed. Retry in a persistent terminal with: $persistent_command\"}"
199
213
  exit 1
200
214
  fi
201
215
  grep "server-started" "$LOG_FILE" | head -1
@@ -0,0 +1,86 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+
5
+ const OPCODES = { TEXT: 0x01, CLOSE: 0x08, PING: 0x09, PONG: 0x0A };
6
+ const WS_MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
7
+ const MAX_FRAME_PAYLOAD_BYTES = 10 * 1024 * 1024;
8
+
9
+ function computeAcceptKey(clientKey) {
10
+ return crypto.createHash('sha1').update(clientKey + WS_MAGIC).digest('base64');
11
+ }
12
+
13
+ function encodeFrame(opcode, payload) {
14
+ const fin = 0x80;
15
+ const len = payload.length;
16
+ let header;
17
+
18
+ if (len < 126) {
19
+ header = Buffer.alloc(2);
20
+ header[0] = fin | opcode;
21
+ header[1] = len;
22
+ } else if (len < 65536) {
23
+ header = Buffer.alloc(4);
24
+ header[0] = fin | opcode;
25
+ header[1] = 126;
26
+ header.writeUInt16BE(len, 2);
27
+ } else {
28
+ header = Buffer.alloc(10);
29
+ header[0] = fin | opcode;
30
+ header[1] = 127;
31
+ header.writeBigUInt64BE(BigInt(len), 2);
32
+ }
33
+
34
+ return Buffer.concat([header, payload]);
35
+ }
36
+
37
+ function decodeFrame(buffer) {
38
+ if (buffer.length < 2) return null;
39
+
40
+ const secondByte = buffer[1];
41
+ const opcode = buffer[0] & 0x0F;
42
+ const masked = (secondByte & 0x80) !== 0;
43
+ let payloadLen = secondByte & 0x7F;
44
+ let offset = 2;
45
+
46
+ if (!masked) throw new Error('Client frames must be masked');
47
+
48
+ if (payloadLen === 126) {
49
+ if (buffer.length < 4) return null;
50
+ payloadLen = buffer.readUInt16BE(2);
51
+ offset = 4;
52
+ } else if (payloadLen === 127) {
53
+ if (buffer.length < 10) return null;
54
+ const extendedLen = buffer.readBigUInt64BE(2);
55
+ if (extendedLen > BigInt(MAX_FRAME_PAYLOAD_BYTES)) {
56
+ throw new Error('WebSocket frame payload exceeds maximum allowed size');
57
+ }
58
+ payloadLen = Number(extendedLen);
59
+ offset = 10;
60
+ }
61
+
62
+ if (payloadLen > MAX_FRAME_PAYLOAD_BYTES) {
63
+ throw new Error('WebSocket frame payload exceeds maximum allowed size');
64
+ }
65
+
66
+ const maskOffset = offset;
67
+ const dataOffset = offset + 4;
68
+ const totalLen = dataOffset + payloadLen;
69
+ if (buffer.length < totalLen) return null;
70
+
71
+ const mask = buffer.slice(maskOffset, dataOffset);
72
+ const data = Buffer.alloc(payloadLen);
73
+ for (let index = 0; index < payloadLen; index += 1) {
74
+ data[index] = buffer[dataOffset + index] ^ mask[index % 4];
75
+ }
76
+
77
+ return { opcode, payload: data, bytesConsumed: totalLen };
78
+ }
79
+
80
+ module.exports = {
81
+ computeAcceptKey,
82
+ encodeFrame,
83
+ decodeFrame,
84
+ OPCODES,
85
+ MAX_FRAME_PAYLOAD_BYTES,
86
+ };
@@ -0,0 +1,57 @@
1
+ ---
2
+ name: wayfinder
3
+ description: "Plan a huge, foggy effort that exceeds one agent session as a shared map of decision tickets, work the unblocked frontier one ticket per session, and hand the resolved map to Spec/ticket planning. Use for multi-session uncertainty, not a well-scoped feature."
4
+ disable-model-invocation: true
5
+ ---
6
+
7
+ # Wayfinder
8
+
9
+ Origin: `mattpocock/skills@2ab9580`, adapted to this repository's tracker and approval contracts.
10
+
11
+ Wayfinder resolves decisions, not deliverables. The destination defines what “the way is clear” means.
12
+
13
+ ## Map Model
14
+
15
+ The configured tracker stores:
16
+
17
+ - one canonical **map** with Destination, Notes, Decisions so far, Not yet specified and Out of scope;
18
+ - child **decision tickets**, each holding one question;
19
+ - explicit blocking edges;
20
+ - a **frontier** of open, unblocked and unclaimed tickets.
21
+
22
+ Ticket types:
23
+
24
+ - `research` (AFK): primary-source evidence via `skills/research/SKILL.md`;
25
+ - `prototype` (HITL): concrete behavior/visual feedback via `skills/prototype/SKILL.md`;
26
+ - `grilling` (HITL): consequential decisions via `skills/grilling/SKILL.md`;
27
+ - `task`: prerequisite work whose result unlocks a decision.
28
+
29
+ Refer to maps and tickets by linked title, not bare identifiers.
30
+
31
+ ## Chart a Map
32
+
33
+ 1. Read tracker/domain configuration. If missing, return `NEEDS_PROJECT_CONTEXT`.
34
+ 2. Use grilling and domain modeling to define the destination and scope.
35
+ 3. Explore breadth-first for decisions visible now.
36
+ 4. Put precise questions into tickets; keep vague future areas under Not yet specified.
37
+ 5. Draft the map, initial tickets and blocking graph.
38
+ 6. Obtain approval before creating local files or external tracker objects.
39
+ 7. Create tickets first, then wire edges after stable identifiers exist.
40
+ 8. Dispatch independent research tickets in parallel only when the runtime allows safe background work.
41
+ 9. Stop after charting; do not implement the destination.
42
+
43
+ If no real fog remains and the work fits one session, return `MAP_NOT_NEEDED` and route normally.
44
+
45
+ ## Work the Map
46
+
47
+ 1. Load only the map's low-resolution view.
48
+ 2. Use the named ticket or first frontier ticket.
49
+ 3. Claim it before work after confirming the tracker mutation.
50
+ 4. Resolve one ticket per session; independent research tickets may run in parallel.
51
+ 5. Record the answer at the ticket, close it, and append a one-line linked gist to Decisions so far.
52
+ 6. Create newly visible tickets, graduate clarified fog, and close anything now outside the destination.
53
+ 7. Stop. A later session takes another frontier ticket.
54
+
55
+ When the frontier and fog are empty, return `WAY_CLEAR` with the map reference. The central router sends
56
+ the resolved decisions to `spec-gate`, then `to-tickets`; do not jump directly to implementation unless
57
+ the effort proved genuinely small.