mindforge-cc 1.0.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 (324) hide show
  1. package/.agent/CLAUDE.md +462 -0
  2. package/.agent/forge/help.md +7 -0
  3. package/.agent/forge/init-project.md +32 -0
  4. package/.agent/forge/plan-phase.md +30 -0
  5. package/.agent/mindforge/approve.md +18 -0
  6. package/.agent/mindforge/audit.md +30 -0
  7. package/.agent/mindforge/benchmark.md +33 -0
  8. package/.agent/mindforge/complete-milestone.md +18 -0
  9. package/.agent/mindforge/debug.md +126 -0
  10. package/.agent/mindforge/discuss-phase.md +138 -0
  11. package/.agent/mindforge/execute-phase.md +165 -0
  12. package/.agent/mindforge/health.md +21 -0
  13. package/.agent/mindforge/help.md +23 -0
  14. package/.agent/mindforge/init-org.md +131 -0
  15. package/.agent/mindforge/init-project.md +155 -0
  16. package/.agent/mindforge/install-skill.md +15 -0
  17. package/.agent/mindforge/map-codebase.md +298 -0
  18. package/.agent/mindforge/metrics.md +22 -0
  19. package/.agent/mindforge/migrate.md +40 -0
  20. package/.agent/mindforge/milestone.md +12 -0
  21. package/.agent/mindforge/next.md +105 -0
  22. package/.agent/mindforge/plan-phase.md +125 -0
  23. package/.agent/mindforge/plugins.md +40 -0
  24. package/.agent/mindforge/pr-review.md +41 -0
  25. package/.agent/mindforge/profile-team.md +23 -0
  26. package/.agent/mindforge/publish-skill.md +19 -0
  27. package/.agent/mindforge/quick.md +135 -0
  28. package/.agent/mindforge/release.md +10 -0
  29. package/.agent/mindforge/retrospective.md +26 -0
  30. package/.agent/mindforge/review.md +157 -0
  31. package/.agent/mindforge/security-scan.md +233 -0
  32. package/.agent/mindforge/ship.md +100 -0
  33. package/.agent/mindforge/skills.md +141 -0
  34. package/.agent/mindforge/status.md +104 -0
  35. package/.agent/mindforge/sync-confluence.md +11 -0
  36. package/.agent/mindforge/sync-jira.md +12 -0
  37. package/.agent/mindforge/tokens.md +8 -0
  38. package/.agent/mindforge/update.md +42 -0
  39. package/.agent/mindforge/verify-phase.md +62 -0
  40. package/.agent/mindforge/workspace.md +29 -0
  41. package/.claude/CLAUDE.md +462 -0
  42. package/.claude/commands/forge/help.md +7 -0
  43. package/.claude/commands/forge/init-project.md +32 -0
  44. package/.claude/commands/forge/plan-phase.md +30 -0
  45. package/.claude/commands/mindforge/approve.md +18 -0
  46. package/.claude/commands/mindforge/audit.md +30 -0
  47. package/.claude/commands/mindforge/benchmark.md +33 -0
  48. package/.claude/commands/mindforge/complete-milestone.md +18 -0
  49. package/.claude/commands/mindforge/debug.md +126 -0
  50. package/.claude/commands/mindforge/discuss-phase.md +138 -0
  51. package/.claude/commands/mindforge/execute-phase.md +165 -0
  52. package/.claude/commands/mindforge/health.md +21 -0
  53. package/.claude/commands/mindforge/help.md +23 -0
  54. package/.claude/commands/mindforge/init-org.md +131 -0
  55. package/.claude/commands/mindforge/init-project.md +155 -0
  56. package/.claude/commands/mindforge/install-skill.md +15 -0
  57. package/.claude/commands/mindforge/map-codebase.md +298 -0
  58. package/.claude/commands/mindforge/metrics.md +22 -0
  59. package/.claude/commands/mindforge/migrate.md +40 -0
  60. package/.claude/commands/mindforge/milestone.md +12 -0
  61. package/.claude/commands/mindforge/next.md +105 -0
  62. package/.claude/commands/mindforge/plan-phase.md +125 -0
  63. package/.claude/commands/mindforge/plugins.md +40 -0
  64. package/.claude/commands/mindforge/pr-review.md +41 -0
  65. package/.claude/commands/mindforge/profile-team.md +23 -0
  66. package/.claude/commands/mindforge/publish-skill.md +19 -0
  67. package/.claude/commands/mindforge/quick.md +135 -0
  68. package/.claude/commands/mindforge/release.md +10 -0
  69. package/.claude/commands/mindforge/retrospective.md +26 -0
  70. package/.claude/commands/mindforge/review.md +157 -0
  71. package/.claude/commands/mindforge/security-scan.md +233 -0
  72. package/.claude/commands/mindforge/ship.md +100 -0
  73. package/.claude/commands/mindforge/skills.md +141 -0
  74. package/.claude/commands/mindforge/status.md +104 -0
  75. package/.claude/commands/mindforge/sync-confluence.md +11 -0
  76. package/.claude/commands/mindforge/sync-jira.md +12 -0
  77. package/.claude/commands/mindforge/tokens.md +8 -0
  78. package/.claude/commands/mindforge/update.md +42 -0
  79. package/.claude/commands/mindforge/verify-phase.md +62 -0
  80. package/.claude/commands/mindforge/workspace.md +29 -0
  81. package/.forge/org/CONVENTIONS.md +0 -0
  82. package/.forge/org/ORG.md +0 -0
  83. package/.forge/org/SECURITY.md +0 -0
  84. package/.forge/org/TOOLS.md +0 -0
  85. package/.forge/personas/analyst.md +0 -0
  86. package/.forge/personas/architect.md +0 -0
  87. package/.forge/personas/debug-specialist.md +0 -0
  88. package/.forge/personas/developer.md +26 -0
  89. package/.forge/personas/qa-engineer.md +0 -0
  90. package/.forge/personas/release-manager.md +0 -0
  91. package/.forge/personas/security-reviewer.md +33 -0
  92. package/.forge/personas/tech-writer.md +0 -0
  93. package/.forge/skills/api-design/SKILL.md +0 -0
  94. package/.forge/skills/code-quality/SKILL.md +0 -0
  95. package/.forge/skills/documentation/SKILL.md +0 -0
  96. package/.forge/skills/security-review/SKILL.md +23 -0
  97. package/.forge/skills/testing-standards/SKILL.md +27 -0
  98. package/.github/workflows/mindforge-ci.yml +224 -0
  99. package/.gitlab-ci-mindforge.yml +18 -0
  100. package/.mindforge/MINDFORGE-SCHEMA.json +165 -0
  101. package/.mindforge/audit/AUDIT-SCHEMA.md +451 -0
  102. package/.mindforge/ci/ci-config-schema.md +21 -0
  103. package/.mindforge/ci/ci-mode.md +179 -0
  104. package/.mindforge/ci/github-actions-adapter.md +224 -0
  105. package/.mindforge/ci/gitlab-ci-adapter.md +31 -0
  106. package/.mindforge/ci/jenkins-adapter.md +44 -0
  107. package/.mindforge/distribution/registry-client.md +166 -0
  108. package/.mindforge/distribution/registry-schema.md +96 -0
  109. package/.mindforge/distribution/skill-publisher.md +44 -0
  110. package/.mindforge/distribution/skill-validator.md +74 -0
  111. package/.mindforge/engine/compaction-protocol.md +182 -0
  112. package/.mindforge/engine/context-injector.md +128 -0
  113. package/.mindforge/engine/dependency-parser.md +113 -0
  114. package/.mindforge/engine/skills/conflict-resolver.md +69 -0
  115. package/.mindforge/engine/skills/loader.md +184 -0
  116. package/.mindforge/engine/skills/registry.md +98 -0
  117. package/.mindforge/engine/skills/versioning.md +75 -0
  118. package/.mindforge/engine/verification-pipeline.md +111 -0
  119. package/.mindforge/engine/wave-executor.md +235 -0
  120. package/.mindforge/governance/GOVERNANCE-CONFIG.md +17 -0
  121. package/.mindforge/governance/approval-workflow.md +37 -0
  122. package/.mindforge/governance/change-classifier.md +63 -0
  123. package/.mindforge/governance/compliance-gates.md +31 -0
  124. package/.mindforge/integrations/confluence.md +27 -0
  125. package/.mindforge/integrations/connection-manager.md +163 -0
  126. package/.mindforge/integrations/github.md +25 -0
  127. package/.mindforge/integrations/gitlab.md +13 -0
  128. package/.mindforge/integrations/jira.md +102 -0
  129. package/.mindforge/integrations/slack.md +41 -0
  130. package/.mindforge/intelligence/antipattern-detector.md +75 -0
  131. package/.mindforge/intelligence/difficulty-scorer.md +55 -0
  132. package/.mindforge/intelligence/health-engine.md +208 -0
  133. package/.mindforge/intelligence/skill-gap-analyser.md +40 -0
  134. package/.mindforge/intelligence/smart-compaction.md +71 -0
  135. package/.mindforge/metrics/METRICS-SCHEMA.md +42 -0
  136. package/.mindforge/metrics/quality-tracker.md +32 -0
  137. package/.mindforge/monorepo/cross-package-planner.md +114 -0
  138. package/.mindforge/monorepo/dependency-graph-builder.md +32 -0
  139. package/.mindforge/monorepo/workspace-detector.md +129 -0
  140. package/.mindforge/org/CONVENTIONS.md +62 -0
  141. package/.mindforge/org/ORG.md +51 -0
  142. package/.mindforge/org/SECURITY.md +50 -0
  143. package/.mindforge/org/TOOLS.md +53 -0
  144. package/.mindforge/org/integrations/INTEGRATIONS-CONFIG.md +58 -0
  145. package/.mindforge/org/skills/MANIFEST.md +38 -0
  146. package/.mindforge/personas/analyst.md +52 -0
  147. package/.mindforge/personas/architect.md +75 -0
  148. package/.mindforge/personas/debug-specialist.md +52 -0
  149. package/.mindforge/personas/developer.md +85 -0
  150. package/.mindforge/personas/overrides/README.md +85 -0
  151. package/.mindforge/personas/qa-engineer.md +61 -0
  152. package/.mindforge/personas/release-manager.md +76 -0
  153. package/.mindforge/personas/security-reviewer.md +91 -0
  154. package/.mindforge/personas/tech-writer.md +51 -0
  155. package/.mindforge/plugins/PLUGINS-MANIFEST.md +23 -0
  156. package/.mindforge/plugins/plugin-loader.md +93 -0
  157. package/.mindforge/plugins/plugin-registry.md +44 -0
  158. package/.mindforge/plugins/plugin-schema.md +68 -0
  159. package/.mindforge/pr-review/ai-reviewer.md +266 -0
  160. package/.mindforge/pr-review/finding-formatter.md +46 -0
  161. package/.mindforge/pr-review/review-prompt-templates.md +44 -0
  162. package/.mindforge/production/compatibility-layer.md +39 -0
  163. package/.mindforge/production/migration-engine.md +52 -0
  164. package/.mindforge/production/production-checklist.md +165 -0
  165. package/.mindforge/production/token-optimiser.md +68 -0
  166. package/.mindforge/skills/accessibility/SKILL.md +106 -0
  167. package/.mindforge/skills/api-design/SKILL.md +98 -0
  168. package/.mindforge/skills/code-quality/SKILL.md +88 -0
  169. package/.mindforge/skills/data-privacy/SKILL.md +126 -0
  170. package/.mindforge/skills/database-patterns/SKILL.md +192 -0
  171. package/.mindforge/skills/documentation/SKILL.md +91 -0
  172. package/.mindforge/skills/incident-response/SKILL.md +180 -0
  173. package/.mindforge/skills/performance/SKILL.md +120 -0
  174. package/.mindforge/skills/security-review/SKILL.md +83 -0
  175. package/.mindforge/skills/testing-standards/SKILL.md +97 -0
  176. package/.mindforge/team/TEAM-PROFILE.md +42 -0
  177. package/.mindforge/team/multi-handoff.md +23 -0
  178. package/.mindforge/team/profiles/README.md +13 -0
  179. package/.mindforge/team/session-merger.md +18 -0
  180. package/.planning/ARCHITECTURE.md +0 -0
  181. package/.planning/AUDIT.jsonl +0 -0
  182. package/.planning/HANDOFF.json +28 -0
  183. package/.planning/PROJECT.md +33 -0
  184. package/.planning/RELEASE-CHECKLIST.md +68 -0
  185. package/.planning/REQUIREMENTS.md +0 -0
  186. package/.planning/ROADMAP.md +0 -0
  187. package/.planning/STATE.md +31 -0
  188. package/.planning/approvals/.gitkeep +1 -0
  189. package/.planning/archive/.gitkeep +1 -0
  190. package/.planning/audit-archive/.gitkeep +1 -0
  191. package/.planning/decisions/.gitkeep +0 -0
  192. package/.planning/decisions/ADR-001-handoff-tracking.md +41 -0
  193. package/.planning/decisions/ADR-002-markdown-commands.md +46 -0
  194. package/.planning/decisions/ADR-003-skills-trigger-model.md +37 -0
  195. package/.planning/decisions/ADR-004-wave-parallelism-model.md +45 -0
  196. package/.planning/decisions/ADR-005-append-only-audit-log.md +51 -0
  197. package/.planning/decisions/ADR-006-tiered-skills-system.md +22 -0
  198. package/.planning/decisions/ADR-007-trigger-keyword-model.md +22 -0
  199. package/.planning/decisions/ADR-008-just-in-time-skill-loading.md +29 -0
  200. package/.planning/decisions/ADR-009-enterprise-integration-retry-policy.md +8 -0
  201. package/.planning/decisions/ADR-010-governance-tier-escalation.md +8 -0
  202. package/.planning/decisions/ADR-011-multi-developer-handoff-contract.md +8 -0
  203. package/.planning/decisions/ADR-012-intelligence-feedback-loops.md +19 -0
  204. package/.planning/decisions/ADR-013-mindforge-md-constitution.md +16 -0
  205. package/.planning/decisions/ADR-014-metrics-as-signals-not-evaluation.md +15 -0
  206. package/.planning/decisions/ADR-015-npm-based-skill-registry.md +26 -0
  207. package/.planning/decisions/ADR-016-ci-exit-code-0-on-timeout.md +27 -0
  208. package/.planning/decisions/ADR-017-sdk-localhost-only.md +28 -0
  209. package/.planning/decisions/ADR-018-installer-self-install-detection.md +15 -0
  210. package/.planning/decisions/ADR-019-self-update-scope-preservation.md +14 -0
  211. package/.planning/decisions/ADR-020-v1.0.0-stable-interface-contract.md +23 -0
  212. package/.planning/jira-sync.json +9 -0
  213. package/.planning/milestones/.gitkeep +1 -0
  214. package/.planning/phases/day1/REVIEW-DAY1.md +50 -0
  215. package/.planning/phases/day1/SECURITY-REVIEW-DAY1.md +15 -0
  216. package/.planning/phases/day2/REVIEW-DAY2.md +521 -0
  217. package/.planning/phases/day3/REVIEW-DAY3.md +234 -0
  218. package/.planning/slack-threads.json +6 -0
  219. package/CHANGELOG.md +175 -0
  220. package/LICENSE +21 -0
  221. package/MINDFORGE.md +76 -0
  222. package/README.md +182 -0
  223. package/RELEASENOTES.md +41 -0
  224. package/SECURITY.md +4 -0
  225. package/bin/install.js +120 -0
  226. package/bin/installer-core.js +292 -0
  227. package/bin/migrations/0.1.0-to-0.5.0.js +37 -0
  228. package/bin/migrations/0.5.0-to-0.6.0.js +17 -0
  229. package/bin/migrations/0.6.0-to-1.0.0.js +100 -0
  230. package/bin/migrations/migrate.js +151 -0
  231. package/bin/migrations/schema-versions.js +64 -0
  232. package/bin/updater/changelog-fetcher.js +62 -0
  233. package/bin/updater/self-update.js +169 -0
  234. package/bin/updater/version-comparator.js +68 -0
  235. package/bin/validate-config.js +92 -0
  236. package/bin/wizard/config-generator.js +112 -0
  237. package/bin/wizard/environment-detector.js +76 -0
  238. package/bin/wizard/setup-wizard.js +237 -0
  239. package/docs/Context/Master-Context.md +701 -0
  240. package/docs/architecture/README.md +35 -0
  241. package/docs/architecture/decision-records-index.md +26 -0
  242. package/docs/ci-cd-integration.md +30 -0
  243. package/docs/ci-quickstart.md +78 -0
  244. package/docs/commands-reference.md +11 -0
  245. package/docs/contributing/CONTRIBUTING.md +38 -0
  246. package/docs/contributing/plugin-authoring.md +50 -0
  247. package/docs/contributing/skill-authoring.md +41 -0
  248. package/docs/enterprise-setup.md +25 -0
  249. package/docs/faq.md +38 -0
  250. package/docs/getting-started.md +36 -0
  251. package/docs/governance-guide.md +23 -0
  252. package/docs/mindforge-md-reference.md +53 -0
  253. package/docs/monorepo-guide.md +26 -0
  254. package/docs/persona-customisation.md +56 -0
  255. package/docs/quick-verify.md +33 -0
  256. package/docs/reference/audit-events.md +53 -0
  257. package/docs/reference/commands.md +82 -0
  258. package/docs/reference/config-reference.md +64 -0
  259. package/docs/reference/sdk-api.md +48 -0
  260. package/docs/reference/skills-api.md +57 -0
  261. package/docs/release-checklist-guide.md +37 -0
  262. package/docs/requirements.md +29 -0
  263. package/docs/sdk-reference.md +27 -0
  264. package/docs/security/SECURITY.md +42 -0
  265. package/docs/security/penetration-test-results.md +31 -0
  266. package/docs/security/threat-model.md +142 -0
  267. package/docs/skills-authoring-guide.md +119 -0
  268. package/docs/skills-publishing-guide.md +21 -0
  269. package/docs/team-setup-guide.md +21 -0
  270. package/docs/troubleshooting.md +119 -0
  271. package/docs/tutorial.md +195 -0
  272. package/docs/upgrade.md +44 -0
  273. package/docs/user-guide.md +131 -0
  274. package/docs/usp-features.md +214 -0
  275. package/eslint.config.mjs +31 -0
  276. package/examples/starter-project/.planning/AUDIT.jsonl +1 -0
  277. package/examples/starter-project/.planning/HANDOFF.json +23 -0
  278. package/examples/starter-project/.planning/PROJECT.md +27 -0
  279. package/examples/starter-project/.planning/STATE.md +10 -0
  280. package/examples/starter-project/MINDFORGE.md +40 -0
  281. package/examples/starter-project/README.md +14 -0
  282. package/implementation-roadmap/day-1-imp/DAY1-HARDEN.md +823 -0
  283. package/implementation-roadmap/day-1-imp/DAY1-IMPLEMENT.md +2459 -0
  284. package/implementation-roadmap/day-1-imp/DAY1-REVIEW.md +288 -0
  285. package/implementation-roadmap/day-2-imp/DAY2-HARDEN.md +954 -0
  286. package/implementation-roadmap/day-2-imp/DAY2-IMPLEMENT.md +2347 -0
  287. package/implementation-roadmap/day-2-imp/DAY2-REVIEW.md +422 -0
  288. package/implementation-roadmap/day-3-imp/DAY3-HARDEN.md +870 -0
  289. package/implementation-roadmap/day-3-imp/DAY3-IMPLEMENT.md +2798 -0
  290. package/implementation-roadmap/day-3-imp/DAY3-REVIEW.md +484 -0
  291. package/implementation-roadmap/day-4-imp/DAY4-HARDEN.md +1087 -0
  292. package/implementation-roadmap/day-4-imp/DAY4-IMPLEMENT.md +2874 -0
  293. package/implementation-roadmap/day-4-imp/DAY4-REVIEW.md +386 -0
  294. package/implementation-roadmap/day-5-imp/DAY5-HARDEN.md +1078 -0
  295. package/implementation-roadmap/day-5-imp/DAY5-IMPLEMENT.md +3151 -0
  296. package/implementation-roadmap/day-5-imp/DAY5-REVIEW.md +345 -0
  297. package/implementation-roadmap/day-6-imp/DAY6-COMPLETE.md +3919 -0
  298. package/implementation-roadmap/day-7-imp-prod/DAY7-PRODUCTION-FINAL.md +4513 -0
  299. package/package.json +31 -0
  300. package/sdk/README.md +69 -0
  301. package/sdk/eslint.config.mjs +34 -0
  302. package/sdk/package-lock.json +1507 -0
  303. package/sdk/package.json +30 -0
  304. package/sdk/src/client.ts +133 -0
  305. package/sdk/src/commands.ts +63 -0
  306. package/sdk/src/events.ts +166 -0
  307. package/sdk/src/index.ts +22 -0
  308. package/sdk/src/types.ts +87 -0
  309. package/sdk/tsconfig.json +13 -0
  310. package/tests/audit.test.js +206 -0
  311. package/tests/ci-mode.test.js +162 -0
  312. package/tests/compaction.test.js +161 -0
  313. package/tests/distribution.test.js +205 -0
  314. package/tests/e2e.test.js +618 -0
  315. package/tests/governance.test.js +130 -0
  316. package/tests/install.test.js +209 -0
  317. package/tests/integrations.test.js +128 -0
  318. package/tests/intelligence.test.js +117 -0
  319. package/tests/metrics.test.js +96 -0
  320. package/tests/migration.test.js +309 -0
  321. package/tests/production.test.js +416 -0
  322. package/tests/sdk.test.js +200 -0
  323. package/tests/skills-platform.test.js +403 -0
  324. package/tests/wave-engine.test.js +338 -0
