@relipa/ai-flow-kit 0.1.1 → 0.1.2-beta.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.
Files changed (253) hide show
  1. package/README.md +0 -0
  2. package/bin/aiflow.js +55 -2
  3. package/bin/ak.js +0 -0
  4. package/custom/mcp-presets/README.md +204 -237
  5. package/custom/mcp-presets/backlog.json +0 -0
  6. package/custom/mcp-presets/figma-desktop.json +0 -0
  7. package/custom/mcp-presets/figma.json +0 -0
  8. package/custom/mcp-presets/gitnexus.json +0 -0
  9. package/custom/mcp-presets/google-sheets.json +0 -0
  10. package/custom/mcp-presets/jira.json +0 -0
  11. package/custom/prompts/bug-fix.md +0 -0
  12. package/custom/prompts/feature.md +0 -0
  13. package/custom/prompts/investigation.md +0 -0
  14. package/custom/rules/code-style.md +0 -0
  15. package/custom/rules/java/code-style.md +0 -0
  16. package/custom/rules/java/naming.md +0 -0
  17. package/custom/rules/java/review-checklist.md +0 -0
  18. package/custom/rules/java/spring-boot-examples.md +0 -0
  19. package/custom/rules/javascript/code-style.md +0 -0
  20. package/custom/rules/javascript/naming.md +0 -0
  21. package/custom/rules/ml-conventions.md +88 -0
  22. package/custom/rules/ml-review-checklist.md +14 -0
  23. package/custom/rules/naming.md +0 -0
  24. package/custom/rules/php/code-style.md +0 -0
  25. package/custom/rules/php/naming.md +0 -0
  26. package/custom/rules/project-conventions.md +0 -0
  27. package/custom/rules/review-checklist.md +0 -0
  28. package/custom/skills/deploy-model/SKILL.md +90 -0
  29. package/custom/skills/design-experiment/SKILL.md +88 -0
  30. package/custom/skills/evaluate-model/SKILL.md +93 -0
  31. package/custom/skills/explore-data/SKILL.md +87 -0
  32. package/custom/skills/figma-to-component/SKILL.md +0 -0
  33. package/custom/skills/frame-ml-problem/SKILL.md +88 -0
  34. package/custom/skills/generate-spec/SKILL.md +0 -0
  35. package/custom/skills/impact-analysis/SKILL.md +0 -0
  36. package/custom/skills/improve-algorithm/SKILL.md +74 -0
  37. package/custom/skills/investigate-bug/SKILL.md +0 -0
  38. package/custom/skills/read-study-requirement/SKILL.md +0 -0
  39. package/custom/skills/report-customer/SKILL.md +0 -0
  40. package/custom/skills/review-plan/SKILL.md +0 -0
  41. package/custom/skills/train-model/SKILL.md +78 -0
  42. package/custom/templates/laravel.md +0 -0
  43. package/custom/templates/nestjs.md +0 -0
  44. package/custom/templates/nextjs.md +0 -0
  45. package/custom/templates/nodejs-express.md +0 -0
  46. package/custom/templates/php-plain.md +0 -0
  47. package/custom/templates/php.md +0 -0
  48. package/custom/templates/python-django.md +0 -0
  49. package/custom/templates/python-fastapi.md +0 -0
  50. package/custom/templates/python-ml.md +273 -0
  51. package/custom/templates/python.md +0 -0
  52. package/custom/templates/reactjs.md +0 -0
  53. package/custom/templates/shared/gate-workflow.md +0 -0
  54. package/custom/templates/shared/ml-gate-workflow.md +103 -0
  55. package/custom/templates/spring-boot.md +0 -0
  56. package/custom/templates/tools/claude.md +0 -0
  57. package/custom/templates/tools/copilot.md +0 -0
  58. package/custom/templates/tools/cursor.md +0 -0
  59. package/custom/templates/tools/gemini.md +0 -0
  60. package/custom/templates/tools/generic.md +0 -0
  61. package/custom/templates/vue-nuxt.md +0 -0
  62. package/docs/common/AIFLOW.md +512 -512
  63. package/docs/common/CHANGELOG.md +0 -0
  64. package/docs/common/QUICK_START.md +0 -0
  65. package/docs/common/ai-integration.md +0 -0
  66. package/docs/common/cli-reference.md +0 -0
  67. package/docs/common/configuration.md +0 -0
  68. package/docs/common/getting-started.md +0 -0
  69. package/docs/common/troubleshooting.md +0 -0
  70. package/docs/common/workflows/bug-fix.md +0 -0
  71. package/docs/common/workflows/feature.md +0 -0
  72. package/docs/common/workflows/figma.md +0 -0
  73. package/docs/common/workflows/impact-analysis.md +0 -0
  74. package/docs/common/workflows/investigation.md +0 -0
  75. package/docs/common/workflows/refactor.md +0 -0
  76. package/docs/project/ARCHITECTURE.md +0 -0
  77. package/index.js +0 -0
  78. package/package.json +1 -1
  79. package/scripts/checkpoint.js +0 -0
  80. package/scripts/config.js +0 -0
  81. package/scripts/context.js +0 -0
  82. package/scripts/create-score-excel.js +0 -0
  83. package/scripts/detect.js +239 -239
  84. package/scripts/doctor.js +192 -218
  85. package/scripts/gitnexus-worker.js +0 -0
  86. package/scripts/guide.js +0 -0
  87. package/scripts/hooks/block-git-write.js +0 -0
  88. package/scripts/hooks/session-start.js +0 -0
  89. package/scripts/hooks/session-stop.js +0 -0
  90. package/scripts/init.js +1112 -1009
  91. package/scripts/link-resolver.js +0 -0
  92. package/scripts/memory.js +0 -0
  93. package/scripts/prompt.js +538 -538
  94. package/scripts/remove.js +0 -0
  95. package/scripts/task.js +546 -546
  96. package/scripts/telemetry/cli.js +0 -0
  97. package/scripts/telemetry/config.js +0 -0
  98. package/scripts/telemetry/crypto.js +0 -0
  99. package/scripts/telemetry/flush.js +0 -0
  100. package/scripts/telemetry/record.js +0 -0
  101. package/scripts/update.js +10 -7
  102. package/scripts/use.js +33 -12
  103. package/scripts/validate.js +0 -0
  104. package/upstream/.claude-plugin/marketplace.json +0 -0
  105. package/upstream/.claude-plugin/plugin.json +0 -0
  106. package/upstream/.codex/INSTALL.md +0 -0
  107. package/upstream/.cursor-plugin/plugin.json +0 -0
  108. package/upstream/.gitattributes +0 -0
  109. package/upstream/.github/FUNDING.yml +0 -0
  110. package/upstream/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  111. package/upstream/.github/ISSUE_TEMPLATE/config.yml +0 -0
  112. package/upstream/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  113. package/upstream/.github/ISSUE_TEMPLATE/platform_support.md +0 -0
  114. package/upstream/.github/PULL_REQUEST_TEMPLATE.md +0 -0
  115. package/upstream/.opencode/INSTALL.md +0 -0
  116. package/upstream/.opencode/plugins/superpowers.js +0 -0
  117. package/upstream/.version-bump.json +0 -0
  118. package/upstream/AGENTS.md +0 -0
  119. package/upstream/CHANGELOG.md +0 -0
  120. package/upstream/CLAUDE.md +0 -0
  121. package/upstream/CODE_OF_CONDUCT.md +0 -0
  122. package/upstream/GEMINI.md +0 -0
  123. package/upstream/LICENSE +0 -0
  124. package/upstream/README.md +0 -0
  125. package/upstream/RELEASE-NOTES.md +0 -0
  126. package/upstream/agents/code-reviewer.md +0 -0
  127. package/upstream/commands/brainstorm.md +0 -0
  128. package/upstream/commands/execute-plan.md +0 -0
  129. package/upstream/commands/write-plan.md +0 -0
  130. package/upstream/docs/README.codex.md +0 -0
  131. package/upstream/docs/README.opencode.md +0 -0
  132. package/upstream/docs/plans/2025-11-22-opencode-support-design.md +0 -0
  133. package/upstream/docs/plans/2025-11-22-opencode-support-implementation.md +0 -0
  134. package/upstream/docs/plans/2025-11-28-skills-improvements-from-user-feedback.md +0 -0
  135. package/upstream/docs/plans/2026-01-17-visual-brainstorming.md +0 -0
  136. package/upstream/docs/superpowers/plans/2026-01-22-document-review-system.md +0 -0
  137. package/upstream/docs/superpowers/plans/2026-02-19-visual-brainstorming-refactor.md +0 -0
  138. package/upstream/docs/superpowers/plans/2026-03-11-zero-dep-brainstorm-server.md +0 -0
  139. package/upstream/docs/superpowers/plans/2026-03-23-codex-app-compatibility.md +0 -0
  140. package/upstream/docs/superpowers/specs/2026-01-22-document-review-system-design.md +0 -0
  141. package/upstream/docs/superpowers/specs/2026-02-19-visual-brainstorming-refactor-design.md +0 -0
  142. package/upstream/docs/superpowers/specs/2026-03-11-zero-dep-brainstorm-server-design.md +0 -0
  143. package/upstream/docs/superpowers/specs/2026-03-23-codex-app-compatibility-design.md +0 -0
  144. package/upstream/docs/testing.md +0 -0
  145. package/upstream/docs/windows/polyglot-hooks.md +0 -0
  146. package/upstream/gemini-extension.json +0 -0
  147. package/upstream/hooks/hooks-cursor.json +0 -0
  148. package/upstream/hooks/hooks.json +0 -0
  149. package/upstream/hooks/run-hook.cmd +0 -0
  150. package/upstream/hooks/session-start +0 -0
  151. package/upstream/package.json +0 -0
  152. package/upstream/scripts/bump-version.sh +0 -0
  153. package/upstream/skills/brainstorming/SKILL.md +0 -0
  154. package/upstream/skills/brainstorming/scripts/frame-template.html +0 -0
  155. package/upstream/skills/brainstorming/scripts/helper.js +0 -0
  156. package/upstream/skills/brainstorming/scripts/server.cjs +0 -0
  157. package/upstream/skills/brainstorming/scripts/start-server.sh +0 -0
  158. package/upstream/skills/brainstorming/scripts/stop-server.sh +0 -0
  159. package/upstream/skills/brainstorming/spec-document-reviewer-prompt.md +0 -0
  160. package/upstream/skills/brainstorming/visual-companion.md +0 -0
  161. package/upstream/skills/dispatching-parallel-agents/SKILL.md +0 -0
  162. package/upstream/skills/executing-plans/SKILL.md +0 -0
  163. package/upstream/skills/finishing-a-development-branch/SKILL.md +0 -0
  164. package/upstream/skills/receiving-code-review/SKILL.md +0 -0
  165. package/upstream/skills/requesting-code-review/SKILL.md +0 -0
  166. package/upstream/skills/requesting-code-review/code-reviewer.md +0 -0
  167. package/upstream/skills/subagent-driven-development/SKILL.md +0 -0
  168. package/upstream/skills/subagent-driven-development/code-quality-reviewer-prompt.md +0 -0
  169. package/upstream/skills/subagent-driven-development/implementer-prompt.md +0 -0
  170. package/upstream/skills/subagent-driven-development/spec-reviewer-prompt.md +0 -0
  171. package/upstream/skills/systematic-debugging/CREATION-LOG.md +0 -0
  172. package/upstream/skills/systematic-debugging/SKILL.md +0 -0
  173. package/upstream/skills/systematic-debugging/condition-based-waiting-example.ts +0 -0
  174. package/upstream/skills/systematic-debugging/condition-based-waiting.md +0 -0
  175. package/upstream/skills/systematic-debugging/defense-in-depth.md +0 -0
  176. package/upstream/skills/systematic-debugging/find-polluter.sh +0 -0
  177. package/upstream/skills/systematic-debugging/root-cause-tracing.md +0 -0
  178. package/upstream/skills/systematic-debugging/test-academic.md +0 -0
  179. package/upstream/skills/systematic-debugging/test-pressure-1.md +0 -0
  180. package/upstream/skills/systematic-debugging/test-pressure-2.md +0 -0
  181. package/upstream/skills/systematic-debugging/test-pressure-3.md +0 -0
  182. package/upstream/skills/tdd-lean/SKILL.md +0 -0
  183. package/upstream/skills/test-driven-development/SKILL.md +0 -0
  184. package/upstream/skills/test-driven-development/testing-anti-patterns.md +0 -0
  185. package/upstream/skills/using-git-worktrees/SKILL.md +0 -0
  186. package/upstream/skills/using-superpowers/SKILL.md +0 -0
  187. package/upstream/skills/using-superpowers/references/codex-tools.md +0 -0
  188. package/upstream/skills/using-superpowers/references/copilot-tools.md +0 -0
  189. package/upstream/skills/using-superpowers/references/gemini-tools.md +0 -0
  190. package/upstream/skills/verification-before-completion/SKILL.md +0 -0
  191. package/upstream/skills/writing-plans/SKILL.md +0 -0
  192. package/upstream/skills/writing-plans/plan-document-reviewer-prompt.md +0 -0
  193. package/upstream/skills/writing-skills/SKILL.md +0 -0
  194. package/upstream/skills/writing-skills/anthropic-best-practices.md +0 -0
  195. package/upstream/skills/writing-skills/examples/CLAUDE_MD_TESTING.md +0 -0
  196. package/upstream/skills/writing-skills/graphviz-conventions.dot +0 -0
  197. package/upstream/skills/writing-skills/persuasion-principles.md +0 -0
  198. package/upstream/skills/writing-skills/render-graphs.js +0 -0
  199. package/upstream/skills/writing-skills/testing-skills-with-subagents.md +0 -0
  200. package/upstream/tests/brainstorm-server/package-lock.json +0 -0
  201. package/upstream/tests/brainstorm-server/package.json +0 -0
  202. package/upstream/tests/brainstorm-server/server.test.js +0 -0
  203. package/upstream/tests/brainstorm-server/windows-lifecycle.test.sh +0 -0
  204. package/upstream/tests/brainstorm-server/ws-protocol.test.js +0 -0
  205. package/upstream/tests/claude-code/README.md +0 -0
  206. package/upstream/tests/claude-code/analyze-token-usage.py +0 -0
  207. package/upstream/tests/claude-code/run-skill-tests.sh +0 -0
  208. package/upstream/tests/claude-code/test-document-review-system.sh +0 -0
  209. package/upstream/tests/claude-code/test-helpers.sh +0 -0
  210. package/upstream/tests/claude-code/test-subagent-driven-development-integration.sh +0 -0
  211. package/upstream/tests/claude-code/test-subagent-driven-development.sh +0 -0
  212. package/upstream/tests/explicit-skill-requests/prompts/action-oriented.txt +0 -0
  213. package/upstream/tests/explicit-skill-requests/prompts/after-planning-flow.txt +0 -0
  214. package/upstream/tests/explicit-skill-requests/prompts/claude-suggested-it.txt +0 -0
  215. package/upstream/tests/explicit-skill-requests/prompts/i-know-what-sdd-means.txt +0 -0
  216. package/upstream/tests/explicit-skill-requests/prompts/mid-conversation-execute-plan.txt +0 -0
  217. package/upstream/tests/explicit-skill-requests/prompts/please-use-brainstorming.txt +0 -0
  218. package/upstream/tests/explicit-skill-requests/prompts/skip-formalities.txt +0 -0
  219. package/upstream/tests/explicit-skill-requests/prompts/subagent-driven-development-please.txt +0 -0
  220. package/upstream/tests/explicit-skill-requests/prompts/use-systematic-debugging.txt +0 -0
  221. package/upstream/tests/explicit-skill-requests/run-all.sh +0 -0
  222. package/upstream/tests/explicit-skill-requests/run-claude-describes-sdd.sh +0 -0
  223. package/upstream/tests/explicit-skill-requests/run-extended-multiturn-test.sh +0 -0
  224. package/upstream/tests/explicit-skill-requests/run-haiku-test.sh +0 -0
  225. package/upstream/tests/explicit-skill-requests/run-multiturn-test.sh +0 -0
  226. package/upstream/tests/explicit-skill-requests/run-test.sh +0 -0
  227. package/upstream/tests/opencode/run-tests.sh +0 -0
  228. package/upstream/tests/opencode/setup.sh +0 -0
  229. package/upstream/tests/opencode/test-plugin-loading.sh +0 -0
  230. package/upstream/tests/opencode/test-priority.sh +0 -0
  231. package/upstream/tests/opencode/test-tools.sh +0 -0
  232. package/upstream/tests/skill-triggering/prompts/dispatching-parallel-agents.txt +0 -0
  233. package/upstream/tests/skill-triggering/prompts/executing-plans.txt +0 -0
  234. package/upstream/tests/skill-triggering/prompts/requesting-code-review.txt +0 -0
  235. package/upstream/tests/skill-triggering/prompts/systematic-debugging.txt +0 -0
  236. package/upstream/tests/skill-triggering/prompts/test-driven-development.txt +0 -0
  237. package/upstream/tests/skill-triggering/prompts/writing-plans.txt +0 -0
  238. package/upstream/tests/skill-triggering/run-all.sh +0 -0
  239. package/upstream/tests/skill-triggering/run-test.sh +0 -0
  240. package/upstream/tests/subagent-driven-dev/go-fractals/design.md +0 -0
  241. package/upstream/tests/subagent-driven-dev/go-fractals/plan.md +0 -0
  242. package/upstream/tests/subagent-driven-dev/go-fractals/scaffold.sh +0 -0
  243. package/upstream/tests/subagent-driven-dev/run-test.sh +0 -0
  244. package/upstream/tests/subagent-driven-dev/svelte-todo/design.md +0 -0
  245. package/upstream/tests/subagent-driven-dev/svelte-todo/plan.md +0 -0
  246. package/upstream/tests/subagent-driven-dev/svelte-todo/scaffold.sh +0 -0
  247. package/custom/mcp-presets/playwright.json +0 -11
  248. package/custom/rules/test-patterns.md +0 -105
  249. package/custom/skills/automation-testing/SKILL.md +0 -168
  250. package/custom/skills/automation-testing/templates/BasePage.ts +0 -30
  251. package/custom/skills/automation-testing/templates/playwright.config.ts +0 -21
  252. package/custom/skills/automation-testing/templates/repos.json +0 -8
  253. package/scripts/score_members.js +0 -320
