@jaimevalasek/aioson 1.6.0 → 1.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (275) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/README.md +729 -232
  3. package/docs/design-previews/pt.squarespace.com-homepage.html +889 -0
  4. package/docs/integrations/sdlc-genius-boundary.md +76 -0
  5. package/docs/integrations/sdlc-genius-eval-matrix.md +75 -0
  6. package/docs/integrations/sdlc-genius-install-checklist.md +93 -0
  7. package/docs/integrations/sdlc-genius-review-samples.md +86 -0
  8. package/docs/pt/README.md +3 -0
  9. package/docs/pt/agentes.md +1 -0
  10. package/docs/pt/comandos-cli.md +888 -2
  11. package/docs/pt/design-hybrid-forge.md +255 -6
  12. package/docs/pt/devlog-pipeline.md +270 -0
  13. package/docs/pt/fluxo-artefatos.md +178 -0
  14. package/docs/pt/hooks-session-guard.md +454 -0
  15. package/docs/pt/monitor-de-contexto.md +59 -5
  16. package/docs/pt/sdd-automation-scripts.md +557 -0
  17. package/docs/pt/site-forge.md +309 -0
  18. package/docs/pt/spec-learnings-pipeline.md +265 -0
  19. package/package.json +1 -1
  20. package/src/a2a/client.js +165 -0
  21. package/src/a2a/server.js +223 -0
  22. package/src/cli.js +235 -1
  23. package/src/commands/agent-audit.js +397 -0
  24. package/src/commands/agent-export-skill.js +229 -0
  25. package/src/commands/artifact-validate.js +189 -0
  26. package/src/commands/brief-gen.js +405 -0
  27. package/src/commands/brief-validate.js +65 -0
  28. package/src/commands/classify.js +256 -0
  29. package/src/commands/context-compact.js +49 -0
  30. package/src/commands/context-health.js +175 -0
  31. package/src/commands/context-monitor.js +71 -0
  32. package/src/commands/context-trim.js +177 -0
  33. package/src/commands/detect-test-runner.js +55 -0
  34. package/src/commands/devlog-export-brains.js +27 -0
  35. package/src/commands/devlog-process.js +292 -0
  36. package/src/commands/devlog-watch.js +131 -0
  37. package/src/commands/feature-close.js +165 -0
  38. package/src/commands/gate-check.js +228 -0
  39. package/src/commands/hooks-emit.js +253 -0
  40. package/src/commands/hooks-install.js +347 -0
  41. package/src/commands/learning-auto-promote.js +195 -0
  42. package/src/commands/learning-evolve.js +18 -9
  43. package/src/commands/learning-export.js +103 -0
  44. package/src/commands/learning-rollback.js +164 -0
  45. package/src/commands/live.js +25 -1
  46. package/src/commands/pattern-detect.js +33 -0
  47. package/src/commands/preflight-context.js +30 -0
  48. package/src/commands/preflight.js +208 -0
  49. package/src/commands/pulse-update.js +130 -0
  50. package/src/commands/runner-daemon.js +274 -0
  51. package/src/commands/runner-plan.js +70 -0
  52. package/src/commands/runner-queue-from-plan.js +166 -0
  53. package/src/commands/runner-queue.js +189 -0
  54. package/src/commands/runner-run.js +129 -0
  55. package/src/commands/runtime.js +47 -1
  56. package/src/commands/self-implement-loop.js +256 -0
  57. package/src/commands/session-guard.js +218 -0
  58. package/src/commands/sizing.js +165 -0
  59. package/src/commands/skill.js +65 -0
  60. package/src/commands/spec-checkpoint.js +177 -0
  61. package/src/commands/spec-status.js +79 -0
  62. package/src/commands/spec-sync.js +190 -0
  63. package/src/commands/spec-tasks.js +288 -0
  64. package/src/commands/squad-autorun.js +1220 -0
  65. package/src/commands/squad-bus.js +217 -0
  66. package/src/commands/squad-card.js +149 -0
  67. package/src/commands/squad-daemon.js +134 -0
  68. package/src/commands/squad-dependency-graph.js +164 -0
  69. package/src/commands/squad-review.js +106 -0
  70. package/src/commands/squad-scaffold.js +55 -0
  71. package/src/commands/squad-tool-register.js +157 -0
  72. package/src/commands/state-save.js +122 -0
  73. package/src/commands/update.js +2 -0
  74. package/src/commands/verify-gate.js +572 -0
  75. package/src/commands/workflow-execute.js +241 -0
  76. package/src/constants.js +22 -0
  77. package/src/install-profile.js +2 -2
  78. package/src/install-wizard.js +3 -2
  79. package/src/installer.js +6 -0
  80. package/src/lib/health-check.js +158 -0
  81. package/src/lib/hook-protocol.js +76 -0
  82. package/src/mcp/apps/squad-dashboard/app.js +163 -0
  83. package/src/mcp/apps/squad-dashboard/index.html +261 -0
  84. package/src/mcp/apps/squad-dashboard/mcp-manifest.json +23 -0
  85. package/src/mcp/resources/squad-state.js +130 -0
  86. package/src/preflight-engine.js +443 -0
  87. package/src/runner/cascade.js +97 -0
  88. package/src/runner/cli-launcher.js +109 -0
  89. package/src/runner/plan-importer.js +63 -0
  90. package/src/runner/queue-store.js +159 -0
  91. package/src/runtime-store.js +61 -3
  92. package/src/squad/agent-teams-adapter.js +264 -0
  93. package/src/squad/brief-validator.js +350 -0
  94. package/src/squad/bus-bridge.js +140 -0
  95. package/src/squad/context-compactor.js +265 -0
  96. package/src/squad/cross-ai-synthesizer.js +250 -0
  97. package/src/squad/hooks-generator.js +196 -0
  98. package/src/squad/inter-squad-events.js +175 -0
  99. package/src/squad/intra-bus.js +345 -0
  100. package/src/squad/learning-extractor.js +213 -0
  101. package/src/squad/pattern-detector.js +365 -0
  102. package/src/squad/preflight-context.js +296 -0
  103. package/src/squad/recovery-context.js +242 -71
  104. package/src/squad/reflection.js +365 -0
  105. package/src/squad/squad-scaffold.js +177 -0
  106. package/src/squad/state-manager.js +310 -0
  107. package/src/squad/task-decomposer.js +652 -0
  108. package/src/squad/verify-gate.js +303 -0
  109. package/src/updater.js +4 -5
  110. package/src/worker-runner.js +186 -1
  111. package/template/.aioson/agents/analyst.md +62 -1
  112. package/template/.aioson/agents/architect.md +61 -1
  113. package/template/.aioson/agents/copywriter.md +463 -0
  114. package/template/.aioson/agents/design-hybrid-forge.md +14 -0
  115. package/template/.aioson/agents/dev.md +271 -25
  116. package/template/.aioson/agents/deyvin.md +67 -8
  117. package/template/.aioson/agents/discovery-design-doc.md +44 -0
  118. package/template/.aioson/agents/genome.md +14 -0
  119. package/template/.aioson/agents/neo.md +83 -2
  120. package/template/.aioson/agents/orache.md +50 -4
  121. package/template/.aioson/agents/orchestrator.md +197 -1
  122. package/template/.aioson/agents/pm.md +35 -0
  123. package/template/.aioson/agents/product.md +50 -5
  124. package/template/.aioson/agents/profiler-enricher.md +14 -0
  125. package/template/.aioson/agents/profiler-forge.md +14 -0
  126. package/template/.aioson/agents/profiler-researcher.md +14 -0
  127. package/template/.aioson/agents/qa.md +273 -21
  128. package/template/.aioson/agents/setup.md +96 -10
  129. package/template/.aioson/agents/sheldon.md +131 -6
  130. package/template/.aioson/agents/site-forge.md +1753 -0
  131. package/template/.aioson/agents/squad.md +352 -0
  132. package/template/.aioson/agents/tester.md +53 -0
  133. package/template/.aioson/agents/ux-ui.md +203 -4
  134. package/template/.aioson/brains/README.md +128 -0
  135. package/template/.aioson/brains/_index.json +16 -0
  136. package/template/.aioson/brains/scripts/query.js +103 -0
  137. package/template/.aioson/brains/site-forge/visual-patterns.brain.json +205 -0
  138. package/template/.aioson/config.md +143 -13
  139. package/template/.aioson/constitution.md +33 -0
  140. package/template/.aioson/context/project-pulse.md +34 -0
  141. package/template/.aioson/docs/LAYERS.md +79 -0
  142. package/template/.aioson/docs/README.md +76 -0
  143. package/template/.aioson/docs/example-external-api-context.md +72 -0
  144. package/template/.aioson/genomes/copywriting.md +204 -0
  145. package/template/.aioson/locales/en/agents/architect.md +17 -0
  146. package/template/.aioson/locales/en/agents/dev.md +79 -13
  147. package/template/.aioson/locales/en/agents/orache.md +6 -0
  148. package/template/.aioson/locales/en/agents/orchestrator.md +24 -0
  149. package/template/.aioson/locales/en/agents/product.md +50 -0
  150. package/template/.aioson/locales/en/agents/sheldon.md +115 -0
  151. package/template/.aioson/locales/en/agents/squad.md +14 -0
  152. package/template/.aioson/locales/en/agents/tester.md +6 -0
  153. package/template/.aioson/locales/es/agents/analyst.md +2 -0
  154. package/template/.aioson/locales/es/agents/architect.md +19 -0
  155. package/template/.aioson/locales/es/agents/dev.md +64 -4
  156. package/template/.aioson/locales/es/agents/deyvin.md +2 -0
  157. package/template/.aioson/locales/es/agents/discovery-design-doc.md +2 -0
  158. package/template/.aioson/locales/es/agents/genome.md +2 -0
  159. package/template/.aioson/locales/es/agents/neo.md +2 -0
  160. package/template/.aioson/locales/es/agents/orache.md +2 -0
  161. package/template/.aioson/locales/es/agents/orchestrator.md +26 -0
  162. package/template/.aioson/locales/es/agents/pair.md +2 -0
  163. package/template/.aioson/locales/es/agents/pm.md +2 -0
  164. package/template/.aioson/locales/es/agents/product.md +52 -0
  165. package/template/.aioson/locales/es/agents/profiler-enricher.md +2 -0
  166. package/template/.aioson/locales/es/agents/profiler-forge.md +2 -0
  167. package/template/.aioson/locales/es/agents/profiler-researcher.md +2 -0
  168. package/template/.aioson/locales/es/agents/qa.md +2 -0
  169. package/template/.aioson/locales/es/agents/setup.md +2 -0
  170. package/template/.aioson/locales/es/agents/sheldon.md +117 -0
  171. package/template/.aioson/locales/es/agents/squad.md +16 -0
  172. package/template/.aioson/locales/es/agents/tester.md +9 -0
  173. package/template/.aioson/locales/es/agents/ux-ui.md +2 -0
  174. package/template/.aioson/locales/fr/agents/analyst.md +2 -0
  175. package/template/.aioson/locales/fr/agents/architect.md +19 -0
  176. package/template/.aioson/locales/fr/agents/dev.md +64 -4
  177. package/template/.aioson/locales/fr/agents/deyvin.md +2 -0
  178. package/template/.aioson/locales/fr/agents/discovery-design-doc.md +2 -0
  179. package/template/.aioson/locales/fr/agents/genome.md +2 -0
  180. package/template/.aioson/locales/fr/agents/neo.md +2 -0
  181. package/template/.aioson/locales/fr/agents/orache.md +2 -0
  182. package/template/.aioson/locales/fr/agents/orchestrator.md +26 -0
  183. package/template/.aioson/locales/fr/agents/pair.md +2 -0
  184. package/template/.aioson/locales/fr/agents/pm.md +2 -0
  185. package/template/.aioson/locales/fr/agents/product.md +52 -0
  186. package/template/.aioson/locales/fr/agents/profiler-enricher.md +2 -0
  187. package/template/.aioson/locales/fr/agents/profiler-forge.md +2 -0
  188. package/template/.aioson/locales/fr/agents/profiler-researcher.md +2 -0
  189. package/template/.aioson/locales/fr/agents/qa.md +2 -0
  190. package/template/.aioson/locales/fr/agents/setup.md +2 -0
  191. package/template/.aioson/locales/fr/agents/sheldon.md +117 -0
  192. package/template/.aioson/locales/fr/agents/squad.md +16 -0
  193. package/template/.aioson/locales/fr/agents/tester.md +9 -0
  194. package/template/.aioson/locales/fr/agents/ux-ui.md +2 -0
  195. package/template/.aioson/locales/pt-BR/agents/analyst.md +64 -3
  196. package/template/.aioson/locales/pt-BR/agents/architect.md +42 -0
  197. package/template/.aioson/locales/pt-BR/agents/dev.md +147 -14
  198. package/template/.aioson/locales/pt-BR/agents/deyvin.md +47 -0
  199. package/template/.aioson/locales/pt-BR/agents/neo.md +62 -1
  200. package/template/.aioson/locales/pt-BR/agents/orchestrator.md +158 -2
  201. package/template/.aioson/locales/pt-BR/agents/pm.md +95 -1
  202. package/template/.aioson/locales/pt-BR/agents/product.md +145 -18
  203. package/template/.aioson/locales/pt-BR/agents/qa.md +16 -0
  204. package/template/.aioson/locales/pt-BR/agents/setup.md +101 -18
  205. package/template/.aioson/locales/pt-BR/agents/sheldon.md +132 -1
  206. package/template/.aioson/locales/pt-BR/agents/squad.md +14 -0
  207. package/template/.aioson/locales/pt-BR/agents/tester.md +449 -0
  208. package/template/.aioson/rules/README.md +69 -0
  209. package/template/.aioson/rules/data-format-convention.md +136 -0
  210. package/template/.aioson/rules/example-monetary-values.md +30 -0
  211. package/template/.aioson/schemas/squad-manifest.schema.json +124 -3
  212. package/template/.aioson/skills/design/cognitive-core-ui/references/motion.md +2 -0
  213. package/template/.aioson/skills/design/pt.squarespace.com/.skill-meta.json +31 -0
  214. package/template/.aioson/skills/design/pt.squarespace.com/SKILL.md +66 -0
  215. package/template/.aioson/skills/design/pt.squarespace.com/references/components.md +368 -0
  216. package/template/.aioson/skills/design/pt.squarespace.com/references/design-tokens.md +150 -0
  217. package/template/.aioson/skills/design/pt.squarespace.com/references/motion.md +270 -0
  218. package/template/.aioson/skills/design/pt.squarespace.com/references/patterns.md +189 -0
  219. package/template/.aioson/skills/design/pt.squarespace.com/references/websites.md +165 -0
  220. package/template/.aioson/skills/marketing/references/anti-patterns.md +254 -0
  221. package/template/.aioson/skills/marketing/references/fascinations.md +192 -0
  222. package/template/.aioson/skills/marketing/references/five-acts.md +248 -0
  223. package/template/.aioson/skills/marketing/references/market-intelligence.md +198 -0
  224. package/template/.aioson/skills/marketing/references/offer-structure.md +203 -0
  225. package/template/.aioson/skills/marketing/references/one-belief.md +149 -0
  226. package/template/.aioson/skills/marketing/references/patterns.md +218 -0
  227. package/template/.aioson/skills/marketing/references/pms-research.md +193 -0
  228. package/template/.aioson/skills/marketing/vsl-craft.md +385 -0
  229. package/template/.aioson/skills/process/aioson-spec-driven/SKILL.md +1 -0
  230. package/template/.aioson/skills/process/aioson-spec-driven/references/analyst.md +30 -0
  231. package/template/.aioson/skills/process/aioson-spec-driven/references/architect.md +23 -0
  232. package/template/.aioson/skills/process/aioson-spec-driven/references/dev.md +47 -0
  233. package/template/.aioson/skills/process/aioson-spec-driven/references/deyvin.md +27 -0
  234. package/template/.aioson/skills/process/aioson-spec-driven/references/maintenance-and-state.md +35 -0
  235. package/template/.aioson/skills/process/aioson-spec-driven/references/product.md +25 -0
  236. package/template/.aioson/skills/process/aioson-spec-driven/references/qa.md +30 -0
  237. package/template/.aioson/skills/process/aioson-spec-driven/references/sheldon.md +25 -0
  238. package/template/.aioson/skills/process/design-hybrid-forge/SKILL.md +4 -1
  239. package/template/.aioson/skills/process/design-hybrid-forge/references/output-contract.md +15 -0
  240. package/template/.aioson/skills/process/design-hybrid-forge/references/pair-compatibility.md +32 -0
  241. package/template/.aioson/skills/process/design-hybrid-forge/references/quality-gates.md +20 -0
  242. package/template/.aioson/skills/process/simplify/SKILL.md +173 -0
  243. package/template/.aioson/skills/static/context-budget-guide.md +46 -0
  244. package/template/.aioson/skills/static/harness-sensors.md +74 -0
  245. package/template/.aioson/skills/static/landing-page-deploy.md +192 -0
  246. package/template/.aioson/skills/static/landing-page-forge.md +730 -0
  247. package/template/.aioson/skills/static/multi-agent-patterns.md +43 -0
  248. package/template/.aioson/skills/static/react-motion-patterns.md +22 -0
  249. package/template/.aioson/skills/static/static-html-patterns/checklists.md +43 -0
  250. package/template/.aioson/skills/static/static-html-patterns/css-tokens.md +609 -0
  251. package/template/.aioson/skills/static/static-html-patterns/motion.md +193 -0
  252. package/template/.aioson/skills/static/static-html-patterns/premium.md +711 -0
  253. package/template/.aioson/skills/static/static-html-patterns/structure.md +209 -0
  254. package/template/.aioson/skills/static/static-html-patterns/utilities.md +190 -0
  255. package/template/.aioson/skills/static/static-html-patterns.md +58 -1913
  256. package/template/.aioson/skills/static/threejs-patterns.md +929 -0
  257. package/template/.aioson/skills/static/ui-ux-modern.md +1 -0
  258. package/template/.aioson/skills/static/web-research-cache.md +112 -0
  259. package/template/.aioson/tasks/implementation-plan.md +21 -1
  260. package/template/.aioson/tasks/squad-create.md +22 -0
  261. package/template/.aioson/tasks/squad-design.md +30 -0
  262. package/template/.aioson/templates/squads/digital-marketing-agency/template.json +96 -0
  263. package/template/.claude/commands/aioson/agent/design-hybrid-forge.md +5 -0
  264. package/template/.claude/commands/aioson/agent/orache.md +5 -0
  265. package/template/.claude/commands/aioson/agent/sheldon.md +5 -0
  266. package/template/.claude/commands/aioson/agent/site-forge.md +5 -0
  267. package/template/AGENTS.md +55 -3
  268. package/template/CLAUDE.md +31 -0
  269. package/template/OPENCODE.md +4 -0
  270. package/template/researchs/.gitkeep +0 -0
  271. package/template/.aioson/skills/design-system/components/SKILL.md:Zone.Identifier +0 -0
  272. package/template/.aioson/skills/design-system/dashboards/SKILL.md:Zone.Identifier +0 -0
  273. package/template/.aioson/skills/design-system/foundations/SKILL.md:Zone.Identifier +0 -0
  274. package/template/.aioson/skills/design-system/motion/SKILL.md:Zone.Identifier +0 -0
  275. package/template/.aioson/skills/design-system/patterns/SKILL.md:Zone.Identifier +0 -0