@@ -0,0 +1,2347 @@
1
+ # MindForge — Day 2 Implementation Prompt
2
+ # Branch: `feat/mindforge-wave-engine`
3
+ # Prerequisite: `feat/mindforge-core-scaffold` merged to `main`
4
+
5
+ ---
6
+
7
+ ## BRANCH SETUP (run before anything else)
8
+
9
+ ```bash
10
+ git checkout main
11
+ git pull origin main
12
+ git checkout -b feat/mindforge-wave-engine
13
+ ```
14
+
15
+ Verify Day 1 is present before starting:
16
+
17
+ ```bash
18
+ ls .claude/CLAUDE.md # must exist
19
+ ls .mindforge/personas/developer.md # must exist
20
+ ls .claude/commands/mindforge/execute-phase.md # must exist
21
+ node tests/install.test.js # must pass
22
+ ```
23
+
24
+ If any of these fail — stop. Merge Day 1 first.
25
+
26
+ ---
27
+
28
+ ## DAY 2 SCOPE
29
+
30
+ Day 2 builds the **execution intelligence layer** of MindForge.
31
+ Day 1 created the structure. Day 2 makes it actually run.
32
+
33
+ | Component | Description |
34
+ |---|---|
35
+ | Wave Execution Engine | Dependency graph parser + wave grouping algorithm |
36
+ | Parallel Orchestration | Subagent spawning with isolated context injection |
37
+ | Context Compaction Engine | Automated 70% threshold detection and state preservation |
38
+ | AUDIT.jsonl Pipeline | Append-only tamper-evident audit log for every agent action |
39
+ | `/mindforge:next` command | Auto-detects project state and routes to the correct next step |
40
+ | `/mindforge:quick` command | Ad-hoc task execution without full lifecycle overhead |
41
+ | `/mindforge:status` command | Rich project dashboard — phases, tasks, health, blockers |
42
+ | `/mindforge:debug` command | Debug Specialist workflow with systematic RCA protocol |
43
+ | Phase verification pipeline | Automated requirement tracing from REQUIREMENTS.md to code |
44
+ | Session handoff automation | HANDOFF.json written automatically at compaction threshold |
45
+
46
+ **Do not** implement on Day 2:
47
+ - Jira / Confluence / Slack integrations (Day 4)
48
+ - GUI dashboard or web interface (Day 5+)
49
+ - Multi-repo support (Day 6+)
50
+ - Team collaboration features (Day 4+)
51
+
52
+ ---
53
+
54
+ ## TASK 1 — Scaffold Day 2 additions to directory structure
55
+
56
+ Add these new directories and files to the existing scaffold:
57
+
58
+ ```bash
59
+ # Wave execution engine
60
+ mkdir -p .mindforge/engine
61
+ touch .mindforge/engine/wave-executor.md
62
+ touch .mindforge/engine/dependency-parser.md
63
+ touch .mindforge/engine/context-injector.md
64
+ touch .mindforge/engine/compaction-protocol.md
65
+
66
+ # Audit system
67
+ mkdir -p .mindforge/audit
68
+ touch .mindforge/audit/AUDIT-SCHEMA.md
69
+ touch .planning/AUDIT.jsonl
70
+
71
+ # New commands
72
+ touch .claude/commands/mindforge/next.md
73
+ touch .claude/commands/mindforge/quick.md
74
+ touch .claude/commands/mindforge/status.md
75
+ touch .claude/commands/mindforge/debug.md
76
+
77
+ # Mirror to Antigravity
78
+ cp .claude/commands/mindforge/next.md .agent/mindforge/next.md
79
+ cp .claude/commands/mindforge/quick.md .agent/mindforge/quick.md
80
+ cp .claude/commands/mindforge/status.md .agent/mindforge/status.md
81
+ cp .claude/commands/mindforge/debug.md .agent/mindforge/debug.md
82
+
83
+ # Phase verification
84
+ touch .mindforge/engine/verification-pipeline.md
85
+
86
+ # Test expansions
87
+ touch tests/wave-engine.test.js
88
+ touch tests/audit.test.js
89
+ touch tests/compaction.test.js
90
+ ```
91
+
92
+ **Commit:**
93
+ ```bash
94
+ git add .
95
+ git commit -m "chore(day2): scaffold Day 2 directory additions"
96
+ ```
97
+
98
+ ---
99
+
100
+ ## TASK 2 — Write the Wave Execution Engine
101
+
102
+ The wave execution engine is the most architecturally significant component in
103
+ MindForge. It transforms a flat list of PLAN files into a dependency-aware
104
+ execution graph, groups independent tasks into parallel waves, and coordinates
105
+ subagent spawning.
106
+
107
+ Write this as an engine specification document AND update the
108
+ `execute-phase.md` command to use it.
109
+
110
+ ---
111
+
112
+ ### `.mindforge/engine/dependency-parser.md`
113
+
114
+ ```markdown
115
+ # MindForge Engine — Dependency Parser
116
+
117
+ ## Purpose
118
+ Parse all PLAN files for a given phase and build a directed acyclic graph (DAG)
119
+ of task dependencies. This graph is the input to the wave grouping algorithm.
120
+
121
+ ## Input
122
+ All files matching: `.planning/phases/[N]/PLAN-[N]-*.md`
123
+
124
+ ## Parsing protocol
125
+
126
+ ### Step 1 — Read all plan files
127
+ For each PLAN file in the phase directory:
128
+ 1. Read the full file content
129
+ 2. Extract the `<task>` XML block
130
+ 3. Parse these fields:
131
+ - `<n>` → task name (string)
132
+ - `<plan>` → plan ID (e.g., "01", "02")
133
+ - `<dependencies>` → comma-separated list of plan IDs, or "none"
134
+ - `<files>` → newline-separated list of file paths
135
+
136
+ ### Step 2 — Build the dependency graph
137
+ Represent the graph as an adjacency list:
138
+
139
+ ```
140
+ Graph = {
141
+ "01": { name: "...", dependsOn: [], blockedBy: [] },
142
+ "02": { name: "...", dependsOn: [], blockedBy: [] },
143
+ "03": { name: "...", dependsOn: ["01"], blockedBy: [] },
144
+ "04": { name: "...", dependsOn: ["01","02"],blockedBy: [] },
145
+ "05": { name: "...", dependsOn: ["03","04"],blockedBy: [] },
146
+ }
147
+ ```
148
+
149
+ ### Step 3 — Validate the graph
150
+ Before proceeding, validate:
151
+
152
+ **Circular dependency check:**
153
+ Perform a depth-first traversal. If any node is visited twice in the same
154
+ traversal path, a cycle exists. Stop and report:
155
+ "Circular dependency detected: [plan A] → [plan B] → [plan A]"
156
+ A cycle makes execution impossible. The user must fix the PLAN files.
157
+
158
+ **Missing dependency check:**
159
+ For every plan ID in any `<dependencies>` list, verify that a corresponding
160
+ PLAN file exists. If not:
161
+ "Plan [N]-[M] declares dependency on [X] but PLAN-[N]-[X].md does not exist."
162
+
163
+ **File conflict check:**
164
+ If two plans in the same potential wave touch the same file, they CANNOT
165
+ run in parallel — they must be in different waves. Flag any such conflicts:
166
+ "Plans [A] and [B] both modify [file]. Placing [B] in a later wave."
167
+ Automatically adjust wave assignment to resolve file conflicts.
168
+
169
+ ### Step 4 — Output the dependency report
170
+ Write to `.planning/phases/[N]/DEPENDENCY-GRAPH-[N].md`:
171
+
172
+ ```markdown
173
+ # Dependency Graph — Phase [N]
174
+
175
+ ## Tasks
176
+ | Plan | Name | Depends On | File Conflicts |
177
+ |------|-----------------------|---------------|----------------|
178
+ | 01 | Create user model | none | none |
179
+ | 02 | Create product model | none | none |
180
+ | 03 | User API endpoints | 01 | none |
181
+ | 04 | Product API endpoints | 02 | none |
182
+ | 05 | Checkout UI | 03, 04 | none |
183
+
184
+ ## Validation
185
+ - Circular dependencies: None ✅
186
+ - Missing dependencies: None ✅
187
+ - File conflicts resolved: [list any that were adjusted]
188
+
189
+ ## Execution order
190
+ Wave 1 → Wave 2 → Wave 3
191
+ (see wave-executor.md for wave grouping)
192
+ ```
193
+ ```
194
+
195
+ ---
196
+
197
+ ### `.mindforge/engine/wave-executor.md`
198
+
199
+ ```markdown
200
+ # MindForge Engine — Wave Executor
201
+
202
+ ## Purpose
203
+ Group tasks from the dependency graph into waves and execute each wave.
204
+ Within a wave, all tasks are independent and can run in parallel.
205
+ Between waves, execution is strictly sequential.
206
+
207
+ ## Wave grouping algorithm
208
+
209
+ ### Input
210
+ The dependency graph from `dependency-parser.md`.
211
+
212
+ ### Algorithm — Kahn's topological sort (adapted for waves)
213
+
214
+ ```
215
+ Initialize:
216
+ remaining = all plan IDs
217
+ completed = empty set
218
+ waves = []
219
+
220
+ Repeat until remaining is empty:
221
+ current_wave = []
222
+ for each plan in remaining:
223
+ if ALL of plan's dependencies are in completed:
224
+ add plan to current_wave
225
+
226
+ if current_wave is empty AND remaining is not empty:
227
+ ERROR: circular dependency detected (should have been caught by parser)
228
+
229
+ waves.append(current_wave)
230
+ completed.add(all plans in current_wave)
231
+ remaining.remove(all plans in current_wave)
232
+
233
+ Return waves
234
+ ```
235
+
236
+ ### Example output for the 5-plan example above:
237
+ ```
238
+ Wave 1: [01, 02] ← No dependencies — run in parallel
239
+ Wave 2: [03, 04] ← Depend on Wave 1 — run in parallel after Wave 1
240
+ Wave 3: [05] ← Depends on both Wave 2 tasks — runs after Wave 2
241
+ ```
242
+
243
+ ## Wave execution protocol
244
+
245
+ ### Before starting a wave
246
+ 1. Confirm all plans in previous wave have:
247
+ - Status: Completed in SUMMARY file
248
+ - Git commit SHA recorded
249
+ - `<verify>` step passed
250
+
251
+ If any plan in the previous wave failed: STOP the entire phase.
252
+ Do not start the next wave. Report which plan failed and why.
253
+
254
+ ### During a wave — parallel execution
255
+ For each plan in the current wave, spawn a subagent with this exact context
256
+ package (see `context-injector.md` for the injection protocol):
257
+
258
+ **Context package per subagent:**
259
+ ```
260
+ REQUIRED (always inject):
261
+ .mindforge/org/CONVENTIONS.md
262
+ .mindforge/org/SECURITY.md
263
+ The specific PLAN file (PLAN-[N]-[M].md)
264
+ The persona file specified in <persona> field
265
+
266
+ CONDITIONAL (inject only if referenced in plan):
267
+ .planning/ARCHITECTURE.md ← if plan touches architecture
268
+ .planning/decisions/ADR-*.md ← only ADRs referenced in plan's <context>
269
+ Relevant SKILL.md files ← only skills listed in plan's <context>
270
+
271
+ NEVER inject to subagents:
272
+ STATE.md ← subagents do not need project-level state
273
+ ROADMAP.md ← subagents do not need project-level roadmap
274
+ HANDOFF.json ← subagents do not maintain session continuity
275
+ Other plans ← subagents must not see sibling task plans
276
+ ```
277
+
278
+ ### After each plan in a wave completes
279
+ The executing subagent must:
280
+ 1. Run the `<verify>` step and capture output
281
+ 2. Write SUMMARY-[N]-[M].md with verify output included
282
+ 3. Commit with: `git add [files-in-plan] && git commit -m "type(scope): task name"`
283
+ 4. Write an AUDIT entry (see `audit/AUDIT-SCHEMA.md`)
284
+ 5. Report completion status back to the orchestrator
285
+
286
+ ### Wave completion
287
+ After all plans in a wave complete:
288
+ 1. Collect all SUMMARY files from this wave
289
+ 2. Run the project's full test suite
290
+ 3. If tests fail: identify which plan introduced the failure (use `git bisect`)
291
+ 4. Do not start the next wave until all tests pass
292
+
293
+ ### Phase completion
294
+ After all waves complete:
295
+ 1. Run the phase verification pipeline (see `verification-pipeline.md`)
296
+ 2. Write VERIFICATION.md
297
+ 3. Update STATE.md: phase N = complete
298
+ 4. Update HANDOFF.json with next phase information
299
+
300
+ ## Wave execution report format
301
+
302
+ Write to `.planning/phases/[N]/WAVE-REPORT-[N].md`:
303
+
304
+ ```markdown
305
+ # Wave Execution Report — Phase [N]
306
+
307
+ ## Wave 1
308
+ | Plan | Task Name | Status | Duration | Commit |
309
+ |------|---------------------|--------|----------|------------|
310
+ | 01 | Create user model | ✅ | ~8 min | abc1234 |
311
+ | 02 | Create product model| ✅ | ~6 min | def5678 |
312
+
313
+ **Wave 1 test results:** All passing ✅
314
+
315
+ ## Wave 2
316
+ | Plan | Task Name | Status | Duration | Commit |
317
+ |------|-----------------------|--------|----------|------------|
318
+ | 03 | User API endpoints | ✅ | ~12 min | ghi9012 |
319
+ | 04 | Product API endpoints | ✅ | ~10 min | jkl3456 |
320
+
321
+ **Wave 2 test results:** All passing ✅
322
+
323
+ ## Wave 3
324
+ | Plan | Task Name | Status | Duration | Commit |
325
+ |------|---------------|--------|----------|------------|
326
+ | 05 | Checkout UI | ✅ | ~15 min | mno7890 |
327
+
328
+ **Wave 3 test results:** All passing ✅
329
+
330
+ ## Phase summary
331
+ - Total tasks: 5
332
+ - Total commits: 5
333
+ - Elapsed: ~51 min
334
+ - Test results: All passing
335
+ - Status: Phase [N] complete ✅
336
+ ```
337
+ ```
338
+
339
+ ---
340
+
341
+ ### `.mindforge/engine/context-injector.md`
342
+
343
+ ```markdown
344
+ # MindForge Engine — Context Injector
345
+
346
+ ## Purpose
347
+ Define exactly what context each subagent receives when spawned during
348
+ wave execution. The context injector enforces the principle of minimum
349
+ necessary context — giving subagents only what they need, nothing more.
350
+
351
+ ## Why minimum context matters
352
+ Each subagent has 200K tokens. Wasting tokens on irrelevant files means less
353
+ capacity for actual reasoning about the task. A subagent that receives only
354
+ its PLAN, its persona, and relevant conventions will produce better output than
355
+ one buried under the entire project's context.
356
+
357
+ ## Context injection template
358
+
359
+ When spawning a subagent for PLAN-[N]-[M].md, construct this system message:
360
+
361
+ ```
362
+ You are a MindForge agent executing a specific task. Read these instructions completely.
363
+
364
+ ## Your identity
365
+ [Full contents of the persona file specified in <persona> field]
366
+
367
+ ## Your conventions
368
+ [Full contents of CONVENTIONS.md]
369
+
370
+ ## Your security requirements
371
+ [Full contents of SECURITY.md]
372
+
373
+ ## Your task
374
+ [Full contents of PLAN-[N]-[M].md]
375
+
376
+ ## Architecture context
377
+ [Contents of ARCHITECTURE.md sections relevant to the files in <files> field]
378
+ [Only include sections, not the entire file]
379
+
380
+ ## Relevant decisions
381
+ [Contents of any ADR files referenced in the plan's <context> field]
382
+ [Only the referenced ones]
383
+
384
+ ## Active skills
385
+ [Contents of any SKILL.md files listed in the plan's <context> field]
386
+ [Only the listed ones]
387
+
388
+ ## Execution rules (mandatory)
389
+ 1. Implement ONLY what is specified in your <task> block. Nothing more.
390
+ 2. Touch ONLY the files listed in <files>. Nothing else.
391
+ 3. Run the <verify> step. Report its exact output.
392
+ 4. If the verify step fails: describe what failed and why. Do not mark done.
393
+ 5. Write your SUMMARY after completion (template below).
394
+ 6. Commit with: type(scope): [task name from <n>]
395
+
396
+ ## SUMMARY template
397
+ File: .planning/phases/[N]/SUMMARY-[N]-[M].md
398
+ [Use the standard SUMMARY template from execute-phase.md]
399
+
400
+ ## Important constraints
401
+ - You are one task in a larger wave. Other tasks are running in parallel.
402
+ - You do not know what the other tasks are doing. That is intentional.
403
+ - Do not read files outside your <files> list. You may read them to
404
+ understand existing code context, but your writes are scoped to <files>.
405
+ - If you encounter something unexpected that requires scope expansion:
406
+ stop, describe what you found, and wait for orchestrator input.
407
+ ```
408
+
409
+ ## Context size budget
410
+
411
+ Before injecting, estimate the total context size:
412
+ - Persona file: ~1-3K tokens
413
+ - CONVENTIONS.md: ~2-5K tokens
414
+ - SECURITY.md: ~2-4K tokens
415
+ - PLAN file: ~500-2K tokens
416
+ - ARCHITECTURE sections: ~2-10K tokens
417
+ - ADR files: ~1-3K tokens each
418
+ - SKILL files: ~2-5K tokens each
419
+
420
+ Target: under 30K tokens for context injection.
421
+ This leaves 170K tokens for actual implementation work.
422
+
423
+ If the context package would exceed 30K tokens:
424
+ 1. Summarise ARCHITECTURE.md to only the directly relevant sections
425
+ 2. Reference ADRs by title rather than full content if not critical
426
+ 3. Never compress the PLAN file or security/conventions files
427
+
428
+ ## Subagent completion protocol
429
+
430
+ After the subagent completes, the orchestrator must receive:
431
+ 1. Status: completed ✅ / failed ❌ / blocked 🚫
432
+ 2. The verify step output (exact text)
433
+ 3. The git commit SHA
434
+ 4. The path to SUMMARY-[N]-[M].md
435
+ 5. Any decisions made that deviated from the plan (for escalation)
436
+
437
+ If status is failed or blocked: the orchestrator stops the wave and
438
+ reports to the user before taking any further action.
439
+ ```
440
+
441
+ ---
442
+
443
+ Now update `.claude/commands/mindforge/execute-phase.md` to incorporate the
444
+ wave engine. Replace the entire file with:
445
+
446
+ ```markdown
447
+ # MindForge — Execute Phase Command
448
+ # Usage: /mindforge:execute-phase [N]
449
+
450
+ ## Pre-checks (all must pass before execution starts)
451
+
452
+ 1. Read STATE.md — confirm phase [N] is in "planned" status.
453
+ If STATE.md shows phase [N] as already "complete": ask user to confirm re-execution.
454
+
455
+ 2. Verify plan files exist:
456
+ ```
457
+ .planning/phases/[N]/PLAN-[N]-01.md (minimum one plan required)
458
+ ```
459
+ If missing: stop. Tell user: "No plans found for Phase [N]. Run /mindforge:plan-phase [N] first."
460
+
461
+ 3. Verify REQUIREMENTS.md exists and has content.
462
+ If empty: warn user but allow continuation.
463
+
464
+ 4. Run the dependency parser (`.mindforge/engine/dependency-parser.md`).
465
+ If validation fails (circular deps, missing deps): stop and report. Do not execute.
466
+
467
+ ## Step 1 — Build and display the execution plan
468
+
469
+ After dependency parsing succeeds, display the wave plan to the user:
470
+
471
+ ```
472
+ Phase [N] Execution Plan
473
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
474
+
475
+ Wave 1 (parallel) Wave 2 (parallel) Wave 3
476
+ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
477
+ │ Plan 01 │ │ Plan 03 │ │ Plan 05 │
478
+ │ User model │──┐ │ User API │──┐ │ Checkout UI │
479
+ └─────────────┘ │ └─────────────┘ │ └─────────────┘
480
+ ┌─────────────┐ │ ┌─────────────┐ │
481
+ │ Plan 02 │──┘ │ Plan 04 │──┘
482
+ │ Product │ │ Product API │
483
+ └─────────────┘ └─────────────┘
484
+
485
+ Total tasks: 5 Waves: 3 Est. time: depends on model speed
486
+
487
+ Proceed? (yes/no)
488
+ ```
489
+
490
+ If the user says no: stop. Do not execute anything.
491
+
492
+ ## Step 2 — Write pre-execution audit entry
493
+
494
+ Append to `.planning/AUDIT.jsonl`:
495
+ ```json
496
+ {
497
+ "id": "[uuid-v4]",
498
+ "timestamp": "[ISO-8601]",
499
+ "event": "phase_execution_started",
500
+ "phase": [N],
501
+ "wave_count": [total waves],
502
+ "task_count": [total tasks],
503
+ "agent": "mindforge-orchestrator",
504
+ "session_id": "[session identifier]"
505
+ }
506
+ ```
507
+
508
+ ## Step 3 — Execute waves using the wave executor
509
+
510
+ Follow the complete protocol in `.mindforge/engine/wave-executor.md`.
511
+
512
+ For each wave:
513
+
514
+ ### Wave start
515
+ Write to console:
516
+ ```
517
+ ━━━ Wave [W] of [total] ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
518
+ Starting [X] tasks in parallel...
519
+ ```
520
+
521
+ ### Per-task execution (inject context per `context-injector.md`)
522
+ For each plan in the wave:
523
+ 1. Load context package (per `context-injector.md`)
524
+ 2. Execute the plan instructions
525
+ 3. Run `<verify>` — capture exact output
526
+ 4. If verify PASSES:
527
+ - Write SUMMARY-[N]-[M].md
528
+ - Execute commit: `git add [files] && git commit -m "[type]([scope]): [task name]"`
529
+ - Capture git SHA
530
+ - Write AUDIT entry for task completion
531
+ 5. If verify FAILS:
532
+ - Write SUMMARY-[N]-[M].md with failure details
533
+ - Write AUDIT entry for task failure
534
+ - STOP this wave immediately
535
+ - Report: "Task [plan ID] failed: [verify output]. Stopping Phase [N]."
536
+ - Do not start next wave
537
+ - Ask user: "Spawn debug agent to diagnose? (yes/no)"
538
+
539
+ ### Wave completion (before starting next wave)
540
+ After all tasks in wave complete:
541
+ 1. Run: `[project test command]`
542
+ 2. If tests fail:
543
+ - Identify failing tests
544
+ - Run `git log --oneline -[wave-task-count]` to see wave commits
545
+ - Report which commit likely introduced the failure
546
+ - Stop. Ask user how to proceed.
547
+ 3. If tests pass:
548
+ - Report: "Wave [W] complete. All [X] tasks passed. Tests passing. ✅"
549
+ - Write WAVE-REPORT update
550
+
551
+ ## Step 4 — Phase-level verification
552
+
553
+ After all waves complete, run the verification pipeline:
554
+
555
+ 1. Read every v1 requirement from REQUIREMENTS.md for this phase
556
+ 2. For each requirement, verify it is implemented:
557
+ - Search the codebase for the implementation
558
+ - Check if a test covers it
559
+ - Mark: ✅ implemented + tested | ⚠️ implemented, no test | ❌ not found
560
+ 3. Write `.planning/phases/[N]/VERIFICATION.md`
561
+ 4. Run the full test suite one final time
562
+ 5. If any requirement is ❌: create a fix plan and report to user
563
+
564
+ ## Step 5 — Update state and write wave report
565
+
566
+ Write `.planning/phases/[N]/WAVE-REPORT-[N].md` (per template in wave-executor.md)
567
+
568
+ Update STATE.md:
569
+ ```markdown
570
+ ## Current phase
571
+ [N] — Execution complete ✅
572
+
573
+ ## Last completed task
574
+ Phase [N]: All [X] tasks completed across [W] waves.
575
+
576
+ ## Next action
577
+ Run /mindforge:verify-phase [N] for human acceptance testing.
578
+ ```
579
+
580
+ Update HANDOFF.json with completed phase info.
581
+
582
+ Write final AUDIT entry:
583
+ ```json
584
+ {
585
+ "id": "[uuid-v4]",
586
+ "timestamp": "[ISO-8601]",
587
+ "event": "phase_execution_completed",
588
+ "phase": [N],
589
+ "tasks_completed": [X],
590
+ "waves_executed": [W],
591
+ "commits": ["sha1", "sha2", "..."],
592
+ "test_result": "passing",
593
+ "agent": "mindforge-orchestrator"
594
+ }
595
+ ```
596
+
597
+ ## Step 6 — Report to user
598
+
599
+ ```
600
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
601
+ ✅ Phase [N] execution complete
602
+
603
+ Tasks completed : [X] / [X]
604
+ Waves executed : [W]
605
+ Commits made : [X]
606
+ Tests : All passing
607
+ Requirements : [X] / [X] implemented
608
+
609
+ Next step: Run /mindforge:verify-phase [N] for UAT sign-off.
610
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
611
+ ```
612
+ ```
613
+
614
+ **Commit:**
615
+ ```bash
616
+ git add .mindforge/engine/ .claude/commands/mindforge/execute-phase.md .agent/mindforge/execute-phase.md
617
+ git commit -m "feat(engine): implement wave executor, dependency parser, context injector"
618
+ ```
619
+
620
+ ---
621
+
622
+ ## TASK 3 — Write the Context Compaction Engine
623
+
624
+ Context compaction is what allows MindForge to survive long, complex sessions
625
+ without degrading. It is an automated protocol, not a manual intervention.
626
+
627
+ ### `.mindforge/engine/compaction-protocol.md`
628
+
629
+ ```markdown
630
+ # MindForge Engine — Context Compaction Protocol
631
+
632
+ ## Purpose
633
+ Preserve agent session state when the context window approaches its limit,
634
+ enabling seamless continuation in a fresh context with full awareness of
635
+ prior work.
636
+
637
+ ## Trigger conditions
638
+ Initiate compaction when ANY of the following are true:
639
+ - Context window usage reaches 70% of capacity
640
+ - User explicitly requests: "compact context" or "save state and continue"
641
+ - A task that would significantly expand context is about to begin
642
+ - The agent detects it cannot recall details from early in the session
643
+
644
+ DO NOT wait for 90%+ context before compacting. By then, the agent may have
645
+ already lost critical early context. 70% is the safe threshold.
646
+
647
+ ## Compaction procedure — execute in strict order
648
+
649
+ ### Step 1 — Capture current task state
650
+ Before writing anything, record exactly where work currently stands:
651
+ - Which PLAN file is active
652
+ - Which step within the plan is in progress
653
+ - Which files have been modified since the last commit
654
+ - Any uncommitted changes and their intent
655
+ - Any decisions made that haven't been documented yet
656
+
657
+ ### Step 2 — Commit any uncommitted work-in-progress
658
+ If there are uncommitted changes:
659
+ ```bash
660
+ git add -A
661
+ git commit -m "wip(phase-[N]-plan-[M]): compaction checkpoint — [brief description]"
662
+ ```
663
+ This ensures no work is lost. WIP commits are acceptable at compaction points.
664
+
665
+ ### Step 3 — Update STATE.md
666
+ Append to the current STATE.md (do not overwrite — append):
667
+
668
+ ```markdown
669
+ ---
670
+ ## Compaction checkpoint — [ISO-8601 timestamp]
671
+
672
+ ### Session summary
673
+ [2-4 sentences summarising what was accomplished in this session]
674
+
675
+ ### Decisions made this session
676
+ - [Decision 1]: [rationale]
677
+ - [Decision 2]: [rationale]
678
+
679
+ ### Current position
680
+ - Phase: [N]
681
+ - Plan: [M]
682
+ - Step within plan: [description of where execution stopped]
683
+
684
+ ### Files modified this session
685
+ - [file 1]: [what changed]
686
+ - [file 2]: [what changed]
687
+
688
+ ### What the next session must know
689
+ [Any critical context that doesn't live in a file — implicit knowledge,
690
+ workarounds discovered, gotchas found, things that seemed like they would
691
+ work but did not]
692
+ ```
693
+
694
+ ### Step 4 — Write HANDOFF.json
695
+ Overwrite `.planning/HANDOFF.json` with complete current state:
696
+
697
+ ```json
698
+ {
699
+ "schema_version": "1.0.0",
700
+ "project": "[project name from PROJECT.md]",
701
+ "phase": [N],
702
+ "plan": [M],
703
+ "plan_step": "[exact step description — be precise enough to restart from here]",
704
+ "last_completed_task": {
705
+ "description": "[task description]",
706
+ "commit_sha": "[git sha or 'wip-checkpoint']",
707
+ "verified": true/false
708
+ },
709
+ "next_task": "[exact instruction for the next session to execute]",
710
+ "in_progress": {
711
+ "file": "[file being modified]",
712
+ "intent": "[what the modification is trying to achieve]",
713
+ "completed_steps": ["step 1", "step 2"],
714
+ "remaining_steps": ["step 3", "step 4"]
715
+ },
716
+ "blockers": [],
717
+ "decisions_needed": [],
718
+ "context_refs": [
719
+ ".planning/PROJECT.md",
720
+ ".planning/STATE.md",
721
+ ".planning/REQUIREMENTS.md",
722
+ ".planning/ARCHITECTURE.md",
723
+ ".planning/phases/[N]/PLAN-[N]-[M].md",
724
+ "[any other files critical for the next session]"
725
+ ],
726
+ "recent_commits": [
727
+ "[sha1]: [message]",
728
+ "[sha2]: [message]"
729
+ ],
730
+ "recent_files": [
731
+ "[most recently touched file 1]",
732
+ "[most recently touched file 2]",
733
+ "[most recently touched file 3]",
734
+ "[most recently touched file 4]",
735
+ "[most recently touched file 5]"
736
+ ],
737
+ "agent_notes": "[anything the agent knows that isn't captured elsewhere]",
738
+ "_warning": "Never store secrets, tokens, or passwords in this file. It is tracked in git.",
739
+ "updated_at": "[ISO-8601 timestamp]"
740
+ }
741
+ ```
742
+
743
+ ### Step 5 — Write compaction AUDIT entry
744
+ ```json
745
+ {
746
+ "id": "[uuid-v4]",
747
+ "timestamp": "[ISO-8601]",
748
+ "event": "context_compaction",
749
+ "phase": [N],
750
+ "plan": [M],
751
+ "context_usage_pct": [70-85],
752
+ "session_summary": "[1 sentence]",
753
+ "handoff_written": true,
754
+ "agent": "mindforge-orchestrator"
755
+ }
756
+ ```
757
+
758
+ ### Step 6 — Compact and continue
759
+ After all state is written:
760
+ 1. Inform the user: "Context compacted and state saved. Continuing with fresh context."
761
+ 2. Discard the accumulated tool call history from working context
762
+ 3. Reload only: ORG.md + PROJECT.md + STATE.md + HANDOFF.json + current PLAN file
763
+ 4. Continue from the exact step documented in `plan_step` field of HANDOFF.json
764
+
765
+ ## Session restart from HANDOFF.json
766
+
767
+ When a new session begins and HANDOFF.json exists:
768
+
769
+ 1. Read HANDOFF.json completely
770
+ 2. Read every file in `context_refs` list
771
+ 3. Run `git log --oneline -10` to verify recent history matches `recent_commits`
772
+ 4. Report to user: "Resuming from: [next_task field]"
773
+ 5. Ask: "Shall I continue from where we left off? (yes/no)"
774
+ 6. If yes: begin from the `plan_step` position
775
+ 7. If no: ask what the user wants to do instead
776
+
777
+ ## What NOT to compact
778
+ Never compact:
779
+ - Uncommitted work (commit it first as WIP)
780
+ - The contents of PLAN files (they are files — they survive context resets)
781
+ - The SUMMARY files (already written to disk)
782
+ - Any information that is already in a file on disk
783
+
784
+ Compaction is about capturing IMPLICIT knowledge — the things in the agent's
785
+ working context that haven't been written to disk yet.
786
+ ```
787
+
788
+ **Commit:**
789
+ ```bash
790
+ git add .mindforge/engine/compaction-protocol.md
791
+ git commit -m "feat(engine): implement context compaction protocol"
792
+ ```
793
+
794
+ ---
795
+
796
+ ## TASK 4 — Write the AUDIT System
797
+
798
+ The audit system is the enterprise governance backbone of MindForge.
799
+ Every significant agent action leaves an immutable, structured trace.
800
+
801
+ ### `.mindforge/audit/AUDIT-SCHEMA.md`
802
+
803
+ ```markdown
804
+ # MindForge Audit System — Schema Reference
805
+
806
+ ## Purpose
807
+ AUDIT.jsonl is an append-only, newline-delimited JSON log of every significant
808
+ MindForge agent action. It provides a complete, tamper-evident history of what
809
+ the agent did, when, and why.
810
+
811
+ ## File location
812
+ `.planning/AUDIT.jsonl`
813
+
814
+ ## Format
815
+ One JSON object per line. Never modify existing lines. Only append.
816
+
817
+ ```
818
+ {"id":"...","timestamp":"...","event":"...","phase":1,...}
819
+ {"id":"...","timestamp":"...","event":"...","phase":1,...}
820
+ ```
821
+
822
+ ## Universal fields (present in every entry)
823
+
824
+ | Field | Type | Description |
825
+ |---|---|---|
826
+ | `id` | string | UUID v4. Unique per entry. |
827
+ | `timestamp` | string | ISO-8601 with timezone: `2026-03-20T14:32:10.000Z` |
828
+ | `event` | string | Event type (see Event Types below) |
829
+ | `agent` | string | Which agent wrote this: `mindforge-orchestrator`, `mindforge-subagent-[plan]`, `mindforge-security-reviewer`, etc. |
830
+ | `phase` | number/null | Phase number, or null if not in a phase |
831
+ | `session_id` | string | Identifies the current agent session (use a short random ID) |
832
+
833
+ ## Event types and their additional fields
834
+
835
+ ### `project_initialised`
836
+ ```json
837
+ {
838
+ "id": "uuid",
839
+ "timestamp": "ISO-8601",
840
+ "event": "project_initialised",
841
+ "agent": "mindforge-orchestrator",
842
+ "phase": null,
843
+ "session_id": "sess_abc",
844
+ "project_name": "my-saas-app",
845
+ "tech_stack": "Next.js + PostgreSQL",
846
+ "compliance": ["GDPR"]
847
+ }
848
+ ```
849
+
850
+ ### `phase_planned`
851
+ ```json
852
+ {
853
+ "id": "uuid",
854
+ "timestamp": "ISO-8601",
855
+ "event": "phase_planned",
856
+ "agent": "mindforge-orchestrator",
857
+ "phase": 1,
858
+ "session_id": "sess_abc",
859
+ "plan_count": 5,
860
+ "wave_count": 3,
861
+ "research_conducted": true
862
+ }
863
+ ```
864
+
865
+ ### `task_started`
866
+ ```json
867
+ {
868
+ "id": "uuid",
869
+ "timestamp": "ISO-8601",
870
+ "event": "task_started",
871
+ "agent": "mindforge-subagent-01",
872
+ "phase": 1,
873
+ "plan": "01",
874
+ "session_id": "sess_abc",
875
+ "task_name": "Create user authentication model",
876
+ "persona": "developer",
877
+ "skills_loaded": ["security-review"],
878
+ "files_in_scope": ["src/models/user.ts", "src/models/user.test.ts"]
879
+ }
880
+ ```
881
+
882
+ ### `task_completed`
883
+ ```json
884
+ {
885
+ "id": "uuid",
886
+ "timestamp": "ISO-8601",
887
+ "event": "task_completed",
888
+ "agent": "mindforge-subagent-01",
889
+ "phase": 1,
890
+ "plan": "01",
891
+ "session_id": "sess_abc",
892
+ "task_name": "Create user authentication model",
893
+ "commit_sha": "abc1234",
894
+ "verify_result": "pass",
895
+ "verify_output": "Tests: 8 passing (342ms)",
896
+ "files_changed": ["src/models/user.ts", "src/models/user.test.ts"],
897
+ "decisions_made": ["Used argon2id over bcrypt per SECURITY.md requirements"]
898
+ }
899
+ ```
900
+
901
+ ### `task_failed`
902
+ ```json
903
+ {
904
+ "id": "uuid",
905
+ "timestamp": "ISO-8601",
906
+ "event": "task_failed",
907
+ "agent": "mindforge-subagent-02",
908
+ "phase": 1,
909
+ "plan": "02",
910
+ "session_id": "sess_abc",
911
+ "task_name": "Create product model",
912
+ "failure_reason": "verify step failed: TypeError: Cannot read property 'id' of undefined",
913
+ "files_modified_at_failure": ["src/models/product.ts"],
914
+ "recovery_action": "debug_agent_spawned"
915
+ }
916
+ ```
917
+
918
+ ### `security_finding`
919
+ ```json
920
+ {
921
+ "id": "uuid",
922
+ "timestamp": "ISO-8601",
923
+ "event": "security_finding",
924
+ "agent": "mindforge-security-reviewer",
925
+ "phase": 1,
926
+ "plan": "03",
927
+ "session_id": "sess_abc",
928
+ "severity": "HIGH",
929
+ "owasp_category": "A03:Injection",
930
+ "finding": "Parameterised query missing in user search endpoint",
931
+ "file": "src/api/users/search.ts",
932
+ "line": 47,
933
+ "remediated": false,
934
+ "report_path": ".planning/phases/1/SECURITY-REVIEW-1.md"
935
+ }
936
+ ```
937
+
938
+ ### `quality_gate_failed`
939
+ ```json
940
+ {
941
+ "id": "uuid",
942
+ "timestamp": "ISO-8601",
943
+ "event": "quality_gate_failed",
944
+ "agent": "mindforge-orchestrator",
945
+ "phase": 1,
946
+ "session_id": "sess_abc",
947
+ "gate": "test_suite",
948
+ "detail": "4 tests failing after wave 2 completion",
949
+ "blocking": true,
950
+ "user_notified": true
951
+ }
952
+ ```
953
+
954
+ ### `context_compaction`
955
+ ```json
956
+ {
957
+ "id": "uuid",
958
+ "timestamp": "ISO-8601",
959
+ "event": "context_compaction",
960
+ "agent": "mindforge-orchestrator",
961
+ "phase": 1,
962
+ "plan": "03",
963
+ "session_id": "sess_abc",
964
+ "context_usage_pct": 72,
965
+ "session_summary": "Completed plans 01 and 02, started plan 03",
966
+ "handoff_written": true
967
+ }
968
+ ```
969
+
970
+ ### `phase_completed`
971
+ ```json
972
+ {
973
+ "id": "uuid",
974
+ "timestamp": "ISO-8601",
975
+ "event": "phase_completed",
976
+ "agent": "mindforge-orchestrator",
977
+ "phase": 1,
978
+ "session_id": "sess_abc",
979
+ "tasks_completed": 5,
980
+ "commits": ["abc1234", "def5678", "ghi9012", "jkl3456", "mno7890"],
981
+ "requirements_met": 8,
982
+ "requirements_total": 8,
983
+ "uat_signed_off": true,
984
+ "duration_estimate": "~51 minutes"
985
+ }
986
+ ```
987
+
988
+ ### `decision_recorded`
989
+ ```json
990
+ {
991
+ "id": "uuid",
992
+ "timestamp": "ISO-8601",
993
+ "event": "decision_recorded",
994
+ "agent": "mindforge-orchestrator",
995
+ "phase": 1,
996
+ "session_id": "sess_abc",
997
+ "decision_type": "architectural",
998
+ "description": "Chose argon2id over bcrypt for password hashing",
999
+ "rationale": "argon2id won PHC and is more memory-hard against GPU attacks",
1000
+ "adr_path": ".planning/decisions/ADR-004-password-hashing.md"
1001
+ }
1002
+ ```
1003
+
1004
+ ## Audit query guide (for `/mindforge:status` command)
1005
+
1006
+ To read the audit log effectively:
1007
+
1008
+ ```bash
1009
+ # All events for phase 1
1010
+ grep '"phase":1' .planning/AUDIT.jsonl | python3 -m json.tool
1011
+
1012
+ # All security findings
1013
+ grep '"event":"security_finding"' .planning/AUDIT.jsonl
1014
+
1015
+ # All task failures
1016
+ grep '"event":"task_failed"' .planning/AUDIT.jsonl
1017
+
1018
+ # Today's activity
1019
+ grep "$(date -u +%Y-%m-%d)" .planning/AUDIT.jsonl
1020
+
1021
+ # Count events by type
1022
+ grep -o '"event":"[^"]*"' .planning/AUDIT.jsonl | sort | uniq -c | sort -rn
1023
+ ```
1024
+
1025
+ ## Audit integrity rules
1026
+
1027
+ 1. **Never delete lines** from AUDIT.jsonl. It is append-only.
1028
+ 2. **Never modify existing lines.** If an entry was wrong, write a correction entry.
1029
+ 3. **Every correction entry** must reference the ID of the entry it corrects:
1030
+ ```json
1031
+ {"id":"new-uuid","event":"correction","corrects_id":"original-uuid","correction":"..."}
1032
+ ```
1033
+ 4. **Write an entry for every significant action** — not just successes.
1034
+ Failures, blockers, and security findings are especially important.
1035
+ 5. **AUDIT.jsonl is committed to git.** Do not write secrets into it.
1036
+ ```
1037
+
1038
+ Now update CLAUDE.md to include the audit writing requirement. Add this section
1039
+ after the "State Artifacts" table:
1040
+
1041
+ ```markdown
1042
+ ## Audit logging (mandatory)
1043
+
1044
+ Write an AUDIT entry to `.planning/AUDIT.jsonl` for:
1045
+ - Every task started (event: task_started)
1046
+ - Every task completed (event: task_completed)
1047
+ - Every task failed (event: task_failed)
1048
+ - Every security finding (event: security_finding)
1049
+ - Every quality gate failure (event: quality_gate_failed)
1050
+ - Every context compaction (event: context_compaction)
1051
+ - Every architectural decision (event: decision_recorded)
1052
+
1053
+ Use the schemas in `.mindforge/audit/AUDIT-SCHEMA.md`.
1054
+ Append only. Never modify existing entries.
1055
+ ```
1056
+
1057
+ **Commit:**
1058
+ ```bash
1059
+ git add .mindforge/audit/ .planning/AUDIT.jsonl .claude/CLAUDE.md .agent/CLAUDE.md
1060
+ git commit -m "feat(audit): implement AUDIT.jsonl append-only audit pipeline with full schema"
1061
+ ```
1062
+
1063
+ ---
1064
+
1065
+ ## TASK 5 — Write the Phase Verification Pipeline
1066
+
1067
+ ### `.mindforge/engine/verification-pipeline.md`
1068
+
1069
+ ```markdown
1070
+ # MindForge Engine — Verification Pipeline
1071
+
1072
+ ## Purpose
1073
+ Automatically verify that a completed phase has actually delivered what it
1074
+ promised in REQUIREMENTS.md. This is the agent's self-audit before human UAT.
1075
+
1076
+ ## Four verification stages
1077
+
1078
+ ### Stage 1 — Automated test suite
1079
+ ```bash
1080
+ # Run the project's test suite (adapt command to project)
1081
+ npm test
1082
+ # or
1083
+ pytest
1084
+ # or
1085
+ cargo test
1086
+ ```
1087
+
1088
+ Pass criteria: ALL tests pass, zero failures.
1089
+ If any fail: stop. Do not proceed to Stage 2.
1090
+ Record in VERIFICATION.md: "Stage 1: FAILED — [X] tests failing"
1091
+
1092
+ ### Stage 2 — Requirement traceability
1093
+ For each functional requirement tagged v1 for this phase in REQUIREMENTS.md:
1094
+
1095
+ 1. Read the requirement and its acceptance criterion
1096
+ 2. Search the codebase for the implementation:
1097
+ ```bash
1098
+ grep -r "[key term from requirement]" src/ --include="*.ts"
1099
+ ```
1100
+ 3. Find a test that covers this requirement:
1101
+ ```bash
1102
+ grep -r "[acceptance criterion term]" tests/ --include="*.test.ts"
1103
+ ```
1104
+ 4. Classify:
1105
+ - ✅ Implemented and tested
1106
+ - ⚠️ Implemented but no test
1107
+ - ❌ Not found
1108
+
1109
+ Any ❌ result: create a fix plan before proceeding to Stage 3.
1110
+ Any ⚠️ result: create a test task for the next phase backlog.
1111
+
1112
+ ### Stage 3 — Type safety and linting (TypeScript/Python projects)
1113
+ ```bash
1114
+ # TypeScript
1115
+ npx tsc --noEmit
1116
+ npx eslint . --ext .ts,.tsx --max-warnings 0
1117
+
1118
+ # Python
1119
+ mypy .
1120
+ ruff check .
1121
+ ```
1122
+
1123
+ Pass criteria: Zero errors, zero warnings.
1124
+ If any errors: create targeted fix tasks. Do not proceed to Stage 4 with errors.
1125
+
1126
+ ### Stage 4 — Security regression check
1127
+ Activate `security-reviewer.md` persona.
1128
+ Run the OWASP checklist from `security-review/SKILL.md` against all files
1129
+ modified in this phase.
1130
+
1131
+ Specifically look for:
1132
+ - Any new endpoints without authentication (if the project uses auth)
1133
+ - Any new database queries without parameterisation
1134
+ - Any new file handling without MIME type validation
1135
+ - Any new environment variables without validation at startup
1136
+
1137
+ Write findings to `.planning/phases/[N]/SECURITY-REVIEW-[N].md`.
1138
+
1139
+ ## VERIFICATION.md template
1140
+
1141
+ Write to `.planning/phases/[N]/VERIFICATION.md`:
1142
+
1143
+ ```markdown
1144
+ # Phase [N] Verification Report
1145
+
1146
+ ## Date
1147
+ [ISO-8601]
1148
+
1149
+ ## Stage 1 — Test suite
1150
+ - Command: `[test command]`
1151
+ - Result: [X] tests passing, [Y] failing
1152
+ - Status: ✅ PASS / ❌ FAIL
1153
+
1154
+ ## Stage 2 — Requirement traceability
1155
+
1156
+ | FR ID | Requirement | Status | Evidence |
1157
+ |-------|-------------------------------|--------|---------------------------------|
1158
+ | FR-01 | [requirement text] | ✅ | `src/auth/login.ts:47` + test |
1159
+ | FR-02 | [requirement text] | ✅ | `src/auth/register.ts:23` + test|
1160
+ | FR-03 | [requirement text] | ⚠️ | `src/auth/reset.ts:15`, no test |
1161
+
1162
+ ## Stage 3 — Static analysis
1163
+ - TypeScript errors: [0 / N]
1164
+ - ESLint warnings: [0 / N]
1165
+ - Status: ✅ PASS / ❌ FAIL
1166
+
1167
+ ## Stage 4 — Security regression
1168
+ - New endpoints reviewed: [X]
1169
+ - New database queries reviewed: [X]
1170
+ - Findings: [None / see SECURITY-REVIEW-[N].md]
1171
+ - Status: ✅ PASS / ❌ FAIL
1172
+
1173
+ ## Overall status
1174
+ ✅ All stages passed — ready for human UAT
1175
+ ❌ [N] stages failed — fix plans created
1176
+
1177
+ ## Fix plans created (if any)
1178
+ - `PLAN-[N]-FIX-01.md`: [what it fixes]
1179
+ ```
1180
+ ```
1181
+
1182
+ **Commit:**
1183
+ ```bash
1184
+ git add .mindforge/engine/verification-pipeline.md
1185
+ git commit -m "feat(engine): implement 4-stage automated verification pipeline"
1186
+ ```
1187
+
1188
+ ---
1189
+
1190
+ ## TASK 6 — Write `/mindforge:next` command
1191
+
1192
+ The `next` command is the single most important UX improvement in Day 2.
1193
+ It makes MindForge usable by someone who doesn't remember the exact workflow.
1194
+
1195
+ ### `.claude/commands/mindforge/next.md`
1196
+
1197
+ ```markdown
1198
+ # MindForge — Next Command
1199
+ # Usage: /mindforge:next
1200
+
1201
+ Auto-detect the current project state and execute the appropriate next step.
1202
+ The user does not need to know the workflow. MindForge figures it out.
1203
+
1204
+ ## State detection logic
1205
+
1206
+ Read STATE.md and HANDOFF.json. Then follow this decision tree:
1207
+
1208
+ ### Decision tree
1209
+
1210
+ ```
1211
+ Does .planning/PROJECT.md exist AND have content?
1212
+ NO → Run /mindforge:init-project
1213
+ YES → Continue
1214
+
1215
+ Does .planning/ROADMAP.md exist AND have phases defined?
1216
+ NO → Tell user: "Project is initialised but no phases are defined yet.
1217
+ Describe what Phase 1 should accomplish and I'll plan it."
1218
+ Then run /mindforge:plan-phase 1
1219
+ YES → Continue
1220
+
1221
+ Read the phase status from STATE.md.
1222
+
1223
+ Does the current phase have plans? (check .planning/phases/[N]/PLAN-[N]-*.md)
1224
+ NO → Run /mindforge:plan-phase [N]
1225
+ YES → Continue
1226
+
1227
+ Do SUMMARY files exist for all plans in the current phase?
1228
+ NO → Run /mindforge:execute-phase [N]
1229
+ YES → Continue
1230
+
1231
+ Does VERIFICATION.md exist for the current phase?
1232
+ NO → Run /mindforge:verify-phase [N] (automated part)
1233
+ YES → Continue
1234
+
1235
+ Does UAT.md exist and show all tests passing?
1236
+ NO → Run /mindforge:verify-phase [N] (UAT part)
1237
+ YES → Continue
1238
+
1239
+ Is this phase marked as shipped in STATE.md?
1240
+ NO → Run /mindforge:ship [N]
1241
+ YES → Continue
1242
+
1243
+ Are there more phases in ROADMAP.md?
1244
+ YES → Increment phase number. Run /mindforge:plan-phase [N+1]
1245
+ NO → Tell user: "All phases complete! Run /mindforge:ship [N] for the final release."
1246
+ ```
1247
+
1248
+ ## Before auto-executing: always confirm
1249
+ Before running any command automatically, tell the user:
1250
+
1251
+ ```
1252
+ MindForge next step detected:
1253
+ Current state : [description of current state]
1254
+ Next action : [what will be run]
1255
+ Command : /mindforge:[command] [args]
1256
+
1257
+ Run this now? (yes/no/different)
1258
+ ```
1259
+
1260
+ If user says "different": ask what they want to do instead.
1261
+ If user says "yes": proceed with the detected command.
1262
+
1263
+ ## Handling HANDOFF.json (session restart)
1264
+ If HANDOFF.json has a `next_task` field from a previous session:
1265
+ Present it prominently:
1266
+
1267
+ ```
1268
+ Previous session found:
1269
+ Saved at : [updated_at from HANDOFF.json]
1270
+ Left off : [last_completed_task]
1271
+ Next task : [next_task]
1272
+
1273
+ Options:
1274
+ 1. Continue from where we left off
1275
+ 2. Check current state and determine next step fresh
1276
+ 3. Tell me what you want to do
1277
+
1278
+ Choose 1, 2, or 3:
1279
+ ```
1280
+ ```
1281
+
1282
+ **Copy to Antigravity:**
1283
+ ```bash
1284
+ cp .claude/commands/mindforge/next.md .agent/mindforge/next.md
1285
+ git add .claude/commands/mindforge/next.md .agent/mindforge/next.md
1286
+ git commit -m "feat(commands): add /mindforge:next auto-detection command"
1287
+ ```
1288
+
1289
+ ---
1290
+
1291
+ ## TASK 7 — Write `/mindforge:quick` command
1292
+
1293
+ The `quick` command handles work that does not fit into the phase lifecycle —
1294
+ urgent fixes, small improvements, and one-off tasks.
1295
+
1296
+ ### `.claude/commands/mindforge/quick.md`
1297
+
1298
+ ```markdown
1299
+ # MindForge — Quick Command
1300
+ # Usage: /mindforge:quick [--research] [--review] [--full]
1301
+ # For ad-hoc tasks that don't need full lifecycle management.
1302
+
1303
+ ## When to use quick vs plan-phase
1304
+ Use QUICK for:
1305
+ - Bug fixes not tied to a current phase
1306
+ - Small improvements (< 3 files, < 2 hours)
1307
+ - Dependency updates
1308
+ - Documentation corrections
1309
+ - One-off scripts or utilities
1310
+
1311
+ Use PLAN-PHASE for:
1312
+ - Feature development
1313
+ - Anything touching more than 6 files
1314
+ - Anything requiring research before implementation
1315
+ - Anything with external dependencies or stakeholder requirements
1316
+
1317
+ ## Step 1 — Task intake
1318
+
1319
+ Ask the user:
1320
+ "What do you want to do?"
1321
+
1322
+ Listen to the description. If the task sounds larger than "quick" scope
1323
+ (more than 6 files, architectural change, new feature), say:
1324
+ "This sounds like more than a quick task. I recommend using /mindforge:plan-phase
1325
+ instead to ensure it's properly planned and verified. Want to proceed with quick anyway?"
1326
+
1327
+ ## Step 2 — Optional research (--research flag or user requests it)
1328
+
1329
+ If `--research` is provided or the task involves unfamiliar libraries:
1330
+ Spawn a focused research subagent. Give it:
1331
+ - The task description
1332
+ - The current tech stack from PROJECT.md
1333
+ Ask it to: investigate the best approach, identify gotchas, recommend specific
1334
+ libraries (with versions), and write a brief research note.
1335
+
1336
+ Report research findings to the user before proceeding.
1337
+
1338
+ ## Step 3 — Create a quick plan
1339
+
1340
+ Create `.planning/quick/[NNN]-[slug]/PLAN.md` where NNN is a sequential number
1341
+ and slug is a 2-4 word kebab-case description.
1342
+
1343
+ Example: `.planning/quick/001-fix-login-null-check/PLAN.md`
1344
+
1345
+ Use the standard XML plan format:
1346
+ ```xml
1347
+ <task type="quick">
1348
+ <n>[task name]</n>
1349
+ <persona>[appropriate persona]</persona>
1350
+ <files>[files to touch]</files>
1351
+ <context>[relevant context]</context>
1352
+ <action>[implementation instructions]</action>
1353
+ <verify>[verification command]</verify>
1354
+ <done>[definition of done]</done>
1355
+ </task>
1356
+ ```
1357
+
1358
+ Show the plan to the user. Wait for approval before executing.
1359
+
1360
+ ## Step 4 — Execute the quick plan
1361
+
1362
+ 1. Load persona from `.mindforge/personas/`
1363
+ 2. Load any relevant skills based on task keywords
1364
+ 3. Execute the plan
1365
+ 4. Run `<verify>` — must pass before committing
1366
+ 5. Commit: `[type](quick/[NNN]): [task name]`
1367
+ 6. Write `.planning/quick/[NNN]-[slug]/SUMMARY.md`
1368
+
1369
+ ## Step 5 — Optional review (--review flag)
1370
+
1371
+ If `--review` is provided:
1372
+ Activate `code-quality.md` skill on the diff.
1373
+ Report any issues before committing.
1374
+ If BLOCKING issues found: fix before commit.
1375
+
1376
+ ## Step 6 — Optional full mode (--full flag)
1377
+
1378
+ If `--full` is provided, additionally:
1379
+ - Run the project's full test suite (not just task-specific verify)
1380
+ - Run the type checker and linter
1381
+ - Activate `security-reviewer.md` if the task touches any security-sensitive code
1382
+ - Write an AUDIT entry for the quick task
1383
+
1384
+ ## Flags are composable
1385
+ ```
1386
+ /mindforge:quick # minimal — task, plan, execute
1387
+ /mindforge:quick --research # adds domain research step
1388
+ /mindforge:quick --review # adds code quality review of diff
1389
+ /mindforge:quick --full # adds full test suite + linting + security
1390
+ /mindforge:quick --research --full # all of the above
1391
+ ```
1392
+
1393
+ ## AUDIT entry for quick tasks
1394
+ ```json
1395
+ {
1396
+ "id": "uuid",
1397
+ "timestamp": "ISO-8601",
1398
+ "event": "quick_task_completed",
1399
+ "agent": "mindforge-orchestrator",
1400
+ "phase": null,
1401
+ "session_id": "sess_abc",
1402
+ "quick_id": "001",
1403
+ "task_name": "Fix login null check",
1404
+ "commit_sha": "abc1234",
1405
+ "files_changed": ["src/auth/login.ts"],
1406
+ "flags_used": ["--review"]
1407
+ }
1408
+ ```
1409
+ ```
1410
+
1411
+ **Commit:**
1412
+ ```bash
1413
+ git add .claude/commands/mindforge/quick.md .agent/mindforge/quick.md
1414
+ git commit -m "feat(commands): add /mindforge:quick ad-hoc task command with flags"
1415
+ ```
1416
+
1417
+ ---
1418
+
1419
+ ## TASK 8 — Write `/mindforge:status` command
1420
+
1421
+ ### `.claude/commands/mindforge/status.md`
1422
+
1423
+ ```markdown
1424
+ # MindForge — Status Command
1425
+ # Usage: /mindforge:status
1426
+
1427
+ Display a rich dashboard of the current project state.
1428
+ Pull data from STATE.md, AUDIT.jsonl, REQUIREMENTS.md, and the phases directory.
1429
+
1430
+ ## Dashboard sections
1431
+
1432
+ ### Section 1 — Project header
1433
+ ```
1434
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1435
+ ⚡ MindForge Status — [Project Name]
1436
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1437
+ Last updated : [STATE.md last updated timestamp]
1438
+ Current phase: Phase [N] — [phase description]
1439
+ Status : [status from STATE.md]
1440
+ ```
1441
+
1442
+ ### Section 2 — Phase progress
1443
+ ```
1444
+ Phase Progress
1445
+ ───────────────────────────────────────────────────────
1446
+ Phase 1 [████████████████████] 100% — Complete ✅
1447
+ Phase 2 [████████░░░░░░░░░░░░] 40% — In progress
1448
+ Phase 3 [░░░░░░░░░░░░░░░░░░░░] 0% — Not started
1449
+ Phase 4 [░░░░░░░░░░░░░░░░░░░░] 0% — Not started
1450
+ ```
1451
+ Calculate percentage from: tasks with SUMMARY files / total tasks in phase.
1452
+
1453
+ ### Section 3 — Requirements coverage
1454
+ Read REQUIREMENTS.md and count:
1455
+ - Total v1 requirements
1456
+ - Requirements with a passing test (from VERIFICATION.md files)
1457
+ - Requirements implemented but untested
1458
+ - Requirements not yet started
1459
+
1460
+ ```
1461
+ Requirements (v1)
1462
+ ───────────────────────────────────────────────────────
1463
+ Total : [N]
1464
+ ✅ Done + tested : [N]
1465
+ ⚠️ Done, no test : [N]
1466
+ 🔴 Not started : [N]
1467
+ ```
1468
+
1469
+ ### Section 4 — Recent activity (from AUDIT.jsonl)
1470
+ Read the last 10 entries from AUDIT.jsonl and display:
1471
+ ```
1472
+ Recent Activity
1473
+ ───────────────────────────────────────────────────────
1474
+ [timestamp] task_completed Plan 03: User API endpoints ✅
1475
+ [timestamp] task_completed Plan 02: Product model ✅
1476
+ [timestamp] task_started Plan 03: User API endpoints
1477
+ [timestamp] task_completed Plan 01: User model ✅
1478
+ [timestamp] context_compaction Phase 2, Plan 03 (72% context)
1479
+ ```
1480
+
1481
+ ### Section 5 — Open issues
1482
+ Check for:
1483
+ - Any open SECURITY-REVIEW files with CRITICAL or HIGH findings
1484
+ - Any BUGS.md files with open issues
1485
+ - Any failed tasks in WAVE-REPORT files
1486
+ - Any blockers in STATE.md
1487
+
1488
+ ```
1489
+ Open Issues
1490
+ ───────────────────────────────────────────────────────
1491
+ 🔴 CRITICAL: [if any — from SECURITY-REVIEW]
1492
+ 🟠 HIGH: [if any]
1493
+ ✅ No open issues
1494
+ ```
1495
+
1496
+ ### Section 6 — Next action
1497
+ ```
1498
+ Next Action
1499
+ ───────────────────────────────────────────────────────
1500
+ [What STATE.md says the next action is]
1501
+ Run: /mindforge:next
1502
+ to auto-execute the next step.
1503
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1504
+ ```
1505
+
1506
+ ## Data sources (in priority order)
1507
+ 1. STATE.md — authoritative for current status
1508
+ 2. AUDIT.jsonl — authoritative for history
1509
+ 3. REQUIREMENTS.md — authoritative for scope
1510
+ 4. VERIFICATION.md files — authoritative for test coverage
1511
+ 5. WAVE-REPORT files — authoritative for execution history
1512
+ 6. HANDOFF.json — authoritative for session state
1513
+ ```
1514
+
1515
+ **Commit:**
1516
+ ```bash
1517
+ git add .claude/commands/mindforge/status.md .agent/mindforge/status.md
1518
+ git commit -m "feat(commands): add /mindforge:status rich project dashboard command"
1519
+ ```
1520
+
1521
+ ---
1522
+
1523
+ ## TASK 9 — Write `/mindforge:debug` command
1524
+
1525
+ ### `.claude/commands/mindforge/debug.md`
1526
+
1527
+ ```markdown
1528
+ # MindForge — Debug Command
1529
+ # Usage: /mindforge:debug [description]
1530
+
1531
+ Systematic debugging using the Debug Specialist persona with full RCA protocol.
1532
+
1533
+ ## Activation
1534
+
1535
+ Load `.mindforge/personas/debug-specialist.md` immediately.
1536
+ This command runs entirely in that persona for its full duration.
1537
+
1538
+ ## Step 1 — Intake
1539
+
1540
+ Ask the user:
1541
+ 1. "Describe the problem. What is happening vs. what should happen?"
1542
+ 2. "Can you reproduce it reliably? If yes: what are the exact steps?"
1543
+ 3. "When did this start? Was it working before? What changed?"
1544
+ 4. "Do you have an error message or stack trace? Paste it here."
1545
+
1546
+ Capture all answers before proceeding.
1547
+
1548
+ ## Step 2 — Triage
1549
+
1550
+ Classify the issue immediately:
1551
+ - **Regression** (was working, now broken) → check recent commits
1552
+ - **Never worked** (new feature failing) → check the plan and verify step
1553
+ - **Environment issue** (works locally, fails in CI) → check environment diffs
1554
+ - **Data issue** (specific data causes failure) → check data shape assumptions
1555
+ - **Integration issue** (fails when calling external service) → check contracts
1556
+
1557
+ Report classification to user: "This looks like a [type] issue. Here's my approach..."
1558
+
1559
+ ## Step 3 — Follow Debug Specialist protocol
1560
+
1561
+ Execute the full protocol from `debug-specialist.md`:
1562
+ 1. Reproduce
1563
+ 2. Isolate
1564
+ 3. Read the error
1565
+ 4. Check recent changes
1566
+ 5. Instrument
1567
+ 6. Form hypothesis
1568
+ 7. Test hypothesis (write a failing test)
1569
+ 8. Fix
1570
+ 9. Verify (test from step 7 now passes, no regressions)
1571
+ 10. Document
1572
+
1573
+ At each step, report what was found before moving to the next step.
1574
+ Do not skip steps or combine them.
1575
+
1576
+ ## Step 4 — Check recent git history
1577
+
1578
+ ```bash
1579
+ git log --oneline -20
1580
+ git diff HEAD~[N] HEAD -- [suspected file]
1581
+ ```
1582
+
1583
+ If a recent commit is the likely cause, show the user the specific diff.
1584
+
1585
+ ## Step 5 — Write the RCA report
1586
+
1587
+ Create `.planning/phases/[current-phase]/DEBUG-[timestamp].md`:
1588
+
1589
+ ```markdown
1590
+ # Debug Report — [short description]
1591
+
1592
+ ## Date
1593
+ [ISO-8601]
1594
+
1595
+ ## Problem
1596
+ [User's description + what was verified during debugging]
1597
+
1598
+ ## Root cause category
1599
+ [Logic error / Data error / Integration error / Concurrency error /
1600
+ Configuration error / Dependency error]
1601
+
1602
+ ## Root cause
1603
+ [Precise description of what the actual cause was]
1604
+
1605
+ ## Evidence
1606
+ - [How the root cause was confirmed]
1607
+ - [Failing test that proved the bug: file:line]
1608
+
1609
+ ## Fix applied
1610
+ - File: [path]
1611
+ - Change: [description]
1612
+ - Commit: [SHA]
1613
+
1614
+ ## Regression test
1615
+ [Test written to prevent this from recurring: file:line]
1616
+
1617
+ ## Prevention
1618
+ [What should change in process/code to prevent this class of bug]
1619
+ ```
1620
+
1621
+ ## Step 6 — Write AUDIT entry
1622
+
1623
+ ```json
1624
+ {
1625
+ "id": "uuid",
1626
+ "timestamp": "ISO-8601",
1627
+ "event": "debug_completed",
1628
+ "agent": "mindforge-debug-specialist",
1629
+ "phase": [current phase or null],
1630
+ "session_id": "sess_abc",
1631
+ "issue_type": "regression",
1632
+ "root_cause_category": "Logic error",
1633
+ "root_cause_summary": "[one sentence]",
1634
+ "commit_sha": "[fix commit sha]",
1635
+ "regression_test_added": true,
1636
+ "report_path": ".planning/phases/[N]/DEBUG-[timestamp].md"
1637
+ }
1638
+ ```
1639
+
1640
+ ## When the bug cannot be reproduced
1641
+
1642
+ Ask:
1643
+ 1. "Does it happen every time or intermittently?"
1644
+ 2. "Does it happen in specific environments only? (dev/staging/prod)"
1645
+ 3. "Does it happen for specific users or all users?"
1646
+
1647
+ If intermittent: focus on concurrency, caching, and race conditions.
1648
+ Write a monitoring/logging plan to catch the next occurrence.
1649
+ Document the inconclusive investigation in the DEBUG report with evidence gathered.
1650
+ ```
1651
+
1652
+ **Commit:**
1653
+ ```bash
1654
+ git add .claude/commands/mindforge/debug.md .agent/mindforge/debug.md
1655
+ git commit -m "feat(commands): add /mindforge:debug systematic RCA debug command"
1656
+ ```
1657
+
1658
+ ---
1659
+
1660
+ ## TASK 10 — Update CLAUDE.md with Day 2 capabilities
1661
+
1662
+ Update `.claude/CLAUDE.md` to add Day 2 engine awareness.
1663
+ Add these sections to the existing CLAUDE.md:
1664
+
1665
+ ```markdown
1666
+ ---
1667
+
1668
+ ## WAVE EXECUTION ENGINE
1669
+
1670
+ When executing phases, always use the full wave engine protocol:
1671
+ 1. Run dependency parser: `.mindforge/engine/dependency-parser.md`
1672
+ 2. Build execution waves: `.mindforge/engine/wave-executor.md`
1673
+ 3. Inject subagent context: `.mindforge/engine/context-injector.md`
1674
+ 4. Run verification pipeline: `.mindforge/engine/verification-pipeline.md`
1675
+
1676
+ Never execute plans sequentially without first checking for parallel opportunities.
1677
+ Parallel execution in isolated subagent contexts produces higher quality output.
1678
+
1679
+ ---
1680
+
1681
+ ## CONTEXT COMPACTION
1682
+
1683
+ Follow `.mindforge/engine/compaction-protocol.md` exactly when context reaches 70%.
1684
+ Do not wait. Do not skip the protocol. Compacting at 85%+ risks losing critical context.
1685
+
1686
+ ---
1687
+
1688
+ ## AUDIT LOGGING
1689
+
1690
+ Every significant action must produce an AUDIT entry.
1691
+ Schema: `.mindforge/audit/AUDIT-SCHEMA.md`
1692
+ File: `.planning/AUDIT.jsonl` (append only — never modify existing entries)
1693
+
1694
+ ---
1695
+
1696
+ ## QUICK TASKS
1697
+
1698
+ For ad-hoc work outside the phase lifecycle: use `/mindforge:quick`.
1699
+ Quick tasks still get plans, verifications, commits, summaries, and audit entries.
1700
+ They skip the phase management overhead only.
1701
+
1702
+ ---
1703
+
1704
+ ## AUTO-DETECTION
1705
+
1706
+ When unsure what to do next: run the state detection logic from
1707
+ `.claude/commands/mindforge/next.md` internally to determine the correct action.
1708
+ This is the same logic `/mindforge:next` uses — it can be applied any time.
1709
+ ```
1710
+
1711
+ Mirror the changes to `.agent/CLAUDE.md`.
1712
+
1713
+ **Commit:**
1714
+ ```bash
1715
+ git add .claude/CLAUDE.md .agent/CLAUDE.md
1716
+ git commit -m "feat(core): update CLAUDE.md with Day 2 engine awareness and audit requirements"
1717
+ ```
1718
+
1719
+ ---
1720
+
1721
+ ## TASK 11 — Write Day 2 test suite
1722
+
1723
+ Write comprehensive tests covering all Day 2 components.
1724
+
1725
+ ### `tests/wave-engine.test.js`
1726
+
1727
+ ```javascript
1728
+ /**
1729
+ * MindForge Wave Engine Tests
1730
+ * Tests: dependency parsing, wave grouping, and execution planning
1731
+ * Run: node tests/wave-engine.test.js
1732
+ */
1733
+
1734
+ const fs = require('fs');
1735
+ const path = require('path');
1736
+ const assert = require('assert');
1737
+
1738
+ let passed = 0;
1739
+ let failed = 0;
1740
+
1741
+ function test(name, fn) {
1742
+ try {
1743
+ fn();
1744
+ console.log(` ✅ ${name}`);
1745
+ passed++;
1746
+ } catch (err) {
1747
+ console.error(` ❌ ${name}`);
1748
+ console.error(` ${err.message}`);
1749
+ failed++;
1750
+ }
1751
+ }
1752
+
1753
+ // ── Simulate the dependency parser and wave grouper ───────────────────────────
1754
+
1755
+ /**
1756
+ * Simulates parsing a PLAN file's dependency field
1757
+ * In real execution, this reads from the actual XML PLAN files
1758
+ */
1759
+ function parseDependencies(depString) {
1760
+ if (!depString || depString.trim().toLowerCase() === 'none') return [];
1761
+ return depString.split(',').map(d => d.trim()).filter(Boolean);
1762
+ }
1763
+
1764
+ /**
1765
+ * Simulates the wave grouping algorithm (Kahn's topological sort)
1766
+ * Input: { "01": { dependsOn: [] }, "02": { dependsOn: ["01"] }, ... }
1767
+ * Output: [["01"], ["02"], ...]
1768
+ */
1769
+ function groupIntoWaves(graph) {
1770
+ const remaining = new Set(Object.keys(graph));
1771
+ const completed = new Set();
1772
+ const waves = [];
1773
+
1774
+ while (remaining.size > 0) {
1775
+ const wave = [];
1776
+ for (const id of remaining) {
1777
+ const deps = graph[id].dependsOn;
1778
+ if (deps.every(d => completed.has(d))) {
1779
+ wave.push(id);
1780
+ }
1781
+ }
1782
+
1783
+ if (wave.length === 0 && remaining.size > 0) {
1784
+ throw new Error(`Circular dependency detected among: ${[...remaining].join(', ')}`);
1785
+ }
1786
+
1787
+ waves.push(wave.sort()); // sort for determinism
1788
+ wave.forEach(id => { completed.add(id); remaining.delete(id); });
1789
+ }
1790
+
1791
+ return waves;
1792
+ }
1793
+
1794
+ /**
1795
+ * Detects circular dependencies
1796
+ */
1797
+ function hasCircularDependency(graph) {
1798
+ try {
1799
+ groupIntoWaves(graph);
1800
+ return false;
1801
+ } catch {
1802
+ return true;
1803
+ }
1804
+ }
1805
+
1806
+ /**
1807
+ * Detects file conflicts between plans
1808
+ */
1809
+ function findFileConflicts(plans) {
1810
+ const fileMap = {};
1811
+ const conflicts = [];
1812
+
1813
+ plans.forEach(({ id, files }) => {
1814
+ files.forEach(file => {
1815
+ if (fileMap[file]) {
1816
+ conflicts.push({ file, plans: [fileMap[file], id] });
1817
+ } else {
1818
+ fileMap[file] = id;
1819
+ }
1820
+ });
1821
+ });
1822
+
1823
+ return conflicts;
1824
+ }
1825
+
1826
+ // ── Tests ─────────────────────────────────────────────────────────────────────
1827
+
1828
+ console.log('\nMindForge Day 2 — Wave Engine Tests\n');
1829
+
1830
+ console.log('Dependency parsing:');
1831
+
1832
+ test('parses "none" as empty dependencies', () => {
1833
+ assert.deepStrictEqual(parseDependencies('none'), []);
1834
+ assert.deepStrictEqual(parseDependencies('None'), []);
1835
+ assert.deepStrictEqual(parseDependencies('NONE'), []);
1836
+ });
1837
+
1838
+ test('parses single dependency', () => {
1839
+ assert.deepStrictEqual(parseDependencies('01'), ['01']);
1840
+ });
1841
+
1842
+ test('parses multiple dependencies', () => {
1843
+ assert.deepStrictEqual(parseDependencies('01, 02, 03'), ['01', '02', '03']);
1844
+ });
1845
+
1846
+ test('handles whitespace in dependency list', () => {
1847
+ assert.deepStrictEqual(parseDependencies('01,02, 03'), ['01', '02', '03']);
1848
+ });
1849
+
1850
+ test('parses empty string as no dependencies', () => {
1851
+ assert.deepStrictEqual(parseDependencies(''), []);
1852
+ });
1853
+
1854
+ console.log('\nWave grouping algorithm:');
1855
+
1856
+ test('single task with no dependencies → 1 wave', () => {
1857
+ const graph = { '01': { dependsOn: [] } };
1858
+ const waves = groupIntoWaves(graph);
1859
+ assert.deepStrictEqual(waves, [['01']]);
1860
+ });
1861
+
1862
+ test('two independent tasks → 1 wave with both', () => {
1863
+ const graph = {
1864
+ '01': { dependsOn: [] },
1865
+ '02': { dependsOn: [] },
1866
+ };
1867
+ const waves = groupIntoWaves(graph);
1868
+ assert.strictEqual(waves.length, 1);
1869
+ assert.deepStrictEqual(waves[0].sort(), ['01', '02']);
1870
+ });
1871
+
1872
+ test('sequential dependency chain → 3 waves, 1 task each', () => {
1873
+ const graph = {
1874
+ '01': { dependsOn: [] },
1875
+ '02': { dependsOn: ['01'] },
1876
+ '03': { dependsOn: ['02'] },
1877
+ };
1878
+ const waves = groupIntoWaves(graph);
1879
+ assert.strictEqual(waves.length, 3);
1880
+ assert.deepStrictEqual(waves[0], ['01']);
1881
+ assert.deepStrictEqual(waves[1], ['02']);
1882
+ assert.deepStrictEqual(waves[2], ['03']);
1883
+ });
1884
+
1885
+ test('diamond dependency (fan-out then fan-in)', () => {
1886
+ const graph = {
1887
+ '01': { dependsOn: [] },
1888
+ '02': { dependsOn: ['01'] },
1889
+ '03': { dependsOn: ['01'] },
1890
+ '04': { dependsOn: ['02', '03'] },
1891
+ };
1892
+ const waves = groupIntoWaves(graph);
1893
+ assert.strictEqual(waves.length, 3);
1894
+ assert.deepStrictEqual(waves[0], ['01']);
1895
+ assert.deepStrictEqual(waves[1].sort(), ['02', '03']);
1896
+ assert.deepStrictEqual(waves[2], ['04']);
1897
+ });
1898
+
1899
+ test('5-plan realistic example (user model → api → checkout)', () => {
1900
+ const graph = {
1901
+ '01': { dependsOn: [] }, // User model
1902
+ '02': { dependsOn: [] }, // Product model
1903
+ '03': { dependsOn: ['01'] }, // User API
1904
+ '04': { dependsOn: ['02'] }, // Product API
1905
+ '05': { dependsOn: ['03', '04'] },// Checkout UI
1906
+ };
1907
+ const waves = groupIntoWaves(graph);
1908
+ assert.strictEqual(waves.length, 3);
1909
+ assert.deepStrictEqual(waves[0].sort(), ['01', '02']);
1910
+ assert.deepStrictEqual(waves[1].sort(), ['03', '04']);
1911
+ assert.deepStrictEqual(waves[2], ['05']);
1912
+ });
1913
+
1914
+ console.log('\nCircular dependency detection:');
1915
+
1916
+ test('detects direct circular dependency (A → B → A)', () => {
1917
+ const graph = {
1918
+ '01': { dependsOn: ['02'] },
1919
+ '02': { dependsOn: ['01'] },
1920
+ };
1921
+ assert.strictEqual(hasCircularDependency(graph), true);
1922
+ });
1923
+
1924
+ test('detects indirect circular dependency (A → B → C → A)', () => {
1925
+ const graph = {
1926
+ '01': { dependsOn: ['03'] },
1927
+ '02': { dependsOn: ['01'] },
1928
+ '03': { dependsOn: ['02'] },
1929
+ };
1930
+ assert.strictEqual(hasCircularDependency(graph), true);
1931
+ });
1932
+
1933
+ test('does not false-positive on valid DAG', () => {
1934
+ const graph = {
1935
+ '01': { dependsOn: [] },
1936
+ '02': { dependsOn: ['01'] },
1937
+ '03': { dependsOn: ['01'] },
1938
+ '04': { dependsOn: ['02', '03'] },
1939
+ };
1940
+ assert.strictEqual(hasCircularDependency(graph), false);
1941
+ });
1942
+
1943
+ console.log('\nFile conflict detection:');
1944
+
1945
+ test('detects conflict when two plans modify the same file', () => {
1946
+ const plans = [
1947
+ { id: '01', files: ['src/models/user.ts', 'src/models/user.test.ts'] },
1948
+ { id: '02', files: ['src/models/product.ts'] },
1949
+ { id: '03', files: ['src/models/user.ts'] }, // conflict with 01
1950
+ ];
1951
+ const conflicts = findFileConflicts(plans);
1952
+ assert.strictEqual(conflicts.length, 1);
1953
+ assert.strictEqual(conflicts[0].file, 'src/models/user.ts');
1954
+ assert.deepStrictEqual(conflicts[0].plans.sort(), ['01', '03']);
1955
+ });
1956
+
1957
+ test('no conflicts when all plans touch different files', () => {
1958
+ const plans = [
1959
+ { id: '01', files: ['src/models/user.ts'] },
1960
+ { id: '02', files: ['src/models/product.ts'] },
1961
+ { id: '03', files: ['src/api/orders.ts'] },
1962
+ ];
1963
+ const conflicts = findFileConflicts(plans);
1964
+ assert.strictEqual(conflicts.length, 0);
1965
+ });
1966
+
1967
+ // ── Results ───────────────────────────────────────────────────────────────────
1968
+ console.log(`\n${'─'.repeat(50)}`);
1969
+ console.log(`Results: ${passed} passed, ${failed} failed`);
1970
+
1971
+ if (failed > 0) {
1972
+ console.error(`\n❌ ${failed} test(s) failed.\n`);
1973
+ process.exit(1);
1974
+ } else {
1975
+ console.log(`\n✅ All wave engine tests passed.\n`);
1976
+ }
1977
+ ```
1978
+
1979
+ ---
1980
+
1981
+ ### `tests/audit.test.js`
1982
+
1983
+ ```javascript
1984
+ /**
1985
+ * MindForge Audit System Tests
1986
+ * Run: node tests/audit.test.js
1987
+ */
1988
+
1989
+ const fs = require('fs');
1990
+ const path = require('path');
1991
+ const assert = require('assert');
1992
+
1993
+ let passed = 0;
1994
+ let failed = 0;
1995
+
1996
+ function test(name, fn) {
1997
+ try {
1998
+ fn();
1999
+ console.log(` ✅ ${name}`);
2000
+ passed++;
2001
+ } catch (err) {
2002
+ console.error(` ❌ ${name}`);
2003
+ console.error(` ${err.message}`);
2004
+ failed++;
2005
+ }
2006
+ }
2007
+
2008
+ // ── Audit utility functions to test ──────────────────────────────────────────
2009
+
2010
+ function validateAuditEntry(entry) {
2011
+ const required = ['id', 'timestamp', 'event', 'agent', 'session_id'];
2012
+ const missing = required.filter(f => !entry[f]);
2013
+ if (missing.length > 0) {
2014
+ throw new Error(`Missing required fields: ${missing.join(', ')}`);
2015
+ }
2016
+ // Validate timestamp format
2017
+ const ts = new Date(entry.timestamp);
2018
+ if (isNaN(ts.getTime())) throw new Error(`Invalid timestamp: ${entry.timestamp}`);
2019
+ // Validate id looks like a UUID (basic check)
2020
+ if (!/^[0-9a-f-]{36}$/.test(entry.id)) throw new Error(`Invalid UUID format: ${entry.id}`);
2021
+ }
2022
+
2023
+ function parseAuditLog(content) {
2024
+ return content.trim().split('\n')
2025
+ .filter(line => line.trim())
2026
+ .map((line, index) => {
2027
+ try {
2028
+ return JSON.parse(line);
2029
+ } catch (e) {
2030
+ throw new Error(`Line ${index + 1} is not valid JSON: ${line.slice(0, 50)}...`);
2031
+ }
2032
+ });
2033
+ }
2034
+
2035
+ // ── Tests ─────────────────────────────────────────────────────────────────────
2036
+
2037
+ console.log('\nMindForge Day 2 — Audit System Tests\n');
2038
+
2039
+ console.log('AUDIT.jsonl file:');
2040
+
2041
+ test('AUDIT.jsonl exists', () => {
2042
+ assert.ok(fs.existsSync('.planning/AUDIT.jsonl'), 'AUDIT.jsonl not found');
2043
+ });
2044
+
2045
+ test('AUDIT.jsonl is valid (empty or valid JSONL)', () => {
2046
+ const content = fs.readFileSync('.planning/AUDIT.jsonl', 'utf8');
2047
+ if (content.trim().length === 0) return; // empty is valid on day 1
2048
+ parseAuditLog(content); // throws if invalid
2049
+ });
2050
+
2051
+ console.log('\nAudit entry validation:');
2052
+
2053
+ test('valid task_completed entry passes validation', () => {
2054
+ const entry = {
2055
+ id: '550e8400-e29b-41d4-a716-446655440000',
2056
+ timestamp: new Date().toISOString(),
2057
+ event: 'task_completed',
2058
+ agent: 'mindforge-subagent-01',
2059
+ phase: 1,
2060
+ plan: '01',
2061
+ session_id: 'sess_test',
2062
+ task_name: 'Create user model',
2063
+ commit_sha: 'abc1234',
2064
+ verify_result: 'pass'
2065
+ };
2066
+ assert.doesNotThrow(() => validateAuditEntry(entry));
2067
+ });
2068
+
2069
+ test('entry missing required field fails validation', () => {
2070
+ const entry = {
2071
+ timestamp: new Date().toISOString(),
2072
+ event: 'task_completed',
2073
+ agent: 'mindforge-subagent-01',
2074
+ // missing: id, session_id
2075
+ };
2076
+ assert.throws(() => validateAuditEntry(entry), /Missing required fields/);
2077
+ });
2078
+
2079
+ test('entry with invalid timestamp fails validation', () => {
2080
+ const entry = {
2081
+ id: '550e8400-e29b-41d4-a716-446655440000',
2082
+ timestamp: 'not-a-date',
2083
+ event: 'task_completed',
2084
+ agent: 'mindforge-subagent-01',
2085
+ session_id: 'sess_test',
2086
+ };
2087
+ assert.throws(() => validateAuditEntry(entry), /Invalid timestamp/);
2088
+ });
2089
+
2090
+ test('JSONL parser handles multi-line audit log', () => {
2091
+ const multiLine = [
2092
+ '{"id":"550e8400-e29b-41d4-a716-446655440000","timestamp":"2026-03-20T10:00:00.000Z","event":"task_started","agent":"test","session_id":"s1"}',
2093
+ '{"id":"550e8400-e29b-41d4-a716-446655440001","timestamp":"2026-03-20T10:05:00.000Z","event":"task_completed","agent":"test","session_id":"s1"}',
2094
+ ].join('\n');
2095
+ const entries = parseAuditLog(multiLine);
2096
+ assert.strictEqual(entries.length, 2);
2097
+ assert.strictEqual(entries[0].event, 'task_started');
2098
+ assert.strictEqual(entries[1].event, 'task_completed');
2099
+ });
2100
+
2101
+ test('JSONL parser rejects malformed JSON', () => {
2102
+ const badLine = '{"id":"abc","timestamp": bad json}';
2103
+ assert.throws(() => parseAuditLog(badLine), /not valid JSON/);
2104
+ });
2105
+
2106
+ console.log('\nAudit schema files:');
2107
+
2108
+ test('AUDIT-SCHEMA.md exists and has content', () => {
2109
+ const schemaPath = '.mindforge/audit/AUDIT-SCHEMA.md';
2110
+ assert.ok(fs.existsSync(schemaPath), 'AUDIT-SCHEMA.md not found');
2111
+ const content = fs.readFileSync(schemaPath, 'utf8');
2112
+ assert.ok(content.length > 500, 'AUDIT-SCHEMA.md seems too short');
2113
+ assert.ok(content.includes('task_completed'), 'Missing task_completed event type');
2114
+ assert.ok(content.includes('security_finding'), 'Missing security_finding event type');
2115
+ assert.ok(content.includes('context_compaction'), 'Missing context_compaction event type');
2116
+ });
2117
+
2118
+ test('HANDOFF.json has _warning anti-secret field', () => {
2119
+ const handoff = JSON.parse(fs.readFileSync('.planning/HANDOFF.json', 'utf8'));
2120
+ assert.ok(handoff._warning, 'Missing _warning anti-secret field in HANDOFF.json');
2121
+ assert.ok(handoff._warning.toLowerCase().includes('secret'), 'Warning should mention secrets');
2122
+ });
2123
+
2124
+ // ── Results ───────────────────────────────────────────────────────────────────
2125
+ console.log(`\n${'─'.repeat(50)}`);
2126
+ console.log(`Results: ${passed} passed, ${failed} failed`);
2127
+
2128
+ if (failed > 0) {
2129
+ console.error(`\n❌ ${failed} test(s) failed.\n`);
2130
+ process.exit(1);
2131
+ } else {
2132
+ console.log(`\n✅ All audit tests passed.\n`);
2133
+ }
2134
+ ```
2135
+
2136
+ ---
2137
+
2138
+ ### `tests/compaction.test.js`
2139
+
2140
+ ```javascript
2141
+ /**
2142
+ * MindForge Context Compaction Tests
2143
+ * Run: node tests/compaction.test.js
2144
+ */
2145
+
2146
+ const fs = require('fs');
2147
+ const assert = require('assert');
2148
+
2149
+ let passed = 0;
2150
+ let failed = 0;
2151
+
2152
+ function test(name, fn) {
2153
+ try {
2154
+ fn();
2155
+ console.log(` ✅ ${name}`);
2156
+ passed++;
2157
+ } catch (err) {
2158
+ console.error(` ❌ ${name}`);
2159
+ console.error(` ${err.message}`);
2160
+ failed++;
2161
+ }
2162
+ }
2163
+
2164
+ // ── Compaction state validator ─────────────────────────────────────────────────
2165
+
2166
+ function validateHandoffJson(obj) {
2167
+ const required = ['schema_version', 'next_task', '_warning', 'context_refs'];
2168
+ const missing = required.filter(f => obj[f] === undefined);
2169
+ if (missing.length > 0) throw new Error(`Missing: ${missing.join(', ')}`);
2170
+ if (!Array.isArray(obj.context_refs)) throw new Error('context_refs must be an array');
2171
+ if (!Array.isArray(obj.blockers)) throw new Error('blockers must be an array');
2172
+ if (obj._warning.toLowerCase().includes('password') === false &&
2173
+ obj._warning.toLowerCase().includes('secret') === false) {
2174
+ throw new Error('_warning must mention secrets/passwords');
2175
+ }
2176
+ }
2177
+
2178
+ function validateStateHasCompactionCheckpoint(content) {
2179
+ // After compaction, STATE.md should have a checkpoint section
2180
+ return content.includes('Compaction checkpoint') || content.includes('compaction');
2181
+ }
2182
+
2183
+ // ── Tests ─────────────────────────────────────────────────────────────────────
2184
+
2185
+ console.log('\nMindForge Day 2 — Context Compaction Tests\n');
2186
+
2187
+ console.log('HANDOFF.json schema validation:');
2188
+
2189
+ test('HANDOFF.json exists', () => {
2190
+ assert.ok(fs.existsSync('.planning/HANDOFF.json'));
2191
+ });
2192
+
2193
+ test('HANDOFF.json is valid JSON', () => {
2194
+ const content = fs.readFileSync('.planning/HANDOFF.json', 'utf8');
2195
+ assert.doesNotThrow(() => JSON.parse(content));
2196
+ });
2197
+
2198
+ test('HANDOFF.json has all required fields', () => {
2199
+ const obj = JSON.parse(fs.readFileSync('.planning/HANDOFF.json', 'utf8'));
2200
+ validateHandoffJson(obj);
2201
+ });
2202
+
2203
+ test('HANDOFF.json schema_version is 1.0.0', () => {
2204
+ const obj = JSON.parse(fs.readFileSync('.planning/HANDOFF.json', 'utf8'));
2205
+ assert.strictEqual(obj.schema_version, '1.0.0');
2206
+ });
2207
+
2208
+ test('HANDOFF.json context_refs is an array', () => {
2209
+ const obj = JSON.parse(fs.readFileSync('.planning/HANDOFF.json', 'utf8'));
2210
+ assert.ok(Array.isArray(obj.context_refs));
2211
+ });
2212
+
2213
+ test('HANDOFF.json blockers is an array', () => {
2214
+ const obj = JSON.parse(fs.readFileSync('.planning/HANDOFF.json', 'utf8'));
2215
+ assert.ok(Array.isArray(obj.blockers));
2216
+ });
2217
+
2218
+ test('HANDOFF.json decisions_needed is an array', () => {
2219
+ const obj = JSON.parse(fs.readFileSync('.planning/HANDOFF.json', 'utf8'));
2220
+ assert.ok(Array.isArray(obj.decisions_needed));
2221
+ });
2222
+
2223
+ console.log('\nCompaction protocol file:');
2224
+
2225
+ test('compaction-protocol.md exists', () => {
2226
+ assert.ok(
2227
+ fs.existsSync('.mindforge/engine/compaction-protocol.md'),
2228
+ 'compaction-protocol.md not found'
2229
+ );
2230
+ });
2231
+
2232
+ test('compaction-protocol.md mentions 70% threshold', () => {
2233
+ const content = fs.readFileSync('.mindforge/engine/compaction-protocol.md', 'utf8');
2234
+ assert.ok(content.includes('70%'), 'Should specify 70% compaction threshold');
2235
+ });
2236
+
2237
+ test('compaction-protocol.md has all 6 steps', () => {
2238
+ const content = fs.readFileSync('.mindforge/engine/compaction-protocol.md', 'utf8');
2239
+ assert.ok(content.includes('Step 1'), 'Missing Step 1');
2240
+ assert.ok(content.includes('Step 2'), 'Missing Step 2');
2241
+ assert.ok(content.includes('Step 3'), 'Missing Step 3');
2242
+ assert.ok(content.includes('Step 4'), 'Missing Step 4');
2243
+ assert.ok(content.includes('Step 5'), 'Missing Step 5');
2244
+ assert.ok(content.includes('Step 6'), 'Missing Step 6');
2245
+ });
2246
+
2247
+ test('compaction-protocol.md covers session restart procedure', () => {
2248
+ const content = fs.readFileSync('.mindforge/engine/compaction-protocol.md', 'utf8');
2249
+ assert.ok(
2250
+ content.includes('Session restart') || content.includes('restart from HANDOFF'),
2251
+ 'Should cover session restart from HANDOFF.json'
2252
+ );
2253
+ });
2254
+
2255
+ // ── Results ───────────────────────────────────────────────────────────────────
2256
+ console.log(`\n${'─'.repeat(50)}`);
2257
+ console.log(`Results: ${passed} passed, ${failed} failed`);
2258
+
2259
+ if (failed > 0) {
2260
+ console.error(`\n❌ ${failed} test(s) failed.\n`);
2261
+ process.exit(1);
2262
+ } else {
2263
+ console.log(`\n✅ All compaction tests passed.\n`);
2264
+ }
2265
+ ```
2266
+
2267
+ **Commit:**
2268
+ ```bash
2269
+ git add tests/
2270
+ git commit -m "test(day2): add wave engine, audit, and compaction test suites"
2271
+ ```
2272
+
2273
+ ---
2274
+
2275
+ ## TASK 12 — Run all tests and verify Day 2 is complete
2276
+
2277
+ ```bash
2278
+ # Day 1 tests (must still pass)
2279
+ node tests/install.test.js
2280
+
2281
+ # Day 2 tests
2282
+ node tests/wave-engine.test.js
2283
+ node tests/audit.test.js
2284
+ node tests/compaction.test.js
2285
+ ```
2286
+
2287
+ All must show: "All tests passed."
2288
+
2289
+ If any fail: fix before proceeding.
2290
+
2291
+ **Final Day 2 commit:**
2292
+ ```bash
2293
+ git add .
2294
+ git commit -m "feat(day2): complete Day 2 MindForge wave engine — all components built"
2295
+ git push origin feat/mindforge-wave-engine
2296
+ ```
2297
+
2298
+ ---
2299
+
2300
+ ## DAY 2 VERIFY — Complete this checklist before pushing
2301
+
2302
+ ```bash
2303
+ # 1. All new engine files exist
2304
+ ls .mindforge/engine/ # 4 files
2305
+ ls .mindforge/audit/ # 1 file
2306
+ ls .planning/AUDIT.jsonl # exists (empty is fine)
2307
+
2308
+ # 2. All new commands exist (both runtimes)
2309
+ ls .claude/commands/mindforge/ # 10 files (6 original + 4 new)
2310
+ ls .agent/mindforge/ # 10 files (must match exactly)
2311
+ diff <(ls .claude/commands/mindforge/ | sort) <(ls .agent/mindforge/ | sort)
2312
+ # expected: no output
2313
+
2314
+ # 3. All tests pass
2315
+ node tests/install.test.js && node tests/wave-engine.test.js && node tests/audit.test.js && node tests/compaction.test.js
2316
+
2317
+ # 4. AUDIT.jsonl is valid (empty or valid JSONL)
2318
+ node -e "
2319
+ const fs = require('fs');
2320
+ const c = fs.readFileSync('.planning/AUDIT.jsonl','utf8').trim();
2321
+ if(c) c.split('\n').forEach((l,i) => {try{JSON.parse(l)}catch(e){throw new Error('Line '+(i+1)+': '+e.message)}});
2322
+ console.log('AUDIT.jsonl valid');
2323
+ "
2324
+
2325
+ # 5. HANDOFF.json schema is correct
2326
+ node -e "
2327
+ const h = JSON.parse(require('fs').readFileSync('.planning/HANDOFF.json','utf8'));
2328
+ ['schema_version','next_task','_warning','context_refs','blockers'].forEach(f => {
2329
+ if(h[f] === undefined) throw new Error('Missing: ' + f);
2330
+ });
2331
+ console.log('HANDOFF.json valid');
2332
+ "
2333
+
2334
+ # 6. Git log: all Day 2 commits present
2335
+ git log --oneline | head -15
2336
+ # Expect: 12 clean commits from today
2337
+
2338
+ # 7. No secrets anywhere
2339
+ grep -r "password\s*=" . --include="*.md" --include="*.js" --include="*.json" \
2340
+ --exclude-dir=node_modules --exclude-dir=.git | grep -v "placeholder\|your-password\|example"
2341
+ # expected: no output
2342
+ ```
2343
+
2344
+ ---
2345
+
2346
+ **Branch:** `feat/mindforge-wave-engine`
2347
+ **Day 2 implementation complete. Proceed to DAY2-REVIEW.md.**