package/scripts/prompt.js CHANGED
@@ -1,538 +1,538 @@
1
- const fs = require('fs-extra');
2
- const path = require('path');
3
- const chalk = require('chalk');
4
- const { spawnSync } = require('child_process');
5
- const { confirm } = require('@inquirer/prompts');
6
-
7
- const PROJECT_DIR = process.cwd();
8
- const CURRENT_FILE = path.join(PROJECT_DIR, '.aiflow', 'context', 'current.json');
9
- const RULES_DIR = path.join(PROJECT_DIR, '.rules');
10
-
11
- // Prompt templates per task type
12
- // Each template includes mandatory superpowers skill invocation steps.
13
- const PROMPT_TEMPLATES = {
14
- 'bug-fix': {
15
- header: 'Fix Bug',
16
- instruction: 'Investigate and fix the bug described below.',
17
- skillWorkflow: `
18
- ## STRICT GATE WORKFLOW — Bug Fix
19
-
20
- Follow gates IN ORDER. Do NOT skip or merge gates.
21
-
22
- ### GATE 1 — AI Analyze Requirement
23
- **INVOKE:** \`read-study-requirement\` skill
24
- AI must:
25
- 1. Load ticket context + read source code related to the bug
26
- 2. Trace data flow to form root cause hypothesis (\`superpowers:systematic-debugging\`)
27
- 3. If unclear → ask ONE question at a time, wait for reply
28
- 4. Output \`plan/[ticket-id]/requirement.md\` with:
29
- - Bug analysis (current vs expected behavior)
30
- - Root cause hypothesis with evidence from source code
31
- - Proposed fix approach (options if multiple)
32
- - Impact analysis — will the fix break anything else?
33
- - Effort estimate (S/M/L/XL)
34
- - Testing plan (reproduce bug + verify fix)
35
- 5. Display "GATE 1: Requirement doc ready" → wait for **APPROVED**
36
-
37
- ### GATE 2 — Implementation Plan (wait for APPROVED)
38
- **INVOKE:** \`generate-spec\` skill → \`superpowers:writing-plans\`
39
- - Create TDD task breakdown: test to reproduce bug → fix → verify
40
- - Display: "GATE 2: Plan ready, type APPROVED to start coding"
41
- - **DO NOT WRITE CODE until APPROVED received**
42
-
43
- ### GATE 3 — Code (TDD)
44
- Only runs after Gate 2 APPROVED.
45
- 1. **INVOKE:** \`superpowers:systematic-debugging\` — confirm root cause
46
- 2. **INVOKE:** \`investigate-bug\` skill — trace Controller→Service→Repository
47
- 3. **INVOKE:** \`superpowers:test-driven-development\` — write failing test to reproduce bug
48
- 4. Implement minimal fix to make test pass
49
-
50
- ### GATE 4 — AI Self-Review (wait for APPROVED)
51
- **INVOKE:** \`review-plan\` skill
52
- 1. \`superpowers:verification-before-completion\` — all tests PASS (including old tests)
53
- 2. \`impact-analysis\` skill — fix doesn't cause new bugs elsewhere
54
- 3. Tick \`custom/rules/review-checklist.md\`
55
- 4. Create \`plan/[ticket-id]/summary.md\`
56
- - Display: "GATE 4: type APPROVED or BUG: [description]"
57
- - Coding bug → fix → repeat Gate 4
58
- - Requirement bug → back to Gate 1
59
-
60
- ### GATE 5 — Peer Review & Done
61
- Only runs after Gate 4 APPROVED.
62
- **INVOKE:** \`superpowers:requesting-code-review\` → guide PR creation
63
- `,
64
- },
65
- 'feature': {
66
- header: 'Implement Feature',
67
- instruction: 'Implement the feature described below following team rules.',
68
- skillWorkflow: `
69
- ## STRICT GATE WORKFLOW — Feature
70
-
71
- Follow gates IN ORDER. Do NOT skip or merge gates.
72
-
73
- ### GATE 1 — AI Analyze Requirement
74
- **INVOKE:** \`read-study-requirement\` skill
75
- AI must:
76
- 1. Load ticket context + read source code to understand architecture
77
- 2. Investigate related files, data flow, existing patterns
78
- 3. Propose 2-3 solution approaches using Q&A if the problem is complex
79
- 4. If unclear → ask ONE question at a time, wait for reply
80
- 5. Output \`plan/[ticket-id]/requirement.md\` with:
81
- - Requirements summary (AI's understanding in technical language)
82
- - Source code analysis (related files, data flow, patterns)
83
- - Proposed solution with options (recommended + alternatives)
84
- - Impact analysis — what areas are affected?
85
- - Effort estimate (S/M/L/XL) with task breakdown
86
- - Testing plan (unit + integration + manual)
87
- 6. Display "GATE 1: Requirement doc ready" → wait for **APPROVED**
88
-
89
- ### GATE 2 — Implementation Plan (wait for APPROVED)
90
- **INVOKE:** \`generate-spec\` skill → \`superpowers:writing-plans\`
91
- - Create TDD task breakdown: test first → implement → verify
92
- - Define commit strategy (small, focused)
93
- - Display: "GATE 2: Plan ready, type APPROVED to start coding"
94
- - **DO NOT WRITE CODE until APPROVED received**
95
-
96
- ### GATE 3 — Code (TDD)
97
- Only runs after Gate 2 APPROVED.
98
- 1. Complex feature (3+ files): **INVOKE:** \`superpowers:subagent-driven-development\`
99
- 2. **INVOKE:** \`superpowers:test-driven-development\` — write failing test first
100
- 3. Implement to make tests pass — verify each small step
101
-
102
- ### GATE 4 — AI Self-Review (wait for APPROVED)
103
- **INVOKE:** \`review-plan\` skill
104
- 1. \`superpowers:verification-before-completion\` — all tests PASS
105
- 2. \`impact-analysis\` skill — no regressions
106
- 3. Tick \`custom/rules/review-checklist.md\`
107
- 4. Create \`plan/[ticket-id]/summary.md\`
108
- - Display: "GATE 4: type APPROVED or BUG: [description]"
109
- - Coding bug → fix → repeat Gate 4
110
- - Requirement bug → back to Gate 1
111
-
112
- ### GATE 5 — Peer Review & Done
113
- Only runs after Gate 4 APPROVED.
114
- **INVOKE:** \`superpowers:requesting-code-review\` → guide PR creation
115
- `,
116
- },
117
- 'investigation': {
118
- header: 'Investigate',
119
- instruction: 'Investigate the topic described below. Document findings before proposing solutions.',
120
- skillWorkflow: `
121
- ## STRICT GATE WORKFLOW — Investigation
122
-
123
- Investigation stops at Gate 1 — produce requirement doc with findings only, no coding.
124
-
125
- ### GATE 1 — AI Analyze & Investigate
126
- **INVOKE:** \`read-study-requirement\` skill
127
- AI must:
128
- 1. Load ticket context + read source code thoroughly
129
- 2. **INVOKE:** \`superpowers:systematic-debugging\` — trace through all layers
130
- 3. **INVOKE:** \`investigate-bug\` skill — trace data flow through all layers
131
- 4. If unclear → ask ONE question at a time
132
- 5. Output \`plan/[ticket-id]/requirement.md\` with:
133
- - Investigation scope and approach
134
- - Source code analysis (all related files traced)
135
- - Findings with evidence (log output, code references)
136
- - Root cause (if applicable)
137
- - Impact analysis — what areas are affected?
138
- - Recommendations and next steps
139
- - Effort estimate for proposed fix (if applicable)
140
- 6. Display "GATE 1: Investigation complete" → wait for **APPROVED**
141
-
142
- **Do NOT implement any fix.** If fix needed → create new ticket → new workflow.
143
- `,
144
- },
145
- 'refactor': {
146
- header: 'Refactor',
147
- instruction: 'Refactor the code described below. Behaviour must be preserved.',
148
- skillWorkflow: `
149
- ## STRICT GATE WORKFLOW — Refactor
150
-
151
- Follow gates IN ORDER. Do NOT skip or merge gates.
152
-
153
- ### GATE 1 — AI Analyze Requirement
154
- **INVOKE:** \`read-study-requirement\` skill
155
- AI must:
156
- 1. Load ticket context + read source code to understand current state
157
- 2. **INVOKE:** \`impact-analysis\` skill — map ALL callers and dependants
158
- 3. If unclear → ask ONE question at a time
159
- 4. Output \`plan/[ticket-id]/requirement.md\` with:
160
- - Current state analysis (what exists, what's wrong)
161
- - Target state (what it should look like after refactor)
162
- - Proposed approach (step-by-step refactor strategy)
163
- - Impact analysis — all callers, dependencies, test coverage
164
- - Risk assessment — what could break?
165
- - Effort estimate (S/M/L/XL)
166
- 5. Display "GATE 1: Requirement doc ready" → wait for **APPROVED**
167
-
168
- ### GATE 2 — Implementation Plan (wait for APPROVED)
169
- **INVOKE:** \`generate-spec\` skill → \`superpowers:writing-plans\`
170
- - Plan: ensure tests cover CURRENT behavior → refactor in steps → verify at each step
171
- - Display: "GATE 2: Plan ready, type APPROVED to start refactoring"
172
- - **DO NOT TOUCH CODE until APPROVED received**
173
-
174
- ### GATE 3 — Refactor (TDD)
175
- Only runs after Gate 2 APPROVED.
176
- 1. **INVOKE:** \`superpowers:test-driven-development\` — ensure tests cover CURRENT behavior
177
- 2. Refactor incrementally — keep tests green at each step
178
- 3. Commit after manual verification
179
-
180
- ### GATE 4 — AI Self-Review (wait for APPROVED)
181
- **INVOKE:** \`review-plan\` skill
182
- 1. \`superpowers:verification-before-completion\` — all tests PASS
183
- 2. \`impact-analysis\` skill — verify no regressions
184
- 3. Tick \`custom/rules/review-checklist.md\`
185
- 4. Create \`plan/[ticket-id]/summary.md\`
186
- - Display: "GATE 4: type APPROVED or BUG: [description]"
187
-
188
- ### GATE 5 — Peer Review & Done
189
- **INVOKE:** \`superpowers:requesting-code-review\` → guide PR creation
190
- `,
191
- },
192
- 'impact-analysis': {
193
- header: 'Impact Analysis',
194
- instruction: 'Analyse the scope and impact of the change described below.',
195
- skillWorkflow: `
196
- ## STRICT GATE WORKFLOW — Impact Analysis
197
-
198
- Impact analysis stops at Gate 1 — produce report only, no coding.
199
-
200
- ### GATE 1 — AI Analyze & Report
201
- **INVOKE:** \`read-study-requirement\` skill
202
- AI must:
203
- 1. Load ticket context + read source code thoroughly
204
- 2. Map all dependencies, callers, services, jobs, tests
205
- 3. If unclear → ask ONE question at a time
206
- 4. Output \`plan/[ticket-id]/requirement.md\` with:
207
- - Change description and scope
208
- - Dependency map (all callers, services, jobs, tests)
209
- - Impact level: 🟢 Low / 🟡 Medium / 🔴 High / 🔥 Critical
210
- - Breaking changes list
211
- - Affected test coverage
212
- - Risk assessment with mitigations
213
- - Recommendations
214
- - Effort estimate for implementation (if applicable)
215
- 5. Display "GATE 1: Impact report complete" → wait for **APPROVED**
216
-
217
- **Do NOT make any code changes.** Implementation needs a separate ticket.
218
- `,
219
- },
220
- 'documentation': {
221
- header: 'Write Documentation',
222
- instruction: 'Write documentation for the topic described below.',
223
- skillWorkflow: `
224
- ## STRICT GATE WORKFLOW — Documentation
225
-
226
- ### GATE 1 — AI Analyze Requirement
227
- **INVOKE:** \`read-study-requirement\` skill
228
- AI must:
229
- 1. Load ticket context + read source code
230
- 2. Understand what needs to be documented and for whom
231
- 3. If unclear → ask ONE question at a time
232
- 4. Output \`plan/[ticket-id]/requirement.md\` with:
233
- - Documentation scope and target audience
234
- - Content outline (sections to cover)
235
- - Source code references
236
- - Effort estimate
237
- 5. Display "GATE 1: Documentation plan ready" → wait for **APPROVED**
238
-
239
- ### GATE 2 — Write Documentation
240
- Only runs after Gate 1 APPROVED.
241
- Read actual code/tests first — docs must reflect real implementation.
242
- Write documentation based on approved outline.
243
-
244
- ### GATE 3 — Review (wait for APPROVED)
245
- **INVOKE:** \`superpowers:verification-before-completion\`
246
- Verify docs match code. No outdated examples.
247
- Display: "GATE 3: Documentation complete. Type APPROVED."
248
- `,
249
- },
250
- };
251
-
252
- // ──────────────────────────────────────────────────────────────
253
- // Entry point
254
- // ──────────────────────────────────────────────────────────────
255
-
256
- module.exports = async function generatePrompt(type, options = {}) {
257
- if (options.list) {
258
- console.log(chalk.cyan('\nAvailable prompt types:\n'));
259
- for (const [key, tpl] of Object.entries(PROMPT_TEMPLATES)) {
260
- console.log(` ${chalk.white(key.padEnd(18))} ${chalk.gray(tpl.instruction.substring(0, 60))}...`);
261
- }
262
- console.log();
263
- return;
264
- }
265
-
266
- // Load context
267
- let ctx = null;
268
- if (await fs.pathExists(CURRENT_FILE)) {
269
- ctx = await fs.readJson(CURRENT_FILE).catch(() => null);
270
- }
271
-
272
- // Resolve task type: CLI arg > context > ask user to specify
273
- const resolvedType = type || ctx?.taskType;
274
- if (!resolvedType || !PROMPT_TEMPLATES[resolvedType]) {
275
- console.log(chalk.red(`Unknown or missing prompt type: ${resolvedType || '(none)'}`));
276
- console.log(chalk.gray('Run: aiflow prompt --list'));
277
- return;
278
- }
279
-
280
- const template = PROMPT_TEMPLATES[resolvedType];
281
- const rules = await loadRules();
282
-
283
- const env = options.env || 'claude';
284
- const prompt = buildPrompt(template, ctx, rules, options, env);
285
-
286
- if (options.output) {
287
- await fs.writeFile(options.output, prompt, 'utf-8');
288
- console.log(chalk.green(`✓ Prompt saved to: ${options.output}`));
289
- return;
290
- }
291
-
292
- const clipResult = copyToClipboard(prompt);
293
- if (clipResult.success) {
294
- const ticket = ctx?.taskId ? chalk.gray(` [${ctx.taskId}]`) : '';
295
- console.log(chalk.green(`✓ Prompt copied to clipboard!${ticket} Paste it into your AI chat to begin.`));
296
- } else {
297
- await handleClipboardFailure(prompt, clipResult);
298
- }
299
- };
300
-
301
- // ──────────────────────────────────────────────────────────────
302
- // Helpers
303
- // ──────────────────────────────────────────────────────────────
304
-
305
- async function loadRules() {
306
- if (!(await fs.pathExists(RULES_DIR))) return '';
307
-
308
- const files = (await fs.readdir(RULES_DIR)).filter(f => f.endsWith('.md'));
309
- if (!files.length) return '';
310
-
311
- const parts = [];
312
- for (const file of files) {
313
- const content = await fs.readFile(path.join(RULES_DIR, file), 'utf-8');
314
- parts.push(`### ${file}\n${content.trim()}`);
315
- }
316
- return parts.join('\n\n');
317
- }
318
-
319
- function buildPrompt(template, ctx, rules, options, env = 'claude') {
320
- const lang = options.lang || 'english';
321
- const detail = options.detail || 'standard';
322
-
323
- const lines = [];
324
-
325
- lines.push(`# ${template.header}`);
326
- lines.push('');
327
- lines.push(`**Task:** ${template.instruction}`);
328
- lines.push('');
329
-
330
- // ── Mandatory skill workflow ───────────────────────────────
331
- if (template.skillWorkflow) {
332
- lines.push(template.skillWorkflow.trim());
333
- lines.push('');
334
- }
335
-
336
- // ── Telemetry instructions ─────────────────────────────────
337
- const ticketArg = ctx?.taskId ? ` --ticket ${ctx.taskId}` : '';
338
- const akCmd = isWSL() ? 'ak.cmd' : 'ak';
339
- lines.push(`> **Telemetry (required):** When **starting** each gate run \`${akCmd} gate N start${ticketArg}\`. When **APPROVED** run \`${akCmd} gate N approved${ticketArg}\`. Replace N with the gate number (1–5).`);
340
- lines.push('');
341
-
342
- // ── Context section ────────────────────────────────────────
343
- if (ctx) {
344
- lines.push('## Context');
345
- lines.push('');
346
- lines.push(`- **Ticket:** ${ctx.taskId || 'N/A'}`);
347
- lines.push(`- **Title:** ${ctx.title || 'N/A'}`);
348
- lines.push(`- **Status:** ${ctx.status || 'N/A'}`);
349
- lines.push(`- **Assignee:** ${ctx.assignee || 'N/A'}`);
350
- lines.push('');
351
-
352
- if (ctx.description) {
353
- lines.push('### Description');
354
- lines.push('');
355
- lines.push(ctx.description.trim());
356
- lines.push('');
357
- }
358
-
359
- if (ctx.acceptanceCriteria?.length) {
360
- lines.push('### Acceptance Criteria');
361
- lines.push('');
362
- for (const c of ctx.acceptanceCriteria) {
363
- lines.push(`- ${c}`);
364
- }
365
- lines.push('');
366
- }
367
-
368
- if (detail === 'comprehensive' && ctx.comments?.length) {
369
- lines.push('### Comments');
370
- lines.push('');
371
- for (const c of ctx.comments) {
372
- lines.push(c);
373
- lines.push('');
374
- }
375
- }
376
-
377
- if (ctx.context?.files?.length) {
378
- lines.push('### Related Files Mentioned');
379
- lines.push('');
380
- for (const f of ctx.context.files) {
381
- lines.push(`- \`${f}\``);
382
- }
383
- lines.push('');
384
- }
385
- } else {
386
- lines.push('> No context loaded. Run `aiflow use <ticket>` to load ticket context.');
387
- lines.push('');
388
- }
389
-
390
- // ── Rules section ──────────────────────────────────────────
391
- if (rules) {
392
- lines.push('## Team Rules');
393
- lines.push('');
394
- lines.push(rules);
395
- lines.push('');
396
- }
397
-
398
- // ── Language instruction ───────────────────────────────────
399
- if (lang === 'vietnamese') {
400
- lines.push('> **Reply in English.**');
401
- lines.push('');
402
- }
403
-
404
- // ── Tool-specific instructions ───────────────────────────────
405
- if (env === 'cursor') {
406
- lines.push('---');
407
- lines.push('> **Cursor Tip:** You can use `@Codebase` to search for more context if needed.');
408
- } else if (env === 'gemini') {
409
- lines.push('---');
410
- lines.push('> **Gemini Tip:** Use the "Upload Files" or "Attach File" feature to provide source code context.');
411
- }
412
-
413
- return lines.join('\n');
414
- }
415
-
416
- function isWSL() {
417
- if (process.platform !== 'linux') return false;
418
- try {
419
- const version = require('fs').readFileSync('/proc/version', 'utf-8');
420
- return /microsoft|wsl/i.test(version);
421
- } catch (_) { return false; }
422
- }
423
-
424
- function detectLinuxPkgManager() {
425
- const candidates = [
426
- { cmd: 'apt-get', installFlag: 'install -y' },
427
- { cmd: 'dnf', installFlag: 'install -y' },
428
- { cmd: 'pacman', installFlag: '-S --noconfirm' },
429
- { cmd: 'zypper', installFlag: 'install -y' },
430
- ];
431
- for (const c of candidates) {
432
- const r = spawnSync('which', [c.cmd], { stdio: 'ignore' });
433
- if (r.status === 0) return c;
434
- }
435
- return null;
436
- }
437
-
438
- function linuxClipboardInfo() {
439
- const isWayland = !!process.env.WAYLAND_DISPLAY;
440
- const pkg = isWayland ? 'wl-clipboard' : 'xclip';
441
- const mgr = detectLinuxPkgManager();
442
- return {
443
- pkg,
444
- pkgManager: mgr ? mgr.cmd : null,
445
- installArgs: mgr ? [...mgr.installFlag.split(' '), pkg] : null,
446
- installDisplayCmd: mgr ? `sudo ${mgr.cmd} ${mgr.installFlag} ${pkg}` : null,
447
- };
448
- }
449
-
450
- // Returns { success: true } or { success: false, pkg, pkgManager, installArgs, installDisplayCmd }
451
- function copyToClipboard(text) {
452
- try {
453
- if (process.platform === 'win32') {
454
- spawnSync(
455
- 'powershell',
456
- ['-NoProfile', '-NonInteractive', '-Command',
457
- '[Console]::InputEncoding = [System.Text.Encoding]::UTF8; Set-Clipboard -Value ([Console]::In.ReadToEnd())'],
458
- { input: text, encoding: 'utf8', stdio: ['pipe', 'ignore', 'ignore'] }
459
- );
460
- return { success: true };
461
- } else if (process.platform === 'darwin') {
462
- spawnSync('pbcopy', [], { input: text, encoding: 'utf8', stdio: ['pipe', 'ignore', 'ignore'] });
463
- return { success: true };
464
- } else if (isWSL()) {
465
- spawnSync(
466
- 'powershell.exe',
467
- ['-NoProfile', '-NonInteractive', '-Command',
468
- '[Console]::InputEncoding = [System.Text.Encoding]::UTF8; Set-Clipboard -Value ([Console]::In.ReadToEnd())'],
469
- { input: text, encoding: 'utf8', stdio: ['pipe', 'ignore', 'ignore'] }
470
- );
471
- return { success: true };
472
- } else {
473
- // Try wl-copy (Wayland), then xclip, then xsel
474
- if (process.env.WAYLAND_DISPLAY) {
475
- const r = spawnSync('wl-copy', [], { input: text, encoding: 'utf8', stdio: ['pipe', 'ignore', 'ignore'] });
476
- if (!r.error && r.status === 0) return { success: true };
477
- }
478
- const r = spawnSync('xclip', ['-selection', 'clipboard'], { input: text, encoding: 'utf8', stdio: ['pipe', 'ignore', 'ignore'] });
479
- if (!r.error && r.status === 0) return { success: true };
480
- const r2 = spawnSync('xsel', ['--clipboard', '--input'], { input: text, encoding: 'utf8', stdio: ['pipe', 'ignore', 'ignore'] });
481
- if (!r2.error && r2.status === 0) return { success: true };
482
- return { success: false, ...linuxClipboardInfo() };
483
- }
484
- } catch (_) {
485
- return { success: false };
486
- }
487
- }
488
-
489
- function showPromptFallback(text) {
490
- console.log(chalk.cyan('\n' + '─'.repeat(60)));
491
- console.log(text);
492
- console.log(chalk.cyan('─'.repeat(60) + '\n'));
493
- console.log(chalk.yellow('Clipboard unavailable — paste the prompt above into your AI chat.'));
494
- }
495
-
496
- async function handleClipboardFailure(text, info) {
497
- if (!info.pkg) {
498
- // Unknown platform failure
499
- showPromptFallback(text);
500
- return;
501
- }
502
-
503
- console.log(chalk.yellow(`\n⚠ Clipboard tool not found (need: ${chalk.white(info.pkg)})`));
504
-
505
- if (!info.installDisplayCmd) {
506
- console.log(chalk.gray(' Could not detect a package manager. Install manually:'));
507
- console.log(chalk.gray(' Wayland: sudo apt install wl-clipboard'));
508
- console.log(chalk.gray(' X11: sudo apt install xclip\n'));
509
- showPromptFallback(text);
510
- return;
511
- }
512
-
513
- console.log(chalk.gray(` Install command: ${chalk.white(info.installDisplayCmd)}\n`));
514
-
515
- try {
516
- const doInstall = await confirm({
517
- message: `Install ${info.pkg} now? (requires sudo)`,
518
- default: true,
519
- });
520
-
521
- if (doInstall) {
522
- console.log(chalk.cyan(`\nRunning: sudo ${info.pkgManager} ${info.installArgs.join(' ')}`));
523
- const r = spawnSync('sudo', [info.pkgManager, ...info.installArgs], { stdio: 'inherit' });
524
- if (r.status === 0) {
525
- const retry = copyToClipboard(text);
526
- if (retry.success) {
527
- console.log(chalk.green('\n✓ Installed! Prompt copied to clipboard. Paste it into your AI chat.'));
528
- return;
529
- }
530
- }
531
- console.log(chalk.red('\nInstallation failed. Showing prompt below:'));
532
- }
533
- } catch (_) {
534
- // Non-interactive terminal (piped) — skip the question
535
- }
536
-
537
- showPromptFallback(text);
538
- }
1
+ const fs = require('fs-extra');
2
+ const path = require('path');
3
+ const chalk = require('chalk');
4
+ const { spawnSync } = require('child_process');
5
+ const { confirm } = require('@inquirer/prompts');
6
+
7
+ const PROJECT_DIR = process.cwd();
8
+ const CURRENT_FILE = path.join(PROJECT_DIR, '.aiflow', 'context', 'current.json');
9
+ const RULES_DIR = path.join(PROJECT_DIR, '.rules');
10
+
11
+ // Prompt templates per task type
12
+ // Each template includes mandatory superpowers skill invocation steps.
13
+ const PROMPT_TEMPLATES = {
14
+ 'bug-fix': {
15
+ header: 'Fix Bug',
16
+ instruction: 'Investigate and fix the bug described below.',
17
+ skillWorkflow: `
18
+ ## STRICT GATE WORKFLOW — Bug Fix
19
+
20
+ Follow gates IN ORDER. Do NOT skip or merge gates.
21
+
22
+ ### GATE 1 — AI Analyze Requirement
23
+ **INVOKE:** \`read-study-requirement\` skill
24
+ AI must:
25
+ 1. Load ticket context + read source code related to the bug
26
+ 2. Trace data flow to form root cause hypothesis (\`superpowers:systematic-debugging\`)
27
+ 3. If unclear → ask ONE question at a time, wait for reply
28
+ 4. Output \`plan/[ticket-id]/requirement.md\` with:
29
+ - Bug analysis (current vs expected behavior)
30
+ - Root cause hypothesis with evidence from source code
31
+ - Proposed fix approach (options if multiple)
32
+ - Impact analysis — will the fix break anything else?
33
+ - Effort estimate (S/M/L/XL)
34
+ - Testing plan (reproduce bug + verify fix)
35
+ 5. Display "GATE 1: Requirement doc ready" → wait for **APPROVED**
36
+
37
+ ### GATE 2 — Implementation Plan (wait for APPROVED)
38
+ **INVOKE:** \`generate-spec\` skill → \`superpowers:writing-plans\`
39
+ - Create TDD task breakdown: test to reproduce bug → fix → verify
40
+ - Display: "GATE 2: Plan ready, type APPROVED to start coding"
41
+ - **DO NOT WRITE CODE until APPROVED received**
42
+
43
+ ### GATE 3 — Code (TDD)
44
+ Only runs after Gate 2 APPROVED.
45
+ 1. **INVOKE:** \`superpowers:systematic-debugging\` — confirm root cause
46
+ 2. **INVOKE:** \`investigate-bug\` skill — trace Controller→Service→Repository
47
+ 3. **INVOKE:** \`superpowers:test-driven-development\` — write failing test to reproduce bug
48
+ 4. Implement minimal fix to make test pass
49
+
50
+ ### GATE 4 — AI Self-Review (wait for APPROVED)
51
+ **INVOKE:** \`review-plan\` skill
52
+ 1. \`superpowers:verification-before-completion\` — all tests PASS (including old tests)
53
+ 2. \`impact-analysis\` skill — fix doesn't cause new bugs elsewhere
54
+ 3. Tick \`custom/rules/review-checklist.md\`
55
+ 4. Create \`plan/[ticket-id]/summary.md\`
56
+ - Display: "GATE 4: type APPROVED or BUG: [description]"
57
+ - Coding bug → fix → repeat Gate 4
58
+ - Requirement bug → back to Gate 1
59
+
60
+ ### GATE 5 — Peer Review & Done
61
+ Only runs after Gate 4 APPROVED.
62
+ **INVOKE:** \`superpowers:requesting-code-review\` → guide PR creation
63
+ `,
64
+ },
65
+ 'feature': {
66
+ header: 'Implement Feature',
67
+ instruction: 'Implement the feature described below following team rules.',
68
+ skillWorkflow: `
69
+ ## STRICT GATE WORKFLOW — Feature
70
+
71
+ Follow gates IN ORDER. Do NOT skip or merge gates.
72
+
73
+ ### GATE 1 — AI Analyze Requirement
74
+ **INVOKE:** \`read-study-requirement\` skill
75
+ AI must:
76
+ 1. Load ticket context + read source code to understand architecture
77
+ 2. Investigate related files, data flow, existing patterns
78
+ 3. Propose 2-3 solution approaches using Q&A if the problem is complex
79
+ 4. If unclear → ask ONE question at a time, wait for reply
80
+ 5. Output \`plan/[ticket-id]/requirement.md\` with:
81
+ - Requirements summary (AI's understanding in technical language)
82
+ - Source code analysis (related files, data flow, patterns)
83
+ - Proposed solution with options (recommended + alternatives)
84
+ - Impact analysis — what areas are affected?
85
+ - Effort estimate (S/M/L/XL) with task breakdown
86
+ - Testing plan (unit + integration + manual)
87
+ 6. Display "GATE 1: Requirement doc ready" → wait for **APPROVED**
88
+
89
+ ### GATE 2 — Implementation Plan (wait for APPROVED)
90
+ **INVOKE:** \`generate-spec\` skill → \`superpowers:writing-plans\`
91
+ - Create TDD task breakdown: test first → implement → verify
92
+ - Define commit strategy (small, focused)
93
+ - Display: "GATE 2: Plan ready, type APPROVED to start coding"
94
+ - **DO NOT WRITE CODE until APPROVED received**
95
+
96
+ ### GATE 3 — Code (TDD)
97
+ Only runs after Gate 2 APPROVED.
98
+ 1. Complex feature (3+ files): **INVOKE:** \`superpowers:subagent-driven-development\`
99
+ 2. **INVOKE:** \`superpowers:test-driven-development\` — write failing test first
100
+ 3. Implement to make tests pass — verify each small step
101
+
102
+ ### GATE 4 — AI Self-Review (wait for APPROVED)
103
+ **INVOKE:** \`review-plan\` skill
104
+ 1. \`superpowers:verification-before-completion\` — all tests PASS
105
+ 2. \`impact-analysis\` skill — no regressions
106
+ 3. Tick \`custom/rules/review-checklist.md\`
107
+ 4. Create \`plan/[ticket-id]/summary.md\`
108
+ - Display: "GATE 4: type APPROVED or BUG: [description]"
109
+ - Coding bug → fix → repeat Gate 4
110
+ - Requirement bug → back to Gate 1
111
+
112
+ ### GATE 5 — Peer Review & Done
113
+ Only runs after Gate 4 APPROVED.
114
+ **INVOKE:** \`superpowers:requesting-code-review\` → guide PR creation
115
+ `,
116
+ },
117
+ 'investigation': {
118
+ header: 'Investigate',
119
+ instruction: 'Investigate the topic described below. Document findings before proposing solutions.',
120
+ skillWorkflow: `
121
+ ## STRICT GATE WORKFLOW — Investigation
122
+
123
+ Investigation stops at Gate 1 — produce requirement doc with findings only, no coding.
124
+
125
+ ### GATE 1 — AI Analyze & Investigate
126
+ **INVOKE:** \`read-study-requirement\` skill
127
+ AI must:
128
+ 1. Load ticket context + read source code thoroughly
129
+ 2. **INVOKE:** \`superpowers:systematic-debugging\` — trace through all layers
130
+ 3. **INVOKE:** \`investigate-bug\` skill — trace data flow through all layers
131
+ 4. If unclear → ask ONE question at a time
132
+ 5. Output \`plan/[ticket-id]/requirement.md\` with:
133
+ - Investigation scope and approach
134
+ - Source code analysis (all related files traced)
135
+ - Findings with evidence (log output, code references)
136
+ - Root cause (if applicable)
137
+ - Impact analysis — what areas are affected?
138
+ - Recommendations and next steps
139
+ - Effort estimate for proposed fix (if applicable)
140
+ 6. Display "GATE 1: Investigation complete" → wait for **APPROVED**
141
+
142
+ **Do NOT implement any fix.** If fix needed → create new ticket → new workflow.
143
+ `,
144
+ },
145
+ 'refactor': {
146
+ header: 'Refactor',
147
+ instruction: 'Refactor the code described below. Behaviour must be preserved.',
148
+ skillWorkflow: `
149
+ ## STRICT GATE WORKFLOW — Refactor
150
+
151
+ Follow gates IN ORDER. Do NOT skip or merge gates.
152
+
153
+ ### GATE 1 — AI Analyze Requirement
154
+ **INVOKE:** \`read-study-requirement\` skill
155
+ AI must:
156
+ 1. Load ticket context + read source code to understand current state
157
+ 2. **INVOKE:** \`impact-analysis\` skill — map ALL callers and dependants
158
+ 3. If unclear → ask ONE question at a time
159
+ 4. Output \`plan/[ticket-id]/requirement.md\` with:
160
+ - Current state analysis (what exists, what's wrong)
161
+ - Target state (what it should look like after refactor)
162
+ - Proposed approach (step-by-step refactor strategy)
163
+ - Impact analysis — all callers, dependencies, test coverage
164
+ - Risk assessment — what could break?
165
+ - Effort estimate (S/M/L/XL)
166
+ 5. Display "GATE 1: Requirement doc ready" → wait for **APPROVED**
167
+
168
+ ### GATE 2 — Implementation Plan (wait for APPROVED)
169
+ **INVOKE:** \`generate-spec\` skill → \`superpowers:writing-plans\`
170
+ - Plan: ensure tests cover CURRENT behavior → refactor in steps → verify at each step
171
+ - Display: "GATE 2: Plan ready, type APPROVED to start refactoring"
172
+ - **DO NOT TOUCH CODE until APPROVED received**
173
+
174
+ ### GATE 3 — Refactor (TDD)
175
+ Only runs after Gate 2 APPROVED.
176
+ 1. **INVOKE:** \`superpowers:test-driven-development\` — ensure tests cover CURRENT behavior
177
+ 2. Refactor incrementally — keep tests green at each step
178
+ 3. Commit after manual verification
179
+
180
+ ### GATE 4 — AI Self-Review (wait for APPROVED)
181
+ **INVOKE:** \`review-plan\` skill
182
+ 1. \`superpowers:verification-before-completion\` — all tests PASS
183
+ 2. \`impact-analysis\` skill — verify no regressions
184
+ 3. Tick \`custom/rules/review-checklist.md\`
185
+ 4. Create \`plan/[ticket-id]/summary.md\`
186
+ - Display: "GATE 4: type APPROVED or BUG: [description]"
187
+
188
+ ### GATE 5 — Peer Review & Done
189
+ **INVOKE:** \`superpowers:requesting-code-review\` → guide PR creation
190
+ `,
191
+ },
192
+ 'impact-analysis': {
193
+ header: 'Impact Analysis',
194
+ instruction: 'Analyse the scope and impact of the change described below.',
195
+ skillWorkflow: `
196
+ ## STRICT GATE WORKFLOW — Impact Analysis
197
+
198
+ Impact analysis stops at Gate 1 — produce report only, no coding.
199
+
200
+ ### GATE 1 — AI Analyze & Report
201
+ **INVOKE:** \`read-study-requirement\` skill
202
+ AI must:
203
+ 1. Load ticket context + read source code thoroughly
204
+ 2. Map all dependencies, callers, services, jobs, tests
205
+ 3. If unclear → ask ONE question at a time
206
+ 4. Output \`plan/[ticket-id]/requirement.md\` with:
207
+ - Change description and scope
208
+ - Dependency map (all callers, services, jobs, tests)
209
+ - Impact level: 🟢 Low / 🟡 Medium / 🔴 High / 🔥 Critical
210
+ - Breaking changes list
211
+ - Affected test coverage
212
+ - Risk assessment with mitigations
213
+ - Recommendations
214
+ - Effort estimate for implementation (if applicable)
215
+ 5. Display "GATE 1: Impact report complete" → wait for **APPROVED**
216
+
217
+ **Do NOT make any code changes.** Implementation needs a separate ticket.
218
+ `,
219
+ },
220
+ 'documentation': {
221
+ header: 'Write Documentation',
222
+ instruction: 'Write documentation for the topic described below.',
223
+ skillWorkflow: `
224
+ ## STRICT GATE WORKFLOW — Documentation
225
+
226
+ ### GATE 1 — AI Analyze Requirement
227
+ **INVOKE:** \`read-study-requirement\` skill
228
+ AI must:
229
+ 1. Load ticket context + read source code
230
+ 2. Understand what needs to be documented and for whom
231
+ 3. If unclear → ask ONE question at a time
232
+ 4. Output \`plan/[ticket-id]/requirement.md\` with:
233
+ - Documentation scope and target audience
234
+ - Content outline (sections to cover)
235
+ - Source code references
236
+ - Effort estimate
237
+ 5. Display "GATE 1: Documentation plan ready" → wait for **APPROVED**
238
+
239
+ ### GATE 2 — Write Documentation
240
+ Only runs after Gate 1 APPROVED.
241
+ Read actual code/tests first — docs must reflect real implementation.
242
+ Write documentation based on approved outline.
243
+
244
+ ### GATE 3 — Review (wait for APPROVED)
245
+ **INVOKE:** \`superpowers:verification-before-completion\`
246
+ Verify docs match code. No outdated examples.
247
+ Display: "GATE 3: Documentation complete. Type APPROVED."
248
+ `,
249
+ },
250
+ };
251
+
252
+ // ──────────────────────────────────────────────────────────────
253
+ // Entry point
254
+ // ──────────────────────────────────────────────────────────────
255
+
256
+ module.exports = async function generatePrompt(type, options = {}) {
257
+ if (options.list) {
258
+ console.log(chalk.cyan('\nAvailable prompt types:\n'));
259
+ for (const [key, tpl] of Object.entries(PROMPT_TEMPLATES)) {
260
+ console.log(` ${chalk.white(key.padEnd(18))} ${chalk.gray(tpl.instruction.substring(0, 60))}...`);
261
+ }
262
+ console.log();
263
+ return;
264
+ }
265
+
266
+ // Load context
267
+ let ctx = null;
268
+ if (await fs.pathExists(CURRENT_FILE)) {
269
+ ctx = await fs.readJson(CURRENT_FILE).catch(() => null);
270
+ }
271
+
272
+ // Resolve task type: CLI arg > context > ask user to specify
273
+ const resolvedType = type || ctx?.taskType;
274
+ if (!resolvedType || !PROMPT_TEMPLATES[resolvedType]) {
275
+ console.log(chalk.red(`Unknown or missing prompt type: ${resolvedType || '(none)'}`));
276
+ console.log(chalk.gray('Run: aiflow prompt --list'));
277
+ return;
278
+ }
279
+
280
+ const template = PROMPT_TEMPLATES[resolvedType];
281
+ const rules = await loadRules();
282
+
283
+ const env = options.env || 'claude';
284
+ const prompt = buildPrompt(template, ctx, rules, options, env);
285
+
286
+ if (options.output) {
287
+ await fs.writeFile(options.output, prompt, 'utf-8');
288
+ console.log(chalk.green(`✓ Prompt saved to: ${options.output}`));
289
+ return;
290
+ }
291
+
292
+ const clipResult = copyToClipboard(prompt);
293
+ if (clipResult.success) {
294
+ const ticket = ctx?.taskId ? chalk.gray(` [${ctx.taskId}]`) : '';
295
+ console.log(chalk.green(`✓ Prompt copied to clipboard!${ticket} Paste it into your AI chat to begin.`));
296
+ } else {
297
+ await handleClipboardFailure(prompt, clipResult);
298
+ }
299
+ };
300
+
301
+ // ──────────────────────────────────────────────────────────────
302
+ // Helpers
303
+ // ──────────────────────────────────────────────────────────────
304
+
305
+ async function loadRules() {
306
+ if (!(await fs.pathExists(RULES_DIR))) return '';
307
+
308
+ const files = (await fs.readdir(RULES_DIR)).filter(f => f.endsWith('.md'));
309
+ if (!files.length) return '';
310
+
311
+ const parts = [];
312
+ for (const file of files) {
313
+ const content = await fs.readFile(path.join(RULES_DIR, file), 'utf-8');
314
+ parts.push(`### ${file}\n${content.trim()}`);
315
+ }
316
+ return parts.join('\n\n');
317
+ }
318
+
319
+ function buildPrompt(template, ctx, rules, options, env = 'claude') {
320
+ const lang = options.lang || 'english';
321
+ const detail = options.detail || 'standard';
322
+
323
+ const lines = [];
324
+
325
+ lines.push(`# ${template.header}`);
326
+ lines.push('');
327
+ lines.push(`**Task:** ${template.instruction}`);
328
+ lines.push('');
329
+
330
+ // ── Mandatory skill workflow ───────────────────────────────
331
+ if (template.skillWorkflow) {
332
+ lines.push(template.skillWorkflow.trim());
333
+ lines.push('');
334
+ }
335
+
336
+ // ── Telemetry instructions ─────────────────────────────────
337
+ const ticketArg = ctx?.taskId ? ` --ticket ${ctx.taskId}` : '';
338
+ const akCmd = isWSL() ? 'ak.cmd' : 'ak';
339
+ lines.push(`> **Telemetry (required):** When **starting** each gate run \`${akCmd} gate N start${ticketArg}\`. When **APPROVED** run \`${akCmd} gate N approved${ticketArg}\`. Replace N with the gate number (1–5).`);
340
+ lines.push('');
341
+
342
+ // ── Context section ────────────────────────────────────────
343
+ if (ctx) {
344
+ lines.push('## Context');
345
+ lines.push('');
346
+ lines.push(`- **Ticket:** ${ctx.taskId || 'N/A'}`);
347
+ lines.push(`- **Title:** ${ctx.title || 'N/A'}`);
348
+ lines.push(`- **Status:** ${ctx.status || 'N/A'}`);
349
+ lines.push(`- **Assignee:** ${ctx.assignee || 'N/A'}`);
350
+ lines.push('');
351
+
352
+ if (ctx.description) {
353
+ lines.push('### Description');
354
+ lines.push('');
355
+ lines.push(ctx.description.trim());
356
+ lines.push('');
357
+ }
358
+
359
+ if (ctx.acceptanceCriteria?.length) {
360
+ lines.push('### Acceptance Criteria');
361
+ lines.push('');
362
+ for (const c of ctx.acceptanceCriteria) {
363
+ lines.push(`- ${c}`);
364
+ }
365
+ lines.push('');
366
+ }
367
+
368
+ if (detail === 'comprehensive' && ctx.comments?.length) {
369
+ lines.push('### Comments');
370
+ lines.push('');
371
+ for (const c of ctx.comments) {
372
+ lines.push(c);
373
+ lines.push('');
374
+ }
375
+ }
376
+
377
+ if (ctx.context?.files?.length) {
378
+ lines.push('### Related Files Mentioned');
379
+ lines.push('');
380
+ for (const f of ctx.context.files) {
381
+ lines.push(`- \`${f}\``);
382
+ }
383
+ lines.push('');
384
+ }
385
+ } else {
386
+ lines.push('> No context loaded. Run `aiflow use <ticket>` to load ticket context.');
387
+ lines.push('');
388
+ }
389
+
390
+ // ── Rules section ──────────────────────────────────────────
391
+ if (rules) {
392
+ lines.push('## Team Rules');
393
+ lines.push('');
394
+ lines.push(rules);
395
+ lines.push('');
396
+ }
397
+
398
+ // ── Language instruction ───────────────────────────────────
399
+ if (lang === 'vietnamese') {
400
+ lines.push('> **Reply in English.**');
401
+ lines.push('');
402
+ }
403
+
404
+ // ── Tool-specific instructions ───────────────────────────────
405
+ if (env === 'cursor') {
406
+ lines.push('---');
407
+ lines.push('> **Cursor Tip:** You can use `@Codebase` to search for more context if needed.');
408
+ } else if (env === 'gemini') {
409
+ lines.push('---');
410
+ lines.push('> **Gemini Tip:** Use the "Upload Files" or "Attach File" feature to provide source code context.');
411
+ }
412
+
413
+ return lines.join('\n');
414
+ }
415
+
416
+ function isWSL() {
417
+ if (process.platform !== 'linux') return false;
418
+ try {
419
+ const version = require('fs').readFileSync('/proc/version', 'utf-8');
420
+ return /microsoft|wsl/i.test(version);
421
+ } catch (_) { return false; }
422
+ }
423
+
424
+ function detectLinuxPkgManager() {
425
+ const candidates = [
426
+ { cmd: 'apt-get', installFlag: 'install -y' },
427
+ { cmd: 'dnf', installFlag: 'install -y' },
428
+ { cmd: 'pacman', installFlag: '-S --noconfirm' },
429
+ { cmd: 'zypper', installFlag: 'install -y' },
430
+ ];
431
+ for (const c of candidates) {
432
+ const r = spawnSync('which', [c.cmd], { stdio: 'ignore' });
433
+ if (r.status === 0) return c;
434
+ }
435
+ return null;
436
+ }
437
+
438
+ function linuxClipboardInfo() {
439
+ const isWayland = !!process.env.WAYLAND_DISPLAY;
440
+ const pkg = isWayland ? 'wl-clipboard' : 'xclip';
441
+ const mgr = detectLinuxPkgManager();
442
+ return {
443
+ pkg,
444
+ pkgManager: mgr ? mgr.cmd : null,
445
+ installArgs: mgr ? [...mgr.installFlag.split(' '), pkg] : null,
446
+ installDisplayCmd: mgr ? `sudo ${mgr.cmd} ${mgr.installFlag} ${pkg}` : null,
447
+ };
448
+ }
449
+
450
+ // Returns { success: true } or { success: false, pkg, pkgManager, installArgs, installDisplayCmd }
451
+ function copyToClipboard(text) {
452
+ try {
453
+ if (process.platform === 'win32') {
454
+ spawnSync(
455
+ 'powershell',
456
+ ['-NoProfile', '-NonInteractive', '-Command',
457
+ '[Console]::InputEncoding = [System.Text.Encoding]::UTF8; Set-Clipboard -Value ([Console]::In.ReadToEnd())'],
458
+ { input: text, encoding: 'utf8', stdio: ['pipe', 'ignore', 'ignore'] }
459
+ );
460
+ return { success: true };
461
+ } else if (process.platform === 'darwin') {
462
+ spawnSync('pbcopy', [], { input: text, encoding: 'utf8', stdio: ['pipe', 'ignore', 'ignore'] });
463
+ return { success: true };
464
+ } else if (isWSL()) {
465
+ spawnSync(
466
+ 'powershell.exe',
467
+ ['-NoProfile', '-NonInteractive', '-Command',
468
+ '[Console]::InputEncoding = [System.Text.Encoding]::UTF8; Set-Clipboard -Value ([Console]::In.ReadToEnd())'],
469
+ { input: text, encoding: 'utf8', stdio: ['pipe', 'ignore', 'ignore'] }
470
+ );
471
+ return { success: true };
472
+ } else {
473
+ // Try wl-copy (Wayland), then xclip, then xsel
474
+ if (process.env.WAYLAND_DISPLAY) {
475
+ const r = spawnSync('wl-copy', [], { input: text, encoding: 'utf8', stdio: ['pipe', 'ignore', 'ignore'] });
476
+ if (!r.error && r.status === 0) return { success: true };
477
+ }
478
+ const r = spawnSync('xclip', ['-selection', 'clipboard'], { input: text, encoding: 'utf8', stdio: ['pipe', 'ignore', 'ignore'] });
479
+ if (!r.error && r.status === 0) return { success: true };
480
+ const r2 = spawnSync('xsel', ['--clipboard', '--input'], { input: text, encoding: 'utf8', stdio: ['pipe', 'ignore', 'ignore'] });
481
+ if (!r2.error && r2.status === 0) return { success: true };
482
+ return { success: false, ...linuxClipboardInfo() };
483
+ }
484
+ } catch (_) {
485
+ return { success: false };
486
+ }
487
+ }
488
+
489
+ function showPromptFallback(text) {
490
+ console.log(chalk.cyan('\n' + '─'.repeat(60)));
491
+ console.log(text);
492
+ console.log(chalk.cyan('─'.repeat(60) + '\n'));
493
+ console.log(chalk.yellow('Clipboard unavailable — paste the prompt above into your AI chat.'));
494
+ }
495
+
496
+ async function handleClipboardFailure(text, info) {
497
+ if (!info.pkg) {
498
+ // Unknown platform failure
499
+ showPromptFallback(text);
500
+ return;
501
+ }
502
+
503
+ console.log(chalk.yellow(`\n⚠ Clipboard tool not found (need: ${chalk.white(info.pkg)})`));
504
+
505
+ if (!info.installDisplayCmd) {
506
+ console.log(chalk.gray(' Could not detect a package manager. Install manually:'));
507
+ console.log(chalk.gray(' Wayland: sudo apt install wl-clipboard'));
508
+ console.log(chalk.gray(' X11: sudo apt install xclip\n'));
509
+ showPromptFallback(text);
510
+ return;
511
+ }
512
+
513
+ console.log(chalk.gray(` Install command: ${chalk.white(info.installDisplayCmd)}\n`));
514
+
515
+ try {
516
+ const doInstall = await confirm({
517
+ message: `Install ${info.pkg} now? (requires sudo)`,
518
+ default: true,
519
+ });
520
+
521
+ if (doInstall) {
522
+ console.log(chalk.cyan(`\nRunning: sudo ${info.pkgManager} ${info.installArgs.join(' ')}`));
523
+ const r = spawnSync('sudo', [info.pkgManager, ...info.installArgs], { stdio: 'inherit' });
524
+ if (r.status === 0) {
525
+ const retry = copyToClipboard(text);
526
+ if (retry.success) {
527
+ console.log(chalk.green('\n✓ Installed! Prompt copied to clipboard. Paste it into your AI chat.'));
528
+ return;
529
+ }
530
+ }
531
+ console.log(chalk.red('\nInstallation failed. Showing prompt below:'));
532
+ }
533
+ } catch (_) {
534
+ // Non-interactive terminal (piped) — skip the question
535
+ }
536
+
537
+ showPromptFallback(text);
538
+ }