@@ -0,0 +1,652 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Squad task decomposer — autonomous goal → execution plan
5
+ *
6
+ * Given a high-level goal, the decomposer:
7
+ * 1. Reads the squad manifest to discover available executors and their roles
8
+ * 2. Breaks the goal into sub-tasks with acceptance criteria
9
+ * 3. Maps each task to the most suitable executor
10
+ * 4. Detects dependencies between tasks (sequential vs parallel)
11
+ * 5. Returns a prioritized execution plan
12
+ *
13
+ * Two decomposition modes:
14
+ * heuristic (default) — regex + keyword matching, zero LLM calls, instant
15
+ * structured — uses a structured prompt template saved to disk
16
+ * for the agent to fill in (LLM completes it on activation)
17
+ *
18
+ * The execution plan is saved to:
19
+ * .aioson/squads/{slug}/sessions/{sessionId}/plan.json
20
+ *
21
+ * Format:
22
+ * {
23
+ * id, session_id, squad_slug, goal, created_at,
24
+ * decomposition_mode,
25
+ * tasks: [{ id, title, description, acceptance_criteria, executor, dependencies,
26
+ * priority, parallel_group, status }],
27
+ * execution_order: [...], // topological order
28
+ * parallel_groups: { N: [...taskIds] }
29
+ * }
30
+ */
31
+
32
+ const fs = require('node:fs/promises');
33
+ const path = require('node:path');
34
+ const { randomUUID } = require('node:crypto');
35
+
36
+ // ─── Squad manifest loading ───────────────────────────────────────────────────
37
+
38
+ async function loadSquadManifest(projectDir, squadSlug) {
39
+ const squadDir = path.join(projectDir, '.aioson', 'squads', squadSlug);
40
+
41
+ // Try squad.manifest.json first (canonical), fall back to squad.json (legacy)
42
+ let squadJson = null;
43
+ let manifestSource = null;
44
+ for (const fileName of ['squad.manifest.json', 'squad.json']) {
45
+ try {
46
+ squadJson = JSON.parse(
47
+ await fs.readFile(path.join(squadDir, fileName), 'utf8')
48
+ );
49
+ manifestSource = fileName;
50
+ break;
51
+ } catch { /* try next */ }
52
+ }
53
+
54
+ // Discover executor agent files from correct path
55
+ const agentsDir = path.join(projectDir, '.aioson', 'squads', squadSlug, 'agents');
56
+ let executorFiles = [];
57
+ try {
58
+ const entries = await fs.readdir(agentsDir, { withFileTypes: true });
59
+ executorFiles = entries
60
+ .filter((e) => e.isFile() && e.name.endsWith('.md') && e.name !== 'agents.md')
61
+ .map((e) => e.name.replace(/\.md$/, ''));
62
+ } catch { /* agents dir optional */ }
63
+
64
+ // Build executor list from manifest + discovered files
65
+ const executors = buildExecutorList(squadJson, executorFiles);
66
+
67
+ const discoverySource = manifestSource
68
+ ? `manifest (${manifestSource}, ${executors.length} executor(s))`
69
+ : `heuristic (${executorFiles.length} agent file(s) discovered)`;
70
+
71
+ return { squadJson, executors, discoverySource };
72
+ }
73
+
74
+ function buildExecutorList(squadJson, discoveredFiles) {
75
+ const execMap = {};
76
+
77
+ // From manifest: supports both array format (squad.manifest.json) and object format (legacy squad.json)
78
+ if (squadJson && squadJson.executors) {
79
+ const executorEntries = Array.isArray(squadJson.executors)
80
+ ? squadJson.executors.map((e) => [e.slug, e])
81
+ : Object.entries(squadJson.executors);
82
+
83
+ for (const [slug, config] of executorEntries) {
84
+ if (!slug) continue;
85
+ execMap[slug] = {
86
+ slug,
87
+ name: config.name || config.title || slug,
88
+ role: config.role || slug,
89
+ skills: config.skills || [],
90
+ keywords: extractKeywords(config.role || '', config.name || config.title || '', config.skills || [])
91
+ };
92
+ }
93
+ }
94
+
95
+ // From discovered agent files (if not already in map)
96
+ for (const slug of discoveredFiles) {
97
+ if (!execMap[slug]) {
98
+ execMap[slug] = {
99
+ slug,
100
+ name: slug,
101
+ role: slug,
102
+ skills: [],
103
+ keywords: extractKeywords(slug)
104
+ };
105
+ }
106
+ }
107
+
108
+ return Object.values(execMap);
109
+ }
110
+
111
+ function extractKeywords(...sources) {
112
+ const text = sources.flat().join(' ').toLowerCase();
113
+ return text.split(/[\s,;_-]+/).filter((w) => w.length > 3);
114
+ }
115
+
116
+ // ─── Heuristic decomposition ─────────────────────────────────────────────────
117
+
118
+ // Action verb patterns → task type mapping
119
+ const ACTION_VERBS = {
120
+ research: ['research', 'investigate', 'analyze', 'study', 'explore', 'discover', 'find'],
121
+ write: ['write', 'create', 'draft', 'compose', 'produce', 'generate', 'craft'],
122
+ review: ['review', 'critique', 'evaluate', 'assess', 'check', 'validate', 'verify'],
123
+ design: ['design', 'plan', 'structure', 'outline', 'architect', 'map'],
124
+ publish: ['publish', 'post', 'distribute', 'share', 'deliver', 'send', 'output'],
125
+ summarize: ['summarize', 'consolidate', 'compile', 'aggregate', 'collect'],
126
+ translate: ['translate', 'adapt', 'localize', 'convert', 'rewrite'],
127
+ optimize: ['optimize', 'improve', 'refine', 'enhance', 'edit', 'revise']
128
+ };
129
+
130
+ const EXECUTOR_ROLE_MAP = {
131
+ research: ['researcher', 'analyst', 'investigator', 'scout', 'explorer'],
132
+ write: ['writer', 'copywriter', 'author', 'creator', 'scriptwriter'],
133
+ review: ['critic', 'reviewer', 'editor', 'qa', 'quality', 'validator'],
134
+ design: ['designer', 'architect', 'strategist', 'planner'],
135
+ publish: ['publisher', 'distributor', 'delivery', 'output'],
136
+ summarize: ['summarizer', 'aggregator', 'curator'],
137
+ translate: ['translator', 'localizer', 'adapter'],
138
+ optimize: ['optimizer', 'editor', 'refiner']
139
+ };
140
+
141
+ function detectVerbType(text) {
142
+ const lower = text.toLowerCase();
143
+ for (const [type, verbs] of Object.entries(ACTION_VERBS)) {
144
+ if (verbs.some((v) => lower.includes(v))) return type;
145
+ }
146
+ return 'write'; // default
147
+ }
148
+
149
+ function scoreExecutorForType(executor, verbType) {
150
+ const roleKeywords = EXECUTOR_ROLE_MAP[verbType] || [];
151
+ const execKeywords = executor.keywords;
152
+ return roleKeywords.reduce((score, rk) => {
153
+ return score + (execKeywords.some((ek) => ek.includes(rk) || rk.includes(ek)) ? 1 : 0);
154
+ }, 0);
155
+ }
156
+
157
+ function assignExecutor(executors, verbType) {
158
+ if (executors.length === 0) return null;
159
+
160
+ const scored = executors.map((e) => ({
161
+ executor: e,
162
+ score: scoreExecutorForType(e, verbType)
163
+ }));
164
+ scored.sort((a, b) => b.score - a.score);
165
+
166
+ return scored[0].score > 0 ? scored[0].executor : executors[0];
167
+ }
168
+
169
+ function extractSubGoals(goal) {
170
+ const text = String(goal || '').trim();
171
+
172
+ // Split on: numbered lists, bullet points, "and then", semicolons, newlines
173
+ const parts = text
174
+ .split(/(?:\d+[.)]\s+|[•\-*]\s+|\band\s+then\b|;\s*|\n+)/)
175
+ .map((s) => s.trim())
176
+ .filter((s) => s.length > 10);
177
+
178
+ if (parts.length > 1) return parts;
179
+
180
+ // Single sentence: split on commas + conjunctions suggesting parallel work
181
+ const commaSplit = text.split(/,\s+(?:and\s+)?/).map((s) => s.trim()).filter((s) => s.length > 10);
182
+ if (commaSplit.length > 1 && commaSplit.length <= 8) return commaSplit;
183
+
184
+ // Single goal — treat as one task
185
+ return [text];
186
+ }
187
+
188
+ function buildAcceptanceCriteria(taskTitle, verbType) {
189
+ const base = [
190
+ `Output directly addresses the task: "${taskTitle.slice(0, 80)}"`,
191
+ 'Content is complete, not truncated',
192
+ 'No generic filler — all content is task-specific'
193
+ ];
194
+
195
+ const specific = {
196
+ research: ['Findings cite at least one concrete source or evidence', 'Distinguishes facts from inferences'],
197
+ write: ['Follows the squad\'s tone and style guidelines', 'Covers all required points from the brief'],
198
+ review: ['Lists specific issues with clear descriptions', 'Each issue has a concrete recommendation'],
199
+ design: ['Plan is actionable — each step is executable', 'Dependencies between steps are explicit'],
200
+ publish: ['Output format matches delivery specification', 'File is written to correct output path'],
201
+ summarize: ['Captures all key points from source material', 'No important information omitted'],
202
+ translate: ['Preserves original meaning accurately', 'Reads naturally in the target language'],
203
+ optimize: ['Each change is explained with a clear reason', 'Original intent is preserved']
204
+ };
205
+
206
+ return [...base, ...(specific[verbType] || [])];
207
+ }
208
+
209
+ // ─── must_haves contract builder ──────────────────────────────────────────────
210
+
211
+ /**
212
+ * Build a must_haves contract for a task based on its verb type.
213
+ * These are heuristic defaults — executors can override in squad.json.
214
+ */
215
+ function buildMustHaves(taskTitle, verbType) {
216
+ const title = taskTitle.slice(0, 60);
217
+
218
+ const contracts = {
219
+ research: {
220
+ truths: [`Research findings address: "${title}"`],
221
+ artifacts: [],
222
+ key_links: []
223
+ },
224
+ write: {
225
+ truths: [`Written content covers the scope of: "${title}"`],
226
+ artifacts: [], // populated if executor writes to a file
227
+ key_links: []
228
+ },
229
+ review: {
230
+ truths: [`Review identifies concrete issues in: "${title}"`],
231
+ artifacts: [],
232
+ key_links: []
233
+ },
234
+ design: {
235
+ truths: [`Design plan is actionable for: "${title}"`],
236
+ artifacts: [],
237
+ key_links: []
238
+ },
239
+ publish: {
240
+ truths: [`Output is delivered for: "${title}"`],
241
+ artifacts: [],
242
+ key_links: []
243
+ },
244
+ summarize: {
245
+ truths: [`Summary captures all key points of: "${title}"`],
246
+ artifacts: [],
247
+ key_links: []
248
+ },
249
+ translate: {
250
+ truths: [`Translation preserves the meaning of: "${title}"`],
251
+ artifacts: [],
252
+ key_links: []
253
+ },
254
+ optimize: {
255
+ truths: [`Optimization is applied to: "${title}"`],
256
+ artifacts: [],
257
+ key_links: []
258
+ }
259
+ };
260
+
261
+ return contracts[verbType] || {
262
+ truths: [`Task output addresses: "${title}"`],
263
+ artifacts: [],
264
+ key_links: []
265
+ };
266
+ }
267
+
268
+ // ─── read_first hints builder ─────────────────────────────────────────────────
269
+
270
+ /**
271
+ * Build read_first hints for a task.
272
+ * These are instructions (not literal paths) telling the executor what to read
273
+ * before starting — avoids loading everything inline and inflating context.
274
+ */
275
+ function buildReadFirstHints(verbType) {
276
+ const hints = {
277
+ research: ['Start with web search or existing researchs/ cache before reading code'],
278
+ write: ['Read the brief/spec document first, then any referenced source material'],
279
+ review: ['Read only the artifact being reviewed — not the full codebase'],
280
+ design: ['Read existing architecture docs and constraints before designing'],
281
+ publish: ['Read output spec and target format before writing to disk'],
282
+ summarize: ['Read source material first, then check for existing summaries to build on'],
283
+ translate: ['Read the original content in full before starting translation'],
284
+ optimize: ['Read the current implementation first — understand before changing']
285
+ };
286
+
287
+ return hints[verbType] || ['Read only files directly relevant to this specific task'];
288
+ }
289
+
290
+ function detectDependencies(tasks) {
291
+ // Simple heuristic: review/optimize/publish tasks depend on write/research tasks
292
+ const DEPENDENT_TYPES = new Set(['review', 'optimize', 'publish', 'summarize']);
293
+ const PRODUCER_TYPES = new Set(['research', 'write', 'design']);
294
+
295
+ const producerIds = tasks
296
+ .filter((t) => PRODUCER_TYPES.has(t._verbType))
297
+ .map((t) => t.id);
298
+
299
+ return tasks.map((task) => ({
300
+ ...task,
301
+ dependencies: DEPENDENT_TYPES.has(task._verbType) ? producerIds.filter((id) => id !== task.id) : []
302
+ }));
303
+ }
304
+
305
+ function assignParallelGroups(tasks) {
306
+ // Group 1: tasks with no dependencies (can run in parallel)
307
+ // Group 2: tasks that depend only on group 1
308
+ // Group N: tasks that depend on group N-1
309
+ const groupMap = {};
310
+ const assigned = new Set();
311
+
312
+ let group = 1;
313
+ let remaining = [...tasks];
314
+
315
+ while (remaining.length > 0) {
316
+ const currentGroup = remaining.filter((t) =>
317
+ t.dependencies.every((dep) => assigned.has(dep))
318
+ );
319
+
320
+ if (currentGroup.length === 0) {
321
+ // Circular dependency or unresolvable — assign all remaining to next group
322
+ for (const t of remaining) {
323
+ groupMap[t.id] = group;
324
+ assigned.add(t.id);
325
+ }
326
+ break;
327
+ }
328
+
329
+ for (const t of currentGroup) {
330
+ groupMap[t.id] = group;
331
+ assigned.add(t.id);
332
+ }
333
+
334
+ remaining = remaining.filter((t) => !assigned.has(t));
335
+ group++;
336
+ }
337
+
338
+ return tasks.map((t) => ({ ...t, parallel_group: groupMap[t.id] || 1 }));
339
+ }
340
+
341
+ function heuristicDecompose(goal, executors) {
342
+ const subGoals = extractSubGoals(goal);
343
+
344
+ let tasks = subGoals.map((sg, i) => {
345
+ const verbType = detectVerbType(sg);
346
+ const executor = assignExecutor(executors, verbType);
347
+ const criteria = buildAcceptanceCriteria(sg, verbType);
348
+ const mustHaves = buildMustHaves(sg, verbType);
349
+ const readFirstHints = buildReadFirstHints(verbType);
350
+
351
+ return {
352
+ id: `task-${String(i + 1).padStart(2, '0')}`,
353
+ title: sg.slice(0, 100),
354
+ description: sg,
355
+ acceptance_criteria: criteria,
356
+ must_haves: mustHaves,
357
+ read_first_hints: readFirstHints,
358
+ executor: executor ? executor.slug : null,
359
+ dependencies: [],
360
+ priority: i + 1,
361
+ parallel_group: 1,
362
+ wave: 1,
363
+ status: 'pending',
364
+ _verbType: verbType
365
+ };
366
+ });
367
+
368
+ tasks = detectDependencies(tasks);
369
+ tasks = assignParallelGroups(tasks);
370
+
371
+ // Topological sort
372
+ const executionOrder = topologicalSort(tasks);
373
+
374
+ // Build parallel group index (kept as parallel_groups for backward compat)
375
+ // and waves (canonical new name)
376
+ const parallelGroups = {};
377
+ const waves = {};
378
+ for (const t of tasks) {
379
+ const g = t.parallel_group;
380
+ if (!parallelGroups[g]) parallelGroups[g] = [];
381
+ if (!waves[g]) waves[g] = [];
382
+ parallelGroups[g].push(t.id);
383
+ waves[g].push(t.id);
384
+ }
385
+
386
+ // Clean up internal field; set wave = parallel_group for clarity
387
+ const cleanTasks = tasks.map(({ _verbType, ...rest }) => ({ ...rest, wave: rest.parallel_group }));
388
+
389
+ return { tasks: cleanTasks, executionOrder, parallelGroups, waves };
390
+ }
391
+
392
+ function topologicalSort(tasks) {
393
+ const inDegree = {};
394
+ const adj = {};
395
+ const order = [];
396
+ const queue = [];
397
+
398
+ for (const t of tasks) {
399
+ inDegree[t.id] = t.dependencies.length;
400
+ adj[t.id] = tasks.filter((o) => o.dependencies.includes(t.id)).map((o) => o.id);
401
+ }
402
+
403
+ for (const t of tasks) {
404
+ if (inDegree[t.id] === 0) queue.push(t.id);
405
+ }
406
+
407
+ while (queue.length > 0) {
408
+ const id = queue.shift();
409
+ order.push(id);
410
+ for (const neighbor of (adj[id] || [])) {
411
+ inDegree[neighbor]--;
412
+ if (inDegree[neighbor] === 0) queue.push(neighbor);
413
+ }
414
+ }
415
+
416
+ // Add any remaining (handles cycles gracefully)
417
+ for (const t of tasks) {
418
+ if (!order.includes(t.id)) order.push(t.id);
419
+ }
420
+
421
+ return order;
422
+ }
423
+
424
+ // ─── Structured prompt template (for LLM-powered decomposition) ──────────────
425
+
426
+ function buildStructuredPrompt(goal, executors, squadSlug) {
427
+ const execList = executors
428
+ .map((e) => `- ${e.slug}: ${e.role}${e.skills.length ? ` (skills: ${e.skills.join(', ')})` : ''}`)
429
+ .join('\n');
430
+
431
+ return `You are the @squad coordinator for squad "${squadSlug}".
432
+
433
+ ## Goal
434
+ ${goal}
435
+
436
+ ## Available executors
437
+ ${execList || '(none discovered — create generic tasks)'}
438
+
439
+ ## Your task
440
+ Decompose the goal above into 2–7 concrete sub-tasks.
441
+
442
+ For each sub-task, provide:
443
+ 1. A short title (max 80 chars)
444
+ 2. A clear description (1–3 sentences)
445
+ 3. 3–5 acceptance criteria (specific, verifiable)
446
+ 4. The executor slug that should handle it
447
+ 5. Dependencies (list task IDs that must complete first, or empty)
448
+
449
+ Output ONLY valid JSON in this format:
450
+ {
451
+ "tasks": [
452
+ {
453
+ "id": "task-01",
454
+ "title": "...",
455
+ "description": "...",
456
+ "acceptance_criteria": ["...", "..."],
457
+ "executor": "executor-slug",
458
+ "dependencies": []
459
+ }
460
+ ]
461
+ }
462
+
463
+ Rules:
464
+ - Do not create tasks for unavailable executors
465
+ - Research tasks always precede write tasks when both exist
466
+ - Review/critique tasks always depend on write tasks
467
+ - Maximum 7 tasks — merge smaller tasks if needed
468
+ - Each task must be completable in one session`;
469
+ }
470
+
471
+ // ─── Plan persistence ─────────────────────────────────────────────────────────
472
+
473
+ async function savePlan(projectDir, squadSlug, sessionId, plan) {
474
+ const planDir = path.join(
475
+ projectDir, '.aioson', 'squads', squadSlug, 'sessions', sessionId
476
+ );
477
+ await fs.mkdir(planDir, { recursive: true });
478
+ const planPath = path.join(planDir, 'plan.json');
479
+ await fs.writeFile(planPath, JSON.stringify(plan, null, 2), 'utf8');
480
+ return planPath;
481
+ }
482
+
483
+ async function loadPlan(projectDir, squadSlug, sessionId) {
484
+ const planPath = path.join(
485
+ projectDir, '.aioson', 'squads', squadSlug, 'sessions', sessionId, 'plan.json'
486
+ );
487
+ try {
488
+ return JSON.parse(await fs.readFile(planPath, 'utf8'));
489
+ } catch {
490
+ return null;
491
+ }
492
+ }
493
+
494
+ async function updateTaskStatus(projectDir, squadSlug, sessionId, taskId, status, result = null) {
495
+ const plan = await loadPlan(projectDir, squadSlug, sessionId);
496
+ if (!plan) return null;
497
+
498
+ const task = plan.tasks.find((t) => t.id === taskId);
499
+ if (!task) return null;
500
+
501
+ task.status = status;
502
+ if (result !== null) task.result = result;
503
+ task.updated_at = new Date().toISOString();
504
+
505
+ await savePlan(projectDir, squadSlug, sessionId, plan);
506
+ return plan;
507
+ }
508
+
509
+ // ─── Public API ───────────────────────────────────────────────────────────────
510
+
511
+ /**
512
+ * Decompose a goal into an execution plan.
513
+ *
514
+ * @param {string} projectDir
515
+ * @param {string} squadSlug
516
+ * @param {string} goal — High-level objective
517
+ * @param {object} [options]
518
+ * @param {string} [options.sessionId] — Defaults to generated UUID
519
+ * @param {string} [options.mode] — 'heuristic' (default) | 'structured'
520
+ * @param {boolean} [options.save] — Save plan to disk (default: true)
521
+ * @returns {Promise<object>} plan
522
+ */
523
+ async function decompose(projectDir, squadSlug, goal, options = {}) {
524
+ const {
525
+ sessionId = randomUUID(),
526
+ mode = 'heuristic',
527
+ save = true
528
+ } = options;
529
+
530
+ const { executors, discoverySource } = await loadSquadManifest(projectDir, squadSlug);
531
+
532
+ let tasks, executionOrder, parallelGroups, waves;
533
+ let structuredPrompt = null;
534
+
535
+ if (mode === 'structured') {
536
+ // Return a prompt template for the agent to fill in with LLM
537
+ structuredPrompt = buildStructuredPrompt(goal, executors, squadSlug);
538
+ // Use heuristic as fallback scaffold
539
+ ({ tasks, executionOrder, parallelGroups, waves } = heuristicDecompose(goal, executors));
540
+ } else {
541
+ ({ tasks, executionOrder, parallelGroups, waves } = heuristicDecompose(goal, executors));
542
+ }
543
+
544
+ const plan = {
545
+ id: randomUUID(),
546
+ session_id: sessionId,
547
+ squad_slug: squadSlug,
548
+ goal,
549
+ created_at: new Date().toISOString(),
550
+ decomposition_mode: mode,
551
+ executor_count: executors.length,
552
+ executor_discovery: discoverySource,
553
+ tasks,
554
+ execution_order: executionOrder,
555
+ parallel_groups: parallelGroups,
556
+ waves,
557
+ structured_prompt: structuredPrompt
558
+ };
559
+
560
+ if (save) {
561
+ await savePlan(projectDir, squadSlug, sessionId, plan);
562
+ }
563
+
564
+ return plan;
565
+ }
566
+
567
+ /**
568
+ * Get the next tasks ready to execute (dependencies satisfied, status pending).
569
+ *
570
+ * @returns {object[]} tasks ready to run
571
+ */
572
+ function getReadyTasks(plan) {
573
+ const completed = new Set(
574
+ plan.tasks.filter((t) => t.status === 'completed' || t.status === 'done').map((t) => t.id)
575
+ );
576
+
577
+ return plan.tasks.filter((t) => {
578
+ if (t.status !== 'pending') return false;
579
+ return t.dependencies.every((dep) => completed.has(dep));
580
+ });
581
+ }
582
+
583
+ /**
584
+ * Check if a plan is fully complete.
585
+ */
586
+ function isPlanComplete(plan) {
587
+ return plan.tasks.every((t) => ['completed', 'done', 'skipped'].includes(t.status));
588
+ }
589
+
590
+ /**
591
+ * Format a plan as a human-readable markdown summary.
592
+ */
593
+ function formatPlan(plan) {
594
+ const lines = [
595
+ `## Execution Plan — ${plan.squad_slug}`,
596
+ `Session: ${plan.session_id}`,
597
+ `Goal: ${plan.goal}`,
598
+ `Decomposition: ${plan.decomposition_mode} | Executors: ${plan.executor_count}`,
599
+ `Created: ${plan.created_at}`,
600
+ '',
601
+ `### Tasks (${plan.tasks.length})`
602
+ ];
603
+
604
+ for (const taskId of plan.execution_order) {
605
+ const task = plan.tasks.find((t) => t.id === taskId);
606
+ if (!task) continue;
607
+ const statusIcon = {
608
+ pending: '○', in_progress: '●', completed: '✓', done: '✓',
609
+ failed: '✗', skipped: '–', escalated: '⚠'
610
+ }[task.status] || '?';
611
+
612
+ lines.push(`\n**[${statusIcon}] ${task.id}: ${task.title}**`);
613
+ lines.push(` Executor: ${task.executor || 'unassigned'} | Wave: ${task.wave || task.parallel_group}`);
614
+ if (task.dependencies.length > 0) lines.push(` Depends on: ${task.dependencies.join(', ')}`);
615
+ if (task.read_first_hints && task.read_first_hints.length > 0) {
616
+ lines.push(` Read first: ${task.read_first_hints[0]}`);
617
+ }
618
+ lines.push(' Acceptance criteria:');
619
+ for (const c of task.acceptance_criteria) lines.push(` - ${c}`);
620
+ if (task.must_haves) {
621
+ if (task.must_haves.truths && task.must_haves.truths.length > 0) {
622
+ lines.push(` Must-have truth: ${task.must_haves.truths[0]}`);
623
+ }
624
+ if (task.must_haves.artifacts && task.must_haves.artifacts.length > 0) {
625
+ lines.push(` Must-have artifact: ${task.must_haves.artifacts[0]}`);
626
+ }
627
+ }
628
+ }
629
+
630
+ const waveMap = plan.waves || plan.parallel_groups;
631
+ if (Object.keys(waveMap).length > 1) {
632
+ lines.push('', '### Execution waves');
633
+ for (const [wave, ids] of Object.entries(waveMap)) {
634
+ lines.push(` Wave ${wave}: ${ids.join(', ')}${ids.length > 1 ? ' (parallel)' : ''}`);
635
+ }
636
+ }
637
+
638
+ return lines.join('\n');
639
+ }
640
+
641
+ module.exports = {
642
+ decompose,
643
+ getReadyTasks,
644
+ isPlanComplete,
645
+ updateTaskStatus,
646
+ loadPlan,
647
+ savePlan,
648
+ formatPlan,
649
+ heuristicDecompose,
650
+ buildStructuredPrompt,
651
+ loadSquadManifest
652
+ };