@siming-org/flow-nodes 1.18.0 → 1.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/package.json +2 -2
- package/siming-nodes.json +61 -16
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @siming-org/flow-nodes
|
|
2
2
|
|
|
3
|
-
Siming 官方 Flow 节点库:通过 npm 分发 23 个可复用 NodePreset、3 套工作流组合,以及节点运行所需的安装闭包——
|
|
3
|
+
Siming 官方 Flow 节点库:通过 npm 分发 23 个可复用 NodePreset、3 套工作流组合,以及节点运行所需的安装闭包——5 个 Skill(workflow-discipline、bugfix-root-cause-verification、tech-design、coding-standards、brainstorming)、8 个 Agent(prd-reviewer、alignment-reviewer、arch-reviewer、code-reviewer、visual-reviewer、test-reviewer、test-executor、arch-info-reviewer)、3 个 Model Alias(powerful-model 强力、economy-model 经济、vision-model 视觉)。
|
|
4
4
|
|
|
5
5
|
## 安装
|
|
6
6
|
|
|
@@ -43,7 +43,7 @@ siming flow compose full-workflow --project <key|id>
|
|
|
43
43
|
|
|
44
44
|
包内 `siming-nodes.json` 是严格的 1.1 manifest:
|
|
45
45
|
|
|
46
|
-
- `assets.skills` 携带完整 Skill payload(
|
|
46
|
+
- `assets.skills` 携带完整 Skill payload(5 个);
|
|
47
47
|
- `assets.agents` 携带完整 Agent payload(8 个);
|
|
48
48
|
- `assets.modelAliases` 携带 Agent.model 所需映射(3 个);
|
|
49
49
|
- `nodes[].skills` 与 `nodes[].agents` 只保存带版本的名称引用(版本取自闭包内对应资产);
|
|
@@ -84,7 +84,7 @@ siming dag template upgrade apply <templateId>
|
|
|
84
84
|
仓库权威生成源为 `source/` 目录(T202609100004 起按资产粒度拆分,改一个资产只需加载对应单文件):
|
|
85
85
|
|
|
86
86
|
- `source/catalog.json`:包身份(`package.name`/`package.version`)+ 五个集合的有序资产名单——集合顺序与完整性的唯一权威。
|
|
87
|
-
- `source/nodes/<code>.json`(23)、`source/skills/<name>.json`(
|
|
87
|
+
- `source/nodes/<code>.json`(23)、`source/skills/<name>.json`(5)、`source/agents/<name>.json`(8)、`source/model-aliases/<code>.json`(3)、`source/compositions/<name>.json`(3):每资产一文件,内容原样。
|
|
88
88
|
- 目录的读取统一经 `scripts/flow-nodes-source.ts` 单一加载器:按 catalog 顺序装配,名单与文件不一致(缺失/孤立)、文件名与资产身份不符时 fail-fast。
|
|
89
89
|
- `siming-nodes.json`:由 `scripts/build-node-library.ts` 生成并提交的 npm 产物。
|
|
90
90
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@siming-org/flow-nodes",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "Official Siming flow library — 23 reusable DAG node presets, 3 workflow compositions, and their installation closure:
|
|
3
|
+
"version": "1.20.1",
|
|
4
|
+
"description": "Official Siming flow library — 23 reusable DAG node presets, 3 workflow compositions, and their installation closure: 5 Skills, 8 Agents, 3 Model Aliases",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Wuchao",
|
|
7
7
|
"publishConfig": {
|
package/siming-nodes.json
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"formatVersion": "1.2",
|
|
3
3
|
"name": "@siming-org/flow-nodes",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.20.1",
|
|
5
5
|
"compositions": [
|
|
6
6
|
{
|
|
7
7
|
"name": "full-workflow",
|
|
8
|
-
"description": "通用软件开发全流程:PRD
|
|
8
|
+
"description": "通用软件开发全流程:PRD 设计与确认、分支对齐,界面任务先经交互设计节点产出可核对交互契约(含人工确认,契约定案是技术方案的输入),再进入完整技术方案双审,按任务轨道进入后端或前端实现——后端轨完成单元测试、前端轨完成前端单元测试与界面呈现验证后汇合到端到端测试,经最终集成验证、发布验收与架构信息归档后收敛。feature 使用完整路径;bugfix 和界面微调可按任务配置跳过 PRD。本版修正节点顺序:INTERACTION 交互设计移至 ALIGN 与 DESIGN 之间(交互契约先于技术方案——契约定案是技术方案的输入;交互契约确认暂停点前置,DESIGN→CODE_BACKEND/CODE_UI 挂技术方案确认)",
|
|
9
9
|
"nodes": [
|
|
10
10
|
"prd-design",
|
|
11
11
|
"align-branch",
|
|
12
|
-
"design-tech",
|
|
13
12
|
"interaction-design",
|
|
13
|
+
"design-tech",
|
|
14
14
|
"code-backend",
|
|
15
15
|
"code-frontend",
|
|
16
16
|
"verify-visual",
|
|
@@ -34,34 +34,38 @@
|
|
|
34
34
|
"autoResume": false
|
|
35
35
|
}
|
|
36
36
|
},
|
|
37
|
+
{
|
|
38
|
+
"from": "ALIGN",
|
|
39
|
+
"to": "INTERACTION"
|
|
40
|
+
},
|
|
37
41
|
{
|
|
38
42
|
"from": "ALIGN",
|
|
39
43
|
"to": "DESIGN"
|
|
40
44
|
},
|
|
41
45
|
{
|
|
42
|
-
"from": "
|
|
43
|
-
"to": "
|
|
46
|
+
"from": "INTERACTION",
|
|
47
|
+
"to": "DESIGN",
|
|
44
48
|
"pausePoint": {
|
|
45
49
|
"type": "human_approval",
|
|
46
|
-
"description": "
|
|
50
|
+
"description": "交互契约确认(交互设计 → 技术方案;须呈现契约要点摘要 + 自检清单核对结果 + 不适用判定(如有);确认后交互契约定案,技术方案基于定案契约设计)",
|
|
47
51
|
"autoResume": false
|
|
48
52
|
}
|
|
49
53
|
},
|
|
50
54
|
{
|
|
51
|
-
"from": "
|
|
55
|
+
"from": "DESIGN",
|
|
52
56
|
"to": "CODE_BACKEND",
|
|
53
57
|
"pausePoint": {
|
|
54
58
|
"type": "human_approval",
|
|
55
|
-
"description": "
|
|
59
|
+
"description": "技术方案确认(技术方案 → 后端编码;须呈现方案摘要 + 评审结果 + 激活轨道)",
|
|
56
60
|
"autoResume": false
|
|
57
61
|
}
|
|
58
62
|
},
|
|
59
63
|
{
|
|
60
|
-
"from": "
|
|
64
|
+
"from": "DESIGN",
|
|
61
65
|
"to": "CODE_UI",
|
|
62
66
|
"pausePoint": {
|
|
63
67
|
"type": "human_approval",
|
|
64
|
-
"description": "
|
|
68
|
+
"description": "技术方案确认(技术方案 → 前端编码;须呈现方案摘要 + 评审结果 + 激活轨道)",
|
|
65
69
|
"autoResume": false
|
|
66
70
|
}
|
|
67
71
|
},
|
|
@@ -290,6 +294,47 @@
|
|
|
290
294
|
"content": "# UI 与 React 编码规范\n\n与 TypeScript 或 JavaScript reference 共同使用。具体组件库、样式框架和数据层服从项目配置。\n\n- 原生语义元素优先于 ARIA 和自绘控件;必须自定义时,同时实现可访问名称、键盘行为和焦点管理。\n- React 组件渲染保持幂等,不在渲染期修改 props、state、全局对象或既有数据。\n- 状态保持最小:能从 props 或现有 state 推导的值在渲染期计算,不重复存储。\n- 互斥界面状态用单一状态机表达,不用可能同时为真的多个布尔值。\n- Effect 只用于同步外部系统;用户事件在事件处理器中执行,渲染数据直接计算。\n- Effect 中的订阅和异步操作必须清理,并防止过期响应覆盖新状态。已有数据层时优先使用其缓存、取消和竞态能力。\n- 列表 key 必须稳定、唯一且来自数据;动态列表不使用数组下标或渲染时随机值。\n- 数据区域显式处理加载、空、错误、成功和边界状态,并为用户提供可执行的下一步。\n- 表单优先使用原生约束;客户端校验用于反馈,服务端仍须验证。错误信息与字段建立可访问关联。\n- 对话框打开时焦点进入,Tab 保持在内部,Escape 可关闭,关闭后焦点返回触发点。\n- `memo`、`useMemo`、`useCallback` 只用于经过测量的性能问题,不作为默认编码模板。\n- 测试用户可见行为,优先通过 role、label 和可见文本定位;只有无法表达用户语义时使用 test id。\n\n依据:reactjs/react.dev、w3c/aria-practices、mdn/content、Testing Library、Playwright 官方仓库。"
|
|
291
295
|
}
|
|
292
296
|
]
|
|
297
|
+
},
|
|
298
|
+
{
|
|
299
|
+
"name": "brainstorming",
|
|
300
|
+
"description": "You MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation.",
|
|
301
|
+
"content": "\n# Brainstorming Ideas Into Designs\n\nHelp turn ideas into fully formed designs and specs through natural collaborative dialogue.\n\nStart by classifying how much process the request needs, then work\nthrough your path: understand the context, refine the idea, present a\ndesign, and get your human partner's approval.\n\n## Establish Shared Understanding\n\nThe outcome of brainstorming is an understanding your human partner can\nrecognize and correct, grounded in what they want to accomplish.\n\n1. **Discover intent.** Use the request and available context to identify\n the intended outcome, who it is for, and what success looks like. When\n that information is missing, ask one focused question about purpose or\n intended use before proposing features or an approach. Knowing the app\n genre does not tell you why your partner wants it. Gathering missing\n requirements does not ask them to authorize the task again.\n2. **Write back your understanding.** Summarize the intended outcome,\n relevant constraints, and success criteria in a short note your partner\n can assess. Separate what they said from assumptions. Invite correction\n and incorporate their answer before treating this as the design brief.\n3. **Carry intent into the design.** Preserve the agreed understanding in\n the selected path's design artifact: the written spec for architectural\n work, or the in-chat design/probe for bounded work and spikes. Check\n proposed features and technical choices against that understanding.\n\nWhen the request already supplies the purpose and constraints, reflect\nthat understanding instead of asking the same questions again. Keep the\nnote concise; its accuracy and the opportunity to correct it matter.\n\n<HARD-GATE>\nBefore taking any implementation action, including invoking an\nimplementation skill, writing product code, scaffolding, installing\nproduct dependencies, or creating an external project, complete the\nselected path's prerequisites:\n\n- Spike: the human partner approves the question and probe.\n- Bounded: the human partner approves the short in-chat design.\n- Architectural: the human partner reviews and approves the written spec,\n then reviews the written implementation plan and selects its execution\n method. Conversational design approval only permits writing the spec;\n written-spec approval only permits invoking writing-plans.\n\nA reply approves the stage actually presented. Approval of an idea or\nfeature scope does not approve artifacts that do not exist yet. Resume\nat the earliest incomplete stage; do not turn one approval into permission\nto skip the rest of the selected path. Read-only project exploration is\nallowed while those prerequisites remain incomplete.\n</HARD-GATE>\n\n## Three Paths\n\nBefore your first question, classify the request and say the\nclassification out loud — \"this looks bounded, so I'll present a short\ndesign here rather than write a spec\" — so your human partner can\noverride it:\n\n- **Spike** — a feasibility question (\"can we...\", \"is it possible...\",\n \"quick and dirty is fine\") whose output is an answer, not code you\n keep. Present the question and what you'll try in 2-3 sentences, get\n a nod, then find out as cheaply as correctness allows. No design\n doc, no spec file. Report findings as a recommendation; anything you\n built stays labeled throwaway.\n- **Bounded** — a well-scoped change to code that already exists in\n this repo: a new flag, a small endpoint, a one-file fix.\n Understanding the kind of app is not enough — bounded means the flow\n you are changing is already here to read. If there is no existing\n flow to change, the task is not bounded. Ask the clarifying\n questions that matter, present a short design IN CHAT (a few\n sentences to a few short paragraphs), and STOP. Implementation\n starts only after your human partner says yes to that design — a\n bounded task's approval is as hard a gate as an architectural\n one. No spec file, no implementation plan document.\n- **Architectural** — new projects, new subsystems, changes that\n restructure how components fit together or alter interfaces others\n depend on. Follow the full process: questions, approaches, sectioned\n design, written spec, then the writing-plans skill.\n\nWhen in doubt between two paths, take the heavier one. The ratchet is\none-way: hidden complexity discovered mid-task upgrades the path —\nstop, say so, and step up. Nothing downgrades mid-task.\n\n## Anti-Pattern: \"Too Simple To Need Approval\"\n\nEvery path ends with your human partner approving the required design\nbefore implementation. A bounded change may need only two sentences in\nchat. A new todo-list project is architectural and requires the written\nspec and planning handoffs. Scale the artifact to the selected path;\ncomplete that path's reviews before implementation.\n\n## Red Flags\n\n| Thought | Reality |\n|---------|---------|\n| \"This is too simple to need a design\" | Follow the selected path: a bounded change gets a short chat design; an architectural change gets the written spec and planning handoffs. |\n| \"I'll call it bounded and skip the spec\" | Reaching for a label to skip work IS the doubt — take the heavier path. |\n| \"It's bounded and the design is obvious — I'll start while they read it\" | The gate is the approval, not the design's length. Present, then stop until you hear yes. |\n| \"I understand this kind of app, so it's bounded\" | Bounded measures the repo, not your familiarity. A new project has no existing flow — it is architectural. |\n| \"The spike works, so I'll keep the code\" | A spike's output is an answer. Keeping the code is a new request — classify it. |\n| \"It grew, but I'm almost done — no need to re-classify\" | Hidden complexity upgrades the path mid-task. Stop and say so. |\n| \"They approved the spike, so the follow-up change is approved too\" | Each task gets its own classification and its own approval. |\n\n## Checklist\n\nClassify first, announce the path, then create a task for each item on\nyour path and complete them in order.\n\n**Spike:**\n1. **Explore project context** — enough to frame the probe\n2. **Present question + probe plan** — 2-3 sentences\n3. **Get approval** — a nod is enough\n4. **Investigate** — as cheaply as correctness allows\n5. **Report findings** — a recommendation; label anything built as throwaway\n\n**Bounded:**\n1. **Explore project context** — check files, docs, recent commits\n2. **Ask clarifying questions** — one at a time, the ones that matter\n3. **Present short design in chat** — approach, files touched, testing\n4. **Get approval** — STOP and wait for an explicit yes; presenting the design and starting in the same breath is skipping the gate\n5. **Implement** — proceed with the normal development workflow (TDD applies); no plan document\n\n**Architectural:**\n1. **Explore project context** — check files, docs, recent commits\n2. **Offer the visual companion just-in-time** — NOT upfront. The first time a question would genuinely be clearer shown than described, offer it then (its own message); on approval its browser tab opens for you. If no visual question ever arises, never offer it. See the Visual Companion section below.\n3. **Ask clarifying questions** — one at a time, understand purpose/constraints/success criteria\n4. **Propose 2-3 approaches** — with trade-offs and your recommendation\n5. **Present design** — in sections scaled to their complexity, get user approval after each section\n6. **Write design doc** — save to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md` and commit\n7. **Spec self-review** — quick inline check for placeholders, contradictions, ambiguity, scope (see below)\n8. **User reviews written spec** — ask user to review the spec file before proceeding\n9. **Transition to implementation** — invoke writing-plans skill to create implementation plan\n\n## Process Flow\n\n```dot\ndigraph brainstorming {\n \"Classify: spike / bounded / architectural\" [shape=diamond];\n \"Present question + probe (2-3 sentences)\" [shape=box];\n \"Ask clarifying questions (bounded)\" [shape=box];\n \"Present short design in chat\" [shape=box];\n \"Human approves?\" [shape=diamond];\n \"Investigate; report recommendation\" [shape=doublecircle];\n \"Implement via normal workflow (no plan doc)\" [shape=doublecircle];\n \"Explore project context\" [shape=box];\n \"Ask clarifying questions\" [shape=box];\n \"Propose 2-3 approaches\" [shape=box];\n \"Present design sections\" [shape=box];\n \"User approves design?\" [shape=diamond];\n \"Write design doc\" [shape=box];\n \"Spec self-review\\n(fix inline)\" [shape=box];\n \"User reviews spec?\" [shape=diamond];\n \"Invoke writing-plans skill\" [shape=doublecircle];\n \"Hidden complexity? Upgrade path\" [shape=box];\n\n \"Classify: spike / bounded / architectural\" -> \"Present question + probe (2-3 sentences)\" [label=\"spike\"];\n \"Classify: spike / bounded / architectural\" -> \"Ask clarifying questions (bounded)\" [label=\"bounded\"];\n \"Classify: spike / bounded / architectural\" -> \"Explore project context\" [label=\"architectural\"];\n \"Present question + probe (2-3 sentences)\" -> \"Human approves?\";\n \"Ask clarifying questions (bounded)\" -> \"Present short design in chat\";\n \"Present short design in chat\" -> \"Human approves?\";\n \"Human approves?\" -> \"Investigate; report recommendation\" [label=\"spike: yes\"];\n \"Human approves?\" -> \"Implement via normal workflow (no plan doc)\" [label=\"bounded: yes\"];\n \"Hidden complexity? Upgrade path\" -> \"Classify: spike / bounded / architectural\";\n \"Explore project context\" -> \"Ask clarifying questions\";\n \"Ask clarifying questions\" -> \"Propose 2-3 approaches\";\n \"Propose 2-3 approaches\" -> \"Present design sections\";\n \"Present design sections\" -> \"User approves design?\";\n \"User approves design?\" -> \"Present design sections\" [label=\"no, revise\"];\n \"User approves design?\" -> \"Write design doc\" [label=\"yes\"];\n \"Write design doc\" -> \"Spec self-review\\n(fix inline)\";\n \"Spec self-review\\n(fix inline)\" -> \"User reviews spec?\";\n \"User reviews spec?\" -> \"Write design doc\" [label=\"changes requested\"];\n \"User reviews spec?\" -> \"Invoke writing-plans skill\" [label=\"approved\"];\n}\n```\n\n**Terminal states are path-bound.** Architectural: the ONLY skill you\ninvoke after brainstorming is writing-plans — never frontend-design,\nmcp-builder, or any other implementation skill. Bounded: after\napproval, implementation proceeds directly through the normal\ndevelopment workflow; no plan document. Spike: the terminal state is a\nreported recommendation.\n\n## The Process\n\nThe subsections below serve the bounded and architectural paths (a\nspike stops at \"present the probe, get a nod\"). Sections from\n**Exploring approaches** onward are architectural-path depth — for\nbounded work, context plus a few questions plus a short in-chat design\nis the whole process.\n\n**Understanding the idea:**\n\n- Check out the current project state first (files, docs, recent commits)\n- Before asking detailed questions, assess scope: if the request describes multiple independent subsystems (e.g., \"build a platform with chat, file storage, billing, and analytics\"), flag this immediately. Don't spend questions refining details of a project that needs to be decomposed first.\n- If the project is too large for a single spec, help the user decompose into sub-projects: what are the independent pieces, how do they relate, what order should they be built? Then brainstorm the first sub-project through the normal design flow. Each sub-project gets its own spec → plan → implementation cycle.\n- For appropriately-scoped projects, ask questions one at a time to refine the idea\n- Prefer multiple choice questions when possible, but open-ended is fine too\n- Only one question per message - if a topic needs more exploration, break it into multiple questions\n- Focus on understanding: purpose, constraints, success criteria\n\n**Exploring approaches:**\n\n- Propose 2-3 different approaches with trade-offs\n- Present options conversationally with your recommendation and reasoning\n- Lead with your recommended option and explain why\n- YAGNI ruthlessly - remove unnecessary features from every approach and design\n\n**Presenting the design:**\n\n- Once you believe you understand what you're building, present the design\n- Scale each section to its complexity: a few sentences if straightforward, up to 200-300 words if nuanced\n- Ask after each section whether it looks right so far\n- Cover: architecture, components, data flow, error handling, testing\n- Be ready to go back and clarify if something doesn't make sense\n\n**Design for isolation and clarity:**\n\n- Break the system into smaller units that each have one clear purpose, communicate through well-defined interfaces, and can be understood and tested independently\n- For each unit, you should be able to answer: what does it do, how do you use it, and what does it depend on?\n- Can someone understand what a unit does without reading its internals? Can you change the internals without breaking consumers? If not, the boundaries need work.\n- Smaller, well-bounded units are also easier for you to work with - you reason better about code you can hold in context at once, and your edits are more reliable when files are focused. When a file grows large, that's often a signal that it's doing too much.\n\n**Working in existing codebases:**\n\n- Explore the current structure before proposing changes. Follow existing patterns.\n- Where existing code has problems that affect the work (e.g., a file that's grown too large, unclear boundaries, tangled responsibilities), include targeted improvements as part of the design - the way a good developer improves code they're working in.\n- Don't propose unrelated refactoring. Stay focused on what serves the current goal.\n\n## After the Design (architectural path)\n\n**Documentation:**\n\n- Write the validated design (spec) to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md`\n - (User preferences for spec location override this default)\n- Use elements-of-style:writing-clearly-and-concisely skill if available\n- Commit the design document to git\n\n**Spec Self-Review:**\nAfter writing the spec document, look at it with fresh eyes:\n\n1. **Placeholder scan:** Any \"TBD\", \"TODO\", incomplete sections, or vague requirements? Fix them.\n2. **Internal consistency:** Do any sections contradict each other? Does the architecture match the feature descriptions?\n3. **Scope check:** Is this focused enough for a single implementation plan, or does it need decomposition?\n4. **Ambiguity check:** Could any requirement be interpreted two different ways? If so, pick one and make it explicit.\n\nFix any issues inline. No need to re-review — just fix and move on.\n\n**User Review Gate:**\nAfter the spec review loop passes, ask the user to review the written spec before proceeding:\n\n> \"Spec written and committed to `<path>`. Please review it and let me know if you want to make any changes before we start writing out the implementation plan.\"\n\nWait for the user's response. If they request changes, make them and re-run the spec review loop. Only proceed once the user approves.\n\n**Implementation:**\n\n- Invoke the writing-plans skill to create a detailed implementation plan\n- Do NOT invoke any other skill. writing-plans is the next step.\n\n## Visual Companion\n\nA browser-based companion for showing mockups, diagrams, and visual options during brainstorming. Available as a tool — not a mode. Accepting the companion means it's available for questions that benefit from visual treatment; it does NOT mean every question goes through the browser.\n\n**Offering the companion (just-in-time):** Do NOT offer it upfront. Wait until a question would genuinely be clearer shown than told — a real mockup / layout / diagram question, not merely a UI *topic*. The first time that happens, offer it then, as its own message:\n> \"This next part might be easier if I show you — I can put together mockups, diagrams, and comparisons in a browser tab as we go. It's still new and can be token-intensive. Want me to? I'll open it for you.\"\n\n**This offer MUST be its own message.** Only the offer — no clarifying question, summary, or other content. Wait for the user's response. If they accept, start the server with `--open` so their browser opens to the first screen automatically. If they decline, continue text-only and don't offer again unless they raise it.\n\n**Per-question decision:** Even after the user accepts, decide FOR EACH QUESTION whether to use the browser or the terminal. The test: **would the user understand this better by seeing it than reading it?**\n\n- **Use the browser** for content that IS visual — mockups, wireframes, layout comparisons, architecture diagrams, side-by-side visual designs\n- **Use the terminal** for content that is text — requirements questions, conceptual choices, tradeoff lists, A/B/C/D text options, scope decisions\n\nA question about a UI topic is not automatically a visual question. \"What does personality mean in this context?\" is a conceptual question — use the terminal. \"Which wizard layout works better?\" is a visual question — use the browser.\n\nIf they agree to the companion, read the detailed guide before proceeding:\n`skills/brainstorming/visual-companion.md`\n",
|
|
302
|
+
"category": "process",
|
|
303
|
+
"version": "1.0.0",
|
|
304
|
+
"references": [
|
|
305
|
+
{
|
|
306
|
+
"path": "visual-companion.md",
|
|
307
|
+
"content": "# Visual Companion Guide\n\nBrowser-based visual brainstorming companion for showing mockups, diagrams, and options.\n\n## When to Use\n\nDecide per-question, not per-session. The test: **would the user understand this better by seeing it than reading it?**\n\n**Use the browser** when the content itself is visual:\n\n- **UI mockups** — wireframes, layouts, navigation structures, component designs\n- **Architecture diagrams** — system components, data flow, relationship maps\n- **Side-by-side visual comparisons** — comparing two layouts, two color schemes, two design directions\n- **Design polish** — when the question is about look and feel, spacing, visual hierarchy\n- **Spatial relationships** — state machines, flowcharts, entity relationships rendered as diagrams\n\n**Use the terminal** when the content is text or tabular:\n\n- **Requirements and scope questions** — \"what does X mean?\", \"which features are in scope?\"\n- **Conceptual A/B/C choices** — picking between approaches described in words\n- **Tradeoff lists** — pros/cons, comparison tables\n- **Technical decisions** — API design, data modeling, architectural approach selection\n- **Clarifying questions** — anything where the answer is words, not a visual preference\n\nA question *about* a UI topic is not automatically a visual question. \"What kind of wizard do you want?\" is conceptual — use the terminal. \"Which of these wizard layouts feels right?\" is visual — use the browser.\n\n## How It Works\n\nThe server watches a directory for HTML files and serves the newest one to the browser. You write HTML content to `screen_dir`, the user sees it in their browser and can click to select options. Selections are recorded to `state_dir/events` that you read on your next turn.\n\n**Content fragments vs full documents:** If your HTML file starts with `<!DOCTYPE` or `<html`, the server serves it as-is (just injects the helper script). Otherwise, the server automatically wraps your content in the frame template — adding the header, CSS theme, connection status, and all interactive infrastructure. **Write content fragments by default.** Only write full documents when you need complete control over the page.\n\n## Starting a Session\n\n```bash\n# Start AFTER the user approves the companion. --open auto-opens their browser on\n# the first screen; --project-dir persists mockups and enables same-port restart.\nbash scripts/start-server.sh --project-dir /path/to/project --open\n\n# Returns: {\"type\":\"server-started\",\"port\":52341,\n# \"url\":\"http://localhost:52341/?key=ab12…\",\n# \"screen_dir\":\"/path/to/project/.superpowers/brainstorm/12345-1706000000/content\",\n# \"state_dir\":\"/path/to/project/.superpowers/brainstorm/12345-1706000000/state\"}\n```\n\nSave `screen_dir` and `state_dir` from the response. With `--open`, the browser opens itself when you push the first screen — you don't need to ask the user to open it, but still share the URL as a fallback (headless/remote setups won't auto-open).\n\n**The URL contains a session key (`?key=…`).** The server rejects any request\nwithout it, so always give the user the **complete** URL from the `url` field —\nnever strip the query string, and never hand out a bare `http://host:port`. The\nkey gates HTTP and WebSocket access so a stray browser tab or another machine on\nthe network can't read the screens or inject events. After the first load the\nbrowser remembers the key via a cookie, so reloads and `/files/*` assets work\nwithout repeating it.\n\n**Finding connection info:** The server writes its startup JSON to `$STATE_DIR/server-info`. If you launched the server in the background and didn't capture stdout, read that file to get the URL and port. When using `--project-dir`, check `<project>/.superpowers/brainstorm/` for the session directory.\n\n**Note:** Pass the project root as `--project-dir` so mockups persist in `.superpowers/brainstorm/` and survive server restarts. Without it, files go to `/tmp` and get cleaned up. Remind the user to add `.superpowers/` to `.gitignore` if it's not already there.\n\n**Launching the server by platform:**\n\n**Claude Code:**\n```bash\n# Default mode works — the script backgrounds the server itself.\nbash scripts/start-server.sh --project-dir /path/to/project --open\n```\n\nOn Windows, the script auto-detects and switches to foreground mode (which blocks the tool call). Use `run_in_background: true` on the Bash tool call so the server survives across conversation turns, then read `$STATE_DIR/server-info` on the next turn to get the URL and port.\n\n**Codex:**\n```bash\n# Codex reaps background processes. The script auto-detects CODEX_CI and\n# switches to foreground mode. Run it normally — no extra flags needed.\nbash scripts/start-server.sh --project-dir /path/to/project --open\n```\n\n**Gemini CLI:**\n```bash\n# Use --foreground and set is_background: true on your shell tool call\n# so the process survives across turns\nbash scripts/start-server.sh --project-dir /path/to/project --open --foreground\n```\n\n**Copilot CLI:**\n```bash\n# Start it with Copilot CLI's non-blocking/background shell mechanism so the\n# server survives across turns. Keep --foreground so the harness, not the\n# script, owns backgrounding. The launcher is a .sh, so invoke it via bash\n# (on Windows, call Git Bash's bash.exe from the PowerShell tool).\nbash scripts/start-server.sh --project-dir /path/to/project --open --foreground\n```\n\n**Other environments:** The server must keep running in the background across conversation turns. If your environment reaps detached processes, use `--foreground` and launch the command with your platform's background execution mechanism.\n\nIf the URL is unreachable from your browser (common in remote/containerized setups), bind a non-loopback host:\n\n```bash\nbash scripts/start-server.sh \\\n --project-dir /path/to/project \\\n --host 0.0.0.0 \\\n --url-host localhost\n```\n\nUse `--url-host` to control what hostname is printed in the returned URL JSON.\n\n## The Loop\n\n1. **Check server is alive**, then **write HTML** to a new file in `screen_dir`:\n - **Required: confirm the server is alive before referring to the URL or pushing a screen.** Check that `$STATE_DIR/server-info` exists and `$STATE_DIR/server-stopped` does not. If it has shut down, restart it with `start-server.sh` using the **same `--project-dir`** — it reuses the same port, so the user's open tab reconnects on its own (it shows a \"paused\" overlay while the server is down) and you don't need to send a new URL. The server auto-exits after 4 hours idle (configurable with `--idle-timeout-minutes`).\n - Use semantic filenames: `platform.html`, `visual-style.html`, `layout.html`\n - **Never reuse filenames** — each screen gets a fresh file\n - Use your file-creation tool — **never use cat/heredoc** (dumps noise into terminal)\n - Server automatically serves the newest file\n\n2. **Tell user what to expect and end your turn:**\n - Remind them of the URL (every step, not just first)\n - Give a brief text summary of what's on screen (e.g., \"Showing 3 layout options for the homepage\")\n - Ask them to respond in the terminal: \"Take a look and let me know what you think. Click to select an option if you'd like.\"\n\n3. **On your next turn** — after the user responds in the terminal:\n - Read `$STATE_DIR/events` if it exists — this contains the user's browser interactions (clicks, selections) as JSON lines\n - Merge with the user's terminal text to get the full picture\n - The terminal message is the primary feedback; `state_dir/events` provides structured interaction data\n\n4. **Iterate or advance** — if feedback changes current screen, write a new file (e.g., `layout-v2.html`). Only move to the next question when the current step is validated.\n\n5. **Unload when returning to terminal** — when the next step doesn't need the browser (e.g., a clarifying question, a tradeoff discussion), push a waiting screen to clear the stale content:\n\n ```html\n <!-- filename: waiting.html (or waiting-2.html, etc.) -->\n <div style=\"display:flex;align-items:center;justify-content:center;min-height:60vh\">\n <p class=\"subtitle\">Continuing in terminal...</p>\n </div>\n ```\n\n This prevents the user from staring at a resolved choice while the conversation has moved on. When the next visual question comes up, push a new content file as usual.\n\n6. Repeat until done.\n\n## Writing Content Fragments\n\nWrite just the content that goes inside the page. The server wraps it in the frame template automatically (header, theme CSS, connection status, and all interactive infrastructure).\n\n**Minimal example:**\n\n```html\n<h2>Which layout works better?</h2>\n<p class=\"subtitle\">Consider readability and visual hierarchy</p>\n\n<div class=\"options\">\n <div class=\"option\" data-choice=\"a\" onclick=\"toggleSelect(this)\">\n <div class=\"letter\">A</div>\n <div class=\"content\">\n <h3>Single Column</h3>\n <p>Clean, focused reading experience</p>\n </div>\n </div>\n <div class=\"option\" data-choice=\"b\" onclick=\"toggleSelect(this)\">\n <div class=\"letter\">B</div>\n <div class=\"content\">\n <h3>Two Column</h3>\n <p>Sidebar navigation with main content</p>\n </div>\n </div>\n</div>\n```\n\nThat's it. No `<html>`, no CSS, no `<script>` tags needed. The server provides all of that.\n\n## CSS Classes Available\n\nThe frame template provides these CSS classes for your content:\n\n### Options (A/B/C choices)\n\n```html\n<div class=\"options\">\n <div class=\"option\" data-choice=\"a\" onclick=\"toggleSelect(this)\">\n <div class=\"letter\">A</div>\n <div class=\"content\">\n <h3>Title</h3>\n <p>Description</p>\n </div>\n </div>\n</div>\n```\n\n**Multi-select:** Add `data-multiselect` to the container to let users select multiple options. Each click toggles the item's selected styling.\n\n```html\n<div class=\"options\" data-multiselect>\n <!-- same option markup — users can select/deselect multiple -->\n</div>\n```\n\n### Cards (visual designs)\n\n```html\n<div class=\"cards\">\n <div class=\"card\" data-choice=\"design1\" onclick=\"toggleSelect(this)\">\n <div class=\"card-image\"><!-- mockup content --></div>\n <div class=\"card-body\">\n <h3>Name</h3>\n <p>Description</p>\n </div>\n </div>\n</div>\n```\n\n### Mockup container\n\n```html\n<div class=\"mockup\">\n <div class=\"mockup-header\">Preview: Dashboard Layout</div>\n <div class=\"mockup-body\"><!-- your mockup HTML --></div>\n</div>\n```\n\n### Split view (side-by-side)\n\n```html\n<div class=\"split\">\n <div class=\"mockup\"><!-- left --></div>\n <div class=\"mockup\"><!-- right --></div>\n</div>\n```\n\n### Pros/Cons\n\n```html\n<div class=\"pros-cons\">\n <div class=\"pros\"><h4>Pros</h4><ul><li>Benefit</li></ul></div>\n <div class=\"cons\"><h4>Cons</h4><ul><li>Drawback</li></ul></div>\n</div>\n```\n\n### Mock elements (wireframe building blocks)\n\n```html\n<div class=\"mock-nav\">Logo | Home | About | Contact</div>\n<div style=\"display: flex;\">\n <div class=\"mock-sidebar\">Navigation</div>\n <div class=\"mock-content\">Main content area</div>\n</div>\n<button class=\"mock-button\">Action Button</button>\n<input class=\"mock-input\" placeholder=\"Input field\">\n<div class=\"placeholder\">Placeholder area</div>\n```\n\n### Typography and sections\n\n- `h2` — page title\n- `h3` — section heading\n- `.subtitle` — secondary text below title\n- `.section` — content block with bottom margin\n- `.label` — small uppercase label text\n\n## Browser Events Format\n\nWhen the user clicks options in the browser, their interactions are recorded to `$STATE_DIR/events` (one JSON object per line). The file is cleared automatically when you push a new screen.\n\n```jsonl\n{\"type\":\"click\",\"choice\":\"a\",\"text\":\"Option A - Simple Layout\",\"timestamp\":1706000101}\n{\"type\":\"click\",\"choice\":\"c\",\"text\":\"Option C - Complex Grid\",\"timestamp\":1706000108}\n{\"type\":\"click\",\"choice\":\"b\",\"text\":\"Option B - Hybrid\",\"timestamp\":1706000115}\n```\n\nThe full event stream shows the user's exploration path — they may click multiple options before settling. The last `choice` event is typically the final selection, but the pattern of clicks can reveal hesitation or preferences worth asking about.\n\nIf `$STATE_DIR/events` doesn't exist, the user didn't interact with the browser — use only their terminal text.\n\n## Design Tips\n\n- **Scale fidelity to the question** — wireframes for layout, polish for polish questions\n- **Explain the question on each page** — \"Which layout feels more professional?\" not just \"Pick one\"\n- **Iterate before advancing** — if feedback changes current screen, write a new version\n- **2-4 options max** per screen\n- **Use real content when it matters** — for a photography portfolio, use actual images (Unsplash). Placeholder content obscures design issues.\n- **Keep mockups simple** — focus on layout and structure, not pixel-perfect design\n\n## File Naming\n\n- Use semantic names: `platform.html`, `visual-style.html`, `layout.html`\n- Never reuse filenames — each screen must be a new file\n- For iterations: append version suffix like `layout-v2.html`, `layout-v3.html`\n- Server serves newest file by modification time\n\n## Cleaning Up\n\n```bash\nbash scripts/stop-server.sh $SESSION_DIR\n```\n\nIf the session used `--project-dir`, mockup files persist in `.superpowers/brainstorm/` for later reference. Only `/tmp` sessions get deleted on stop.\n\n## Reference\n\n- Frame template (CSS reference): `scripts/frame-template.html`\n- Helper script (client-side): `scripts/helper.js`\n"
|
|
308
|
+
},
|
|
309
|
+
{
|
|
310
|
+
"path": "spec-document-reviewer-prompt.md",
|
|
311
|
+
"content": "# Spec Document Reviewer Prompt Template\n\nUse this template when dispatching a spec document reviewer subagent.\n\n**Purpose:** Verify the spec is complete, consistent, and ready for implementation planning.\n\n**Dispatch after:** Spec document is written to docs/superpowers/specs/\n\n```\nSubagent (general-purpose):\n description: \"Review spec document\"\n prompt: |\n You are a spec document reviewer. Verify this spec is complete and ready for planning.\n\n **Spec to review:** [SPEC_FILE_PATH]\n\n ## What to Check\n\n | Category | What to Look For |\n |----------|------------------|\n | Completeness | TODOs, placeholders, \"TBD\", incomplete sections |\n | Consistency | Internal contradictions, conflicting requirements |\n | Clarity | Requirements ambiguous enough to cause someone to build the wrong thing |\n | Scope | Focused enough for a single plan — not covering multiple independent subsystems |\n | YAGNI | Unrequested features, over-engineering |\n\n ## Calibration\n\n **Only flag issues that would cause real problems during implementation planning.**\n A missing section, a contradiction, or a requirement so ambiguous it could be\n interpreted two different ways — those are issues. Minor wording improvements,\n stylistic preferences, and \"sections less detailed than others\" are not.\n\n Approve unless there are serious gaps that would lead to a flawed plan.\n\n ## Output Format\n\n ## Spec Review\n\n **Status:** Approved | Issues Found\n\n **Issues (if any):**\n - [Section X]: [specific issue] - [why it matters for planning]\n\n **Recommendations (advisory, do not block approval):**\n - [suggestions for improvement]\n```\n\n**Reviewer returns:** Status, Issues (if any), Recommendations\n"
|
|
312
|
+
},
|
|
313
|
+
{
|
|
314
|
+
"path": "scripts/frame-template.html",
|
|
315
|
+
"content": "<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <title>Superpowers Brainstorming</title>\n <style>\n /*\n * BRAINSTORM COMPANION FRAME TEMPLATE\n *\n * This template provides a consistent frame with:\n * - OS-aware light/dark theming\n * - Header branding and connection status\n * - Scrollable main content area\n * - CSS helpers for common UI patterns\n *\n * Content is injected via placeholder comment in #frame-content.\n */\n\n * { box-sizing: border-box; margin: 0; padding: 0; }\n html, body { height: 100%; overflow: hidden; }\n\n /* ===== THEME VARIABLES ===== */\n :root {\n --bg-primary: #f5f5f7;\n --bg-secondary: #ffffff;\n --bg-tertiary: #e5e5e7;\n --border: #d1d1d6;\n --text-primary: #1d1d1f;\n --text-secondary: #86868b;\n --text-tertiary: #aeaeb2;\n --accent: #0071e3;\n --accent-hover: #0077ed;\n --success: #34c759;\n --warning: #ff9f0a;\n --error: #ff3b30;\n --selected-bg: #e8f4fd;\n --selected-border: #0071e3;\n }\n\n @media (prefers-color-scheme: dark) {\n :root {\n --bg-primary: #1d1d1f;\n --bg-secondary: #2d2d2f;\n --bg-tertiary: #3d3d3f;\n --border: #424245;\n --text-primary: #f5f5f7;\n --text-secondary: #86868b;\n --text-tertiary: #636366;\n --accent: #0a84ff;\n --accent-hover: #409cff;\n --selected-bg: rgba(10, 132, 255, 0.15);\n --selected-border: #0a84ff;\n }\n }\n\n body {\n font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;\n background: var(--bg-primary);\n color: var(--text-primary);\n display: flex;\n flex-direction: column;\n line-height: 1.5;\n }\n\n /* ===== FRAME STRUCTURE ===== */\n .brand { display: flex; align-items: center; min-width: 0; overflow: hidden; color: var(--text-secondary); line-height: 1; }\n .brand a { color: inherit; text-decoration: none; display: flex; align-items: center; gap: 0.5rem; min-width: 0; max-width: 100%; line-height: 1; }\n .brand-copy { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 1; transform: translateY(-1px); }\n .brand-logo { display: block; height: 1em; width: auto; max-width: 180px; flex-shrink: 0; filter: invert(1); }\n @media (prefers-color-scheme: dark) {\n .brand-logo { filter: none; }\n }\n .status { font-size: 0.7rem; color: var(--status-color, var(--success)); display: flex; align-items: center; gap: 0.4rem; justify-self: end; white-space: nowrap; line-height: 1; }\n .status::before { content: ''; width: 6px; height: 6px; background: var(--status-color, var(--success)); border-radius: 50%; }\n\n .main { flex: 1; overflow-y: auto; }\n #frame-content { padding: 2rem; min-height: 100%; }\n\n .header {\n background: var(--bg-secondary);\n border-bottom: 1px solid var(--border);\n padding: 0.5rem 1.5rem;\n flex-shrink: 0;\n display: grid;\n grid-template-columns: minmax(0, 1fr) auto;\n align-items: center;\n gap: 1rem;\n min-height: 42px;\n }\n .header .brand { justify-self: start; width: 100%; font-size: 0.75rem; line-height: 1; }\n .header .status { grid-column: 2; line-height: 1; }\n .header span {\n font-size: 0.75rem;\n color: var(--text-secondary);\n }\n .header .selected-text {\n color: var(--accent);\n font-weight: 500;\n }\n\n /* ===== TYPOGRAPHY ===== */\n h2 { font-size: 1.5rem; font-weight: 600; margin-bottom: 0.5rem; }\n h3 { font-size: 1.1rem; font-weight: 600; margin-bottom: 0.25rem; }\n .subtitle { color: var(--text-secondary); margin-bottom: 1.5rem; }\n .section { margin-bottom: 2rem; }\n .label { font-size: 0.7rem; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 0.5rem; }\n\n /* ===== OPTIONS (for A/B/C choices) ===== */\n .options { display: flex; flex-direction: column; gap: 0.75rem; }\n .option {\n background: var(--bg-secondary);\n border: 2px solid var(--border);\n border-radius: 12px;\n padding: 1rem 1.25rem;\n cursor: pointer;\n transition: all 0.15s ease;\n display: flex;\n align-items: flex-start;\n gap: 1rem;\n }\n .option:hover { border-color: var(--accent); }\n .option.selected { background: var(--selected-bg); border-color: var(--selected-border); }\n .option .letter {\n background: var(--bg-tertiary);\n color: var(--text-secondary);\n width: 1.75rem; height: 1.75rem;\n border-radius: 6px;\n display: flex; align-items: center; justify-content: center;\n font-weight: 600; font-size: 0.85rem; flex-shrink: 0;\n }\n .option.selected .letter { background: var(--accent); color: white; }\n .option .content { flex: 1; }\n .option .content h3 { font-size: 0.95rem; margin-bottom: 0.15rem; }\n .option .content p { color: var(--text-secondary); font-size: 0.85rem; margin: 0; }\n\n /* ===== CARDS (for showing designs/mockups) ===== */\n .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 1rem; }\n .card {\n background: var(--bg-secondary);\n border: 1px solid var(--border);\n border-radius: 12px;\n overflow: hidden;\n cursor: pointer;\n transition: all 0.15s ease;\n }\n .card:hover { border-color: var(--accent); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }\n .card.selected { border-color: var(--selected-border); border-width: 2px; }\n .card-image { background: var(--bg-tertiary); aspect-ratio: 16/10; display: flex; align-items: center; justify-content: center; }\n .card-body { padding: 1rem; }\n .card-body h3 { margin-bottom: 0.25rem; }\n .card-body p { color: var(--text-secondary); font-size: 0.85rem; }\n\n /* ===== MOCKUP CONTAINER ===== */\n .mockup {\n background: var(--bg-secondary);\n border: 1px solid var(--border);\n border-radius: 12px;\n overflow: hidden;\n margin-bottom: 1.5rem;\n }\n .mockup-header {\n background: var(--bg-tertiary);\n padding: 0.5rem 1rem;\n font-size: 0.75rem;\n color: var(--text-secondary);\n border-bottom: 1px solid var(--border);\n }\n .mockup-body { padding: 1.5rem; }\n\n /* ===== SPLIT VIEW (side-by-side comparison) ===== */\n .split { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; }\n @media (max-width: 700px) { .split { grid-template-columns: 1fr; } }\n\n /* ===== PROS/CONS ===== */\n .pros-cons { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin: 1rem 0; }\n .pros, .cons { background: var(--bg-secondary); border-radius: 8px; padding: 1rem; }\n .pros h4 { color: var(--success); font-size: 0.85rem; margin-bottom: 0.5rem; }\n .cons h4 { color: var(--error); font-size: 0.85rem; margin-bottom: 0.5rem; }\n .pros ul, .cons ul { margin-left: 1.25rem; font-size: 0.85rem; color: var(--text-secondary); }\n .pros li, .cons li { margin-bottom: 0.25rem; }\n\n /* ===== PLACEHOLDER (for mockup areas) ===== */\n .placeholder {\n background: var(--bg-tertiary);\n border: 2px dashed var(--border);\n border-radius: 8px;\n padding: 2rem;\n text-align: center;\n color: var(--text-tertiary);\n }\n\n /* ===== INLINE MOCKUP ELEMENTS ===== */\n .mock-nav { background: var(--accent); color: white; padding: 0.75rem 1rem; display: flex; gap: 1.5rem; font-size: 0.9rem; }\n .mock-sidebar { background: var(--bg-tertiary); padding: 1rem; min-width: 180px; }\n .mock-content { padding: 1.5rem; flex: 1; }\n .mock-button { background: var(--accent); color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; font-size: 0.85rem; }\n .mock-input { background: var(--bg-primary); border: 1px solid var(--border); border-radius: 6px; padding: 0.5rem; width: 100%; }\n </style>\n</head>\n<body>\n <div class=\"header\">\n <!-- BRANDING -->\n <div class=\"status\">Connecting…</div>\n </div>\n\n <div class=\"main\">\n <div id=\"frame-content\">\n <!-- CONTENT -->\n </div>\n </div>\n\n</body>\n</html>\n"
|
|
316
|
+
},
|
|
317
|
+
{
|
|
318
|
+
"path": "scripts/helper.js",
|
|
319
|
+
"content": "(function() {\n const MIN_RECONNECT_MS = 500;\n const MAX_RECONNECT_MS = 30000;\n const TOMBSTONE_AFTER_MS = 15000; // show the \"paused\" overlay after this long disconnected\n\n // Pure: next backoff delay (doubles, capped). Exported for unit tests.\n function nextReconnectDelay(current, max) {\n return Math.min(current * 2, max);\n }\n if (typeof module !== 'undefined' && module.exports) {\n module.exports = { nextReconnectDelay, MIN_RECONNECT_MS, MAX_RECONNECT_MS, TOMBSTONE_AFTER_MS };\n }\n\n // Everything below is browser-only; bail out when loaded in Node (tests).\n if (typeof window === 'undefined') return;\n\n let ws = null;\n let eventQueue = [];\n let reconnectDelay = MIN_RECONNECT_MS;\n let reconnectTimer = null;\n let disconnectedSince = null;\n let everConnected = false;\n let tombstoneShown = false;\n\n function sessionKey() {\n try {\n return window.sessionStorage && window.sessionStorage.getItem('brainstorm-session-key');\n } catch (e) {}\n return null;\n }\n\n function websocketUrl() {\n const key = sessionKey();\n return 'ws://' + window.location.host + (key ? '/?key=' + encodeURIComponent(key) : '');\n }\n\n function reloadAfterRecovery() {\n const key = sessionKey();\n if (key) {\n window.location.replace('/?key=' + encodeURIComponent(key));\n } else {\n window.location.reload();\n }\n }\n\n // Reflect connection state in the frame's status pill (absent on full-doc screens).\n function setStatus(state) {\n const el = document.querySelector('.status');\n if (!el) return;\n const map = {\n connecting: ['Connecting…', 'var(--text-tertiary)'],\n connected: ['Connected', 'var(--success)'],\n reconnecting: ['Reconnecting…', 'var(--warning)'],\n disconnected: ['Disconnected', 'var(--error)']\n };\n const [text, color] = map[state] || map.disconnected;\n el.textContent = text;\n el.style.setProperty('--status-color', color);\n }\n\n // Self-styled so it works on framed and full-document screens alike.\n function showTombstone() {\n if (tombstoneShown) return;\n tombstoneShown = true;\n const el = document.createElement('div');\n el.id = 'bs-tombstone';\n el.style.cssText = 'position:fixed;inset:0;z-index:99999;display:flex;' +\n 'align-items:center;justify-content:center;padding:2rem;text-align:center;' +\n 'background:rgba(20,20,22,0.92);color:#f5f5f7;font-family:system-ui,sans-serif';\n el.innerHTML = '<div style=\"max-width:480px\">' +\n '<h2 style=\"margin:0 0 .5rem;font-weight:600\">Companion paused</h2>' +\n '<p style=\"margin:0;opacity:.85\">This brainstorm companion has stopped. ' +\n 'Ask your coding agent to bring it back — this page reconnects automatically.</p></div>';\n if (document.body) document.body.appendChild(el);\n }\n\n function connect() {\n if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }\n setStatus(everConnected ? 'reconnecting' : 'connecting');\n ws = new WebSocket(websocketUrl());\n\n ws.onopen = () => {\n const recovered = tombstoneShown;\n everConnected = true;\n disconnectedSince = null;\n reconnectDelay = MIN_RECONNECT_MS;\n tombstoneShown = false;\n setStatus('connected');\n eventQueue.forEach(e => ws.send(JSON.stringify(e)));\n eventQueue = [];\n // Recovered from a tombstoned outage (e.g. the server restarted on the same\n // port) — reload through the keyed bootstrap when possible so the cookie is\n // refreshed before the visible URL returns to bare /.\n if (recovered) reloadAfterRecovery();\n };\n\n ws.onmessage = (msg) => {\n let data;\n try { data = JSON.parse(msg.data); } catch (e) { return; }\n if (data.type === 'reload') window.location.reload();\n };\n\n ws.onclose = () => {\n ws = null;\n if (disconnectedSince === null) disconnectedSince = Date.now();\n if (Date.now() - disconnectedSince >= TOMBSTONE_AFTER_MS) {\n setStatus('disconnected');\n showTombstone();\n } else {\n setStatus('reconnecting');\n }\n reconnectTimer = setTimeout(connect, reconnectDelay);\n reconnectDelay = nextReconnectDelay(reconnectDelay, MAX_RECONNECT_MS);\n };\n\n // Let onclose own reconnection so we don't schedule it twice.\n ws.onerror = () => { try { ws.close(); } catch (e) {} };\n }\n\n function sendEvent(event) {\n event.timestamp = Date.now();\n if (ws && ws.readyState === WebSocket.OPEN) {\n ws.send(JSON.stringify(event));\n } else {\n eventQueue.push(event);\n }\n }\n\n // Capture clicks on choice elements\n document.addEventListener('click', (e) => {\n const target = e.target.closest('[data-choice]');\n if (!target) return;\n\n sendEvent({\n type: 'click',\n text: target.textContent.trim(),\n choice: target.dataset.choice,\n id: target.id || null\n });\n\n });\n\n // Frame UI: selection tracking\n window.selectedChoice = null;\n\n window.toggleSelect = function(el) {\n const container = el.closest('.options') || el.closest('.cards');\n const multi = container && container.dataset.multiselect !== undefined;\n if (container && !multi) {\n container.querySelectorAll('.option, .card').forEach(o => o.classList.remove('selected'));\n }\n if (multi) {\n el.classList.toggle('selected');\n } else {\n el.classList.add('selected');\n }\n window.selectedChoice = el.dataset.choice;\n };\n\n // Expose API for explicit use\n window.brainstorm = {\n send: sendEvent,\n choice: (value, metadata = {}) => sendEvent({ type: 'choice', value, ...metadata })\n };\n\n connect();\n})();\n"
|
|
320
|
+
},
|
|
321
|
+
{
|
|
322
|
+
"path": "scripts/server.cjs",
|
|
323
|
+
"content": "const crypto = require('crypto');\nconst http = require('http');\nconst fs = require('fs');\nconst path = require('path');\n\n// ========== WebSocket Protocol (RFC 6455) ==========\n\nconst OPCODES = { TEXT: 0x01, CLOSE: 0x08, PING: 0x09, PONG: 0x0A };\nconst WS_MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';\nconst MAX_FRAME_PAYLOAD_BYTES = 10 * 1024 * 1024;\n\nfunction computeAcceptKey(clientKey) {\n return crypto.createHash('sha1').update(clientKey + WS_MAGIC).digest('base64');\n}\n\nfunction encodeFrame(opcode, payload) {\n const fin = 0x80;\n const len = payload.length;\n let header;\n\n if (len < 126) {\n header = Buffer.alloc(2);\n header[0] = fin | opcode;\n header[1] = len;\n } else if (len < 65536) {\n header = Buffer.alloc(4);\n header[0] = fin | opcode;\n header[1] = 126;\n header.writeUInt16BE(len, 2);\n } else {\n header = Buffer.alloc(10);\n header[0] = fin | opcode;\n header[1] = 127;\n header.writeBigUInt64BE(BigInt(len), 2);\n }\n\n return Buffer.concat([header, payload]);\n}\n\nfunction decodeFrame(buffer) {\n if (buffer.length < 2) return null;\n\n const secondByte = buffer[1];\n const opcode = buffer[0] & 0x0F;\n const masked = (secondByte & 0x80) !== 0;\n let payloadLen = secondByte & 0x7F;\n let offset = 2;\n\n if (!masked) throw new Error('Client frames must be masked');\n\n if (payloadLen === 126) {\n if (buffer.length < 4) return null;\n payloadLen = buffer.readUInt16BE(2);\n offset = 4;\n } else if (payloadLen === 127) {\n if (buffer.length < 10) return null;\n const extendedLen = buffer.readBigUInt64BE(2);\n if (extendedLen > BigInt(MAX_FRAME_PAYLOAD_BYTES)) {\n throw new Error('WebSocket frame payload exceeds maximum allowed size');\n }\n payloadLen = Number(extendedLen);\n offset = 10;\n }\n\n if (payloadLen > MAX_FRAME_PAYLOAD_BYTES) {\n throw new Error('WebSocket frame payload exceeds maximum allowed size');\n }\n\n const maskOffset = offset;\n const dataOffset = offset + 4;\n const totalLen = dataOffset + payloadLen;\n if (buffer.length < totalLen) return null;\n\n const mask = buffer.slice(maskOffset, dataOffset);\n const data = Buffer.alloc(payloadLen);\n for (let i = 0; i < payloadLen; i++) {\n data[i] = buffer[dataOffset + i] ^ mask[i % 4];\n }\n\n return { opcode, payload: data, bytesConsumed: totalLen };\n}\n\n// ========== Configuration ==========\n\nconst PORT_FILE = process.env.BRAINSTORM_PORT_FILE || null;\nconst randomPort = () => 49152 + Math.floor(Math.random() * 16383);\n// Prefer an explicit port, else the port this session last bound (so a restart\n// reuses it and an already-open browser tab reconnects), else a random high port.\nfunction preferredPort() {\n if (process.env.BRAINSTORM_PORT) return Number(process.env.BRAINSTORM_PORT);\n if (PORT_FILE) {\n try {\n const p = Number(fs.readFileSync(PORT_FILE, 'utf-8').trim());\n if (Number.isInteger(p) && p > 1023 && p < 65536) return p;\n } catch (e) { /* no prior port recorded */ }\n }\n return randomPort();\n}\nlet PORT = preferredPort();\nconst HOST = process.env.BRAINSTORM_HOST || '127.0.0.1';\nconst URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST);\nconst SESSION_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm';\nconst CONTENT_DIR = path.join(SESSION_DIR, 'content');\nconst STATE_DIR = path.join(SESSION_DIR, 'state');\nconst SUPERPOWERS_VERSION = readSuperpowersVersion();\nconst SUPERPOWERS_BRAND_IMAGE_URL = 'https://primeradiant.com/brand/superpowers-visual-brainstorming-logo.png';\nconst TELEMETRY_DISABLE_ENV_VARS = [\n 'SUPERPOWERS_DISABLE_TELEMETRY',\n 'DISABLE_TELEMETRY',\n 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC'\n];\nconst SUPERPOWERS_TELEMETRY_DISABLED = TELEMETRY_DISABLE_ENV_VARS.some(name => isTruthyEnv(process.env[name]));\nlet ownerPid = process.env.BRAINSTORM_OWNER_PID ? Number(process.env.BRAINSTORM_OWNER_PID) : null;\n\n// Per-session secret key. The companion is reachable by any local browser tab\n// and, when bound to a non-loopback host, by any host that can route to it.\n// The key authenticates the real client uniformly across loopback, tunnel, and\n// remote binds — and defeats DNS rebinding — where a Host/Origin allowlist\n// cannot. It rides the served URL as ?key= and is mirrored into a cookie on\n// first load so same-origin subresources and the WebSocket carry it for free.\n// Persisted alongside the port (BRAINSTORM_TOKEN_FILE) so a restart keeps the\n// same key and an already-open tab's cookie still validates.\nconst TOKEN_FILE = process.env.BRAINSTORM_TOKEN_FILE || null;\nfunction generateToken() {\n return crypto.randomBytes(32).toString('hex');\n}\n\nfunction chmodOwnerOnly(file) {\n try { fs.chmodSync(file, 0o600); } catch (e) { /* best effort */ }\n}\n\nfunction initialToken() {\n if (process.env.BRAINSTORM_TOKEN) {\n return { value: process.env.BRAINSTORM_TOKEN, source: 'env' };\n }\n if (TOKEN_FILE) {\n try {\n const t = fs.readFileSync(TOKEN_FILE, 'utf-8').trim();\n if (/^[0-9a-f]{32,}$/i.test(t)) {\n chmodOwnerOnly(TOKEN_FILE);\n return { value: t, source: 'file' };\n }\n } catch (e) { /* no prior token recorded */ }\n }\n return { value: generateToken(), source: 'generated' };\n}\n\nconst tokenInfo = initialToken();\nlet TOKEN = tokenInfo.value;\nlet tokenSource = tokenInfo.source;\nlet COOKIE_NAME = 'brainstorm-key-' + PORT; // refined to the actual bound port in onListen\n\nconst MIME_TYPES = {\n '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',\n '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml'\n};\n\n// ========== Templates and Constants ==========\n\nfunction waitingPage() {\n return renderBranding(`<!DOCTYPE html>\n<html>\n<head><meta charset=\"utf-8\"><title>Brainstorm Companion</title>\n<style>\nbody { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }\nh1 { color: #333; } p { color: #666; }\n.brand { display: flex; align-items: center; min-width: 0; overflow: hidden; margin-bottom: 1.5rem; color: #666; font-size: 0.9rem; line-height: 1; }\n.brand a { color: inherit; text-decoration: none; display: flex; align-items: center; gap: 0.5rem; min-width: 0; max-width: 100%; line-height: 1; }\n.brand-copy { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 1; transform: translateY(-1px); }\n.brand-logo { display: block; height: 1em; width: auto; max-width: 180px; filter: invert(1); }\n</style>\n</head>\n<body><!-- BRANDING --><h1>Brainstorm Companion</h1>\n<p>Waiting for the agent to push a screen...</p></body></html>`);\n}\n\nconst FORBIDDEN_PAGE = `<!DOCTYPE html>\n<html>\n<head><meta charset=\"utf-8\"><title>Session key required</title>\n<style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }\nh1 { color: #333; } p { color: #666; } code { background: #f0f0f0; padding: 0.1em 0.3em; border-radius: 4px; }</style>\n</head>\n<body><h1>Session key required</h1>\n<p>This page needs the full URL your coding agent gave you, including the\n<code>?key=…</code> part. Copy the complete URL and open it again.</p></body></html>`;\n\nfunction bootstrapPage(key) {\n const jsonKey = JSON.stringify(String(key));\n return `<!DOCTYPE html>\n<html>\n<head><meta charset=\"utf-8\"><title>Opening Brainstorm Companion</title></head>\n<body>\n<script>\ntry { sessionStorage.setItem('brainstorm-session-key', ${jsonKey}); } catch (e) {}\nlocation.replace('/');\n</script>\n</body>\n</html>`;\n}\n\nconst frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8');\nconst helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');\nconst helperInjection = '<script>\\n' + helperScript + '\\n</script>';\n\n// ========== Helper Functions ==========\n\nfunction readSuperpowersVersion() {\n const root = path.join(__dirname, '../../..');\n const manifests = [\n path.join(root, 'package.json'),\n path.join(root, '.codex-plugin/plugin.json')\n ];\n\n for (const manifest of manifests) {\n try {\n const data = JSON.parse(fs.readFileSync(manifest, 'utf-8'));\n if (data.version) return String(data.version);\n } catch (e) {\n // Packaged Codex plugins omit package.json; try the next manifest.\n }\n }\n\n return 'unknown';\n}\n\nfunction isTruthyEnv(value) {\n if (!value) return false;\n const normalized = String(value).trim().toLowerCase();\n if (!normalized) return false;\n return !['0', 'false', 'no', 'off'].includes(normalized);\n}\n\nfunction escapeHtmlText(value) {\n return String(value)\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"');\n}\n\nfunction brandMarkup() {\n const version = escapeHtmlText(SUPERPOWERS_VERSION);\n const text = SUPERPOWERS_TELEMETRY_DISABLED\n ? 'Prime Radiant Superpowers v' + version\n : 'Superpowers v' + version;\n const logo = SUPERPOWERS_TELEMETRY_DISABLED\n ? ''\n : '<img class=\"brand-logo\" src=\"' + SUPERPOWERS_BRAND_IMAGE_URL + '?v=' + encodeURIComponent(SUPERPOWERS_VERSION) + '\" alt=\"Prime Radiant\" referrerpolicy=\"no-referrer\" decoding=\"async\">';\n\n return '<div class=\"brand\"><a href=\"https://github.com/obra/superpowers\">' + logo + '<span class=\"brand-copy\">' + text + '</span></a></div>';\n}\n\nfunction renderBranding(html) {\n return html.split('<!-- BRANDING -->').join(brandMarkup());\n}\n\nfunction isFullDocument(html) {\n const trimmed = html.trimStart().toLowerCase();\n return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html');\n}\n\nfunction wrapInFrame(content) {\n return renderBranding(frameTemplate).replace('<!-- CONTENT -->', content);\n}\n\nfunction getNewestScreen() {\n const files = fs.readdirSync(CONTENT_DIR)\n .filter(f => !f.startsWith('.') && f.endsWith('.html'))\n .map(f => {\n const fp = path.join(CONTENT_DIR, f);\n if (!isRegularFileInsideContentDir(fp)) return null;\n return { path: fp, mtime: fs.statSync(fp).mtime.getTime() };\n })\n .filter(Boolean)\n .sort((a, b) => b.mtime - a.mtime);\n return files.length > 0 ? files[0].path : null;\n}\n\nfunction urlHostForHttp(host) {\n const h = String(host);\n if (h.startsWith('[') && h.endsWith(']')) return h;\n return h.includes(':') ? '[' + h + ']' : h;\n}\n\nfunction companionUrl() {\n return 'http://' + urlHostForHttp(URL_HOST) + ':' + PORT + '/?key=' + TOKEN;\n}\n\nfunction browserLauncherForPlatform(url, {\n platform = process.platform,\n osRelease = require('os').release(),\n env = process.env\n} = {}) {\n const isWSL = platform === 'linux' && /microsoft/i.test(osRelease);\n if (platform === 'darwin') return { bin: 'open', args: [url] };\n if (platform === 'win32' || isWSL) {\n return { bin: 'rundll32.exe', args: ['url.dll,FileProtocolHandler', url] };\n }\n if (env.DISPLAY || env.WAYLAND_DISPLAY) return { bin: 'xdg-open', args: [url] };\n return null;\n}\n\nfunction isRegularFileInsideContentDir(filePath) {\n let stat, realContentDir, realFilePath;\n try {\n stat = fs.lstatSync(filePath);\n if (stat.isSymbolicLink()) return false;\n if (!stat.isFile()) return false;\n if (stat.nlink !== 1) return false;\n realContentDir = fs.realpathSync(CONTENT_DIR);\n realFilePath = fs.realpathSync(filePath);\n } catch (e) {\n return false;\n }\n return realFilePath.startsWith(realContentDir + path.sep);\n}\n\n// ========== Authentication ==========\n\nfunction timingSafeEqualStr(a, b) {\n const ab = Buffer.from(String(a));\n const bb = Buffer.from(String(b));\n if (ab.length !== bb.length) return false;\n return crypto.timingSafeEqual(ab, bb);\n}\n\nfunction parseCookies(header) {\n const out = {};\n if (!header) return out;\n for (const part of header.split(';')) {\n const eq = part.indexOf('=');\n if (eq < 0) continue;\n out[part.slice(0, eq).trim()] = part.slice(eq + 1).trim();\n }\n return out;\n}\n\n// A request is authorized if it carries the session key as ?key= or as the\n// session cookie. Both are compared in constant time.\nfunction isAuthorized(req) {\n const q = req.url.indexOf('?');\n if (q >= 0) {\n const params = new URLSearchParams(req.url.slice(q + 1));\n if (params.has('key')) {\n const key = params.get('key');\n return Boolean(key && timingSafeEqualStr(key, TOKEN));\n }\n }\n const cookie = parseCookies(req.headers['cookie'])[COOKIE_NAME];\n if (cookie && timingSafeEqualStr(cookie, TOKEN)) return true;\n return false;\n}\n\nfunction pathnameOf(url) {\n const q = url.indexOf('?');\n return q >= 0 ? url.slice(0, q) : url;\n}\n\nfunction queryKey(url) {\n const q = url.indexOf('?');\n if (q < 0) return null;\n return new URLSearchParams(url.slice(q + 1)).get('key');\n}\n\nfunction securityHeaders(headers = {}) {\n return {\n 'Referrer-Policy': 'no-referrer',\n 'Cache-Control': 'no-store',\n 'X-Frame-Options': 'DENY',\n 'Content-Security-Policy': \"frame-ancestors 'none'\",\n 'Cross-Origin-Resource-Policy': 'same-origin',\n ...headers\n };\n}\n\nfunction isAllowedWebSocketOrigin(req) {\n const origin = req.headers.origin;\n if (!origin) return true;\n const host = req.headers.host;\n if (!host) return false;\n return origin === 'http://' + host;\n}\n\n// ========== HTTP Request Handler ==========\n\nfunction handleRequest(req, res) {\n if (!isAuthorized(req)) {\n res.writeHead(403, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }));\n res.end(FORBIDDEN_PAGE);\n return;\n }\n touchActivity(); // only authorized requests count as activity\n\n // Mirror the key into a cookie so same-origin subresources (/files/*) can\n // authenticate after bootstrap. HttpOnly keeps it away from page scripts; the\n // WebSocket Origin check below is what blocks cross-origin localhost injection.\n res.setHeader('Set-Cookie',\n COOKIE_NAME + '=' + TOKEN + '; HttpOnly; SameSite=Strict; Path=/');\n\n const pathname = pathnameOf(req.url);\n const keyFromQuery = queryKey(req.url);\n if (req.method === 'GET' && pathname === '/' && keyFromQuery && timingSafeEqualStr(keyFromQuery, TOKEN)) {\n res.writeHead(200, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }));\n res.end(bootstrapPage(keyFromQuery));\n } else if (req.method === 'GET' && pathname === '/') {\n const screenFile = getNewestScreen();\n let html = screenFile\n ? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8'))\n : waitingPage();\n\n if (html.includes('</body>')) {\n html = html.replace('</body>', helperInjection + '\\n</body>');\n } else {\n html += helperInjection;\n }\n\n res.writeHead(200, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }));\n res.end(html);\n } else if (req.method === 'GET' && pathname.startsWith('/files/')) {\n const fileName = path.basename(pathname.slice(7));\n const filePath = path.join(CONTENT_DIR, fileName);\n // Reject empty/dotfile names and anything that isn't a regular file —\n // `/files/` would otherwise resolve to CONTENT_DIR and crash readFileSync (EISDIR).\n if (!fileName || fileName.startsWith('.') || !isRegularFileInsideContentDir(filePath)) {\n res.writeHead(404, securityHeaders());\n res.end('Not found');\n return;\n }\n const ext = path.extname(filePath).toLowerCase();\n const contentType = MIME_TYPES[ext] || 'application/octet-stream';\n res.writeHead(200, securityHeaders({ 'Content-Type': contentType }));\n res.end(fs.readFileSync(filePath));\n } else {\n res.writeHead(404, securityHeaders());\n res.end('Not found');\n }\n}\n\n// ========== WebSocket Connection Handling ==========\n\nconst clients = new Set();\n\nfunction handleUpgrade(req, socket) {\n if (!isAuthorized(req) || !isAllowedWebSocketOrigin(req)) { socket.destroy(); return; }\n\n const key = req.headers['sec-websocket-key'];\n if (!key) { socket.destroy(); return; }\n\n const accept = computeAcceptKey(key);\n socket.write(\n 'HTTP/1.1 101 Switching Protocols\\r\\n' +\n 'Upgrade: websocket\\r\\n' +\n 'Connection: Upgrade\\r\\n' +\n 'Sec-WebSocket-Accept: ' + accept + '\\r\\n\\r\\n'\n );\n\n let buffer = Buffer.alloc(0);\n clients.add(socket);\n\n socket.on('data', (chunk) => {\n buffer = Buffer.concat([buffer, chunk]);\n while (buffer.length > 0) {\n let result;\n try {\n result = decodeFrame(buffer);\n } catch (e) {\n socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));\n clients.delete(socket);\n return;\n }\n if (!result) break;\n buffer = buffer.slice(result.bytesConsumed);\n\n switch (result.opcode) {\n case OPCODES.TEXT:\n handleMessage(result.payload.toString());\n break;\n case OPCODES.CLOSE:\n socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));\n clients.delete(socket);\n return;\n case OPCODES.PING:\n socket.write(encodeFrame(OPCODES.PONG, result.payload));\n break;\n case OPCODES.PONG:\n break;\n default: {\n const closeBuf = Buffer.alloc(2);\n closeBuf.writeUInt16BE(1003);\n socket.end(encodeFrame(OPCODES.CLOSE, closeBuf));\n clients.delete(socket);\n return;\n }\n }\n }\n });\n\n socket.on('close', () => clients.delete(socket));\n socket.on('error', () => clients.delete(socket));\n}\n\nfunction handleMessage(text) {\n let event;\n try {\n event = JSON.parse(text);\n } catch (e) {\n console.error('Failed to parse WebSocket message:', e.message);\n return;\n }\n touchActivity();\n console.log(JSON.stringify({ source: 'user-event', ...event }));\n if (event && event.choice) {\n const eventsFile = path.join(STATE_DIR, 'events');\n fs.appendFileSync(eventsFile, JSON.stringify(event) + '\\n');\n }\n}\n\nfunction broadcast(msg) {\n const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg)));\n for (const socket of clients) {\n try { socket.write(frame); } catch (e) { clients.delete(socket); }\n }\n}\n\n// Best-effort: open the user's browser the first time a screen is actually ready\n// to show. Skips when disabled, on a non-loopback (remote) bind, or when a\n// browser is already connected. Override the launcher with BRAINSTORM_OPEN_CMD.\nlet browserOpened = false;\nfunction maybeOpenBrowser() {\n if (browserOpened) return;\n browserOpened = true;\n if (!process.env.BRAINSTORM_OPEN) return; // opt-in: only after the user approves the companion\n if (HOST !== '127.0.0.1' && HOST !== 'localhost') return;\n if (clients.size > 0) return; // the user already opened it\n const url = companionUrl(); // must carry the key or the gate 403s it\n const cp = require('child_process');\n // Operator-provided launcher: run as given (this env var is trusted operator input).\n if (process.env.BRAINSTORM_OPEN_CMD) {\n try { cp.exec(process.env.BRAINSTORM_OPEN_CMD + ' ' + JSON.stringify(url), () => {}); } catch (e) { /* best effort */ }\n return;\n }\n // Platform launchers: pass the URL as an argv element via execFile (no shell),\n // so a url-host containing shell metacharacters can't inject a command.\n const launcher = browserLauncherForPlatform(url);\n if (!launcher) return; // headless: nothing to open\n try { cp.execFile(launcher.bin, launcher.args, () => {}); } catch (e) { /* best effort */ }\n}\n\n// ========== Activity Tracking ==========\n\n// Idle timeout: shut down after this long with no activity. Default 4 hours;\n// override with BRAINSTORM_IDLE_TIMEOUT_MS (start-server.sh: --idle-timeout-minutes).\nconst IDLE_TIMEOUT_MS = (() => {\n const ms = Number(process.env.BRAINSTORM_IDLE_TIMEOUT_MS);\n return Number.isFinite(ms) && ms > 0 ? ms : 4 * 60 * 60 * 1000;\n})();\n// How often the watchdog checks for owner-death / idleness. Configurable mainly\n// so tests can run fast; production default is 60s.\nconst LIFECYCLE_CHECK_MS = (() => {\n const ms = Number(process.env.BRAINSTORM_LIFECYCLE_CHECK_MS);\n return Number.isFinite(ms) && ms > 0 ? ms : 60 * 1000;\n})();\nlet lastActivity = Date.now();\n\nfunction touchActivity() {\n lastActivity = Date.now();\n}\n\n// ========== File Watching ==========\n\nconst debounceTimers = new Map();\n\n// ========== Server Startup ==========\n\nfunction startServer() {\n if (!fs.existsSync(CONTENT_DIR)) fs.mkdirSync(CONTENT_DIR, { recursive: true });\n if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true });\n\n // Track known files to distinguish new screens from updates.\n // macOS fs.watch reports 'rename' for both new files and overwrites,\n // so we can't rely on eventType alone.\n const knownFiles = new Set(\n fs.readdirSync(CONTENT_DIR).filter(f => !f.startsWith('.') && f.endsWith('.html'))\n );\n\n const server = http.createServer(handleRequest);\n server.on('upgrade', handleUpgrade);\n\n const watcher = fs.watch(CONTENT_DIR, (eventType, filename) => {\n if (!filename || filename.startsWith('.') || !filename.endsWith('.html')) return;\n\n if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename));\n debounceTimers.set(filename, setTimeout(() => {\n debounceTimers.delete(filename);\n const filePath = path.join(CONTENT_DIR, filename);\n\n if (!fs.existsSync(filePath)) return; // file was deleted\n touchActivity();\n\n if (!knownFiles.has(filename)) {\n knownFiles.add(filename);\n const eventsFile = path.join(STATE_DIR, 'events');\n if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);\n console.log(JSON.stringify({ type: 'screen-added', file: filePath }));\n maybeOpenBrowser();\n } else {\n console.log(JSON.stringify({ type: 'screen-updated', file: filePath }));\n }\n\n broadcast({ type: 'reload' });\n }, 100));\n });\n watcher.on('error', (err) => console.error('fs.watch error:', err.message));\n\n function shutdown(reason) {\n console.log(JSON.stringify({ type: 'server-stopped', reason }));\n const infoFile = path.join(STATE_DIR, 'server-info');\n if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile);\n fs.writeFileSync(\n path.join(STATE_DIR, 'server-stopped'),\n JSON.stringify({ reason, timestamp: Date.now() }) + '\\n'\n );\n watcher.close();\n clearInterval(lifecycleCheck);\n // Close any upgraded WebSocket sockets so server.close() can complete and\n // the process actually exits instead of lingering on an open connection.\n for (const socket of clients) {\n try { socket.destroy(); } catch (e) { /* already gone */ }\n }\n server.close(() => process.exit(0));\n }\n\n function ownerAlive() {\n if (!ownerPid) return true;\n try { process.kill(ownerPid, 0); return true; } catch (e) { return e.code === 'EPERM'; }\n }\n\n // Periodically exit if the owner process died or we've been idle too long.\n const lifecycleCheck = setInterval(() => {\n if (!ownerAlive()) shutdown('owner process exited');\n else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout');\n }, LIFECYCLE_CHECK_MS);\n lifecycleCheck.unref();\n\n // Validate owner PID at startup. If it's already dead, the PID resolution\n // was wrong (common on WSL, Tailscale SSH, and cross-user scenarios).\n // Disable monitoring and rely on the idle timeout instead.\n if (ownerPid) {\n try { process.kill(ownerPid, 0); }\n catch (e) {\n if (e.code !== 'EPERM') {\n console.log(JSON.stringify({ type: 'owner-pid-invalid', pid: ownerPid, reason: 'dead at startup' }));\n ownerPid = null;\n }\n }\n }\n\n // If the preferred port is already taken (e.g. a previous server is still\n // alive), fall back to a random port once instead of failing.\n let triedFallback = false;\n\n function onListen() {\n // Cookie name keys on the ACTUAL bound port (may differ from the preferred\n // one after an EADDRINUSE fallback) so it can't collide with another server's\n // cookie in the shared localhost jar.\n COOKIE_NAME = 'brainstorm-key-' + PORT;\n // Record the bound port AND token so the next restart of this session reuses\n // them — but ONLY when we got our preferred port. On a fallback we bound a\n // *different* port because someone else holds the preferred one; persisting\n // would overwrite the shared files and strand that other session's open tab.\n if (PORT_FILE && !triedFallback) {\n try { fs.writeFileSync(PORT_FILE, String(PORT)); } catch (e) { /* best effort */ }\n if (TOKEN_FILE) {\n try {\n fs.writeFileSync(TOKEN_FILE, TOKEN, { mode: 0o600 });\n chmodOwnerOnly(TOKEN_FILE);\n } catch (e) { /* best effort */ }\n }\n }\n const info = JSON.stringify({\n type: 'server-started', port: Number(PORT), host: HOST,\n url_host: URL_HOST, url: companionUrl(),\n screen_dir: CONTENT_DIR, state_dir: STATE_DIR, idle_timeout_ms: IDLE_TIMEOUT_MS\n });\n console.log(info);\n // server-info embeds the key — keep it owner-only.\n fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\\n', { mode: 0o600 });\n }\n\n server.on('error', (err) => {\n if (err.code === 'EADDRINUSE' && !triedFallback) {\n if (tokenSource === 'env') {\n console.error('Server failed to bind: preferred port is in use and BRAINSTORM_TOKEN is set; refusing fallback with explicit token');\n process.exit(1);\n }\n triedFallback = true;\n PORT = randomPort();\n if (tokenSource === 'file') {\n TOKEN = generateToken();\n tokenSource = 'generated-fallback';\n }\n server.listen(PORT, HOST, onListen);\n } else {\n console.error('Server failed to bind:', err.message);\n process.exit(1);\n }\n });\n server.listen(PORT, HOST, onListen);\n}\n\nif (require.main === module) {\n startServer();\n}\n\nmodule.exports = {\n computeAcceptKey,\n encodeFrame,\n decodeFrame,\n browserLauncherForPlatform,\n OPCODES,\n MAX_FRAME_PAYLOAD_BYTES\n};\n"
|
|
324
|
+
},
|
|
325
|
+
{
|
|
326
|
+
"path": "scripts/start-server.sh",
|
|
327
|
+
"content": "#!/usr/bin/env bash\n# Start the brainstorm server and output connection info\n# Usage: start-server.sh [--project-dir <path>] [--host <bind-host>] [--url-host <display-host>] [--foreground] [--background]\n#\n# Starts server on a random high port, outputs JSON with URL.\n# Each session gets its own directory to avoid conflicts.\n#\n# Options:\n# --project-dir <path> Store session files under <path>/.superpowers/brainstorm/\n# instead of /tmp. Files persist after server stops.\n# --host <bind-host> Host/interface to bind (default: 127.0.0.1).\n# Use 0.0.0.0 in remote/containerized environments.\n# --url-host <host> Hostname shown in returned URL JSON.\n# --idle-timeout-minutes <n> Shut down after n minutes idle (default 240 = 4h).\n# --open Auto-open the browser on the first screen (use only\n# after the user approves the visual companion).\n# --foreground Run server in the current terminal (no backgrounding).\n# --background Force background mode (overrides Codex auto-foreground).\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\n\n# Parse arguments\nPROJECT_DIR=\"\"\nFOREGROUND=\"false\"\nFORCE_BACKGROUND=\"false\"\nBIND_HOST=\"127.0.0.1\"\nURL_HOST=\"\"\nIDLE_TIMEOUT_MINUTES=\"\"\nwhile [[ $# -gt 0 ]]; do\n case \"$1\" in\n --project-dir)\n PROJECT_DIR=\"$2\"\n shift 2\n ;;\n --host)\n BIND_HOST=\"$2\"\n shift 2\n ;;\n --url-host)\n URL_HOST=\"$2\"\n shift 2\n ;;\n --idle-timeout-minutes)\n IDLE_TIMEOUT_MINUTES=\"$2\"\n shift 2\n ;;\n --open)\n export BRAINSTORM_OPEN=1\n shift\n ;;\n --foreground|--no-daemon)\n FOREGROUND=\"true\"\n shift\n ;;\n --background|--daemon)\n FORCE_BACKGROUND=\"true\"\n shift\n ;;\n *)\n echo \"{\\\"error\\\": \\\"Unknown argument: $1\\\"}\"\n exit 1\n ;;\n esac\ndone\n\nif [[ -z \"$URL_HOST\" ]]; then\n if [[ \"$BIND_HOST\" == \"127.0.0.1\" || \"$BIND_HOST\" == \"localhost\" ]]; then\n URL_HOST=\"localhost\"\n else\n URL_HOST=\"$BIND_HOST\"\n fi\nfi\n\nif [[ -n \"$IDLE_TIMEOUT_MINUTES\" ]]; then\n if ! [[ \"$IDLE_TIMEOUT_MINUTES\" =~ ^[0-9]+$ ]] || [[ \"$IDLE_TIMEOUT_MINUTES\" -lt 1 ]]; then\n echo \"{\\\"error\\\": \\\"--idle-timeout-minutes must be a positive integer\\\"}\"\n exit 1\n fi\n export BRAINSTORM_IDLE_TIMEOUT_MS=$(( IDLE_TIMEOUT_MINUTES * 60 * 1000 ))\nfi\n\nis_windows_like_shell() {\n case \"${OSTYPE:-}\" in\n msys*|cygwin*|mingw*) return 0 ;;\n esac\n if [[ -n \"${MSYSTEM:-}\" ]]; then\n return 0\n fi\n local uname_s\n uname_s=\"$(uname -s 2>/dev/null || true)\"\n case \"$uname_s\" in\n MSYS*|MINGW*|CYGWIN*) return 0 ;;\n esac\n return 1\n}\n\n# Some environments reap detached/background processes. Auto-foreground when detected.\nif [[ -n \"${CODEX_CI:-}\" && \"$FOREGROUND\" != \"true\" && \"$FORCE_BACKGROUND\" != \"true\" ]]; then\n FOREGROUND=\"true\"\nfi\n\n# Windows/Git Bash reaps nohup background processes. Auto-foreground when detected.\nif [[ \"$FOREGROUND\" != \"true\" && \"$FORCE_BACKGROUND\" != \"true\" ]]; then\n if is_windows_like_shell; then\n FOREGROUND=\"true\"\n fi\nfi\n\n# Session files (server.log, server-info, .last-token) embed the session key —\n# keep everything this script and the server create owner-only.\numask 077\n\n# Generate unique session directory\nSESSION_ID=\"$$-$(date +%s)\"\n\nif [[ -n \"$PROJECT_DIR\" ]]; then\n SESSION_DIR=\"${PROJECT_DIR}/.superpowers/brainstorm/${SESSION_ID}\"\n # Persist the bound port and key per project so a restart reuses them and an\n # already-open browser tab reconnects to the same URL with a valid cookie.\n export BRAINSTORM_PORT_FILE=\"${PROJECT_DIR}/.superpowers/brainstorm/.last-port\"\n export BRAINSTORM_TOKEN_FILE=\"${PROJECT_DIR}/.superpowers/brainstorm/.last-token\"\nelse\n SESSION_DIR=\"/tmp/brainstorm-${SESSION_ID}\"\nfi\n\nSTATE_DIR=\"${SESSION_DIR}/state\"\nPID_FILE=\"${STATE_DIR}/server.pid\"\nLOG_FILE=\"${STATE_DIR}/server.log\"\nSERVER_ID_FILE=\"${STATE_DIR}/server-instance-id\"\n\n# Create fresh session directory with content and state peers\nmkdir -p \"${SESSION_DIR}/content\" \"$STATE_DIR\"\n\nSERVER_ID=\"\"\nif [[ -r /dev/urandom ]]; then\n SERVER_ID=\"$(od -An -N24 -tx1 /dev/urandom 2>/dev/null | tr -d ' \\n' || true)\"\nfi\nif ! [[ \"$SERVER_ID\" =~ ^[A-Za-z0-9_-]{32,64}$ ]]; then\n SERVER_ID=\"$(printf '%08x%08x%08x%08x' \"$$\" \"$(date +%s)\" \"${RANDOM:-0}\" \"${RANDOM:-0}\")\"\nfi\nprintf '%s\\n' \"$SERVER_ID\" > \"$SERVER_ID_FILE\"\nchmod 600 \"$SERVER_ID_FILE\" 2>/dev/null || true\n\n# Kill any existing server\nif [[ -f \"$PID_FILE\" ]]; then\n old_pid=$(cat \"$PID_FILE\")\n kill \"$old_pid\" 2>/dev/null\n rm -f \"$PID_FILE\"\nfi\n\ncd \"$SCRIPT_DIR\" || exit 1\n\n# Resolve the harness PID (grandparent of this script).\n# $PPID is the ephemeral shell the harness spawned to run us — it dies\n# when this script exits. The harness itself is $PPID's parent.\nOWNER_PID=\"$(ps -o ppid= -p \"$PPID\" 2>/dev/null | tr -d ' ')\"\nif [[ -z \"$OWNER_PID\" || \"$OWNER_PID\" == \"1\" ]]; then\n OWNER_PID=\"$PPID\"\nfi\n\n# Windows/MSYS2: Node.js cannot see POSIX PIDs from the MSYS2 namespace.\n# Passing a PID node cannot verify causes server to log owner-pid-invalid\n# and self-terminate at the 60-second lifecycle check. Clear it so the\n# watchdog is disabled and the idle timeout becomes the only shutdown trigger.\nif is_windows_like_shell; then\n OWNER_PID=\"\"\nfi\n\n# Foreground mode for environments that reap detached/background processes.\nif [[ \"$FOREGROUND\" == \"true\" ]]; then\n 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\" &\n SERVER_PID=$!\n echo \"$SERVER_PID\" > \"$PID_FILE\"\n wait \"$SERVER_PID\"\n exit $?\nfi\n\n# Start server, capturing output to log file\n# Use nohup to survive shell exit; disown to remove from job table\nnohup 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 &\nSERVER_PID=$!\ndisown \"$SERVER_PID\" 2>/dev/null\necho \"$SERVER_PID\" > \"$PID_FILE\"\n\n# Wait for server-started message (check log file)\nfor _ in {1..50}; do\n if grep -q \"server-started\" \"$LOG_FILE\" 2>/dev/null; then\n # Verify server is still alive after a short window (catches process reapers)\n alive=\"true\"\n for _ in {1..20}; do\n if ! kill -0 \"$SERVER_PID\" 2>/dev/null; then\n alive=\"false\"\n break\n fi\n sleep 0.1\n done\n if [[ \"$alive\" != \"true\" ]]; then\n 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\\\"}\"\n exit 1\n fi\n grep \"server-started\" \"$LOG_FILE\" | head -1\n exit 0\n fi\n sleep 0.1\ndone\n\n# Timeout - server didn't start\necho '{\"error\": \"Server failed to start within 5 seconds\"}'\nexit 1\n"
|
|
328
|
+
},
|
|
329
|
+
{
|
|
330
|
+
"path": "scripts/stop-server.sh",
|
|
331
|
+
"content": "#!/usr/bin/env bash\n# Stop the brainstorm server and clean up\n# Usage: stop-server.sh <session_dir>\n#\n# Kills the server process. Only deletes session directory if it's\n# under /tmp (ephemeral). Persistent directories (.superpowers/) are\n# kept so mockups can be reviewed later.\n\nSESSION_DIR=\"$1\"\n\nif [[ -z \"$SESSION_DIR\" ]]; then\n echo '{\"error\": \"Usage: stop-server.sh <session_dir>\"}'\n exit 1\nfi\n\nSTATE_DIR=\"${SESSION_DIR}/state\"\nPID_FILE=\"${STATE_DIR}/server.pid\"\nSERVER_ID_FILE=\"${STATE_DIR}/server-instance-id\"\n\nmark_stopped() {\n local reason=\"$1\"\n rm -f \"${STATE_DIR}/server-info\"\n printf '{\"reason\":\"%s\",\"timestamp\":%s}\\n' \"$reason\" \"$(date +%s)\" > \"${STATE_DIR}/server-stopped\"\n}\n\nread_expected_server_id() {\n [[ -f \"$SERVER_ID_FILE\" ]] || return 1\n local id\n id=\"$(tr -d '\\r\\n' < \"$SERVER_ID_FILE\" 2>/dev/null || true)\"\n [[ \"$id\" =~ ^[A-Za-z0-9_-]{32,64}$ ]] || return 1\n printf '%s\\n' \"$id\"\n}\n\ncommand_line_for_pid() {\n local pid=\"$1\"\n if [[ -r \"/proc/$pid/cmdline\" ]]; then\n tr '\\0' '\\n' < \"/proc/$pid/cmdline\" 2>/dev/null || true\n return 0\n fi\n ps -ww -p \"$pid\" -o command= 2>/dev/null || ps -f -p \"$pid\" 2>/dev/null | sed '1d' || true\n}\n\ncommand_has_server_id() {\n local pid=\"$1\"\n local expected=\"$2\"\n local expected_arg=\"--brainstorm-server-id=$expected\"\n if [[ -r \"/proc/$pid/cmdline\" ]]; then\n local arg\n while IFS= read -r -d '' arg || [[ -n \"$arg\" ]]; do\n [[ \"$arg\" == \"$expected_arg\" ]] && return 0\n done < \"/proc/$pid/cmdline\"\n return 1\n fi\n local command_line\n command_line=\"$(command_line_for_pid \"$pid\")\"\n [[ -n \"$command_line\" ]] || return 1\n case \" $command_line \" in\n *\" $expected_arg \"*) return 0 ;;\n *) return 1 ;;\n esac\n}\n\n# Confirm a PID has this session's per-start instance id, not just a familiar\n# process name. Ambiguous or legacy metadata fails closed as stale_pid.\nis_brainstorm_server() {\n kill -0 \"$1\" 2>/dev/null || return 1\n local expected_id\n expected_id=\"$(read_expected_server_id)\" || return 1\n command_has_server_id \"$1\" \"$expected_id\" || return 1\n return 0\n}\n\nif [[ -f \"$PID_FILE\" ]]; then\n pid=$(cat \"$PID_FILE\")\n\n # Refuse to signal a PID we can't prove is our server. A stale pid file may\n # point at an unrelated process after a reboot/PID wraparound.\n if ! is_brainstorm_server \"$pid\"; then\n rm -f \"$PID_FILE\" \"$SERVER_ID_FILE\"\n mark_stopped \"stale_pid\"\n echo '{\"status\": \"stale_pid\"}'\n exit 0\n fi\n\n # Try to stop gracefully, fallback to force if still alive\n kill \"$pid\" 2>/dev/null || true\n\n # Wait for graceful shutdown (up to ~2s)\n for _ in {1..20}; do\n if ! kill -0 \"$pid\" 2>/dev/null; then\n break\n fi\n sleep 0.1\n done\n\n # If still running, escalate to SIGKILL\n if kill -0 \"$pid\" 2>/dev/null; then\n kill -9 \"$pid\" 2>/dev/null || true\n\n # Give SIGKILL a moment to take effect\n sleep 0.1\n fi\n\n if kill -0 \"$pid\" 2>/dev/null; then\n echo '{\"status\": \"failed\", \"error\": \"process still running\"}'\n exit 1\n fi\n\n rm -f \"$PID_FILE\" \"$SERVER_ID_FILE\" \"${STATE_DIR}/server.log\"\n mark_stopped \"stop-server.sh\"\n\n # Only delete ephemeral /tmp directories\n if [[ \"$SESSION_DIR\" == /tmp/* ]]; then\n rm -rf \"$SESSION_DIR\"\n fi\n\n echo '{\"status\": \"stopped\"}'\nelse\n echo '{\"status\": \"not_running\"}'\nfi\n"
|
|
332
|
+
},
|
|
333
|
+
{
|
|
334
|
+
"path": "LICENSE",
|
|
335
|
+
"content": "# Upstream provenance (siming packaging layer; license text below is verbatim)\n# Repository: https://github.com/obra/superpowers\n# Skill path: skills/brainstorming\n# SKILL.md git blob sha: e3f17885f8d5f87d7a92f0469141662b476e1288\n# Fetched: 2026-10-08\n# License: MIT — original text follows\n\nMIT License\n\nCopyright (c) 2025 Jesse Vincent\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
|
|
336
|
+
}
|
|
337
|
+
]
|
|
293
338
|
}
|
|
294
339
|
],
|
|
295
340
|
"agents": [
|
|
@@ -468,7 +513,7 @@
|
|
|
468
513
|
"nodeId": "DESIGN",
|
|
469
514
|
"phase": "entry",
|
|
470
515
|
"track": "all",
|
|
471
|
-
"prompt": "# 技术方案\n\n## 节点职责\n\n将已确认的产品需求转化为可直接指导实现和验证的技术方案,并通过需求对齐审查、架构评审建立实现基线;用户确认由流程暂停点承载。本节点只产出设计,不编写生产代码或测试代码。\n\n## 依赖信息\n\n检查当前任务上下文、需求与验收标准、非目标、PRD、前序节点产物、项目提示词和相关架构资料;已有信息直接复用,缺失时再加载。\n\n按名称加载:\n\n- `tech-design` Skill:技术方案设计方法及文档模板;\n- `workflow-discipline` Skill:执行、审查和暂停点纪律。\n\n方案完成后,依次调用:\n\n1. `alignment-reviewer` Agent:检查方案与需求的对齐关系;\n2. `arch-reviewer` Agent:检查方案的架构质量。\n\n## 正向执行流程\n\n1. 确认需求范围和后端、前端或混合轨道,并读取相关项目约束与现有架构。\n2. 使用 `tech-design` Skill 设计方案,并读取其 `references/template.md` 生成技术方案文档;方案默认包含架构图与核心功能流程图——用可渲染的图形语法表达(项目未约定时用 Mermaid),不使用文字罗列代替,且图中模块、步骤、分支在正文均有对应说明。\n3. 项目有文档目录时按项目声明保存方案文件;登记任务产物时必须携带方案全文(`record-artifact-add` 用 `file` 或 `content`),纯路径引用仅用于超过 200k 字符快照上限的文件,且须说明理由。\n4. 调用 `alignment-reviewer`。存在需求偏差时先修订方案,直至总体 `PASS`。\n5. 调用 `arch-reviewer`。处理 BLOCKER 和 HIGH;MEDIUM、LOW 逐项修订或记录保留理由,直至总体 `PASS`。\n6. 向用户呈现已保存的方案文档及其可读位置,以及方案摘要、关键取舍、两道审查结论和即将进入的实现轨道——用户在审批前必须能打开完整方案。\n7. 按项目分支规则创建任务分支;完成产出检查后推进,进入暂停点等待用户审批——审批通过即进入实现阶段,确认原文以审批记录留痕。\n\n## 产出检查\n\n推进前确认:\n\n- 技术方案全文可读取、已保存,登记值携带全文(超限时为路径引用且已说明理由);\n- 文档符合 `tech-design` 模板使用规则,最低必备信息完整;\n- 方案默认包含架构图与核心功能流程图,以可渲染的图形呈现且与正文一致;确实不适用时已在“不适用项”写明具体对象和理由;\n- 需求、验收标准和非目标均有对应设计;\n- 按需设计已完成,或在“不适用项”中写明具体对象和理由;\n- `alignment-reviewer` 总体为 `PASS`;\n- `arch-reviewer` 总体为 `PASS`,其余 Finding 已处理或记录保留理由;\n- 审批材料(方案文档、摘要、关键取舍、审查结论、实现轨道)已完整呈现,可支撑暂停点审批;\n- 呈现给用户的方案文档可独立打开阅读,且与当前方案版本一致。\n\n## 任务差异处理\n\n没有独立 PRD 时,以任务需求、验收标准和非目标作为对齐基线。\n\n方案出现需要用户决定的产品方向、破坏性变更、新依赖或重大架构取舍时,先呈现选项、影响和建议。\n\n任一道审查处于 `BLOCKED` 或 `FAIL`,或项目约束与方案无法同时满足时,保留在本节点继续处理。\n\n## 节点记录与推进\n\n记录技术方案产物、方案摘要、关键决策与取舍、完成检查、两道审查的结论与轮次、Finding 处理结果、不适用项及理由,以及呈现给用户的审批材料索引(确认原文由暂停点审批记录承载,须逐字引用用户确认表态、不得转述失真;不双写)。\n\n全部产出检查满足后再推进;创建任务分支后,记录任务与分支的关联。",
|
|
516
|
+
"prompt": "# 技术方案\n\n## 节点职责\n\n将已确认的产品需求转化为可直接指导实现和验证的技术方案,并通过需求对齐审查、架构评审建立实现基线;用户确认由流程暂停点承载。本节点只产出设计,不编写生产代码或测试代码。\n\n## 依赖信息\n\n检查当前任务上下文、需求与验收标准、非目标、PRD、前序节点产物、项目提示词和相关架构资料;已有信息直接复用,缺失时再加载。\n\n存在交互契约产物时(ui 轨或组合任务含 ui 成员),以已确认的交互契约为技术方案的显式输入——实现设计须与契约定案一致。\n\n按名称加载:\n\n- `tech-design` Skill:技术方案设计方法及文档模板;\n- `workflow-discipline` Skill:执行、审查和暂停点纪律。\n\n方案完成后,依次调用:\n\n1. `alignment-reviewer` Agent:检查方案与需求的对齐关系;\n2. `arch-reviewer` Agent:检查方案的架构质量。\n\n## 正向执行流程\n\n1. 确认需求范围和后端、前端或混合轨道,并读取相关项目约束与现有架构。\n2. 使用 `tech-design` Skill 设计方案,并读取其 `references/template.md` 生成技术方案文档;方案默认包含架构图与核心功能流程图——用可渲染的图形语法表达(项目未约定时用 Mermaid),不使用文字罗列代替,且图中模块、步骤、分支在正文均有对应说明。\n3. 项目有文档目录时按项目声明保存方案文件;登记任务产物时必须携带方案全文(`record-artifact-add` 用 `file` 或 `content`),纯路径引用仅用于超过 200k 字符快照上限的文件,且须说明理由。\n4. 调用 `alignment-reviewer`。存在需求偏差时先修订方案,直至总体 `PASS`。\n5. 调用 `arch-reviewer`。处理 BLOCKER 和 HIGH;MEDIUM、LOW 逐项修订或记录保留理由,直至总体 `PASS`。\n6. 向用户呈现已保存的方案文档及其可读位置,以及方案摘要、关键取舍、两道审查结论和即将进入的实现轨道——用户在审批前必须能打开完整方案。\n7. 按项目分支规则创建任务分支;完成产出检查后推进,进入暂停点等待用户审批——审批通过即进入实现阶段,确认原文以审批记录留痕。\n\n## 产出检查\n\n推进前确认:\n\n- 技术方案全文可读取、已保存,登记值携带全文(超限时为路径引用且已说明理由);\n- 文档符合 `tech-design` 模板使用规则,最低必备信息完整;\n- 方案默认包含架构图与核心功能流程图,以可渲染的图形呈现且与正文一致;确实不适用时已在“不适用项”写明具体对象和理由;\n- 需求、验收标准和非目标均有对应设计;\n- 按需设计已完成,或在“不适用项”中写明具体对象和理由;\n- `alignment-reviewer` 总体为 `PASS`;\n- `arch-reviewer` 总体为 `PASS`,其余 Finding 已处理或记录保留理由;\n- 审批材料(方案文档、摘要、关键取舍、审查结论、实现轨道)已完整呈现,可支撑暂停点审批;\n- 呈现给用户的方案文档可独立打开阅读,且与当前方案版本一致。\n\n## 任务差异处理\n\n没有独立 PRD 时,以任务需求、验收标准和非目标作为对齐基线。\n\n方案出现需要用户决定的产品方向、破坏性变更、新依赖或重大架构取舍时,先呈现选项、影响和建议。\n\n任一道审查处于 `BLOCKED` 或 `FAIL`,或项目约束与方案无法同时满足时,保留在本节点继续处理。\n\n## 节点记录与推进\n\n记录技术方案产物、方案摘要、关键决策与取舍、完成检查、两道审查的结论与轮次、Finding 处理结果、不适用项及理由,以及呈现给用户的审批材料索引(确认原文由暂停点审批记录承载,须逐字引用用户确认表态、不得转述失真;不双写)。\n\n全部产出检查满足后再推进;创建任务分支后,记录任务与分支的关联。",
|
|
472
517
|
"skills": [
|
|
473
518
|
{
|
|
474
519
|
"name": "tech-design",
|
|
@@ -480,7 +525,7 @@
|
|
|
480
525
|
}
|
|
481
526
|
],
|
|
482
527
|
"description": "技术方案通用节点",
|
|
483
|
-
"version": "1.
|
|
528
|
+
"version": "1.8.1",
|
|
484
529
|
"toolChecks": [
|
|
485
530
|
{
|
|
486
531
|
"type": "git-branch-exists"
|
|
@@ -520,7 +565,7 @@
|
|
|
520
565
|
"nodeId": "INTERACTION",
|
|
521
566
|
"phase": "entry",
|
|
522
567
|
"track": "ui",
|
|
523
|
-
"prompt": "# 交互设计\n\n## 节点职责\n\n
|
|
568
|
+
"prompt": "# 交互设计\n\n## 节点职责\n\n把已确认需求中用户可见的交互意图,翻译为不依赖具体实现、可逐项核对的交互契约——界面结构与路径总览、状态矩阵、交互契约规则、键盘与焦点、反馈与播报、边界与内容策略、文案逐字稿、令牌绑定、自检清单——经独立对齐核验后,作为技术方案与编码节点的显式输入依赖、视觉验证的验收依据;用户确认由流程暂停点承载。本节点不编写生产代码、不做视觉审美裁定、不做技术选型、不产出可运行原型。\n\n## 依赖信息\n\n先检查当前任务上下文:PRD 或需求描述、验收标准、非目标、前序节点产物,以及项目和所属模块的提示词。加载 `workflow-discipline`;契约完成后调用 `alignment-reviewer` 核验契约与需求的回溯关系。\n\n本节点位于技术方案(DESIGN)之前:定案的交互契约是技术方案的直接输入——技术方案基于已确认的交互契约做实现设计,交互契约未经暂停点确认不得进入技术设计。\n\n形态层映射(Web/桌面/游戏引擎等)以 PRD/需求声明的产品形态与载体为准;载体未明确时先向用户澄清(澄清结论写入节点记录,供技术方案承接),不猜测。\n\n## 正向执行流程\n\n1. 从需求与交互澄清记录提取全部用户可见交互面:每个数据驱动视图、每个可触发元素、每条用户路径。任务无任何用户可见交互面时,判定本节点不适用,在节点记录写明判定与理由后推进。\n2. 逐项产出契约必备项,每项均可逐字核对、不依赖对话上下文:\n - 界面结构与路径总览:布局用文本线框、状态流转用状态图、用户路径用流程图,以可渲染的图形语法内嵌契约文档(项目未约定时用 Mermaid),作为人工审阅的第一入口;\n - 状态矩阵:每个数据驱动视图的 loading / empty / error / disabled 呈现定义与文案;\n - 交互契约规则:触发元素、事件、效果元素、效果类型、效果位置、可逆性、目标状态;\n - 键盘与焦点契约:Tab 顺序、初始焦点、Esc/Enter 语义、disabled 元素可聚焦策略;\n - 反馈与播报机制:每个状态变更选用哪种机制(focus / role=status / live region 等)及理由;\n - 边界与内容策略:最小支持宽度、320px 级重排、超长文本截断、大数据分页/滚动、空值文案;\n - 文案逐字稿:含错误文案与空态文案,逐字给出,不留占位符;\n - 令牌绑定:颜色、间距、圆角、字阶引用设计令牌,禁止裸值;\n - 自检清单:实现者可逐项勾选的验收点清单,覆盖以上全部条款。\n3. 每条交互规则标注回溯来源(需求哪一条 / 澄清问答哪项结论);无法回溯的条目视为新增需求,上升用户裁定后才可写入契约。\n4. 将契约全文保存为项目文档并登记任务产物(携带全文;超限时路径引用须说明理由),向用户呈现契约要点、自检清单核对结果与文档可读位置(作为暂停点审批材料)。\n5. 随后按通用层与形态层组织契约:通用层条款形态无关;形态层条款按已澄清的载体映射(HTML/CSS、UXML/USS、.tscn/Theme 等),映射关系写入契约。\n\n## 产出与检查\n\n推进前确认:\n\n- 全部必备产出(含界面结构与路径总览)齐全,不适用的单项已写明具体对象和理由;\n- 每条交互规则可回溯到需求或澄清记录,无发明需求;\n- 文案全部逐字给出,令牌引用无裸值;\n- 自检清单覆盖全部契约条款;\n- `alignment-reviewer` 对回溯关系的核验为 PASS,Findings 已处理或记录保留理由;\n- 审批材料(契约要点、自检清单核对结果、文档位置)已完整呈现,可支撑暂停点审批;\n- 契约文档已保存登记,呈现给用户的版本与确认版本一致。\n\n## 任务差异处理\n\n无用户可见交互面的任务:判定不适用并记录理由后推进,下游编码节点按「无契约」路径实现。信息不足以产出某项契约时,保留在本节点补齐或向用户澄清,不静默降级;确属可选项的增强(视觉基线、设计文件同步、动效规格)按需说明取舍,不默认纳入。\n\n可运行草图:默认不产出。用户点名要求审查辅助时,按当前版本契约生成静态草图到工作区 `temp/` 供用户在浏览器查看;草图是契约的派生视图而非第二设计来源——契约发生任何修订即作废重生成并重新呈现,草图页首声明「非契约正文,与契约不一致时以契约文档为准」,草图暴露的契约缺口只能回写契约修正,不在草图上直接改。草图不写入契约文档、不登记为任务产物,节点推进后即完成使命。\n\n## 节点记录与推进\n\n将契约文档产物与引用、必备产出核对结果、不适用判定及理由(如有)、草图辅助审查事实(如有,含生成路径与派生版本对应关系)、`alignment-reviewer` 结论与轮次、呈现给用户的审批材料索引写入当前节点记录(确认原文由暂停点审批记录承载,须逐字引用用户确认表态、不得转述失真;不双写),完成产出检查后推进下一节点。",
|
|
524
569
|
"skills": [
|
|
525
570
|
{
|
|
526
571
|
"name": "workflow-discipline",
|
|
@@ -528,7 +573,7 @@
|
|
|
528
573
|
}
|
|
529
574
|
],
|
|
530
575
|
"description": "交互设计通用节点",
|
|
531
|
-
"version": "1.
|
|
576
|
+
"version": "1.2.0",
|
|
532
577
|
"agents": [
|
|
533
578
|
{
|
|
534
579
|
"name": "alignment-reviewer",
|
|
@@ -542,7 +587,7 @@
|
|
|
542
587
|
"nodeId": "CODE_BACKEND",
|
|
543
588
|
"phase": "track",
|
|
544
589
|
"track": "backend",
|
|
545
|
-
"prompt": "# 后端编码\n\n## 节点职责\n\n依据已确认的需求和技术方案完成后端生产代码,并通过项目静态检查和独立代码评审。测试设计、测试代码与测试执行由后续节点负责。\n\n## 依赖信息\n\n
|
|
590
|
+
"prompt": "# 后端编码\n\n## 节点职责\n\n依据已确认的需求和技术方案完成后端生产代码,并通过项目静态检查和独立代码评审。测试设计、测试代码与测试执行由后续节点负责。\n\n## 依赖信息\n\n先检查当前任务上下文,读取需求、验收标准、非目标、技术方案、既有决策以及项目和所属模块的提示词。任务含界面交付(组合任务含 ui 成员或交互设计节点已产出契约)时,读取已确认的交互契约,以契约定型 API 形态、字段语义与反馈行为,不自行猜测交互形态;确与后端约束冲突时说明冲突点并暂停上升,不单方面改约。加载 `coding-standards`、`workflow-discipline`,并按实际技术栈读取 `coding-standards` 对应 reference;调用独立 `code-reviewer` 评审实现。\n\n缺少实现所必需的需求、设计或项目约束时,先从任务上下文和仓库现状补齐;仍无法确定关键行为时,说明缺失信息并暂停,不猜测实现。\n\n## 执行流程\n\n1. 将需求、验收标准和技术方案整理为可核对的实现项,明确行为边界、错误处理、状态变化和副作用。\n2. 调查相关入口、调用链、数据模型、持久化、配置和既有接口,确认真实代码契约与项目惯例。\n3. 按最小充分范围实现生产代码,遵循项目分层和编码规范;只修改与本任务有关的生产代码,不修改测试、fixture 或其他验证代码,不清除无关注释。\n4. 处理配置、存储、兼容性、权限、并发和资源生命周期影响;不涉及的项目无需制造改动。\n5. 按项目声明执行适用的类型检查、编译、构建和静态分析,并保留可追溯结果。测试命令留给后续测试节点。\n6. 将需求、技术方案、项目约束和代码变更位置交给 `code-reviewer` 独立评审,不提供主会话结论或预期结果。修复 BLOCKER 和 HIGH Findings 后重新评审,直至获得 PASS;MEDIUM、LOW 逐项处理或记录保留理由。\n\n## 产出与检查\n\n推进前确认:\n\n- 需求、设计与生产实现可以逐项对应;\n- 生产代码完成,未修改验证代码,未清除无关注释;\n- 配置、存储、兼容性和其他副作用已正确处理;\n- 适用的静态检查通过并留有结果;\n- `code-reviewer` 最终结论为 PASS,所有 Findings 均已处理或说明;\n- 生产代码和必要说明已形成可引用产物。\n\n## 任务差异处理\n\n新增依赖、破坏性变更、数据迁移、公开契约变化或真实范围扩张需要用户决定时,先呈现必要性和影响再暂停。某项检查因技术栈或任务性质不适用时,说明理由,不得静默跳过;执行障碍和评审修订按 `workflow-discipline` 处理。\n\n## 节点记录与推进\n\n将实现摘要、主要变更、静态检查结果、代码产物引用、关键决策、未适用项及理由、`code-reviewer` 结论与 Findings 处理情况写入当前节点记录。完成上述检查后推进下一节点。",
|
|
546
591
|
"skills": [
|
|
547
592
|
{
|
|
548
593
|
"name": "coding-standards",
|
|
@@ -554,7 +599,7 @@
|
|
|
554
599
|
}
|
|
555
600
|
],
|
|
556
601
|
"description": "后端编码通用节点",
|
|
557
|
-
"version": "1.5.
|
|
602
|
+
"version": "1.5.1",
|
|
558
603
|
"toolChecks": [
|
|
559
604
|
{
|
|
560
605
|
"type": "git-worktree-clean"
|