@soleri/core 2.1.0 → 2.5.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 (377) hide show
  1. package/dist/brain/brain.d.ts +10 -1
  2. package/dist/brain/brain.d.ts.map +1 -1
  3. package/dist/brain/brain.js +116 -13
  4. package/dist/brain/brain.js.map +1 -1
  5. package/dist/brain/intelligence.d.ts +36 -1
  6. package/dist/brain/intelligence.d.ts.map +1 -1
  7. package/dist/brain/intelligence.js +119 -14
  8. package/dist/brain/intelligence.js.map +1 -1
  9. package/dist/brain/types.d.ts +34 -2
  10. package/dist/brain/types.d.ts.map +1 -1
  11. package/dist/cognee/client.d.ts +3 -0
  12. package/dist/cognee/client.d.ts.map +1 -1
  13. package/dist/cognee/client.js +17 -0
  14. package/dist/cognee/client.js.map +1 -1
  15. package/dist/cognee/sync-manager.d.ts +94 -0
  16. package/dist/cognee/sync-manager.d.ts.map +1 -0
  17. package/dist/cognee/sync-manager.js +293 -0
  18. package/dist/cognee/sync-manager.js.map +1 -0
  19. package/dist/control/identity-manager.d.ts +22 -0
  20. package/dist/control/identity-manager.d.ts.map +1 -0
  21. package/dist/control/identity-manager.js +233 -0
  22. package/dist/control/identity-manager.js.map +1 -0
  23. package/dist/control/intent-router.d.ts +32 -0
  24. package/dist/control/intent-router.d.ts.map +1 -0
  25. package/dist/control/intent-router.js +242 -0
  26. package/dist/control/intent-router.js.map +1 -0
  27. package/dist/control/types.d.ts +68 -0
  28. package/dist/control/types.d.ts.map +1 -0
  29. package/dist/control/types.js +9 -0
  30. package/dist/control/types.js.map +1 -0
  31. package/dist/curator/curator.d.ts +37 -1
  32. package/dist/curator/curator.d.ts.map +1 -1
  33. package/dist/curator/curator.js +199 -1
  34. package/dist/curator/curator.js.map +1 -1
  35. package/dist/errors/classify.d.ts +13 -0
  36. package/dist/errors/classify.d.ts.map +1 -0
  37. package/dist/errors/classify.js +97 -0
  38. package/dist/errors/classify.js.map +1 -0
  39. package/dist/errors/index.d.ts +6 -0
  40. package/dist/errors/index.d.ts.map +1 -0
  41. package/dist/errors/index.js +4 -0
  42. package/dist/errors/index.js.map +1 -0
  43. package/dist/errors/retry.d.ts +40 -0
  44. package/dist/errors/retry.d.ts.map +1 -0
  45. package/dist/errors/retry.js +97 -0
  46. package/dist/errors/retry.js.map +1 -0
  47. package/dist/errors/types.d.ts +48 -0
  48. package/dist/errors/types.d.ts.map +1 -0
  49. package/dist/errors/types.js +59 -0
  50. package/dist/errors/types.js.map +1 -0
  51. package/dist/facades/types.d.ts +1 -1
  52. package/dist/governance/governance.d.ts +42 -0
  53. package/dist/governance/governance.d.ts.map +1 -0
  54. package/dist/governance/governance.js +488 -0
  55. package/dist/governance/governance.js.map +1 -0
  56. package/dist/governance/index.d.ts +3 -0
  57. package/dist/governance/index.d.ts.map +1 -0
  58. package/dist/governance/index.js +2 -0
  59. package/dist/governance/index.js.map +1 -0
  60. package/dist/governance/types.d.ts +102 -0
  61. package/dist/governance/types.d.ts.map +1 -0
  62. package/dist/governance/types.js +3 -0
  63. package/dist/governance/types.js.map +1 -0
  64. package/dist/index.d.ts +52 -3
  65. package/dist/index.d.ts.map +1 -1
  66. package/dist/index.js +47 -1
  67. package/dist/index.js.map +1 -1
  68. package/dist/intake/content-classifier.d.ts +14 -0
  69. package/dist/intake/content-classifier.d.ts.map +1 -0
  70. package/dist/intake/content-classifier.js +125 -0
  71. package/dist/intake/content-classifier.js.map +1 -0
  72. package/dist/intake/dedup-gate.d.ts +17 -0
  73. package/dist/intake/dedup-gate.d.ts.map +1 -0
  74. package/dist/intake/dedup-gate.js +66 -0
  75. package/dist/intake/dedup-gate.js.map +1 -0
  76. package/dist/intake/intake-pipeline.d.ts +63 -0
  77. package/dist/intake/intake-pipeline.d.ts.map +1 -0
  78. package/dist/intake/intake-pipeline.js +373 -0
  79. package/dist/intake/intake-pipeline.js.map +1 -0
  80. package/dist/intake/types.d.ts +65 -0
  81. package/dist/intake/types.d.ts.map +1 -0
  82. package/dist/intake/types.js +3 -0
  83. package/dist/intake/types.js.map +1 -0
  84. package/dist/intelligence/loader.js +1 -1
  85. package/dist/intelligence/loader.js.map +1 -1
  86. package/dist/intelligence/types.d.ts +3 -1
  87. package/dist/intelligence/types.d.ts.map +1 -1
  88. package/dist/logging/logger.d.ts +37 -0
  89. package/dist/logging/logger.d.ts.map +1 -0
  90. package/dist/logging/logger.js +145 -0
  91. package/dist/logging/logger.js.map +1 -0
  92. package/dist/logging/types.d.ts +19 -0
  93. package/dist/logging/types.d.ts.map +1 -0
  94. package/dist/logging/types.js +2 -0
  95. package/dist/logging/types.js.map +1 -0
  96. package/dist/loop/loop-manager.d.ts +100 -0
  97. package/dist/loop/loop-manager.d.ts.map +1 -0
  98. package/dist/loop/loop-manager.js +379 -0
  99. package/dist/loop/loop-manager.js.map +1 -0
  100. package/dist/loop/types.d.ts +103 -0
  101. package/dist/loop/types.d.ts.map +1 -0
  102. package/dist/loop/types.js +11 -0
  103. package/dist/loop/types.js.map +1 -0
  104. package/dist/persistence/index.d.ts +3 -0
  105. package/dist/persistence/index.d.ts.map +1 -0
  106. package/dist/persistence/index.js +2 -0
  107. package/dist/persistence/index.js.map +1 -0
  108. package/dist/persistence/sqlite-provider.d.ts +25 -0
  109. package/dist/persistence/sqlite-provider.d.ts.map +1 -0
  110. package/dist/persistence/sqlite-provider.js +59 -0
  111. package/dist/persistence/sqlite-provider.js.map +1 -0
  112. package/dist/persistence/types.d.ts +36 -0
  113. package/dist/persistence/types.d.ts.map +1 -0
  114. package/dist/persistence/types.js +8 -0
  115. package/dist/persistence/types.js.map +1 -0
  116. package/dist/planning/gap-analysis.d.ts +72 -0
  117. package/dist/planning/gap-analysis.d.ts.map +1 -0
  118. package/dist/planning/gap-analysis.js +442 -0
  119. package/dist/planning/gap-analysis.js.map +1 -0
  120. package/dist/planning/gap-types.d.ts +29 -0
  121. package/dist/planning/gap-types.d.ts.map +1 -0
  122. package/dist/planning/gap-types.js +28 -0
  123. package/dist/planning/gap-types.js.map +1 -0
  124. package/dist/planning/planner.d.ts +421 -4
  125. package/dist/planning/planner.d.ts.map +1 -1
  126. package/dist/planning/planner.js +949 -21
  127. package/dist/planning/planner.js.map +1 -1
  128. package/dist/playbooks/generic/brainstorming.d.ts +9 -0
  129. package/dist/playbooks/generic/brainstorming.d.ts.map +1 -0
  130. package/dist/playbooks/generic/brainstorming.js +105 -0
  131. package/dist/playbooks/generic/brainstorming.js.map +1 -0
  132. package/dist/playbooks/generic/code-review.d.ts +11 -0
  133. package/dist/playbooks/generic/code-review.d.ts.map +1 -0
  134. package/dist/playbooks/generic/code-review.js +176 -0
  135. package/dist/playbooks/generic/code-review.js.map +1 -0
  136. package/dist/playbooks/generic/subagent-execution.d.ts +9 -0
  137. package/dist/playbooks/generic/subagent-execution.d.ts.map +1 -0
  138. package/dist/playbooks/generic/subagent-execution.js +68 -0
  139. package/dist/playbooks/generic/subagent-execution.js.map +1 -0
  140. package/dist/playbooks/generic/systematic-debugging.d.ts +9 -0
  141. package/dist/playbooks/generic/systematic-debugging.d.ts.map +1 -0
  142. package/dist/playbooks/generic/systematic-debugging.js +87 -0
  143. package/dist/playbooks/generic/systematic-debugging.js.map +1 -0
  144. package/dist/playbooks/generic/tdd.d.ts +9 -0
  145. package/dist/playbooks/generic/tdd.d.ts.map +1 -0
  146. package/dist/playbooks/generic/tdd.js +70 -0
  147. package/dist/playbooks/generic/tdd.js.map +1 -0
  148. package/dist/playbooks/generic/verification.d.ts +9 -0
  149. package/dist/playbooks/generic/verification.d.ts.map +1 -0
  150. package/dist/playbooks/generic/verification.js +74 -0
  151. package/dist/playbooks/generic/verification.js.map +1 -0
  152. package/dist/playbooks/index.d.ts +4 -0
  153. package/dist/playbooks/index.d.ts.map +1 -0
  154. package/dist/playbooks/index.js +5 -0
  155. package/dist/playbooks/index.js.map +1 -0
  156. package/dist/playbooks/playbook-registry.d.ts +42 -0
  157. package/dist/playbooks/playbook-registry.d.ts.map +1 -0
  158. package/dist/playbooks/playbook-registry.js +227 -0
  159. package/dist/playbooks/playbook-registry.js.map +1 -0
  160. package/dist/playbooks/playbook-seeder.d.ts +47 -0
  161. package/dist/playbooks/playbook-seeder.d.ts.map +1 -0
  162. package/dist/playbooks/playbook-seeder.js +104 -0
  163. package/dist/playbooks/playbook-seeder.js.map +1 -0
  164. package/dist/playbooks/playbook-types.d.ts +132 -0
  165. package/dist/playbooks/playbook-types.d.ts.map +1 -0
  166. package/dist/playbooks/playbook-types.js +12 -0
  167. package/dist/playbooks/playbook-types.js.map +1 -0
  168. package/dist/project/project-registry.d.ts +79 -0
  169. package/dist/project/project-registry.d.ts.map +1 -0
  170. package/dist/project/project-registry.js +274 -0
  171. package/dist/project/project-registry.js.map +1 -0
  172. package/dist/project/types.d.ts +28 -0
  173. package/dist/project/types.d.ts.map +1 -0
  174. package/dist/project/types.js +5 -0
  175. package/dist/project/types.js.map +1 -0
  176. package/dist/prompts/index.d.ts +4 -0
  177. package/dist/prompts/index.d.ts.map +1 -0
  178. package/dist/prompts/index.js +3 -0
  179. package/dist/prompts/index.js.map +1 -0
  180. package/dist/prompts/parser.d.ts +17 -0
  181. package/dist/prompts/parser.d.ts.map +1 -0
  182. package/dist/prompts/parser.js +47 -0
  183. package/dist/prompts/parser.js.map +1 -0
  184. package/dist/prompts/template-manager.d.ts +25 -0
  185. package/dist/prompts/template-manager.d.ts.map +1 -0
  186. package/dist/prompts/template-manager.js +71 -0
  187. package/dist/prompts/template-manager.js.map +1 -0
  188. package/dist/prompts/types.d.ts +26 -0
  189. package/dist/prompts/types.d.ts.map +1 -0
  190. package/dist/prompts/types.js +5 -0
  191. package/dist/prompts/types.js.map +1 -0
  192. package/dist/runtime/admin-extra-ops.d.ts +15 -0
  193. package/dist/runtime/admin-extra-ops.d.ts.map +1 -0
  194. package/dist/runtime/admin-extra-ops.js +595 -0
  195. package/dist/runtime/admin-extra-ops.js.map +1 -0
  196. package/dist/runtime/admin-ops.d.ts +15 -0
  197. package/dist/runtime/admin-ops.d.ts.map +1 -0
  198. package/dist/runtime/admin-ops.js +329 -0
  199. package/dist/runtime/admin-ops.js.map +1 -0
  200. package/dist/runtime/capture-ops.d.ts +15 -0
  201. package/dist/runtime/capture-ops.d.ts.map +1 -0
  202. package/dist/runtime/capture-ops.js +363 -0
  203. package/dist/runtime/capture-ops.js.map +1 -0
  204. package/dist/runtime/cognee-sync-ops.d.ts +12 -0
  205. package/dist/runtime/cognee-sync-ops.d.ts.map +1 -0
  206. package/dist/runtime/cognee-sync-ops.js +55 -0
  207. package/dist/runtime/cognee-sync-ops.js.map +1 -0
  208. package/dist/runtime/core-ops.d.ts +9 -3
  209. package/dist/runtime/core-ops.d.ts.map +1 -1
  210. package/dist/runtime/core-ops.js +693 -10
  211. package/dist/runtime/core-ops.js.map +1 -1
  212. package/dist/runtime/curator-extra-ops.d.ts +9 -0
  213. package/dist/runtime/curator-extra-ops.d.ts.map +1 -0
  214. package/dist/runtime/curator-extra-ops.js +71 -0
  215. package/dist/runtime/curator-extra-ops.js.map +1 -0
  216. package/dist/runtime/domain-ops.d.ts.map +1 -1
  217. package/dist/runtime/domain-ops.js +61 -15
  218. package/dist/runtime/domain-ops.js.map +1 -1
  219. package/dist/runtime/grading-ops.d.ts +14 -0
  220. package/dist/runtime/grading-ops.d.ts.map +1 -0
  221. package/dist/runtime/grading-ops.js +105 -0
  222. package/dist/runtime/grading-ops.js.map +1 -0
  223. package/dist/runtime/intake-ops.d.ts +14 -0
  224. package/dist/runtime/intake-ops.d.ts.map +1 -0
  225. package/dist/runtime/intake-ops.js +110 -0
  226. package/dist/runtime/intake-ops.js.map +1 -0
  227. package/dist/runtime/loop-ops.d.ts +14 -0
  228. package/dist/runtime/loop-ops.d.ts.map +1 -0
  229. package/dist/runtime/loop-ops.js +251 -0
  230. package/dist/runtime/loop-ops.js.map +1 -0
  231. package/dist/runtime/memory-cross-project-ops.d.ts +12 -0
  232. package/dist/runtime/memory-cross-project-ops.d.ts.map +1 -0
  233. package/dist/runtime/memory-cross-project-ops.js +165 -0
  234. package/dist/runtime/memory-cross-project-ops.js.map +1 -0
  235. package/dist/runtime/memory-extra-ops.d.ts +13 -0
  236. package/dist/runtime/memory-extra-ops.d.ts.map +1 -0
  237. package/dist/runtime/memory-extra-ops.js +173 -0
  238. package/dist/runtime/memory-extra-ops.js.map +1 -0
  239. package/dist/runtime/orchestrate-ops.d.ts +17 -0
  240. package/dist/runtime/orchestrate-ops.d.ts.map +1 -0
  241. package/dist/runtime/orchestrate-ops.js +246 -0
  242. package/dist/runtime/orchestrate-ops.js.map +1 -0
  243. package/dist/runtime/planning-extra-ops.d.ts +25 -0
  244. package/dist/runtime/planning-extra-ops.d.ts.map +1 -0
  245. package/dist/runtime/planning-extra-ops.js +663 -0
  246. package/dist/runtime/planning-extra-ops.js.map +1 -0
  247. package/dist/runtime/playbook-ops.d.ts +14 -0
  248. package/dist/runtime/playbook-ops.d.ts.map +1 -0
  249. package/dist/runtime/playbook-ops.js +141 -0
  250. package/dist/runtime/playbook-ops.js.map +1 -0
  251. package/dist/runtime/project-ops.d.ts +15 -0
  252. package/dist/runtime/project-ops.d.ts.map +1 -0
  253. package/dist/runtime/project-ops.js +186 -0
  254. package/dist/runtime/project-ops.js.map +1 -0
  255. package/dist/runtime/runtime.d.ts.map +1 -1
  256. package/dist/runtime/runtime.js +65 -3
  257. package/dist/runtime/runtime.js.map +1 -1
  258. package/dist/runtime/types.d.ts +29 -0
  259. package/dist/runtime/types.d.ts.map +1 -1
  260. package/dist/runtime/vault-extra-ops.d.ts +10 -0
  261. package/dist/runtime/vault-extra-ops.d.ts.map +1 -0
  262. package/dist/runtime/vault-extra-ops.js +536 -0
  263. package/dist/runtime/vault-extra-ops.js.map +1 -0
  264. package/dist/telemetry/telemetry.d.ts +48 -0
  265. package/dist/telemetry/telemetry.d.ts.map +1 -0
  266. package/dist/telemetry/telemetry.js +87 -0
  267. package/dist/telemetry/telemetry.js.map +1 -0
  268. package/dist/vault/playbook.d.ts +34 -0
  269. package/dist/vault/playbook.d.ts.map +1 -0
  270. package/dist/vault/playbook.js +60 -0
  271. package/dist/vault/playbook.js.map +1 -0
  272. package/dist/vault/vault.d.ts +97 -4
  273. package/dist/vault/vault.d.ts.map +1 -1
  274. package/dist/vault/vault.js +424 -65
  275. package/dist/vault/vault.js.map +1 -1
  276. package/package.json +7 -3
  277. package/src/__tests__/admin-extra-ops.test.ts +467 -0
  278. package/src/__tests__/admin-ops.test.ts +271 -0
  279. package/src/__tests__/brain-intelligence.test.ts +205 -0
  280. package/src/__tests__/brain.test.ts +134 -3
  281. package/src/__tests__/capture-ops.test.ts +509 -0
  282. package/src/__tests__/cognee-integration.test.ts +80 -0
  283. package/src/__tests__/cognee-sync-manager.test.ts +103 -0
  284. package/src/__tests__/core-ops.test.ts +292 -2
  285. package/src/__tests__/curator-extra-ops.test.ts +381 -0
  286. package/src/__tests__/domain-ops.test.ts +66 -0
  287. package/src/__tests__/errors.test.ts +388 -0
  288. package/src/__tests__/governance.test.ts +522 -0
  289. package/src/__tests__/grading-ops.test.ts +361 -0
  290. package/src/__tests__/identity-manager.test.ts +243 -0
  291. package/src/__tests__/intake-pipeline.test.ts +162 -0
  292. package/src/__tests__/intent-router.test.ts +222 -0
  293. package/src/__tests__/logger.test.ts +200 -0
  294. package/src/__tests__/loop-ops.test.ts +469 -0
  295. package/src/__tests__/memory-cross-project-ops.test.ts +248 -0
  296. package/src/__tests__/memory-extra-ops.test.ts +352 -0
  297. package/src/__tests__/orchestrate-ops.test.ts +289 -0
  298. package/src/__tests__/persistence.test.ts +225 -0
  299. package/src/__tests__/planner.test.ts +416 -7
  300. package/src/__tests__/planning-extra-ops.test.ts +706 -0
  301. package/src/__tests__/playbook-registry.test.ts +326 -0
  302. package/src/__tests__/playbook-seeder.test.ts +163 -0
  303. package/src/__tests__/playbook.test.ts +389 -0
  304. package/src/__tests__/project-ops.test.ts +381 -0
  305. package/src/__tests__/template-manager.test.ts +222 -0
  306. package/src/__tests__/vault-extra-ops.test.ts +482 -0
  307. package/src/brain/brain.ts +185 -16
  308. package/src/brain/intelligence.ts +179 -10
  309. package/src/brain/types.ts +40 -2
  310. package/src/cognee/client.ts +18 -0
  311. package/src/cognee/sync-manager.ts +389 -0
  312. package/src/control/identity-manager.ts +354 -0
  313. package/src/control/intent-router.ts +326 -0
  314. package/src/control/types.ts +102 -0
  315. package/src/curator/curator.ts +295 -1
  316. package/src/errors/classify.ts +102 -0
  317. package/src/errors/index.ts +5 -0
  318. package/src/errors/retry.ts +132 -0
  319. package/src/errors/types.ts +81 -0
  320. package/src/governance/governance.ts +698 -0
  321. package/src/governance/index.ts +18 -0
  322. package/src/governance/types.ts +111 -0
  323. package/src/index.ts +213 -2
  324. package/src/intake/content-classifier.ts +146 -0
  325. package/src/intake/dedup-gate.ts +92 -0
  326. package/src/intake/intake-pipeline.ts +503 -0
  327. package/src/intake/types.ts +69 -0
  328. package/src/intelligence/loader.ts +1 -1
  329. package/src/intelligence/types.ts +3 -1
  330. package/src/logging/logger.ts +154 -0
  331. package/src/logging/types.ts +21 -0
  332. package/src/loop/loop-manager.ts +448 -0
  333. package/src/loop/types.ts +115 -0
  334. package/src/persistence/index.ts +7 -0
  335. package/src/persistence/sqlite-provider.ts +62 -0
  336. package/src/persistence/types.ts +44 -0
  337. package/src/planning/gap-analysis.ts +775 -0
  338. package/src/planning/gap-types.ts +61 -0
  339. package/src/planning/planner.ts +1273 -24
  340. package/src/playbooks/generic/brainstorming.ts +110 -0
  341. package/src/playbooks/generic/code-review.ts +181 -0
  342. package/src/playbooks/generic/subagent-execution.ts +74 -0
  343. package/src/playbooks/generic/systematic-debugging.ts +92 -0
  344. package/src/playbooks/generic/tdd.ts +75 -0
  345. package/src/playbooks/generic/verification.ts +79 -0
  346. package/src/playbooks/index.ts +27 -0
  347. package/src/playbooks/playbook-registry.ts +284 -0
  348. package/src/playbooks/playbook-seeder.ts +119 -0
  349. package/src/playbooks/playbook-types.ts +162 -0
  350. package/src/project/project-registry.ts +370 -0
  351. package/src/project/types.ts +31 -0
  352. package/src/prompts/index.ts +3 -0
  353. package/src/prompts/parser.ts +59 -0
  354. package/src/prompts/template-manager.ts +77 -0
  355. package/src/prompts/types.ts +28 -0
  356. package/src/runtime/admin-extra-ops.ts +652 -0
  357. package/src/runtime/admin-ops.ts +340 -0
  358. package/src/runtime/capture-ops.ts +404 -0
  359. package/src/runtime/cognee-sync-ops.ts +63 -0
  360. package/src/runtime/core-ops.ts +787 -9
  361. package/src/runtime/curator-extra-ops.ts +85 -0
  362. package/src/runtime/domain-ops.ts +67 -15
  363. package/src/runtime/grading-ops.ts +130 -0
  364. package/src/runtime/intake-ops.ts +126 -0
  365. package/src/runtime/loop-ops.ts +277 -0
  366. package/src/runtime/memory-cross-project-ops.ts +191 -0
  367. package/src/runtime/memory-extra-ops.ts +186 -0
  368. package/src/runtime/orchestrate-ops.ts +278 -0
  369. package/src/runtime/planning-extra-ops.ts +718 -0
  370. package/src/runtime/playbook-ops.ts +169 -0
  371. package/src/runtime/project-ops.ts +202 -0
  372. package/src/runtime/runtime.ts +77 -3
  373. package/src/runtime/types.ts +29 -0
  374. package/src/runtime/vault-extra-ops.ts +606 -0
  375. package/src/telemetry/telemetry.ts +118 -0
  376. package/src/vault/playbook.ts +87 -0
  377. package/src/vault/vault.ts +575 -98
