@siming-org/flow-nodes 1.17.0 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @siming-org/flow-nodes
2
2
 
3
- Siming 官方 Flow 节点库:通过 npm 分发 23 个可复用 NodePreset、3 套工作流组合,以及节点运行所需的安装闭包——4 个 Skill(workflow-discipline、bugfix-root-cause-verification、tech-design、coding-standards)、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 视觉)。
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(4 个);
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`(4)、`source/agents/<name>.json`(8)、`source/model-aliases/<code>.json`(3)、`source/compositions/<name>.json`(3):每资产一文件,内容原样。
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.17.0",
4
- "description": "Official Siming flow library — 23 reusable DAG node presets, 3 workflow compositions, and their installation closure: 4 Skills, 8 Agents, 3 Model Aliases",
3
+ "version": "1.19.0",
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,7 +1,7 @@
1
1
  {
2
2
  "formatVersion": "1.2",
3
3
  "name": "@siming-org/flow-nodes",
4
- "version": "1.17.0",
4
+ "version": "1.19.0",
5
5
  "compositions": [
6
6
  {
7
7
  "name": "full-workflow",
@@ -212,9 +212,9 @@
212
212
  {
213
213
  "name": "workflow-discipline",
214
214
  "description": "DAG 节点执行、角色分离、授权、暂停点与任务边界纪律",
215
- "content": "# workflow-discipline\n\n保证所有 DAG 节点以一致方式确定工作边界、分离执行与验证、处理授权与暂停点,并在完成判定满足后安全推进。\n\n## 铁律\n\n本 Skill 是保障 siming 流程正确执行的基础资产。执行会话加载本 Skill 后,任何上下文压缩操作一律不得压缩本 Skill 正文——它是后续所有节点判定与推进的准绳,必须完整留存在上下文中。\n\n执行会话只专注当前任务本身,不关注执行效率等其他因素;节点提示词、skill、委派 brief 中不得出现任何让 AI 转移任务注意力的描述。\n\n## 适用边界\n\n- 所有节点执行者都应用本 Skill;任务简单、用户催促或改动很小,不改变节点步骤、质量门和完成标准。\n- 本 Skill规定跨节点通用纪律,不替代当前节点提示词中的职责、产出、检查项和具体执行方法。\n- 当前节点提示词与本 Skill共同生效;发现冲突时不得自行忽略任一约束,应先按权限和任务边界判断,无法收敛再向用户呈现冲突。\n\n## 节点执行流程\n\n1. **确认当前边界**:读取任务上下文、当前节点职责、所需产出、完成判定、暂停点和项目约束。执行 git 操作前确认当前分支及项目声明的分支模型。\n2. **确定执行角色**:设计文档和编码由主会话完成;测试命令由 `test-executor` 执行;节点要求独立审查时,由不同 session 的只读 Verifier 执行。\n3. **完成节点工作**:只实施当前节点和已确认任务范围内的工作。发现死代码删留、顺手重构、范围扩张或其他范围外动作时,将其作为独立决策呈现给用户,不自行纳入。\n4. **执行独立验证**:Worker 与 Verifier 必须分离。Verifier 只接收评审目标与材料(评审对象路径、参照位置、已认定非问题的历史事项),不接收设计结论、决策理由或“用户已确认”等预设结论。\n5. **处理审查结果**:审查是否通过,以 Verifier 本次输出为准。逐条修复 finding,或记录不修复理由;修复阻塞问题后重新审查。交互式审查最多 3 轮,连续 3 轮仍未通过时,保留在当前节点并请用户决定。\n6. **检查并记录**:逐项核对当前节点的完成判定,记录实际产出、检查结果、评审结论与轮次、关键决定、不适用项及其理由。\n7. **提交节点成果**:完成判定全部满足后、推进节点前,检查工作树和 diff。存在本节点产生的应提交改动时,只纳入当前任务与当前节点范围内的代码、测试、文档等成果并创建 git commit;不得混入无关改动,也不得用空提交代替成果提交。提交失败或本节点应提交改动仍有遗漏时,留在当前节点处理。\n8. **推进节点**:推进前先核对当前节点资料包的检查项——aiChecks 逐项自检并经 record-check-add 留痕(结论含核对对象与结果,不适用须记理由,refId 对应检查项 id);随后执行 task advance,门禁打回时读失败原因与修复指引,处理完成后重推;仅用户明确指示时才可用 --force --force-reason(附用户原文),不得自行决定。没有应提交改动的纯审查、纯审批节点直接推进,不制造空提交。\n\n## 执行与质量边界\n\n- Track 编码节点只修改生产代码,不修改测试或其他验证代码;测试节点不得以“现有测试已经覆盖”代替逐项验证。\n- 本任务改动导致的测试失败必须完成根因调查并处理,不得标记为“既有问题”后拒绝处理,也不得通过删除测试、放宽断言或添加 skip 制造通过。\n- 预算或时间不足是暂停并上升决策的理由,不是降低质量门的理由。\n- 已知问题必须逐条判断是否影响功能完整性;影响验收的,在任务结束前处理。只有用户明确接受风险并留下原文记录,才可作为例外。\n- 增量测试或增量评审只能缩小经过证据证明的受影响范围,不得降低原有测试、审查和通过标准。\n\n## 委派纪律\n\n- Worker 与 Verifier 使用不同 session;Verifier 只读,不修改代码或文档,不接管主会话协调。\n- 增量复审聚焦本轮改动及其影响面,但沿用完整审查标准。\n- 委派 prompt 只提供评审目标与原始材料:目标 = 评什么、不评什么、主会话已认定不属于问题的历史事项;材料 = 原始需求、技术方案、代码等任务信息与信息地址(路径 / 命令 / 文档位置),怎么使用由 subagent 自行决策。目标必须精准——该评的项必须列全(不缺),不得把无关或大范围扫描类目标并入本次委派(不扩散);评估范围由目标层锁定,评审不自行扩张到目标之外。\n- 执行策略全部由 subagent 自行决策——如何分析、如何组织报告、按什么步骤工作、何时结束,均不在 brief 中指定;主会话不设预算、轮次、时限,不给检索范围限制,不指定评估方式、不追加取证要求、不扩张评估范围;发现 agent 定义有缺陷时修正定义本身,不以委派限制替代。\n- 需要评估时按角色选择对应 reviewer,不以主会话自评替代独立评估;确无匹配 agent 时上升用户。\n- 主会话与 reviewer 结论出现明显问题或冲突时,上升人类决策;流程本身有问题时,通知人类调整流程。\n- subagent 完成指定产出后立即结束;审查修订、重新委派和多轮协调由主会话负责。\n\n## 授权与暂停点\n\n- **决策授权**只覆盖具体方案或风险选择,不自动跳过审查、复审、测试或其他流程步骤。\n- **流程授权**只覆盖用户明确指名跳过的步骤,不得扩展到其他质量门。\n- “跳过人工审批”只跳过对应的用户暂停点,不等于跳过自动审查或验证。\n- 暂停点只有用户明确肯定当前待确认内容时才算通过,并记录用户原文。用户的提问、评估、条件句或新诉求不是确认;应先回应并继续等待明确结论。\n\n## 任务完成边界\n\n- 当前节点全部完成判定满足,且本节点产生的应提交成果已经提交后,才能推进到下一节点;单项测试通过、核心代码完成、存在未提交成果或分支合并,都不能代替节点完成。没有应提交改动的节点不制造空提交。\n- 节点完成不等于任务完成。架构信息归档完成,或该步骤经用户明确授权跳过并留下记录后,任务才进入终态。\n- 任务终止前,不推荐、不询问、不切换到下一个任务;终止后再输出完整任务总结。",
215
+ "content": "# workflow-discipline\n\n保证所有 DAG 节点以一致方式确定工作边界、分离执行与验证、处理授权与暂停点,并在完成判定满足后安全推进。\n\n## 铁律\n\n本 Skill 是保障 siming 流程正确执行的基础资产。执行会话加载本 Skill 后,任何上下文压缩操作一律不得压缩本 Skill 正文——它是后续所有节点判定与推进的准绳,必须完整留存在上下文中。\n\n执行会话只专注当前任务本身,不关注执行效率等其他因素;节点提示词、skill、委派 brief 中不得出现任何让 AI 转移任务注意力的描述。\n\n## 适用边界\n\n- 所有节点执行者都应用本 Skill;任务简单、用户催促或改动很小,不改变节点步骤、质量门和完成标准。\n- 本 Skill规定跨节点通用纪律,不替代当前节点提示词中的职责、产出、检查项和具体执行方法。\n- 当前节点提示词与本 Skill共同生效;发现冲突时不得自行忽略任一约束,应先按权限和任务边界判断,无法收敛再向用户呈现冲突。\n\n## 节点执行流程\n\n1. **确认当前边界**:读取任务上下文、当前节点职责、所需产出、完成判定、暂停点和项目约束。执行 git 操作前确认当前分支及项目声明的分支模型。\n2. **确定执行角色**:设计文档和编码由主会话完成;测试命令由 `test-executor` 执行;节点要求独立审查时,由不同 session 的只读 Verifier 执行。\n3. **完成节点工作**:只实施当前节点和已确认任务范围内的工作。发现死代码删留、顺手重构、范围扩张或其他范围外动作时,将其作为独立决策呈现给用户,不自行纳入。\n4. **执行独立验证**:Worker 与 Verifier 必须分离。Verifier 只接收评审目标与材料(评审对象路径、参照位置、已认定非问题的历史事项),不接收设计结论、决策理由或“用户已确认”等预设结论。\n5. **处理审查结果**:审查是否通过,以 Verifier 本次输出为准。逐条修复 finding,或记录不修复理由;修复阻塞问题后重新审查。交互式审查最多 3 轮,连续 3 轮仍未通过时,保留在当前节点并请用户决定。\n6. **检查并记录**:逐项核对当前节点的完成判定,记录实际产出、检查结果、评审结论与轮次、关键决定、不适用项及其理由。\n7. **提交节点成果**:完成判定全部满足后、推进节点前,检查工作树和 diff。存在本节点产生的应提交改动时,只纳入当前任务与当前节点范围内的代码、测试、文档等成果并创建 git commit;不得混入无关改动,也不得用空提交代替成果提交。提交失败或本节点应提交改动仍有遗漏时,留在当前节点处理。\n8. **推进节点**:推进前先核对当前节点资料包的检查项——aiChecks 逐项自检并经 record-check-add 留痕(结论含核对对象与结果,不适用须记理由,refId 对应检查项 id);随后执行 task advance,门禁打回时读失败原因与修复指引,处理完成后重推;仅用户明确指示时才可用 --force --force-reason(附用户原文),不得自行决定。没有应提交改动的纯审查、纯审批节点直接推进,不制造空提交。\n\n## 执行与质量边界\n\n- Track 编码节点只修改生产代码,不修改测试或其他验证代码;测试节点不得以“现有测试已经覆盖”代替逐项验证。\n- 本任务改动导致的测试失败必须完成根因调查并处理,不得标记为“既有问题”后拒绝处理,也不得通过删除测试、放宽断言或添加 skip 制造通过。\n- 预算或时间不足是暂停并上升决策的理由,不是降低质量门的理由。\n- 已知问题必须逐条判断是否影响功能完整性;影响验收的,在任务结束前处理。只有用户明确接受风险并留下原文记录,才可作为例外。\n- 增量测试或增量评审只能缩小经过证据证明的受影响范围,不得降低原有测试、审查和通过标准。\n\n## 委派纪律\n\n- Worker 与 Verifier 使用不同 session;Verifier 只读,不修改代码或文档,不接管主会话协调。\n- 增量复审聚焦本轮改动及其影响面,但沿用完整审查标准。\n- 多轮复审优先在同一 reviewer 会话内续聊(宿主支持会话续用时传会话标识,reviewer 已持有上轮评审上下文);换新会话时,重审 prompt 随附上轮全量 Findings 与处置状态(已修复待验证 / 记录保留理由),reviewer 只重验本轮修订触及的条目与受影响面,未触及项沿用上轮结论;每轮报告保持全量 Findings 快照,已解决的标记关闭、不静默丢弃,是否处理由主会话决策。\n- 委派 prompt 只提供评审目标与原始材料:目标 = 评什么、不评什么、主会话已认定不属于问题的历史事项;材料 = 原始需求、技术方案、代码等任务信息与信息地址(路径 / 命令 / 文档位置),怎么使用由 subagent 自行决策。目标必须精准——该评的项必须列全(不缺),不得把无关或大范围扫描类目标并入本次委派(不扩散);评估范围由目标层锁定,评审不自行扩张到目标之外。\n- 执行策略全部由 subagent 自行决策——如何分析、如何组织报告、按什么步骤工作、何时结束,均不在 brief 中指定;主会话不设预算、轮次、时限,不给检索范围限制,不指定评估方式、不追加取证要求、不扩张评估范围;发现 agent 定义有缺陷时修正定义本身,不以委派限制替代。\n- 需要评估时按角色选择对应 reviewer,不以主会话自评替代独立评估;确无匹配 agent 时上升用户。\n- 主会话与 reviewer 结论出现明显问题或冲突时,上升人类决策;流程本身有问题时,通知人类调整流程。\n- subagent 完成指定产出后立即结束;审查修订、重新委派和多轮协调由主会话负责。\n\n## 授权与暂停点\n\n- **决策授权**只覆盖具体方案或风险选择,不自动跳过审查、复审、测试或其他流程步骤。\n- **流程授权**只覆盖用户明确指名跳过的步骤,不得扩展到其他质量门。\n- “跳过人工审批”只跳过对应的用户暂停点,不等于跳过自动审查或验证。\n- 暂停点只有用户明确肯定当前待确认内容时才算通过,并记录用户原文。用户的提问、评估、条件句或新诉求不是确认;应先回应并继续等待明确结论。\n\n## 任务完成边界\n\n- 当前节点全部完成判定满足,且本节点产生的应提交成果已经提交后,才能推进到下一节点;单项测试通过、核心代码完成、存在未提交成果或分支合并,都不能代替节点完成。没有应提交改动的节点不制造空提交。\n- 节点完成不等于任务完成。架构信息归档完成,或该步骤经用户明确授权跳过并留下记录后,任务才进入终态。\n- 任务终止前,不推荐、不询问、不切换到下一个任务;终止后再输出完整任务总结。",
216
216
  "category": "process",
217
- "version": "1.4.0",
217
+ "version": "1.5.0",
218
218
  "references": []
219
219
  },
220
220
  {
@@ -290,6 +290,47 @@
290
290
  "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
291
  }
292
292
  ]
293
+ },
294
+ {
295
+ "name": "brainstorming",
296
+ "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.",
297
+ "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",
298
+ "category": "process",
299
+ "version": "1.0.0",
300
+ "references": [
301
+ {
302
+ "path": "visual-companion.md",
303
+ "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"
304
+ },
305
+ {
306
+ "path": "spec-document-reviewer-prompt.md",
307
+ "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"
308
+ },
309
+ {
310
+ "path": "scripts/frame-template.html",
311
+ "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"
312
+ },
313
+ {
314
+ "path": "scripts/helper.js",
315
+ "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"
316
+ },
317
+ {
318
+ "path": "scripts/server.cjs",
319
+ "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=&hellip;</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, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;');\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"
320
+ },
321
+ {
322
+ "path": "scripts/start-server.sh",
323
+ "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"
324
+ },
325
+ {
326
+ "path": "scripts/stop-server.sh",
327
+ "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"
328
+ },
329
+ {
330
+ "path": "LICENSE",
331
+ "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"
332
+ }
333
+ ]
293
334
  }
294
335
  ],
295
336
  "agents": [
@@ -419,7 +460,7 @@
419
460
  "skills": [
420
461
  {
421
462
  "name": "workflow-discipline",
422
- "version": "1.4.0"
463
+ "version": "1.5.0"
423
464
  }
424
465
  ],
425
466
  "description": "PRD 设计通用节点",
@@ -441,7 +482,7 @@
441
482
  "skills": [
442
483
  {
443
484
  "name": "workflow-discipline",
444
- "version": "1.4.0"
485
+ "version": "1.5.0"
445
486
  }
446
487
  ],
447
488
  "description": "分支对齐通用节点",
@@ -476,7 +517,7 @@
476
517
  },
477
518
  {
478
519
  "name": "workflow-discipline",
479
- "version": "1.4.0"
520
+ "version": "1.5.0"
480
521
  }
481
522
  ],
482
523
  "description": "技术方案通用节点",
@@ -524,7 +565,7 @@
524
565
  "skills": [
525
566
  {
526
567
  "name": "workflow-discipline",
527
- "version": "1.4.0"
568
+ "version": "1.5.0"
528
569
  }
529
570
  ],
530
571
  "description": "交互设计通用节点",
@@ -550,7 +591,7 @@
550
591
  },
551
592
  {
552
593
  "name": "workflow-discipline",
553
- "version": "1.4.0"
594
+ "version": "1.5.0"
554
595
  }
555
596
  ],
556
597
  "description": "后端编码通用节点",
@@ -587,7 +628,7 @@
587
628
  },
588
629
  {
589
630
  "name": "workflow-discipline",
590
- "version": "1.4.0"
631
+ "version": "1.5.0"
591
632
  }
592
633
  ],
593
634
  "description": "前端编码通用节点",
@@ -620,7 +661,7 @@
620
661
  "skills": [
621
662
  {
622
663
  "name": "workflow-discipline",
623
- "version": "1.4.0"
664
+ "version": "1.5.0"
624
665
  }
625
666
  ],
626
667
  "description": "视觉验证通用节点",
@@ -653,7 +694,7 @@
653
694
  "skills": [
654
695
  {
655
696
  "name": "workflow-discipline",
656
- "version": "1.4.0"
697
+ "version": "1.5.0"
657
698
  }
658
699
  ],
659
700
  "description": "单元测试设计通用节点",
@@ -679,7 +720,7 @@
679
720
  },
680
721
  {
681
722
  "name": "workflow-discipline",
682
- "version": "1.4.0"
723
+ "version": "1.5.0"
683
724
  }
684
725
  ],
685
726
  "description": "单元测试开发通用节点",
@@ -722,7 +763,7 @@
722
763
  "skills": [
723
764
  {
724
765
  "name": "workflow-discipline",
725
- "version": "1.4.0"
766
+ "version": "1.5.0"
726
767
  }
727
768
  ],
728
769
  "description": "前端单元测试设计通用节点(用例清单 + 覆盖目标对应项目覆盖率门)",
@@ -748,7 +789,7 @@
748
789
  },
749
790
  {
750
791
  "name": "workflow-discipline",
751
- "version": "1.4.0"
792
+ "version": "1.5.0"
752
793
  }
753
794
  ],
754
795
  "description": "前端单元测试开发通用节点(按清单实现 + 测试与覆盖率门通过 + 独立评审)",
@@ -791,7 +832,7 @@
791
832
  "skills": [
792
833
  {
793
834
  "name": "workflow-discipline",
794
- "version": "1.4.0"
835
+ "version": "1.5.0"
795
836
  }
796
837
  ],
797
838
  "description": "端到端测试设计通用节点",
@@ -828,7 +869,7 @@
828
869
  },
829
870
  {
830
871
  "name": "workflow-discipline",
831
- "version": "1.4.0"
872
+ "version": "1.5.0"
832
873
  }
833
874
  ],
834
875
  "description": "端到端测试开发通用节点",
@@ -871,7 +912,7 @@
871
912
  "skills": [
872
913
  {
873
914
  "name": "workflow-discipline",
874
- "version": "1.4.0"
915
+ "version": "1.5.0"
875
916
  }
876
917
  ],
877
918
  "description": "集成验证通用节点",
@@ -920,7 +961,7 @@
920
961
  "skills": [
921
962
  {
922
963
  "name": "workflow-discipline",
923
- "version": "1.4.0"
964
+ "version": "1.5.0"
924
965
  }
925
966
  ],
926
967
  "description": "发布验收通用节点",
@@ -957,7 +998,7 @@
957
998
  "skills": [
958
999
  {
959
1000
  "name": "workflow-discipline",
960
- "version": "1.4.0"
1001
+ "version": "1.5.0"
961
1002
  }
962
1003
  ],
963
1004
  "description": "架构信息归档通用节点",
@@ -996,7 +1037,7 @@
996
1037
  "skills": [
997
1038
  {
998
1039
  "name": "workflow-discipline",
999
- "version": "1.4.0"
1040
+ "version": "1.5.0"
1000
1041
  }
1001
1042
  ],
1002
1043
  "description": "轻量设计通用节点",
@@ -1013,7 +1054,7 @@
1013
1054
  "skills": [
1014
1055
  {
1015
1056
  "name": "workflow-discipline",
1016
- "version": "1.4.0"
1057
+ "version": "1.5.0"
1017
1058
  }
1018
1059
  ],
1019
1060
  "description": "快速设计通用节点(AI 评审 + 人工确认)",
@@ -1039,7 +1080,7 @@
1039
1080
  },
1040
1081
  {
1041
1082
  "name": "workflow-discipline",
1042
- "version": "1.4.0"
1083
+ "version": "1.5.0"
1043
1084
  }
1044
1085
  ],
1045
1086
  "description": "后端编码与测试一体通用节点(测试全绿 + 代码评审)",
@@ -1069,7 +1110,7 @@
1069
1110
  },
1070
1111
  {
1071
1112
  "name": "workflow-discipline",
1072
- "version": "1.4.0"
1113
+ "version": "1.5.0"
1073
1114
  }
1074
1115
  ],
1075
1116
  "description": "前端编码与测试一体通用节点(测试全绿 + 视觉验证 + 代码评审)",
@@ -1099,7 +1140,7 @@
1099
1140
  "skills": [
1100
1141
  {
1101
1142
  "name": "workflow-discipline",
1102
- "version": "1.4.0"
1143
+ "version": "1.5.0"
1103
1144
  }
1104
1145
  ],
1105
1146
  "description": "调研范围确认通用节点",
@@ -1116,7 +1157,7 @@
1116
1157
  "skills": [
1117
1158
  {
1118
1159
  "name": "workflow-discipline",
1119
- "version": "1.4.0"
1160
+ "version": "1.5.0"
1120
1161
  }
1121
1162
  ],
1122
1163
  "description": "调研执行通用节点",
@@ -1133,7 +1174,7 @@
1133
1174
  "skills": [
1134
1175
  {
1135
1176
  "name": "workflow-discipline",
1136
- "version": "1.4.0"
1177
+ "version": "1.5.0"
1137
1178
  }
1138
1179
  ],
1139
1180
  "description": "调研验收通用节点",