@@ -1,10 +1,112 @@
1
1
  import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
2
+ import { createHash } from 'node:crypto';
2
3
  import { dirname } from 'node:path';
4
+ import { SEVERITY_WEIGHTS, CATEGORY_PENALTY_CAPS } from './gap-types.js';
5
+ import { runGapAnalysis } from './gap-analysis.js';
6
+ /**
7
+ * Valid status transitions.
8
+ * Each key maps to the set of statuses it can transition to.
9
+ * Ported from Salvador's LIFECYCLE_TRANSITIONS.
10
+ */
11
+ export const LIFECYCLE_TRANSITIONS = {
12
+ brainstorming: ['draft'],
13
+ draft: ['approved'],
14
+ approved: ['executing'],
15
+ executing: ['validating', 'reconciling'],
16
+ validating: ['reconciling', 'executing'],
17
+ reconciling: ['completed'],
18
+ completed: ['archived'],
19
+ archived: [],
20
+ };
21
+ /**
22
+ * Statuses where the 30-minute TTL should NOT apply.
23
+ * Plans in these states may span multiple sessions.
24
+ */
25
+ export const NON_EXPIRING_STATUSES = [
26
+ 'brainstorming',
27
+ 'executing',
28
+ 'validating',
29
+ 'reconciling',
30
+ ];
31
+ /**
32
+ * Validate a lifecycle status transition.
33
+ * Returns true if the transition is valid, false otherwise.
34
+ */
35
+ export function isValidTransition(from, to) {
36
+ return LIFECYCLE_TRANSITIONS[from].includes(to);
37
+ }
38
+ /**
39
+ * Get the valid next statuses for a given status.
40
+ */
41
+ export function getValidNextStatuses(status) {
42
+ return LIFECYCLE_TRANSITIONS[status];
43
+ }
44
+ /**
45
+ * Check if a status should have TTL expiration.
46
+ * Plans in executing/reconciling states persist indefinitely.
47
+ */
48
+ export function shouldExpire(status) {
49
+ return !NON_EXPIRING_STATUSES.includes(status);
50
+ }
51
+ /**
52
+ * Severity weights for drift accuracy score calculation.
53
+ * Score = 100 - sum(drift_items * weight_per_impact)
54
+ * Ported from Salvador's plan-lifecycle-types.ts.
55
+ */
56
+ export const DRIFT_WEIGHTS = {
57
+ high: 20,
58
+ medium: 10,
59
+ low: 5,
60
+ };
61
+ /**
62
+ * Calculate drift accuracy score from drift items.
63
+ * Score = max(0, 100 - sum(weight_per_impact))
64
+ * Ported from Salvador's calculateDriftScore.
65
+ */
66
+ export function calculateDriftScore(items) {
67
+ let deductions = 0;
68
+ for (const item of items) {
69
+ deductions += DRIFT_WEIGHTS[item.impact];
70
+ }
71
+ return Math.max(0, 100 - deductions);
72
+ }
73
+ /**
74
+ * Calculate score from gaps with severity-weighted deductions and iteration leniency.
75
+ * Ported from Salvador MCP's plan-grading.ts.
76
+ *
77
+ * - Minor gaps: weight=0 on iteration 1 (free sketching), weight=1 on iteration 2, full weight on 3+
78
+ * - Per-category deductions are capped before summing (prevents one category from tanking the score)
79
+ * - Score = max(0, 100 - totalDeductions)
80
+ */
81
+ export function calculateScore(gaps, iteration = 1) {
82
+ const categoryTotals = new Map();
83
+ for (const gap of gaps) {
84
+ let weight = SEVERITY_WEIGHTS[gap.severity];
85
+ // Iteration leniency for minor gaps
86
+ if (gap.severity === 'minor') {
87
+ if (iteration === 1)
88
+ weight = 0;
89
+ else if (iteration === 2)
90
+ weight = 1;
91
+ // iteration 3+: full weight (2)
92
+ }
93
+ const category = gap.category;
94
+ categoryTotals.set(category, (categoryTotals.get(category) ?? 0) + weight);
95
+ }
96
+ let deductions = 0;
97
+ for (const [category, total] of categoryTotals) {
98
+ const cap = CATEGORY_PENALTY_CAPS[category];
99
+ deductions += cap !== undefined ? Math.min(total, cap) : total;
100
+ }
101
+ return Math.max(0, 100 - deductions);
102
+ }
3
103
  export class Planner {
4
104
  filePath;
5
105
  store;
6
- constructor(filePath) {
106
+ gapOptions;
107
+ constructor(filePath, gapOptions) {
7
108
  this.filePath = filePath;
109
+ this.gapOptions = gapOptions;
8
110
  this.store = this.load();
9
111
  }
10
112
  load() {
@@ -13,7 +115,12 @@ export class Planner {
13
115
  }
14
116
  try {
15
117
  const data = readFileSync(this.filePath, 'utf-8');
16
- return JSON.parse(data);
118
+ const store = JSON.parse(data);
119
+ // Backward compatibility: ensure every plan has a checks array
120
+ for (const plan of store.plans) {
121
+ plan.checks = plan.checks ?? [];
122
+ }
123
+ return store;
17
124
  }
18
125
  catch {
19
126
  return { version: '1.0', plans: [] };
@@ -29,7 +136,7 @@ export class Planner {
29
136
  id: `plan-${now}-${Math.random().toString(36).slice(2, 8)}`,
30
137
  objective: params.objective,
31
138
  scope: params.scope,
32
- status: 'draft',
139
+ status: params.initialStatus ?? 'draft',
33
140
  decisions: params.decisions ?? [],
34
141
  tasks: (params.tasks ?? []).map((t, i) => ({
35
142
  id: `task-${i + 1}`,
@@ -38,6 +145,13 @@ export class Planner {
38
145
  status: 'pending',
39
146
  updatedAt: now,
40
147
  })),
148
+ ...(params.approach !== undefined && { approach: params.approach }),
149
+ ...(params.context !== undefined && { context: params.context }),
150
+ ...(params.success_criteria !== undefined && { success_criteria: params.success_criteria }),
151
+ ...(params.tool_chain !== undefined && { tool_chain: params.tool_chain }),
152
+ ...(params.flow !== undefined && { flow: params.flow }),
153
+ ...(params.target_mode !== undefined && { target_mode: params.target_mode }),
154
+ checks: [],
41
155
  createdAt: now,
42
156
  updatedAt: now,
43
157
  };
@@ -51,14 +165,36 @@ export class Planner {
51
165
  list() {
52
166
  return [...this.store.plans];
53
167
  }
168
+ /**
169
+ * Transition a plan to a new status using the typed FSM.
170
+ * Validates that the transition is allowed before applying it.
171
+ */
172
+ transition(plan, to) {
173
+ if (!isValidTransition(plan.status, to)) {
174
+ const valid = getValidNextStatuses(plan.status);
175
+ throw new Error(`Invalid transition: '${plan.status}' → '${to}'. ` +
176
+ `Valid transitions from '${plan.status}': ${valid.length > 0 ? valid.join(', ') : 'none'}`);
177
+ }
178
+ plan.status = to;
179
+ plan.updatedAt = Date.now();
180
+ }
181
+ /**
182
+ * Promote a brainstorming plan to draft status.
183
+ * Only allowed from 'brainstorming'.
184
+ */
185
+ promoteToDraft(planId) {
186
+ const plan = this.get(planId);
187
+ if (!plan)
188
+ throw new Error(`Plan not found: ${planId}`);
189
+ this.transition(plan, 'draft');
190
+ this.save();
191
+ return plan;
192
+ }
54
193
  approve(planId) {
55
194
  const plan = this.get(planId);
56
195
  if (!plan)
57
196
  throw new Error(`Plan not found: ${planId}`);
58
- if (plan.status !== 'draft')
59
- throw new Error(`Cannot approve plan in '${plan.status}' status — must be 'draft'`);
60
- plan.status = 'approved';
61
- plan.updatedAt = Date.now();
197
+ this.transition(plan, 'approved');
62
198
  this.save();
63
199
  return plan;
64
200
  }
@@ -66,10 +202,7 @@ export class Planner {
66
202
  const plan = this.get(planId);
67
203
  if (!plan)
68
204
  throw new Error(`Plan not found: ${planId}`);
69
- if (plan.status !== 'approved')
70
- throw new Error(`Cannot execute plan in '${plan.status}' status — must be 'approved'`);
71
- plan.status = 'executing';
72
- plan.updatedAt = Date.now();
205
+ this.transition(plan, 'executing');
73
206
  this.save();
74
207
  return plan;
75
208
  }
@@ -77,33 +210,828 @@ export class Planner {
77
210
  const plan = this.get(planId);
78
211
  if (!plan)
79
212
  throw new Error(`Plan not found: ${planId}`);
80
- if (plan.status !== 'executing')
81
- throw new Error(`Cannot update tasks on plan in '${plan.status}' status — must be 'executing'`);
213
+ if (plan.status !== 'executing' && plan.status !== 'validating')
214
+ throw new Error(`Cannot update tasks on plan in '${plan.status}' status — must be 'executing' or 'validating'`);
82
215
  const task = plan.tasks.find((t) => t.id === taskId);
83
216
  if (!task)
84
217
  throw new Error(`Task not found: ${taskId}`);
218
+ const now = Date.now();
219
+ // Auto-set startedAt on first in_progress transition
220
+ if (status === 'in_progress' && !task.startedAt) {
221
+ task.startedAt = now;
222
+ }
223
+ // Auto-set completedAt and compute durationMs on terminal transitions
224
+ if (status === 'completed' || status === 'skipped' || status === 'failed') {
225
+ task.completedAt = now;
226
+ if (task.startedAt) {
227
+ if (!task.metrics)
228
+ task.metrics = {};
229
+ task.metrics.durationMs = now - task.startedAt;
230
+ }
231
+ }
85
232
  task.status = status;
86
- task.updatedAt = Date.now();
87
- plan.updatedAt = Date.now();
233
+ task.updatedAt = now;
234
+ plan.updatedAt = now;
235
+ this.save();
236
+ return plan;
237
+ }
238
+ /**
239
+ * Transition plan to 'validating' state (post-execution verification).
240
+ * Only allowed from 'executing'.
241
+ */
242
+ startValidation(planId) {
243
+ const plan = this.get(planId);
244
+ if (!plan)
245
+ throw new Error(`Plan not found: ${planId}`);
246
+ this.transition(plan, 'validating');
88
247
  this.save();
89
248
  return plan;
90
249
  }
250
+ /**
251
+ * Transition plan to 'reconciling' state.
252
+ * Allowed from 'executing' or 'validating'.
253
+ */
254
+ startReconciliation(planId) {
255
+ const plan = this.get(planId);
256
+ if (!plan)
257
+ throw new Error(`Plan not found: ${planId}`);
258
+ this.transition(plan, 'reconciling');
259
+ this.save();
260
+ return plan;
261
+ }
262
+ /**
263
+ * Complete a plan. Only allowed from 'reconciling'.
264
+ * Use startReconciliation() + reconcile() + complete() for the full lifecycle,
265
+ * or reconcile() which auto-transitions through reconciling → completed.
266
+ */
91
267
  complete(planId) {
92
268
  const plan = this.get(planId);
93
269
  if (!plan)
94
270
  throw new Error(`Plan not found: ${planId}`);
95
- if (plan.status !== 'executing')
96
- throw new Error(`Cannot complete plan in '${plan.status}' status — must be 'executing'`);
97
- plan.status = 'completed';
98
- plan.updatedAt = Date.now();
271
+ plan.executionSummary = this.computeExecutionSummary(plan);
272
+ this.transition(plan, 'completed');
99
273
  this.save();
100
274
  return plan;
101
275
  }
102
276
  getExecuting() {
103
- return this.store.plans.filter((p) => p.status === 'executing');
277
+ return this.store.plans.filter((p) => p.status === 'executing' || p.status === 'validating');
104
278
  }
105
279
  getActive() {
106
- return this.store.plans.filter((p) => p.status === 'draft' || p.status === 'approved' || p.status === 'executing');
280
+ return this.store.plans.filter((p) => p.status === 'brainstorming' ||
281
+ p.status === 'draft' ||
282
+ p.status === 'approved' ||
283
+ p.status === 'executing' ||
284
+ p.status === 'validating' ||
285
+ p.status === 'reconciling');
286
+ }
287
+ /**
288
+ * Iterate on a draft plan — modify objective, scope, decisions, or tasks.
289
+ * Only allowed on plans in 'draft' status.
290
+ */
291
+ iterate(planId, changes) {
292
+ const plan = this.get(planId);
293
+ if (!plan)
294
+ throw new Error(`Plan not found: ${planId}`);
295
+ if (plan.status !== 'draft' && plan.status !== 'brainstorming')
296
+ throw new Error(`Cannot iterate plan in '${plan.status}' status — must be 'draft' or 'brainstorming'`);
297
+ const now = Date.now();
298
+ if (changes.objective !== undefined)
299
+ plan.objective = changes.objective;
300
+ if (changes.scope !== undefined)
301
+ plan.scope = changes.scope;
302
+ if (changes.decisions !== undefined)
303
+ plan.decisions = changes.decisions;
304
+ if (changes.approach !== undefined)
305
+ plan.approach = changes.approach;
306
+ if (changes.context !== undefined)
307
+ plan.context = changes.context;
308
+ if (changes.success_criteria !== undefined)
309
+ plan.success_criteria = changes.success_criteria;
310
+ if (changes.tool_chain !== undefined)
311
+ plan.tool_chain = changes.tool_chain;
312
+ if (changes.flow !== undefined)
313
+ plan.flow = changes.flow;
314
+ if (changes.target_mode !== undefined)
315
+ plan.target_mode = changes.target_mode;
316
+ // Remove tasks by ID
317
+ if (changes.removeTasks && changes.removeTasks.length > 0) {
318
+ const removeSet = new Set(changes.removeTasks);
319
+ plan.tasks = plan.tasks.filter((t) => !removeSet.has(t.id));
320
+ }
321
+ // Add new tasks
322
+ if (changes.addTasks && changes.addTasks.length > 0) {
323
+ const maxIndex = plan.tasks.reduce((max, t) => {
324
+ const num = parseInt(t.id.replace('task-', ''), 10);
325
+ return isNaN(num) ? max : Math.max(max, num);
326
+ }, 0);
327
+ for (let i = 0; i < changes.addTasks.length; i++) {
328
+ plan.tasks.push({
329
+ id: `task-${maxIndex + i + 1}`,
330
+ title: changes.addTasks[i].title,
331
+ description: changes.addTasks[i].description,
332
+ status: 'pending',
333
+ updatedAt: now,
334
+ });
335
+ }
336
+ }
337
+ plan.updatedAt = now;
338
+ this.save();
339
+ return plan;
340
+ }
341
+ /**
342
+ * Split a plan's tasks into sub-tasks with dependency tracking.
343
+ * Replaces existing tasks with a new set that includes dependency references.
344
+ * Only allowed on 'draft' or 'approved' plans.
345
+ */
346
+ splitTasks(planId, tasks) {
347
+ const plan = this.get(planId);
348
+ if (!plan)
349
+ throw new Error(`Plan not found: ${planId}`);
350
+ if (plan.status !== 'brainstorming' && plan.status !== 'draft' && plan.status !== 'approved')
351
+ throw new Error(`Cannot split tasks on plan in '${plan.status}' status — must be 'brainstorming', 'draft', or 'approved'`);
352
+ const now = Date.now();
353
+ plan.tasks = tasks.map((t, i) => ({
354
+ id: `task-${i + 1}`,
355
+ title: t.title,
356
+ description: t.description,
357
+ status: 'pending',
358
+ dependsOn: t.dependsOn,
359
+ ...(t.acceptanceCriteria && { acceptanceCriteria: t.acceptanceCriteria }),
360
+ updatedAt: now,
361
+ }));
362
+ // Validate dependency references
363
+ const taskIds = new Set(plan.tasks.map((t) => t.id));
364
+ for (const task of plan.tasks) {
365
+ if (task.dependsOn) {
366
+ for (const dep of task.dependsOn) {
367
+ if (!taskIds.has(dep)) {
368
+ throw new Error(`Task '${task.id}' depends on unknown task '${dep}'`);
369
+ }
370
+ }
371
+ }
372
+ }
373
+ plan.updatedAt = now;
374
+ this.save();
375
+ return plan;
376
+ }
377
+ /**
378
+ * Reconcile a plan — compare what was planned vs what actually happened.
379
+ * Uses impact-weighted drift scoring (ported from Salvador's calculateDriftScore).
380
+ *
381
+ * Transitions: executing → reconciling → completed (automatic).
382
+ * Also allowed from 'validating' and 'reconciling' states.
383
+ */
384
+ reconcile(planId, report) {
385
+ const plan = this.get(planId);
386
+ if (!plan)
387
+ throw new Error(`Plan not found: ${planId}`);
388
+ if (plan.status !== 'executing' &&
389
+ plan.status !== 'validating' &&
390
+ plan.status !== 'reconciling')
391
+ throw new Error(`Cannot reconcile plan in '${plan.status}' status — must be 'executing', 'validating', or 'reconciling'`);
392
+ const driftItems = report.driftItems ?? [];
393
+ // Impact-weighted drift scoring (ported from Salvador)
394
+ const accuracy = calculateDriftScore(driftItems);
395
+ plan.reconciliation = {
396
+ planId,
397
+ accuracy,
398
+ driftItems,
399
+ summary: report.actualOutcome,
400
+ reconciledAt: Date.now(),
401
+ };
402
+ // Compute execution summary from per-task metrics
403
+ plan.executionSummary = this.computeExecutionSummary(plan);
404
+ // Transition through reconciling → completed via FSM
405
+ if (plan.status === 'executing' || plan.status === 'validating') {
406
+ plan.status = 'reconciling';
407
+ }
408
+ // Auto-complete after reconciliation
409
+ plan.status = 'completed';
410
+ plan.updatedAt = Date.now();
411
+ this.save();
412
+ return plan;
413
+ }
414
+ /**
415
+ * Add review evidence to a plan or specific task.
416
+ */
417
+ addReview(planId, review) {
418
+ const plan = this.get(planId);
419
+ if (!plan)
420
+ throw new Error(`Plan not found: ${planId}`);
421
+ if (review.taskId) {
422
+ const task = plan.tasks.find((t) => t.id === review.taskId);
423
+ if (!task)
424
+ throw new Error(`Task not found: ${review.taskId}`);
425
+ }
426
+ if (!plan.reviews)
427
+ plan.reviews = [];
428
+ plan.reviews.push({
429
+ planId,
430
+ taskId: review.taskId,
431
+ reviewer: review.reviewer,
432
+ outcome: review.outcome,
433
+ comments: review.comments,
434
+ reviewedAt: Date.now(),
435
+ });
436
+ plan.updatedAt = Date.now();
437
+ this.save();
438
+ return plan;
439
+ }
440
+ /**
441
+ * Get dispatch instructions for a specific task — returns the task and its
442
+ * unmet dependencies so a subagent knows what to work on and what to wait for.
443
+ */
444
+ getDispatch(planId, taskId) {
445
+ const plan = this.get(planId);
446
+ if (!plan)
447
+ throw new Error(`Plan not found: ${planId}`);
448
+ const task = plan.tasks.find((t) => t.id === taskId);
449
+ if (!task)
450
+ throw new Error(`Task not found: ${taskId}`);
451
+ const unmetDependencies = [];
452
+ if (task.dependsOn) {
453
+ for (const depId of task.dependsOn) {
454
+ const dep = plan.tasks.find((t) => t.id === depId);
455
+ if (dep && dep.status !== 'completed') {
456
+ unmetDependencies.push(dep);
457
+ }
458
+ }
459
+ }
460
+ const result = {
461
+ task,
462
+ unmetDependencies,
463
+ ready: unmetDependencies.length === 0,
464
+ };
465
+ // Include deliverable status if deliverables exist
466
+ if (task.deliverables && task.deliverables.length > 0) {
467
+ result.deliverableStatus = {
468
+ count: task.deliverables.length,
469
+ staleCount: task.deliverables.filter((d) => d.stale).length,
470
+ };
471
+ }
472
+ return result;
473
+ }
474
+ // ─── Execution Metrics & Deliverables ──────────────────────────
475
+ /**
476
+ * Compute aggregate execution summary from per-task metrics.
477
+ * Called from reconcile() and complete() to populate plan.executionSummary.
478
+ */
479
+ computeExecutionSummary(plan) {
480
+ let totalDurationMs = 0;
481
+ let tasksCompleted = 0;
482
+ let tasksSkipped = 0;
483
+ let tasksFailed = 0;
484
+ let tasksWithDuration = 0;
485
+ for (const task of plan.tasks) {
486
+ if (task.status === 'completed')
487
+ tasksCompleted++;
488
+ else if (task.status === 'skipped')
489
+ tasksSkipped++;
490
+ else if (task.status === 'failed')
491
+ tasksFailed++;
492
+ if (task.metrics?.durationMs) {
493
+ totalDurationMs += task.metrics.durationMs;
494
+ tasksWithDuration++;
495
+ }
496
+ }
497
+ return {
498
+ totalDurationMs,
499
+ tasksCompleted,
500
+ tasksSkipped,
501
+ tasksFailed,
502
+ avgTaskDurationMs: tasksWithDuration > 0 ? Math.round(totalDurationMs / tasksWithDuration) : 0,
503
+ };
504
+ }
505
+ /**
506
+ * Submit a deliverable for a task. Auto-computes SHA-256 hash for file deliverables.
507
+ */
508
+ submitDeliverable(planId, taskId, deliverable) {
509
+ const plan = this.get(planId);
510
+ if (!plan)
511
+ throw new Error(`Plan not found: ${planId}`);
512
+ const task = plan.tasks.find((t) => t.id === taskId);
513
+ if (!task)
514
+ throw new Error(`Task not found: ${taskId}`);
515
+ const entry = {
516
+ type: deliverable.type,
517
+ path: deliverable.path,
518
+ };
519
+ // Auto-compute hash for file deliverables
520
+ if (deliverable.type === 'file' && !deliverable.hash) {
521
+ try {
522
+ if (existsSync(deliverable.path)) {
523
+ const content = readFileSync(deliverable.path);
524
+ entry.hash = createHash('sha256').update(content).digest('hex');
525
+ }
526
+ }
527
+ catch {
528
+ // Graceful degradation — skip hash if file can't be read
529
+ }
530
+ }
531
+ else if (deliverable.hash) {
532
+ entry.hash = deliverable.hash;
533
+ }
534
+ if (!task.deliverables)
535
+ task.deliverables = [];
536
+ task.deliverables.push(entry);
537
+ task.updatedAt = Date.now();
538
+ plan.updatedAt = Date.now();
539
+ this.save();
540
+ return task;
541
+ }
542
+ /**
543
+ * Verify all deliverables for a task.
544
+ * - file: checks existsSync + SHA-256 hash match
545
+ * - vault_entry: checks vault.get(path) non-null (requires vault instance)
546
+ * - url: skips (just records, no fetch)
547
+ */
548
+ verifyDeliverables(planId, taskId, vault) {
549
+ const plan = this.get(planId);
550
+ if (!plan)
551
+ throw new Error(`Plan not found: ${planId}`);
552
+ const task = plan.tasks.find((t) => t.id === taskId);
553
+ if (!task)
554
+ throw new Error(`Task not found: ${taskId}`);
555
+ const deliverables = task.deliverables ?? [];
556
+ let staleCount = 0;
557
+ const now = Date.now();
558
+ for (const d of deliverables) {
559
+ d.stale = false;
560
+ if (d.type === 'file') {
561
+ if (!existsSync(d.path)) {
562
+ d.stale = true;
563
+ staleCount++;
564
+ }
565
+ else if (d.hash) {
566
+ try {
567
+ const content = readFileSync(d.path);
568
+ const currentHash = createHash('sha256').update(content).digest('hex');
569
+ if (currentHash !== d.hash) {
570
+ d.stale = true;
571
+ staleCount++;
572
+ }
573
+ }
574
+ catch {
575
+ d.stale = true;
576
+ staleCount++;
577
+ }
578
+ }
579
+ d.verifiedAt = now;
580
+ }
581
+ else if (d.type === 'vault_entry') {
582
+ if (vault) {
583
+ const entry = vault.get(d.path);
584
+ if (!entry) {
585
+ d.stale = true;
586
+ staleCount++;
587
+ }
588
+ }
589
+ d.verifiedAt = now;
590
+ }
591
+ // url: skip — just record
592
+ }
593
+ plan.updatedAt = Date.now();
594
+ this.save();
595
+ return { verified: staleCount === 0, deliverables, staleCount };
596
+ }
597
+ // ─── Evidence & Verification ────────────────────────────────────
598
+ /**
599
+ * Submit evidence for a task acceptance criterion.
600
+ * Evidence is stored on the task and used by verifyTask() to check completeness.
601
+ */
602
+ submitEvidence(planId, taskId, evidence) {
603
+ const plan = this.get(planId);
604
+ if (!plan)
605
+ throw new Error(`Plan not found: ${planId}`);
606
+ const task = plan.tasks.find((t) => t.id === taskId);
607
+ if (!task)
608
+ throw new Error(`Task not found: ${taskId}`);
609
+ if (!task.evidence)
610
+ task.evidence = [];
611
+ task.evidence.push({
612
+ criterion: evidence.criterion,
613
+ content: evidence.content,
614
+ type: evidence.type,
615
+ submittedAt: Date.now(),
616
+ });
617
+ task.updatedAt = Date.now();
618
+ plan.updatedAt = Date.now();
619
+ this.save();
620
+ return task;
621
+ }
622
+ /**
623
+ * Verify a task — check that evidence exists for all acceptance criteria
624
+ * and any reviews have passed.
625
+ * Returns verification status with details.
626
+ */
627
+ verifyTask(planId, taskId) {
628
+ const plan = this.get(planId);
629
+ if (!plan)
630
+ throw new Error(`Plan not found: ${planId}`);
631
+ const task = plan.tasks.find((t) => t.id === taskId);
632
+ if (!task)
633
+ throw new Error(`Task not found: ${taskId}`);
634
+ // Check evidence coverage
635
+ const criteria = task.acceptanceCriteria ?? [];
636
+ const evidencedCriteria = new Set((task.evidence ?? []).map((e) => e.criterion));
637
+ const missingCriteria = criteria.filter((c) => !evidencedCriteria.has(c));
638
+ // Check task-level reviews
639
+ const taskReviews = (plan.reviews ?? []).filter((r) => r.taskId === taskId);
640
+ let reviewStatus = 'no_reviews';
641
+ if (taskReviews.length > 0) {
642
+ const latest = taskReviews[taskReviews.length - 1];
643
+ reviewStatus = latest.outcome;
644
+ }
645
+ const verified = task.status === 'completed' &&
646
+ missingCriteria.length === 0 &&
647
+ (reviewStatus === 'approved' || reviewStatus === 'no_reviews');
648
+ if (verified !== task.verified) {
649
+ task.verified = verified;
650
+ task.updatedAt = Date.now();
651
+ plan.updatedAt = Date.now();
652
+ this.save();
653
+ }
654
+ return { verified, task, missingCriteria, reviewStatus };
655
+ }
656
+ /**
657
+ * Verify an entire plan — check all tasks are in a final state,
658
+ * all verification-required tasks have evidence, no tasks stuck in_progress.
659
+ * Returns a validation report.
660
+ */
661
+ verifyPlan(planId) {
662
+ const plan = this.get(planId);
663
+ if (!plan)
664
+ throw new Error(`Plan not found: ${planId}`);
665
+ const issues = [];
666
+ let verified = 0;
667
+ let completed = 0;
668
+ let skipped = 0;
669
+ let failed = 0;
670
+ let pending = 0;
671
+ let inProgress = 0;
672
+ for (const task of plan.tasks) {
673
+ switch (task.status) {
674
+ case 'completed':
675
+ completed++;
676
+ break;
677
+ case 'skipped':
678
+ skipped++;
679
+ break;
680
+ case 'failed':
681
+ failed++;
682
+ break;
683
+ case 'pending':
684
+ pending++;
685
+ break;
686
+ case 'in_progress':
687
+ inProgress++;
688
+ break;
689
+ }
690
+ if (task.verified)
691
+ verified++;
692
+ // Check for stuck tasks
693
+ if (task.status === 'in_progress') {
694
+ issues.push({ taskId: task.id, issue: 'Task stuck in in_progress state' });
695
+ }
696
+ if (task.status === 'pending') {
697
+ issues.push({ taskId: task.id, issue: 'Task still pending — not started' });
698
+ }
699
+ // Check evidence for completed tasks with acceptance criteria
700
+ if (task.status === 'completed' &&
701
+ task.acceptanceCriteria &&
702
+ task.acceptanceCriteria.length > 0) {
703
+ const evidencedCriteria = new Set((task.evidence ?? []).map((e) => e.criterion));
704
+ const missing = task.acceptanceCriteria.filter((c) => !evidencedCriteria.has(c));
705
+ if (missing.length > 0) {
706
+ issues.push({
707
+ taskId: task.id,
708
+ issue: `Missing evidence for ${missing.length} criteria: ${missing.join(', ')}`,
709
+ });
710
+ }
711
+ }
712
+ }
713
+ const valid = issues.length === 0 && pending === 0 && inProgress === 0;
714
+ return {
715
+ valid,
716
+ planId,
717
+ issues,
718
+ summary: {
719
+ total: plan.tasks.length,
720
+ completed,
721
+ skipped,
722
+ failed,
723
+ pending,
724
+ inProgress,
725
+ verified,
726
+ },
727
+ };
728
+ }
729
+ /**
730
+ * Auto-reconcile a plan — fast path for plans with minimal drift.
731
+ * Checks all tasks are in final state, generates reconciliation report automatically.
732
+ * Returns null if drift is too significant for auto-reconciliation (>2 non-completed tasks).
733
+ */
734
+ autoReconcile(planId) {
735
+ const plan = this.get(planId);
736
+ if (!plan)
737
+ throw new Error(`Plan not found: ${planId}`);
738
+ if (plan.status !== 'executing' && plan.status !== 'validating')
739
+ throw new Error(`Cannot auto-reconcile plan in '${plan.status}' status — must be 'executing' or 'validating'`);
740
+ const completed = plan.tasks.filter((t) => t.status === 'completed').length;
741
+ const skipped = plan.tasks.filter((t) => t.status === 'skipped').length;
742
+ const failed = plan.tasks.filter((t) => t.status === 'failed').length;
743
+ const pending = plan.tasks.filter((t) => t.status === 'pending').length;
744
+ const inProgress = plan.tasks.filter((t) => t.status === 'in_progress').length;
745
+ // Can't auto-reconcile if tasks are still in progress
746
+ if (inProgress > 0)
747
+ return null;
748
+ // Can't auto-reconcile if too many non-completed tasks
749
+ if (pending + failed > 2)
750
+ return null;
751
+ const driftItems = [];
752
+ for (const task of plan.tasks) {
753
+ if (task.status === 'skipped') {
754
+ driftItems.push({
755
+ type: 'skipped',
756
+ description: `Task '${task.title}' was skipped`,
757
+ impact: 'medium',
758
+ rationale: 'Task not executed during plan implementation',
759
+ });
760
+ }
761
+ else if (task.status === 'failed') {
762
+ driftItems.push({
763
+ type: 'modified',
764
+ description: `Task '${task.title}' failed`,
765
+ impact: 'high',
766
+ rationale: 'Task execution failed',
767
+ });
768
+ }
769
+ else if (task.status === 'pending') {
770
+ driftItems.push({
771
+ type: 'skipped',
772
+ description: `Task '${task.title}' was never started`,
773
+ impact: 'low',
774
+ rationale: 'Task left in pending state',
775
+ });
776
+ }
777
+ }
778
+ return this.reconcile(planId, {
779
+ actualOutcome: `Auto-reconciled: ${completed}/${plan.tasks.length} tasks completed, ${skipped} skipped, ${failed} failed`,
780
+ driftItems,
781
+ reconciledBy: 'auto',
782
+ });
783
+ }
784
+ /**
785
+ * Generate a review prompt for spec compliance checking.
786
+ * Used by subagent dispatch — the controller generates the prompt, a subagent executes it.
787
+ */
788
+ generateReviewSpec(planId, taskId) {
789
+ const plan = this.get(planId);
790
+ if (!plan)
791
+ throw new Error(`Plan not found: ${planId}`);
792
+ const task = plan.tasks.find((t) => t.id === taskId);
793
+ if (!task)
794
+ throw new Error(`Task not found: ${taskId}`);
795
+ const criteria = task.acceptanceCriteria?.length
796
+ ? `\n\nAcceptance Criteria:\n${task.acceptanceCriteria.map((c, i) => `${i + 1}. ${c}`).join('\n')}`
797
+ : '';
798
+ const prompt = [
799
+ `# Spec Compliance Review`,
800
+ ``,
801
+ `## Task: ${task.title}`,
802
+ `**Description:** ${task.description}`,
803
+ `**Plan Objective:** ${plan.objective}${criteria}`,
804
+ ``,
805
+ `## Review Checklist`,
806
+ `1. Does the implementation match the task description?`,
807
+ `2. Are all acceptance criteria satisfied?`,
808
+ `3. Does it align with the plan's overall objective?`,
809
+ `4. Are there any spec deviations?`,
810
+ ``,
811
+ `Provide: outcome (approved/rejected/needs_changes) and detailed comments.`,
812
+ ].join('\n');
813
+ return { prompt, task, plan };
814
+ }
815
+ /**
816
+ * Generate a review prompt for code quality checking.
817
+ */
818
+ generateReviewQuality(planId, taskId) {
819
+ const plan = this.get(planId);
820
+ if (!plan)
821
+ throw new Error(`Plan not found: ${planId}`);
822
+ const task = plan.tasks.find((t) => t.id === taskId);
823
+ if (!task)
824
+ throw new Error(`Task not found: ${taskId}`);
825
+ const prompt = [
826
+ `# Code Quality Review`,
827
+ ``,
828
+ `## Task: ${task.title}`,
829
+ `**Description:** ${task.description}`,
830
+ ``,
831
+ `## Quality Checklist`,
832
+ `1. **Correctness** — Does it work as intended?`,
833
+ `2. **Security** — No injection, XSS, or OWASP top 10 vulnerabilities?`,
834
+ `3. **Performance** — No unnecessary allocations, N+1 queries, or blocking calls?`,
835
+ `4. **Maintainability** — Clear naming, appropriate abstractions, documented intent?`,
836
+ `5. **Testing** — Adequate test coverage for the changes?`,
837
+ `6. **Error Handling** — Graceful degradation, no swallowed errors?`,
838
+ `7. **Conventions** — Follows project coding standards?`,
839
+ ``,
840
+ `Provide: outcome (approved/rejected/needs_changes) and detailed comments.`,
841
+ ].join('\n');
842
+ return { prompt, task, plan };
843
+ }
844
+ /**
845
+ * Archive completed plans — transitions them to 'archived' status.
846
+ * If olderThanDays is provided, only archives plans older than that.
847
+ * Returns the archived plans.
848
+ */
849
+ archive(olderThanDays) {
850
+ const cutoff = olderThanDays !== undefined
851
+ ? Date.now() - olderThanDays * 24 * 60 * 60 * 1000
852
+ : Date.now() + 1; // +1ms so archive() with no args archives all completed plans
853
+ const toArchive = this.store.plans.filter((p) => p.status === 'completed' && p.updatedAt < cutoff);
854
+ for (const plan of toArchive) {
855
+ plan.status = 'archived';
856
+ plan.updatedAt = Date.now();
857
+ }
858
+ if (toArchive.length > 0) {
859
+ this.save();
860
+ }
861
+ return toArchive;
862
+ }
863
+ /**
864
+ * Get statistics about all plans.
865
+ */
866
+ stats() {
867
+ const plans = this.store.plans;
868
+ const byStatus = {
869
+ brainstorming: 0,
870
+ draft: 0,
871
+ approved: 0,
872
+ executing: 0,
873
+ validating: 0,
874
+ reconciling: 0,
875
+ completed: 0,
876
+ archived: 0,
877
+ };
878
+ const tasksByStatus = {
879
+ pending: 0,
880
+ in_progress: 0,
881
+ completed: 0,
882
+ skipped: 0,
883
+ failed: 0,
884
+ };
885
+ let totalTasks = 0;
886
+ for (const p of plans) {
887
+ byStatus[p.status]++;
888
+ totalTasks += p.tasks.length;
889
+ for (const t of p.tasks) {
890
+ tasksByStatus[t.status]++;
891
+ }
892
+ }
893
+ return {
894
+ total: plans.length,
895
+ byStatus,
896
+ avgTasksPerPlan: plans.length > 0 ? Math.round((totalTasks / plans.length) * 100) / 100 : 0,
897
+ totalTasks,
898
+ tasksByStatus,
899
+ };
900
+ }
901
+ // ─── Grading ──────────────────────────────────────────────────────
902
+ /**
903
+ * Grade a plan using gap analysis with severity-weighted scoring.
904
+ * Ported from Salvador MCP's multi-pass grading engine.
905
+ *
906
+ * 6 built-in passes + optional custom passes (domain-specific checks).
907
+ *
908
+ * Scoring:
909
+ * - Each gap has a severity (critical=30, major=15, minor=2, info=0)
910
+ * - Deductions are per-category with optional caps
911
+ * - Iteration leniency: minor gaps free on iter 1, half on iter 2, full on 3+
912
+ * - Score = max(0, 100 - deductions)
913
+ *
914
+ * Grade thresholds: A+=95, A=90, B=80, C=70, D=60, F=<60
915
+ */
916
+ grade(planId) {
917
+ const plan = this.get(planId);
918
+ if (!plan)
919
+ throw new Error(`Plan not found: ${planId}`);
920
+ // Run 6-pass gap analysis
921
+ const gaps = runGapAnalysis(plan, this.gapOptions);
922
+ // Add circular dependency check (structural, not covered by gap-analysis passes)
923
+ if (this.hasCircularDependencies(plan)) {
924
+ gaps.push({
925
+ id: `gap_${Date.now()}_circ`,
926
+ severity: 'critical',
927
+ category: 'structure',
928
+ description: 'Circular dependencies detected among tasks.',
929
+ recommendation: 'Remove circular dependency chains so tasks can be executed in order.',
930
+ location: 'tasks',
931
+ _trigger: 'circular_dependencies',
932
+ });
933
+ }
934
+ // Iteration = number of previous checks + 1
935
+ const iteration = plan.checks.length + 1;
936
+ const score = calculateScore(gaps, iteration);
937
+ const grade = this.scoreToGrade(score);
938
+ const check = {
939
+ checkId: `chk-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
940
+ planId,
941
+ grade,
942
+ score,
943
+ gaps,
944
+ iteration,
945
+ checkedAt: Date.now(),
946
+ };
947
+ plan.checks.push(check);
948
+ plan.latestCheck = check;
949
+ plan.updatedAt = Date.now();
950
+ this.save();
951
+ return check;
952
+ }
953
+ /**
954
+ * Get the latest check for a plan.
955
+ */
956
+ getLatestCheck(planId) {
957
+ const plan = this.get(planId);
958
+ if (!plan)
959
+ throw new Error(`Plan not found: ${planId}`);
960
+ return plan.latestCheck ?? null;
961
+ }
962
+ /**
963
+ * Get all checks for a plan (history).
964
+ */
965
+ getCheckHistory(planId) {
966
+ const plan = this.get(planId);
967
+ if (!plan)
968
+ throw new Error(`Plan not found: ${planId}`);
969
+ return [...plan.checks];
970
+ }
971
+ /**
972
+ * Auto-grade: grade the plan and return whether it meets a target grade.
973
+ */
974
+ meetsGrade(planId, targetGrade) {
975
+ const check = this.grade(planId);
976
+ const targetScore = this.gradeToMinScore(targetGrade);
977
+ return { meets: check.score >= targetScore, check };
978
+ }
979
+ // ─── Grading Helpers ──────────────────────────────────────────────
980
+ scoreToGrade(score) {
981
+ if (score >= 95)
982
+ return 'A+';
983
+ if (score >= 90)
984
+ return 'A';
985
+ if (score >= 80)
986
+ return 'B';
987
+ if (score >= 70)
988
+ return 'C';
989
+ if (score >= 60)
990
+ return 'D';
991
+ return 'F';
992
+ }
993
+ gradeToMinScore(grade) {
994
+ switch (grade) {
995
+ case 'A+':
996
+ return 95;
997
+ case 'A':
998
+ return 90;
999
+ case 'B':
1000
+ return 80;
1001
+ case 'C':
1002
+ return 70;
1003
+ case 'D':
1004
+ return 60;
1005
+ case 'F':
1006
+ return 0;
1007
+ }
1008
+ }
1009
+ hasCircularDependencies(plan) {
1010
+ const visited = new Set();
1011
+ const inStack = new Set();
1012
+ const taskMap = new Map(plan.tasks.map((t) => [t.id, t]));
1013
+ const dfs = (taskId) => {
1014
+ if (inStack.has(taskId))
1015
+ return true;
1016
+ if (visited.has(taskId))
1017
+ return false;
1018
+ visited.add(taskId);
1019
+ inStack.add(taskId);
1020
+ const task = taskMap.get(taskId);
1021
+ if (task?.dependsOn) {
1022
+ for (const dep of task.dependsOn) {
1023
+ if (dfs(dep))
1024
+ return true;
1025
+ }
1026
+ }
1027
+ inStack.delete(taskId);
1028
+ return false;
1029
+ };
1030
+ for (const task of plan.tasks) {
1031
+ if (dfs(task.id))
1032
+ return true;
1033
+ }
1034
+ return false;
107
1035
  }
108
1036
  }
109
1037
  //# sourceMappingURL=planner.js.map