@cluesmith/codev 2.0.0-rc.5 → 2.0.0-rc.50

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 (330) hide show
  1. package/bin/af.js +2 -2
  2. package/bin/consult.js +1 -1
  3. package/bin/porch.js +6 -35
  4. package/dashboard/dist/assets/index-BIHeqvy0.css +32 -0
  5. package/dashboard/dist/assets/index-VvUWRPNP.js +120 -0
  6. package/dashboard/dist/assets/index-VvUWRPNP.js.map +1 -0
  7. package/dashboard/dist/index.html +14 -0
  8. package/dist/agent-farm/cli.d.ts.map +1 -1
  9. package/dist/agent-farm/cli.js +93 -64
  10. package/dist/agent-farm/cli.js.map +1 -1
  11. package/dist/agent-farm/commands/architect.d.ts.map +1 -1
  12. package/dist/agent-farm/commands/architect.js +13 -6
  13. package/dist/agent-farm/commands/architect.js.map +1 -1
  14. package/dist/agent-farm/commands/attach.d.ts +13 -0
  15. package/dist/agent-farm/commands/attach.d.ts.map +1 -0
  16. package/dist/agent-farm/commands/attach.js +179 -0
  17. package/dist/agent-farm/commands/attach.js.map +1 -0
  18. package/dist/agent-farm/commands/cleanup.d.ts.map +1 -1
  19. package/dist/agent-farm/commands/cleanup.js +30 -3
  20. package/dist/agent-farm/commands/cleanup.js.map +1 -1
  21. package/dist/agent-farm/commands/consult.js +1 -1
  22. package/dist/agent-farm/commands/consult.js.map +1 -1
  23. package/dist/agent-farm/commands/index.d.ts +2 -2
  24. package/dist/agent-farm/commands/index.d.ts.map +1 -1
  25. package/dist/agent-farm/commands/index.js +2 -2
  26. package/dist/agent-farm/commands/index.js.map +1 -1
  27. package/dist/agent-farm/commands/{util.d.ts → shell.d.ts} +5 -5
  28. package/dist/agent-farm/commands/shell.d.ts.map +1 -0
  29. package/dist/agent-farm/commands/{util.js → shell.js} +23 -36
  30. package/dist/agent-farm/commands/shell.js.map +1 -0
  31. package/dist/agent-farm/commands/spawn.d.ts.map +1 -1
  32. package/dist/agent-farm/commands/spawn.js +455 -217
  33. package/dist/agent-farm/commands/spawn.js.map +1 -1
  34. package/dist/agent-farm/commands/start.d.ts +3 -0
  35. package/dist/agent-farm/commands/start.d.ts.map +1 -1
  36. package/dist/agent-farm/commands/start.js +92 -79
  37. package/dist/agent-farm/commands/start.js.map +1 -1
  38. package/dist/agent-farm/commands/status.d.ts +2 -0
  39. package/dist/agent-farm/commands/status.d.ts.map +1 -1
  40. package/dist/agent-farm/commands/status.js +56 -1
  41. package/dist/agent-farm/commands/status.js.map +1 -1
  42. package/dist/agent-farm/commands/stop.d.ts +6 -0
  43. package/dist/agent-farm/commands/stop.d.ts.map +1 -1
  44. package/dist/agent-farm/commands/stop.js +115 -11
  45. package/dist/agent-farm/commands/stop.js.map +1 -1
  46. package/dist/agent-farm/commands/tower.d.ts +9 -0
  47. package/dist/agent-farm/commands/tower.d.ts.map +1 -1
  48. package/dist/agent-farm/commands/tower.js +59 -19
  49. package/dist/agent-farm/commands/tower.js.map +1 -1
  50. package/dist/agent-farm/db/index.d.ts.map +1 -1
  51. package/dist/agent-farm/db/index.js +59 -0
  52. package/dist/agent-farm/db/index.js.map +1 -1
  53. package/dist/agent-farm/db/schema.d.ts +2 -2
  54. package/dist/agent-farm/db/schema.d.ts.map +1 -1
  55. package/dist/agent-farm/db/schema.js +8 -3
  56. package/dist/agent-farm/db/schema.js.map +1 -1
  57. package/dist/agent-farm/db/types.d.ts +3 -0
  58. package/dist/agent-farm/db/types.d.ts.map +1 -1
  59. package/dist/agent-farm/db/types.js +3 -0
  60. package/dist/agent-farm/db/types.js.map +1 -1
  61. package/dist/agent-farm/hq-connector.d.ts +2 -2
  62. package/dist/agent-farm/hq-connector.js +2 -2
  63. package/dist/agent-farm/lib/tower-client.d.ts +157 -0
  64. package/dist/agent-farm/lib/tower-client.d.ts.map +1 -0
  65. package/dist/agent-farm/lib/tower-client.js +223 -0
  66. package/dist/agent-farm/lib/tower-client.js.map +1 -0
  67. package/dist/agent-farm/servers/tower-server.js +1152 -95
  68. package/dist/agent-farm/servers/tower-server.js.map +1 -1
  69. package/dist/agent-farm/state.d.ts +4 -10
  70. package/dist/agent-farm/state.d.ts.map +1 -1
  71. package/dist/agent-farm/state.js +30 -31
  72. package/dist/agent-farm/state.js.map +1 -1
  73. package/dist/agent-farm/types.d.ts +48 -0
  74. package/dist/agent-farm/types.d.ts.map +1 -1
  75. package/dist/agent-farm/utils/config.d.ts.map +1 -1
  76. package/dist/agent-farm/utils/config.js +12 -11
  77. package/dist/agent-farm/utils/config.js.map +1 -1
  78. package/dist/agent-farm/utils/deps.d.ts.map +1 -1
  79. package/dist/agent-farm/utils/deps.js +0 -16
  80. package/dist/agent-farm/utils/deps.js.map +1 -1
  81. package/dist/agent-farm/utils/notifications.d.ts +30 -0
  82. package/dist/agent-farm/utils/notifications.d.ts.map +1 -0
  83. package/dist/agent-farm/utils/notifications.js +121 -0
  84. package/dist/agent-farm/utils/notifications.js.map +1 -0
  85. package/dist/agent-farm/utils/server-utils.d.ts +2 -1
  86. package/dist/agent-farm/utils/server-utils.d.ts.map +1 -1
  87. package/dist/agent-farm/utils/server-utils.js +11 -1
  88. package/dist/agent-farm/utils/server-utils.js.map +1 -1
  89. package/dist/agent-farm/utils/shell.d.ts +9 -22
  90. package/dist/agent-farm/utils/shell.d.ts.map +1 -1
  91. package/dist/agent-farm/utils/shell.js +34 -34
  92. package/dist/agent-farm/utils/shell.js.map +1 -1
  93. package/dist/agent-farm/utils/terminal-ports.d.ts +1 -1
  94. package/dist/agent-farm/utils/terminal-ports.js +1 -1
  95. package/dist/cli.d.ts.map +1 -1
  96. package/dist/cli.js +5 -54
  97. package/dist/cli.js.map +1 -1
  98. package/dist/commands/adopt.d.ts.map +1 -1
  99. package/dist/commands/adopt.js +39 -4
  100. package/dist/commands/adopt.js.map +1 -1
  101. package/dist/commands/consult/index.d.ts.map +1 -1
  102. package/dist/commands/consult/index.js +63 -3
  103. package/dist/commands/consult/index.js.map +1 -1
  104. package/dist/commands/doctor.d.ts.map +1 -1
  105. package/dist/commands/doctor.js +0 -15
  106. package/dist/commands/doctor.js.map +1 -1
  107. package/dist/commands/init.d.ts.map +1 -1
  108. package/dist/commands/init.js +31 -2
  109. package/dist/commands/init.js.map +1 -1
  110. package/dist/commands/porch/build-counter.d.ts +5 -0
  111. package/dist/commands/porch/build-counter.d.ts.map +1 -0
  112. package/dist/commands/porch/build-counter.js +5 -0
  113. package/dist/commands/porch/build-counter.js.map +1 -0
  114. package/dist/commands/porch/checks.d.ts +16 -29
  115. package/dist/commands/porch/checks.d.ts.map +1 -1
  116. package/dist/commands/porch/checks.js +90 -144
  117. package/dist/commands/porch/checks.js.map +1 -1
  118. package/dist/commands/porch/claude.d.ts +27 -0
  119. package/dist/commands/porch/claude.d.ts.map +1 -0
  120. package/dist/commands/porch/claude.js +107 -0
  121. package/dist/commands/porch/claude.js.map +1 -0
  122. package/dist/commands/porch/index.d.ts +21 -43
  123. package/dist/commands/porch/index.d.ts.map +1 -1
  124. package/dist/commands/porch/index.js +456 -1015
  125. package/dist/commands/porch/index.js.map +1 -1
  126. package/dist/commands/porch/plan.d.ts +70 -0
  127. package/dist/commands/porch/plan.d.ts.map +1 -0
  128. package/dist/commands/porch/plan.js +190 -0
  129. package/dist/commands/porch/plan.js.map +1 -0
  130. package/dist/commands/porch/prompts.d.ts +19 -0
  131. package/dist/commands/porch/prompts.d.ts.map +1 -0
  132. package/dist/commands/porch/prompts.js +250 -0
  133. package/dist/commands/porch/prompts.js.map +1 -0
  134. package/dist/commands/porch/protocol.d.ts +59 -0
  135. package/dist/commands/porch/protocol.d.ts.map +1 -0
  136. package/dist/commands/porch/protocol.js +260 -0
  137. package/dist/commands/porch/protocol.js.map +1 -0
  138. package/dist/commands/porch/run.d.ts +40 -0
  139. package/dist/commands/porch/run.d.ts.map +1 -0
  140. package/dist/commands/porch/run.js +893 -0
  141. package/dist/commands/porch/run.js.map +1 -0
  142. package/dist/commands/porch/state.d.ts +23 -112
  143. package/dist/commands/porch/state.d.ts.map +1 -1
  144. package/dist/commands/porch/state.js +81 -699
  145. package/dist/commands/porch/state.js.map +1 -1
  146. package/dist/commands/porch/types.d.ts +72 -173
  147. package/dist/commands/porch/types.d.ts.map +1 -1
  148. package/dist/commands/porch/types.js +2 -1
  149. package/dist/commands/porch/types.js.map +1 -1
  150. package/dist/commands/update.d.ts.map +1 -1
  151. package/dist/commands/update.js +22 -0
  152. package/dist/commands/update.js.map +1 -1
  153. package/dist/lib/scaffold.d.ts +24 -0
  154. package/dist/lib/scaffold.d.ts.map +1 -1
  155. package/dist/lib/scaffold.js +78 -0
  156. package/dist/lib/scaffold.js.map +1 -1
  157. package/dist/terminal/index.d.ts +8 -0
  158. package/dist/terminal/index.d.ts.map +1 -0
  159. package/dist/terminal/index.js +5 -0
  160. package/dist/terminal/index.js.map +1 -0
  161. package/dist/terminal/pty-manager.d.ts +60 -0
  162. package/dist/terminal/pty-manager.d.ts.map +1 -0
  163. package/dist/terminal/pty-manager.js +334 -0
  164. package/dist/terminal/pty-manager.js.map +1 -0
  165. package/dist/terminal/pty-session.d.ts +79 -0
  166. package/dist/terminal/pty-session.d.ts.map +1 -0
  167. package/dist/terminal/pty-session.js +215 -0
  168. package/dist/terminal/pty-session.js.map +1 -0
  169. package/dist/terminal/ring-buffer.d.ts +27 -0
  170. package/dist/terminal/ring-buffer.d.ts.map +1 -0
  171. package/dist/terminal/ring-buffer.js +74 -0
  172. package/dist/terminal/ring-buffer.js.map +1 -0
  173. package/dist/terminal/ws-protocol.d.ts +27 -0
  174. package/dist/terminal/ws-protocol.d.ts.map +1 -0
  175. package/dist/terminal/ws-protocol.js +44 -0
  176. package/dist/terminal/ws-protocol.js.map +1 -0
  177. package/package.json +18 -3
  178. package/skeleton/DEPENDENCIES.md +3 -29
  179. package/skeleton/builders.md +1 -1
  180. package/skeleton/protocol-schema.json +282 -0
  181. package/skeleton/protocols/bugfix/builder-prompt.md +49 -0
  182. package/skeleton/protocols/bugfix/protocol.json +14 -2
  183. package/skeleton/protocols/experiment/builder-prompt.md +47 -0
  184. package/skeleton/protocols/experiment/protocol.json +101 -0
  185. package/skeleton/protocols/maintain/builder-prompt.md +41 -0
  186. package/skeleton/protocols/maintain/prompts/audit.md +111 -0
  187. package/skeleton/protocols/maintain/prompts/clean.md +91 -0
  188. package/skeleton/protocols/maintain/prompts/sync.md +113 -0
  189. package/skeleton/protocols/maintain/prompts/verify.md +110 -0
  190. package/skeleton/protocols/maintain/protocol.json +141 -0
  191. package/skeleton/protocols/maintain/protocol.md +13 -7
  192. package/skeleton/protocols/protocol-schema.json +53 -0
  193. package/skeleton/protocols/spider/builder-prompt.md +53 -0
  194. package/skeleton/protocols/spider/prompts/implement.md +109 -50
  195. package/skeleton/protocols/spider/prompts/specify.md +29 -4
  196. package/skeleton/protocols/spider/protocol.json +96 -154
  197. package/skeleton/protocols/spider/protocol.md +26 -16
  198. package/skeleton/protocols/spider/templates/plan.md +14 -0
  199. package/skeleton/protocols/tick/builder-prompt.md +51 -0
  200. package/skeleton/protocols/tick/protocol.json +7 -2
  201. package/skeleton/resources/commands/agent-farm.md +25 -43
  202. package/skeleton/resources/commands/overview.md +6 -16
  203. package/skeleton/resources/workflow-reference.md +2 -2
  204. package/skeleton/roles/architect.md +152 -315
  205. package/skeleton/roles/builder.md +109 -218
  206. package/skeleton/templates/AGENTS.md +1 -1
  207. package/skeleton/templates/CLAUDE.md +1 -1
  208. package/skeleton/templates/cheatsheet.md +4 -2
  209. package/templates/dashboard/index.html +17 -43
  210. package/templates/dashboard/js/dialogs.js +7 -7
  211. package/templates/dashboard/js/files.js +2 -2
  212. package/templates/dashboard/js/main.js +3 -3
  213. package/templates/dashboard/js/projects.js +3 -3
  214. package/templates/dashboard/js/tabs.js +1 -1
  215. package/templates/dashboard/js/utils.js +22 -87
  216. package/templates/tower.html +542 -27
  217. package/dist/agent-farm/commands/kickoff.d.ts +0 -19
  218. package/dist/agent-farm/commands/kickoff.d.ts.map +0 -1
  219. package/dist/agent-farm/commands/kickoff.js +0 -331
  220. package/dist/agent-farm/commands/kickoff.js.map +0 -1
  221. package/dist/agent-farm/commands/rename.d.ts +0 -13
  222. package/dist/agent-farm/commands/rename.d.ts.map +0 -1
  223. package/dist/agent-farm/commands/rename.js +0 -33
  224. package/dist/agent-farm/commands/rename.js.map +0 -1
  225. package/dist/agent-farm/commands/tutorial.d.ts +0 -10
  226. package/dist/agent-farm/commands/tutorial.d.ts.map +0 -1
  227. package/dist/agent-farm/commands/tutorial.js +0 -49
  228. package/dist/agent-farm/commands/tutorial.js.map +0 -1
  229. package/dist/agent-farm/commands/util.d.ts.map +0 -1
  230. package/dist/agent-farm/commands/util.js.map +0 -1
  231. package/dist/agent-farm/servers/dashboard-server.d.ts +0 -7
  232. package/dist/agent-farm/servers/dashboard-server.d.ts.map +0 -1
  233. package/dist/agent-farm/servers/dashboard-server.js +0 -1872
  234. package/dist/agent-farm/servers/dashboard-server.js.map +0 -1
  235. package/dist/agent-farm/tutorial/index.d.ts +0 -8
  236. package/dist/agent-farm/tutorial/index.d.ts.map +0 -1
  237. package/dist/agent-farm/tutorial/index.js +0 -8
  238. package/dist/agent-farm/tutorial/index.js.map +0 -1
  239. package/dist/agent-farm/tutorial/prompts.d.ts +0 -57
  240. package/dist/agent-farm/tutorial/prompts.d.ts.map +0 -1
  241. package/dist/agent-farm/tutorial/prompts.js +0 -147
  242. package/dist/agent-farm/tutorial/prompts.js.map +0 -1
  243. package/dist/agent-farm/tutorial/runner.d.ts +0 -52
  244. package/dist/agent-farm/tutorial/runner.d.ts.map +0 -1
  245. package/dist/agent-farm/tutorial/runner.js +0 -204
  246. package/dist/agent-farm/tutorial/runner.js.map +0 -1
  247. package/dist/agent-farm/tutorial/state.d.ts +0 -26
  248. package/dist/agent-farm/tutorial/state.d.ts.map +0 -1
  249. package/dist/agent-farm/tutorial/state.js +0 -89
  250. package/dist/agent-farm/tutorial/state.js.map +0 -1
  251. package/dist/agent-farm/tutorial/steps/first-spec.d.ts +0 -7
  252. package/dist/agent-farm/tutorial/steps/first-spec.d.ts.map +0 -1
  253. package/dist/agent-farm/tutorial/steps/first-spec.js +0 -136
  254. package/dist/agent-farm/tutorial/steps/first-spec.js.map +0 -1
  255. package/dist/agent-farm/tutorial/steps/implementation.d.ts +0 -7
  256. package/dist/agent-farm/tutorial/steps/implementation.d.ts.map +0 -1
  257. package/dist/agent-farm/tutorial/steps/implementation.js +0 -76
  258. package/dist/agent-farm/tutorial/steps/implementation.js.map +0 -1
  259. package/dist/agent-farm/tutorial/steps/index.d.ts +0 -10
  260. package/dist/agent-farm/tutorial/steps/index.d.ts.map +0 -1
  261. package/dist/agent-farm/tutorial/steps/index.js +0 -10
  262. package/dist/agent-farm/tutorial/steps/index.js.map +0 -1
  263. package/dist/agent-farm/tutorial/steps/planning.d.ts +0 -7
  264. package/dist/agent-farm/tutorial/steps/planning.d.ts.map +0 -1
  265. package/dist/agent-farm/tutorial/steps/planning.js +0 -143
  266. package/dist/agent-farm/tutorial/steps/planning.js.map +0 -1
  267. package/dist/agent-farm/tutorial/steps/review.d.ts +0 -7
  268. package/dist/agent-farm/tutorial/steps/review.d.ts.map +0 -1
  269. package/dist/agent-farm/tutorial/steps/review.js +0 -78
  270. package/dist/agent-farm/tutorial/steps/review.js.map +0 -1
  271. package/dist/agent-farm/tutorial/steps/setup.d.ts +0 -7
  272. package/dist/agent-farm/tutorial/steps/setup.d.ts.map +0 -1
  273. package/dist/agent-farm/tutorial/steps/setup.js +0 -126
  274. package/dist/agent-farm/tutorial/steps/setup.js.map +0 -1
  275. package/dist/agent-farm/tutorial/steps/welcome.d.ts +0 -7
  276. package/dist/agent-farm/tutorial/steps/welcome.d.ts.map +0 -1
  277. package/dist/agent-farm/tutorial/steps/welcome.js +0 -50
  278. package/dist/agent-farm/tutorial/steps/welcome.js.map +0 -1
  279. package/dist/commands/pcheck/cache.d.ts +0 -48
  280. package/dist/commands/pcheck/cache.d.ts.map +0 -1
  281. package/dist/commands/pcheck/cache.js +0 -170
  282. package/dist/commands/pcheck/cache.js.map +0 -1
  283. package/dist/commands/pcheck/evaluator.d.ts +0 -15
  284. package/dist/commands/pcheck/evaluator.d.ts.map +0 -1
  285. package/dist/commands/pcheck/evaluator.js +0 -246
  286. package/dist/commands/pcheck/evaluator.js.map +0 -1
  287. package/dist/commands/pcheck/index.d.ts +0 -12
  288. package/dist/commands/pcheck/index.d.ts.map +0 -1
  289. package/dist/commands/pcheck/index.js +0 -249
  290. package/dist/commands/pcheck/index.js.map +0 -1
  291. package/dist/commands/pcheck/parser.d.ts +0 -39
  292. package/dist/commands/pcheck/parser.d.ts.map +0 -1
  293. package/dist/commands/pcheck/parser.js +0 -155
  294. package/dist/commands/pcheck/parser.js.map +0 -1
  295. package/dist/commands/pcheck/types.d.ts +0 -82
  296. package/dist/commands/pcheck/types.d.ts.map +0 -1
  297. package/dist/commands/pcheck/types.js +0 -5
  298. package/dist/commands/pcheck/types.js.map +0 -1
  299. package/dist/commands/porch/consultation.d.ts +0 -56
  300. package/dist/commands/porch/consultation.d.ts.map +0 -1
  301. package/dist/commands/porch/consultation.js +0 -330
  302. package/dist/commands/porch/consultation.js.map +0 -1
  303. package/dist/commands/porch/notifications.d.ts +0 -99
  304. package/dist/commands/porch/notifications.d.ts.map +0 -1
  305. package/dist/commands/porch/notifications.js +0 -223
  306. package/dist/commands/porch/notifications.js.map +0 -1
  307. package/dist/commands/porch/plan-parser.d.ts +0 -38
  308. package/dist/commands/porch/plan-parser.d.ts.map +0 -1
  309. package/dist/commands/porch/plan-parser.js +0 -166
  310. package/dist/commands/porch/plan-parser.js.map +0 -1
  311. package/dist/commands/porch/protocol-loader.d.ts +0 -46
  312. package/dist/commands/porch/protocol-loader.d.ts.map +0 -1
  313. package/dist/commands/porch/protocol-loader.js +0 -253
  314. package/dist/commands/porch/protocol-loader.js.map +0 -1
  315. package/dist/commands/porch/signal-parser.d.ts +0 -88
  316. package/dist/commands/porch/signal-parser.d.ts.map +0 -1
  317. package/dist/commands/porch/signal-parser.js +0 -148
  318. package/dist/commands/porch/signal-parser.js.map +0 -1
  319. package/dist/commands/tower.d.ts +0 -16
  320. package/dist/commands/tower.d.ts.map +0 -1
  321. package/dist/commands/tower.js +0 -21
  322. package/dist/commands/tower.js.map +0 -1
  323. package/skeleton/config.json +0 -7
  324. package/skeleton/porch/protocols/bugfix.json +0 -85
  325. package/skeleton/porch/protocols/spider.json +0 -135
  326. package/skeleton/porch/protocols/tick.json +0 -76
  327. package/skeleton/protocols/spider/prompts/defend.md +0 -215
  328. package/skeleton/protocols/spider/prompts/evaluate.md +0 -241
  329. package/templates/dashboard/css/activity.css +0 -151
  330. package/templates/dashboard/js/activity.js +0 -112
@@ -1,1103 +1,544 @@
1
1
  /**
2
2
  * Porch - Protocol Orchestrator
3
3
  *
4
- * Generic loop orchestrator that reads protocol definitions from JSON
5
- * and executes them with Claude. Implements the Ralph pattern: fresh
6
- * context per iteration with state persisted to files.
4
+ * Claude calls porch as a tool; porch returns prescriptive instructions.
5
+ * All commands produce clear, actionable output.
7
6
  */
8
7
  import * as fs from 'node:fs';
9
8
  import * as path from 'node:path';
10
- import * as readline from 'node:readline';
11
- import { spawn } from 'node:child_process';
12
9
  import chalk from 'chalk';
13
- import { findProjectRoot, getSkeletonDir } from '../../lib/skeleton.js';
14
- import { getProjectDir, readState, writeState, createInitialState, updateState, approveGate, requestGateApproval, updatePhaseStatus, setPlanPhases, findProjects, findExecutions, findStatusFile, findPendingGates, getConsultationAttempts, incrementConsultationAttempts, resetConsultationAttempts, } from './state.js';
15
- import { extractPhasesFromPlanFile, findPlanFile, } from './plan-parser.js';
16
- import { extractSignal } from './signal-parser.js';
17
- import { runPhaseChecks, formatCheckResults } from './checks.js';
18
- import { runConsultationLoop, formatConsultationResults, hasConsultation, } from './consultation.js';
19
- import { loadProtocol as loadProtocolFromLoader, listProtocols as listProtocolsFromLoader, } from './protocol-loader.js';
20
- import { createNotifier, } from './notifications.js';
10
+ import { readState, writeState, createInitialState, findStatusPath, getStatusPath, detectProjectId, } from './state.js';
11
+ import { loadProtocol, getPhaseConfig, getNextPhase, getPhaseChecks, getPhaseGate, isPhased, getPhaseCompletionChecks, } from './protocol.js';
12
+ import { findPlanFile, extractPhasesFromFile, getCurrentPlanPhase, getPhaseContent, advancePlanPhase, allPlanPhasesComplete, } from './plan.js';
13
+ import { runPhaseChecks, formatCheckResults, allChecksPassed, } from './checks.js';
21
14
  // ============================================================================
22
- // Protocol Loading (delegates to protocol-loader.ts)
15
+ // Output Helpers
23
16
  // ============================================================================
24
- /**
25
- * List available protocols
26
- * Delegates to protocol-loader.ts for proper conversion
27
- */
28
- export function listProtocols(projectRoot) {
29
- const root = projectRoot || findProjectRoot();
30
- return listProtocolsFromLoader(root);
31
- }
32
- /**
33
- * Load a protocol definition
34
- * Delegates to protocol-loader.ts which properly converts steps→substates
35
- */
36
- export function loadProtocol(name, projectRoot) {
37
- const root = projectRoot || findProjectRoot();
38
- const protocol = loadProtocolFromLoader(root, name);
39
- if (!protocol) {
40
- throw new Error(`Protocol not found: ${name}\nAvailable protocols: ${listProtocols(root).join(', ')}`);
41
- }
42
- return protocol;
43
- }
44
- /**
45
- * Load a prompt file for a phase
46
- */
47
- function loadPrompt(protocol, phaseId, projectRoot) {
48
- const phase = protocol.phases.find(p => p.id === phaseId);
49
- if (!phase?.prompt) {
50
- return null;
51
- }
52
- // New structure: protocols/<protocol>/prompts/<prompt>.md
53
- const promptPaths = [
54
- path.join(projectRoot, 'codev', 'protocols', protocol.name, 'prompts', phase.prompt),
55
- path.join(getSkeletonDir(), 'protocols', protocol.name, 'prompts', phase.prompt),
56
- // Legacy paths
57
- path.join(projectRoot, 'codev', 'porch', 'prompts', phase.prompt),
58
- path.join(getSkeletonDir(), 'porch', 'prompts', phase.prompt),
59
- ];
60
- for (const promptPath of promptPaths) {
61
- if (fs.existsSync(promptPath)) {
62
- return fs.readFileSync(promptPath, 'utf-8');
63
- }
64
- // Try with .md extension
65
- if (fs.existsSync(`${promptPath}.md`)) {
66
- return fs.readFileSync(`${promptPath}.md`, 'utf-8');
67
- }
68
- }
69
- return null;
70
- }
71
- // ============================================================================
72
- // Protocol Helpers
73
- // ============================================================================
74
- /**
75
- * Check if a phase is terminal
76
- */
77
- function isTerminalPhase(protocol, phaseId) {
78
- const phase = protocol.phases.find(p => p.id === phaseId);
79
- return phase?.terminal === true;
80
- }
81
- /**
82
- * Find the phase that has a gate blocking after the given state
83
- */
84
- function getGateForState(protocol, state) {
85
- const [phaseId, substate] = state.split(':');
86
- const phase = protocol.phases.find(p => p.id === phaseId);
87
- if (phase?.gate && phase.gate.after === substate) {
88
- const gateId = `${phaseId}_approval`;
89
- return { gateId, phase };
90
- }
91
- return null;
17
+ function header(text) {
18
+ const line = '═'.repeat(50);
19
+ return `${line}\n ${text}\n${line}`;
92
20
  }
93
- /**
94
- * Get next state after gate passes
95
- */
96
- function getGateNextState(protocol, phaseId) {
97
- const phase = protocol.phases.find(p => p.id === phaseId);
98
- return phase?.gate?.next || null;
99
- }
100
- /**
101
- * Get signal-based next state
102
- */
103
- function getSignalNextState(protocol, phaseId, signal) {
104
- const phase = protocol.phases.find(p => p.id === phaseId);
105
- return phase?.signals?.[signal] || null;
106
- }
107
- /**
108
- * Get the default next state for a phase (first substate or next phase)
109
- */
110
- function getDefaultNextState(protocol, state) {
111
- const [phaseId, substate] = state.split(':');
112
- const phase = protocol.phases.find(p => p.id === phaseId);
113
- if (!phase)
114
- return null;
115
- // If phase has substates, move to next substate
116
- if (phase.substates && substate) {
117
- const currentIdx = phase.substates.indexOf(substate);
118
- if (currentIdx >= 0 && currentIdx < phase.substates.length - 1) {
119
- return `${phaseId}:${phase.substates[currentIdx + 1]}`;
120
- }
121
- }
122
- // Move to next phase
123
- const phaseIdx = protocol.phases.findIndex(p => p.id === phaseId);
124
- if (phaseIdx >= 0 && phaseIdx < protocol.phases.length - 1) {
125
- const nextPhase = protocol.phases[phaseIdx + 1];
126
- if (nextPhase.substates && nextPhase.substates.length > 0) {
127
- return `${nextPhase.id}:${nextPhase.substates[0]}`;
128
- }
129
- return nextPhase.id;
130
- }
131
- return null;
21
+ function section(title, content) {
22
+ return `\n${chalk.bold(title)}:\n${content}`;
132
23
  }
133
24
  // ============================================================================
134
- // Claude Invocation
25
+ // Commands
135
26
  // ============================================================================
136
- // Note: extractSignal is now imported from signal-parser.js
137
27
  /**
138
- * Invoke Claude for a phase
28
+ * porch status <id>
29
+ * Shows current state and prescriptive next steps.
139
30
  */
140
- async function invokeClaude(protocol, phaseId, state, statusFilePath, projectRoot, options) {
141
- const promptContent = loadPrompt(protocol, phaseId, projectRoot);
142
- if (!promptContent) {
143
- console.log(chalk.yellow(`[porch] No prompt file for phase: ${phaseId}`));
144
- return '';
145
- }
146
- if (options.dryRun) {
147
- console.log(chalk.yellow(`[porch] [DRY RUN] Would invoke Claude for phase: ${phaseId}`));
148
- return '';
149
- }
150
- if (options.noClaude) {
151
- console.log(chalk.blue(`[porch] [NO_CLAUDE] Simulating phase: ${phaseId}`));
152
- await new Promise(r => setTimeout(r, 1000));
153
- console.log(chalk.green(`[porch] Simulated completion of phase: ${phaseId}`));
154
- return '';
155
- }
156
- console.log(chalk.cyan(`[phase] Invoking Claude for phase: ${phaseId}`));
157
- const timeout = protocol.config?.claude_timeout || 600000; // 10 minutes default
158
- const fullPrompt = `## Protocol: ${protocol.name}
159
- ## Phase: ${phaseId}
160
- ## Project ID: ${state.id}
161
-
162
- ## Current Status
163
- \`\`\`yaml
164
- state: "${state.current_state}"
165
- iteration: ${state.iteration}
166
- started_at: "${state.started_at}"
167
- \`\`\`
168
-
169
- ## Task
170
- Execute the ${phaseId} phase for project ${state.id} - ${state.title}
171
-
172
- ## Phase Instructions
173
- ${promptContent}
174
-
175
- ## Important
176
- - Project ID: ${state.id}
177
- - Protocol: ${protocol.name}
178
- - Follow the instructions above precisely
179
- - Output <signal>...</signal> tags when you reach completion points
180
- `;
181
- return new Promise((resolve, reject) => {
182
- const args = ['--print', '-p', fullPrompt, '--dangerously-skip-permissions'];
183
- const proc = spawn('claude', args, {
184
- stdio: ['ignore', 'pipe', 'pipe'],
185
- timeout,
186
- });
187
- let output = '';
188
- let stderr = '';
189
- proc.stdout.on('data', (data) => {
190
- output += data.toString();
191
- process.stdout.write(data);
192
- });
193
- proc.stderr.on('data', (data) => {
194
- stderr += data.toString();
195
- process.stderr.write(data);
196
- });
197
- proc.on('close', (code) => {
198
- if (code !== 0) {
199
- reject(new Error(`Claude exited with code ${code}\n${stderr}`));
31
+ export async function status(projectRoot, projectId) {
32
+ const statusPath = findStatusPath(projectRoot, projectId);
33
+ if (!statusPath) {
34
+ throw new Error(`Project ${projectId} not found.\nRun 'porch init' to create a new project.`);
35
+ }
36
+ const state = readState(statusPath);
37
+ const protocol = loadProtocol(projectRoot, state.protocol);
38
+ const phaseConfig = getPhaseConfig(protocol, state.phase);
39
+ // Header
40
+ console.log('');
41
+ console.log(header(`PROJECT: ${state.id} - ${state.title}`));
42
+ console.log(` PROTOCOL: ${state.protocol}`);
43
+ console.log(` PHASE: ${state.phase} (${phaseConfig?.name || 'unknown'})`);
44
+ // For phased protocols, show plan phase status
45
+ if (isPhased(protocol, state.phase) && state.plan_phases.length > 0) {
46
+ console.log('');
47
+ console.log(chalk.bold('PLAN PHASES:'));
48
+ console.log('');
49
+ // Status icons
50
+ const icon = (status) => {
51
+ switch (status) {
52
+ case 'complete': return chalk.green('✓');
53
+ case 'in_progress': return chalk.yellow('►');
54
+ default: return chalk.gray('○');
55
+ }
56
+ };
57
+ // Show phases
58
+ for (const phase of state.plan_phases) {
59
+ const isCurrent = phase.status === 'in_progress';
60
+ const prefix = isCurrent ? chalk.cyan('→ ') : ' ';
61
+ const title = isCurrent ? chalk.bold(phase.title) : phase.title;
62
+ console.log(`${prefix}${icon(phase.status)} ${phase.id}: ${title}`);
63
+ }
64
+ const currentPlanPhase = getCurrentPlanPhase(state.plan_phases);
65
+ if (currentPlanPhase) {
66
+ console.log('');
67
+ console.log(chalk.bold(`CURRENT: ${currentPlanPhase.id} - ${currentPlanPhase.title}`));
68
+ // Show phase content from plan
69
+ const planPath = findPlanFile(projectRoot, state.id, state.title);
70
+ if (planPath) {
71
+ const content = fs.readFileSync(planPath, 'utf-8');
72
+ const phaseContent = getPhaseContent(content, currentPlanPhase.id);
73
+ if (phaseContent) {
74
+ console.log(section('FROM THE PLAN', phaseContent.slice(0, 500)));
75
+ }
76
+ }
77
+ // Find the next phase name for the warning
78
+ const currentIdx = state.plan_phases.findIndex(p => p.id === currentPlanPhase.id);
79
+ const nextPlanPhase = state.plan_phases[currentIdx + 1];
80
+ console.log('');
81
+ console.log(chalk.red.bold('╔══════════════════════════════════════════════════════════════╗'));
82
+ console.log(chalk.red.bold('║ 🛑 CRITICAL RULES ║'));
83
+ if (nextPlanPhase) {
84
+ console.log(chalk.red.bold(`║ 1. DO NOT start ${nextPlanPhase.id} until you run porch again!`.padEnd(63) + '║'));
200
85
  }
201
86
  else {
202
- resolve(output);
87
+ console.log(chalk.red.bold('║ 1. DO NOT start the next phase until you run porch again! ║'));
203
88
  }
204
- });
205
- proc.on('error', reject);
206
- });
207
- }
208
- // ============================================================================
209
- // Commands
210
- // ============================================================================
211
- /**
212
- * Initialize a new project with a protocol
213
- */
214
- export async function init(protocolName, projectId, projectName, options = {}) {
215
- const projectRoot = findProjectRoot();
216
- const protocol = loadProtocol(protocolName, projectRoot);
217
- // Create project directory
218
- const projectDir = getProjectDir(projectRoot, projectId, projectName);
219
- fs.mkdirSync(projectDir, { recursive: true });
220
- // Create initial state
221
- const state = createInitialState(protocol, projectId, projectName, options.worktree);
222
- const statusPath = path.join(projectDir, 'status.yaml');
223
- await writeState(statusPath, state);
224
- console.log(chalk.green(`[porch] Initialized project ${projectId} with protocol ${protocolName}`));
225
- console.log(chalk.blue(`[porch] Project directory: ${projectDir}`));
226
- console.log(chalk.blue(`[porch] Initial state: ${state.current_state}`));
227
- }
228
- /**
229
- * Check if a protocol phase is a "phased" phase (runs per plan-phase)
230
- */
231
- function isPhasedPhase(protocol, phaseId) {
232
- const phase = protocol.phases.find(p => p.id === phaseId);
233
- return phase?.phased === true;
234
- }
235
- /**
236
- * Get the IDE phases (implement, defend, evaluate) that run per plan-phase
237
- */
238
- function getIDEPhases(protocol) {
239
- return protocol.phases
240
- .filter(p => p.phased === true)
241
- .map(p => p.id);
242
- }
243
- /**
244
- * Parse the current plan-phase from state like "implement:phase_1"
245
- */
246
- function parsePlanPhaseFromState(state) {
247
- const parts = state.split(':');
248
- const phaseId = parts[0];
249
- // Check if second part is a plan phase (phase_N) or a substate
250
- if (parts.length > 1) {
251
- if (parts[1].startsWith('phase_')) {
252
- return { phaseId, planPhaseId: parts[1], substate: parts[2] || null };
89
+ console.log(chalk.red.bold('║ 2. Run /compact before starting each new phase ║'));
90
+ console.log(chalk.red.bold('║ 3. After completing this phase, run: porch done ' + state.id.padEnd(12) + '║'));
91
+ console.log(chalk.red.bold('╚══════════════════════════════════════════════════════════════╝'));
253
92
  }
254
- return { phaseId, planPhaseId: null, substate: parts[1] };
255
93
  }
256
- return { phaseId, planPhaseId: null, substate: null };
257
- }
258
- /**
259
- * Get the next IDE state for a phased phase
260
- * implement:phase_1 → defend:phase_1 → evaluate:phase_1 → implement:phase_2 → ...
261
- */
262
- function getNextIDEState(protocol, currentState, planPhases, signal) {
263
- const { phaseId, planPhaseId } = parsePlanPhaseFromState(currentState);
264
- if (!planPhaseId)
265
- return null;
266
- const idePhases = getIDEPhases(protocol);
267
- const currentIdeIndex = idePhases.indexOf(phaseId);
268
- if (currentIdeIndex < 0)
269
- return null;
270
- // If not at the end of IDE phases, move to next IDE phase for same plan-phase
271
- if (currentIdeIndex < idePhases.length - 1) {
272
- return `${idePhases[currentIdeIndex + 1]}:${planPhaseId}`;
94
+ // Show checks status
95
+ const checks = getPhaseChecks(protocol, state.phase);
96
+ if (Object.keys(checks).length > 0) {
97
+ const checkLines = Object.keys(checks).map(name => ` ○ ${name} (not yet run)`);
98
+ console.log(section('CRITERIA', checkLines.join('\n')));
273
99
  }
274
- // At end of IDE phases (evaluate), move to next plan-phase
275
- const currentPlanIndex = planPhases.findIndex(p => p.id === planPhaseId);
276
- if (currentPlanIndex < 0)
277
- return null;
278
- // Check if there's a next plan phase
279
- if (currentPlanIndex < planPhases.length - 1) {
280
- const nextPlanPhase = planPhases[currentPlanIndex + 1];
281
- return `${idePhases[0]}:${nextPlanPhase.id}`; // Start implement for next phase
100
+ // Instructions
101
+ const gate = getPhaseGate(protocol, state.phase);
102
+ if (gate && state.gates[gate]?.status === 'pending' && state.gates[gate]?.requested_at) {
103
+ console.log(section('STATUS', chalk.yellow('WAITING FOR HUMAN APPROVAL')));
104
+ console.log(`\n Gate: ${gate}`);
105
+ console.log(' Do not proceed until gate is approved.');
106
+ console.log(`\n To approve: porch approve ${state.id} ${gate}`);
282
107
  }
283
- // All plan phases complete, move to review
284
- const reviewPhase = protocol.phases.find(p => p.id === 'review');
285
- if (reviewPhase) {
286
- return 'review';
108
+ else {
109
+ console.log(section('INSTRUCTIONS', getInstructions(state, protocol)));
287
110
  }
288
- return 'complete';
289
- }
290
- // ============================================================================
291
- // Interactive REPL
292
- // ============================================================================
293
- /**
294
- * Create a readline interface for interactive input
295
- */
296
- function createRepl() {
297
- return readline.createInterface({
298
- input: process.stdin,
299
- output: process.stdout,
300
- terminal: true,
301
- });
302
- }
303
- /**
304
- * Prompt user for input with a given message
305
- */
306
- async function prompt(rl, message) {
307
- return new Promise((resolve) => {
308
- rl.question(message, (answer) => {
309
- resolve(answer.trim().toLowerCase());
310
- });
311
- });
312
- }
313
- /**
314
- * Show REPL help
315
- */
316
- function showReplHelp() {
317
- console.log('');
318
- console.log(chalk.blue('Porch REPL Commands:'));
319
- console.log(' ' + chalk.green('approve') + ' [gate] - Approve pending gate (or current if omitted)');
320
- console.log(' ' + chalk.green('view') + ' - View the full artifact for current gate');
321
- console.log(' ' + chalk.green('status') + ' - Show current project status');
322
- console.log(' ' + chalk.green('continue') + ' - Continue to next iteration');
323
- console.log(' ' + chalk.green('skip') + ' - Skip current phase (use with caution)');
324
- console.log(' ' + chalk.green('help') + ' - Show this help');
325
- console.log(' ' + chalk.green('quit') + ' - Exit porch');
111
+ console.log(section('NEXT ACTION', getNextAction(state, protocol)));
326
112
  console.log('');
327
113
  }
328
114
  /**
329
- * Display current status summary
115
+ * porch check <id>
116
+ * Runs the phase checks and reports results.
330
117
  */
331
- function displayStatus(state, protocol) {
332
- console.log('');
333
- console.log(chalk.blue('─'.repeat(50)));
334
- console.log(chalk.blue(`Project: ${state.id} - ${state.title}`));
335
- console.log(chalk.blue(`Protocol: ${state.protocol}`));
336
- console.log(chalk.blue(`State: ${state.current_state}`));
337
- console.log(chalk.blue(`Iteration: ${state.iteration}`));
338
- // Show pending gates
339
- const pendingGates = Object.entries(state.gates)
340
- .filter(([, g]) => g.status === 'pending' && g.requested_at)
341
- .map(([id]) => id);
342
- if (pendingGates.length > 0) {
343
- console.log(chalk.yellow(`Pending gates: ${pendingGates.join(', ')}`));
118
+ export async function check(projectRoot, projectId) {
119
+ const statusPath = findStatusPath(projectRoot, projectId);
120
+ if (!statusPath) {
121
+ throw new Error(`Project ${projectId} not found.`);
122
+ }
123
+ const state = readState(statusPath);
124
+ const protocol = loadProtocol(projectRoot, state.protocol);
125
+ const checks = getPhaseChecks(protocol, state.phase);
126
+ if (Object.keys(checks).length === 0) {
127
+ console.log(chalk.dim('No checks defined for this phase.'));
128
+ return;
344
129
  }
345
- console.log(chalk.blue('─'.repeat(50)));
130
+ const checkEnv = { PROJECT_ID: state.id, PROJECT_TITLE: state.title };
346
131
  console.log('');
347
- }
348
- /**
349
- * Get the artifact file path for a gate
350
- */
351
- function getGateArtifact(gateId, state, projectRoot) {
352
- const projectDir = `${state.id}-${state.title}`;
353
- if (gateId === 'specify_approval') {
354
- // Look for spec file
355
- const specPath = path.join(projectRoot, 'codev', 'specs', `${projectDir}.md`);
356
- if (fs.existsSync(specPath))
357
- return specPath;
358
- // Try alternate naming
359
- const altPath = path.join(projectRoot, 'codev', 'specs', `${state.id}-${state.title}.md`);
360
- if (fs.existsSync(altPath))
361
- return altPath;
362
- }
363
- else if (gateId === 'plan_approval') {
364
- // Look for plan file
365
- const planPath = path.join(projectRoot, 'codev', 'plans', `${projectDir}.md`);
366
- if (fs.existsSync(planPath))
367
- return planPath;
368
- const altPath = path.join(projectRoot, 'codev', 'plans', `${state.id}-${state.title}.md`);
369
- if (fs.existsSync(altPath))
370
- return altPath;
371
- }
372
- else if (gateId === 'review_approval') {
373
- // Look for review file
374
- const reviewPath = path.join(projectRoot, 'codev', 'reviews', `${projectDir}.md`);
375
- if (fs.existsSync(reviewPath))
376
- return reviewPath;
377
- }
378
- return null;
379
- }
380
- /**
381
- * Display gate context - show what artifact was created and key information
382
- */
383
- function displayGateContext(gateId, state, projectRoot) {
384
- const artifactPath = getGateArtifact(gateId, state, projectRoot);
132
+ console.log(chalk.bold('RUNNING CHECKS...'));
385
133
  console.log('');
386
- console.log(chalk.cyan('─'.repeat(50)));
387
- console.log(chalk.cyan(' CONTEXT FOR REVIEW'));
388
- console.log(chalk.cyan(''.repeat(50)));
389
- if (artifactPath) {
390
- console.log(chalk.white(` Artifact: ${artifactPath}`));
391
- console.log('');
392
- // Read and show first ~30 lines of the artifact
393
- try {
394
- const content = fs.readFileSync(artifactPath, 'utf-8');
395
- const lines = content.split('\n');
396
- const preview = lines.slice(0, 30).join('\n');
397
- console.log(chalk.gray(' ┌' + '─'.repeat(46) + '┐'));
398
- for (const line of preview.split('\n')) {
399
- console.log(chalk.gray(' │ ') + line.slice(0, 44));
400
- }
401
- if (lines.length > 30) {
402
- console.log(chalk.gray(` │ ... (${lines.length - 30} more lines)`));
403
- }
404
- console.log(chalk.gray(' └' + '─'.repeat(46) + '┘'));
405
- console.log('');
406
- console.log(chalk.white(` To view full document: cat ${artifactPath}`));
407
- }
408
- catch (e) {
409
- console.log(chalk.yellow(` Could not read artifact: ${e}`));
410
- }
134
+ const results = await runPhaseChecks(checks, projectRoot, checkEnv);
135
+ console.log(formatCheckResults(results));
136
+ console.log('');
137
+ if (allChecksPassed(results)) {
138
+ console.log(chalk.green('RESULT: ALL CHECKS PASSED'));
139
+ console.log(`\n Run: porch done ${state.id} (to advance)`);
411
140
  }
412
141
  else {
413
- console.log(chalk.yellow(' No artifact file found for this gate.'));
414
- console.log(chalk.yellow(' This may indicate Claude did not produce the expected output.'));
415
- // Show what we expected
416
- if (gateId === 'specify_approval') {
417
- console.log(chalk.gray(` Expected: codev/specs/${state.id}-${state.title}.md`));
418
- }
419
- else if (gateId === 'plan_approval') {
420
- console.log(chalk.gray(` Expected: codev/plans/${state.id}-${state.title}.md`));
421
- }
142
+ console.log(chalk.red('RESULT: CHECKS FAILED'));
143
+ console.log(`\n Fix the failures and run: porch check ${state.id}`);
422
144
  }
423
145
  console.log('');
424
146
  }
425
147
  /**
426
- * Run the protocol loop for a project (Interactive REPL mode)
148
+ * porch done <id>
149
+ * Advances to next phase if checks pass. Refuses if checks fail.
427
150
  */
428
- export async function run(projectId, options = {}) {
429
- const projectRoot = findProjectRoot();
430
- // Find status file
431
- const statusFilePath = findStatusFile(projectRoot, projectId);
432
- if (!statusFilePath) {
433
- throw new Error(`Status file not found for project: ${projectId}\n` +
434
- `Run: porch init <protocol> ${projectId} <project-name>`);
435
- }
436
- // Read state and load protocol
437
- const state = readState(statusFilePath);
438
- if (!state) {
439
- throw new Error(`Could not read state from: ${statusFilePath}`);
440
- }
441
- const protocol = loadProtocol(state.protocol, projectRoot);
442
- const maxIterations = protocol.config?.max_iterations || 100;
443
- // Create notifier for this project (desktop notifications for important events)
444
- const notifier = createNotifier(projectId, { desktop: true });
445
- // Create REPL interface
446
- const rl = createRepl();
447
- console.log('');
448
- console.log(chalk.green('═'.repeat(50)));
449
- console.log(chalk.green(` PORCH - Protocol Orchestrator`));
450
- console.log(chalk.green('═'.repeat(50)));
451
- console.log(chalk.blue(` Project: ${state.id} - ${state.title}`));
452
- console.log(chalk.blue(` Protocol: ${state.protocol}`));
453
- console.log(chalk.blue(` State: ${state.current_state}`));
454
- console.log(chalk.green('═'.repeat(50)));
455
- console.log('');
456
- console.log(chalk.gray('Type "help" for commands, "quit" to exit'));
457
- console.log('');
458
- let currentState = state;
459
- // Extract plan phases if not already done and we're past planning
460
- if (!currentState.plan_phases || currentState.plan_phases.length === 0) {
461
- const planFile = findPlanFile(projectRoot, projectId, currentState.title);
462
- if (planFile) {
463
- try {
464
- const planPhases = extractPhasesFromPlanFile(planFile);
465
- currentState = setPlanPhases(currentState, planPhases);
466
- await writeState(statusFilePath, currentState);
467
- console.log(chalk.blue(`[porch] Extracted ${planPhases.length} phases from plan`));
468
- for (const phase of planPhases) {
469
- console.log(chalk.blue(` - ${phase.id}: ${phase.title}`));
470
- }
471
- }
472
- catch (e) {
473
- console.log(chalk.yellow(`[porch] Could not extract plan phases: ${e}`));
474
- }
151
+ export async function done(projectRoot, projectId) {
152
+ const statusPath = findStatusPath(projectRoot, projectId);
153
+ if (!statusPath) {
154
+ throw new Error(`Project ${projectId} not found.`);
155
+ }
156
+ let state = readState(statusPath);
157
+ const protocol = loadProtocol(projectRoot, state.protocol);
158
+ const checks = getPhaseChecks(protocol, state.phase);
159
+ // Run checks first
160
+ if (Object.keys(checks).length > 0) {
161
+ const checkEnv = { PROJECT_ID: state.id, PROJECT_TITLE: state.title };
162
+ console.log('');
163
+ console.log(chalk.bold('RUNNING CHECKS...'));
164
+ const results = await runPhaseChecks(checks, projectRoot, checkEnv);
165
+ console.log(formatCheckResults(results));
166
+ if (!allChecksPassed(results)) {
167
+ console.log('');
168
+ console.log(chalk.red('CHECKS FAILED. Cannot advance.'));
169
+ console.log(`\n Fix the failures and try again.`);
170
+ process.exit(1);
475
171
  }
476
172
  }
477
- for (let iteration = currentState.iteration; iteration <= maxIterations; iteration++) {
478
- console.log(chalk.blue('━'.repeat(40)));
479
- console.log(chalk.blue(`[porch] Iteration ${iteration}`));
480
- console.log(chalk.blue(''.repeat(40)));
481
- // Fresh read of state each iteration (Ralph pattern)
482
- currentState = readState(statusFilePath) || currentState;
483
- console.log(chalk.blue(`[porch] Current state: ${currentState.current_state}`));
484
- // Parse state into phase and substate
485
- const { phaseId, planPhaseId, substate } = parsePlanPhaseFromState(currentState.current_state);
486
- // Re-attempt plan phase extraction if entering a phased phase without plan phases
487
- // This handles the case where porch started during Specify phase (no plan file yet)
488
- if (isPhasedPhase(protocol, phaseId) && (!currentState.plan_phases || currentState.plan_phases.length === 0)) {
489
- const planFile = findPlanFile(projectRoot, projectId, currentState.title);
490
- if (planFile) {
491
- try {
492
- const planPhases = extractPhasesFromPlanFile(planFile);
493
- currentState = setPlanPhases(currentState, planPhases);
494
- await writeState(statusFilePath, currentState);
495
- console.log(chalk.blue(`[porch] Late discovery: Extracted ${planPhases.length} phases from plan`));
496
- for (const phase of planPhases) {
497
- console.log(chalk.blue(` - ${phase.id}: ${phase.title}`));
498
- }
499
- }
500
- catch (e) {
501
- console.log(chalk.yellow(`[porch] Could not extract plan phases: ${e}`));
502
- }
503
- }
504
- else {
505
- console.log(chalk.yellow(`[porch] Warning: Entering phased phase '${phaseId}' but no plan file found`));
506
- }
507
- }
508
- // Check if terminal phase
509
- if (isTerminalPhase(protocol, phaseId)) {
510
- console.log(chalk.green('━'.repeat(40)));
511
- console.log(chalk.green(`[porch] ${state.protocol} loop COMPLETE`));
512
- console.log(chalk.green(`[porch] Project ${projectId} finished all phases`));
513
- console.log(chalk.green('━'.repeat(40)));
514
- rl.close();
515
- return;
516
- }
517
- // Check if there's a pending gate from a previous iteration (step already executed)
518
- const pendingGateInfo = getGateForState(protocol, currentState.current_state);
519
- if (pendingGateInfo) {
520
- const { gateId } = pendingGateInfo;
521
- // Check if gate is already approved
522
- if (currentState.gates[gateId]?.status === 'passed') {
523
- // Gate approved - proceed to next state
524
- const nextState = getGateNextState(protocol, phaseId);
525
- if (nextState) {
526
- console.log(chalk.green(`[porch] Gate ${gateId} passed! Proceeding to ${nextState}`));
527
- await notifier.gateApproved(gateId);
528
- // Reset any consultation attempts for the gated state
529
- currentState = resetConsultationAttempts(currentState, currentState.current_state);
530
- // If entering a phased phase, start with first plan phase
531
- if (isPhasedPhase(protocol, nextState.split(':')[0]) && currentState.plan_phases?.length) {
532
- const firstPlanPhase = currentState.plan_phases[0];
533
- currentState = updateState(currentState, `${nextState.split(':')[0]}:${firstPlanPhase.id}`);
534
- currentState = updatePhaseStatus(currentState, firstPlanPhase.id, 'in_progress');
535
- }
536
- else {
537
- currentState = updateState(currentState, nextState);
538
- }
539
- await writeState(statusFilePath, currentState);
540
- continue; // Start next iteration with new state
541
- }
542
- }
543
- else if (currentState.gates[gateId]?.requested_at) {
544
- // Gate requested but not approved - prompt user interactively
173
+ // Check for gate
174
+ const gate = getPhaseGate(protocol, state.phase);
175
+ if (gate && state.gates[gate]?.status !== 'approved') {
176
+ console.log('');
177
+ console.log(chalk.yellow(`GATE REQUIRED: ${gate}`));
178
+ console.log(`\n Run: porch gate ${state.id}`);
179
+ console.log(' Wait for human approval before advancing.');
180
+ return;
181
+ }
182
+ // Handle phased protocols (plan phases with checks at completion)
183
+ if (isPhased(protocol, state.phase) && state.plan_phases.length > 0) {
184
+ const currentPlanPhase = getCurrentPlanPhase(state.plan_phases);
185
+ if (currentPlanPhase && !allPlanPhasesComplete(state.plan_phases)) {
186
+ // Run phase completion checks (implement + defend + evaluate all at once)
187
+ const completionChecks = getPhaseCompletionChecks(protocol);
188
+ if (Object.keys(completionChecks).length > 0) {
189
+ const checkEnv = { PROJECT_ID: state.id, PROJECT_TITLE: state.title };
545
190
  console.log('');
546
- console.log(chalk.yellow('═'.repeat(50)));
547
- console.log(chalk.yellow(` GATE PENDING: ${gateId}`));
548
- console.log(chalk.yellow('═'.repeat(50)));
549
- console.log(chalk.cyan(` Phase: ${phaseId}`));
550
- console.log(chalk.cyan(` State: ${currentState.current_state}`));
551
- // Show context for the gate - what artifact was created
552
- displayGateContext(gateId, currentState, projectRoot);
553
- // Interactive gate approval loop
554
- let gateHandled = false;
555
- while (!gateHandled) {
556
- const answer = await prompt(rl, chalk.yellow(`Approve ${gateId}? [y/n/help]: `));
557
- switch (answer) {
558
- case 'y':
559
- case 'yes':
560
- case 'approve':
561
- currentState = approveGate(currentState, gateId);
562
- await writeState(statusFilePath, currentState);
563
- console.log(chalk.green(`✓ Gate ${gateId} approved`));
564
- gateHandled = true;
565
- break;
566
- case 'n':
567
- case 'no':
568
- console.log(chalk.yellow('Gate not approved. Staying in current state.'));
569
- console.log(chalk.gray('Type "quit" to exit or wait for changes.'));
570
- break;
571
- case 'status':
572
- displayStatus(currentState, protocol);
573
- break;
574
- case 'view':
575
- case 'cat':
576
- case 'show':
577
- // Show full artifact
578
- const artifactPath = getGateArtifact(gateId, currentState, projectRoot);
579
- if (artifactPath) {
580
- console.log(chalk.cyan(`\n─── ${artifactPath} ───\n`));
581
- try {
582
- const content = fs.readFileSync(artifactPath, 'utf-8');
583
- console.log(content);
584
- console.log(chalk.cyan(`\n─── End of ${artifactPath} ───\n`));
585
- }
586
- catch (e) {
587
- console.log(chalk.red(`Error reading file: ${e}`));
588
- }
589
- }
590
- else {
591
- console.log(chalk.yellow('No artifact file found for this gate.'));
592
- }
593
- break;
594
- case 'help':
595
- case '?':
596
- showReplHelp();
597
- break;
598
- case 'quit':
599
- case 'exit':
600
- console.log(chalk.blue('Exiting porch...'));
601
- rl.close();
602
- return;
603
- default:
604
- console.log(chalk.gray('Type "y" to approve, "n" to decline, or "help" for commands'));
605
- }
191
+ console.log(chalk.bold(`RUNNING PHASE COMPLETION CHECKS (${currentPlanPhase.id})...`));
192
+ const results = await runPhaseChecks(completionChecks, projectRoot, checkEnv);
193
+ console.log(formatCheckResults(results));
194
+ if (!allChecksPassed(results)) {
195
+ console.log('');
196
+ console.log(chalk.red('PHASE COMPLETION CHECKS FAILED. Cannot advance.'));
197
+ console.log(`\n Ensure your commit includes:`);
198
+ console.log(` - Implementation code`);
199
+ console.log(` - Tests`);
200
+ console.log(` - 3-way review results in commit message`);
201
+ console.log(`\n Then try again.`);
202
+ process.exit(1);
606
203
  }
607
- continue;
608
- }
609
- // If gate not yet requested, fall through to execute phase first
610
- }
611
- // Get the current phase definition
612
- const phase = protocol.phases.find(p => p.id === phaseId);
613
- // Show plan phase context if in a phased phase
614
- if (planPhaseId && currentState.plan_phases) {
615
- const planPhase = currentState.plan_phases.find(p => p.id === planPhaseId);
616
- if (planPhase) {
617
- console.log(chalk.cyan(`[phase] IDE Phase: ${phaseId} | Plan Phase: ${planPhase.title}`));
618
204
  }
619
- else {
620
- console.log(chalk.cyan(`[phase] Phase: ${phaseId}`));
621
- }
622
- }
623
- else {
624
- console.log(chalk.cyan(`[phase] Phase: ${phaseId}`));
625
- }
626
- // Notify phase start
627
- await notifier.phaseStart(phaseId);
628
- // Execute phase
629
- const output = await invokeClaude(protocol, phaseId, currentState, statusFilePath, projectRoot, options);
630
- const signal = extractSignal(output);
631
- // Run phase checks (build/test) if defined
632
- if (phase?.checks && !options.dryRun) {
633
- console.log(chalk.blue(`[porch] Running checks for phase ${phaseId}...`));
634
- const checkResult = await runPhaseChecks(phase, {
635
- cwd: projectRoot,
636
- dryRun: options.dryRun,
637
- });
638
- console.log(formatCheckResults(checkResult));
639
- if (!checkResult.success) {
640
- // Notify about check failure
641
- const failedCheck = checkResult.checks.find(c => !c.success);
642
- await notifier.checkFailed(phaseId, failedCheck?.name || 'build/test', failedCheck?.error || 'Check failed');
643
- // If checks fail, handle based on check configuration
644
- if (checkResult.returnTo) {
645
- console.log(chalk.yellow(`[porch] Checks failed, returning to ${checkResult.returnTo}`));
646
- if (planPhaseId) {
647
- currentState = updateState(currentState, `${checkResult.returnTo}:${planPhaseId}`);
648
- }
649
- else {
650
- currentState = updateState(currentState, checkResult.returnTo);
651
- }
652
- await writeState(statusFilePath, currentState);
653
- continue;
654
- }
655
- // No returnTo means we should retry (already handled in checks)
205
+ // Advance to next plan phase
206
+ const { phases: updatedPhases, moveToReview } = advancePlanPhase(state.plan_phases, currentPlanPhase.id);
207
+ state.plan_phases = updatedPhases;
208
+ console.log('');
209
+ console.log(chalk.green(`PLAN PHASE COMPLETE: ${currentPlanPhase.id} - ${currentPlanPhase.title}`));
210
+ // Check if moving to review (all plan phases done)
211
+ if (moveToReview) {
212
+ state.phase = 'review';
213
+ state.current_plan_phase = null;
214
+ writeState(statusPath, state);
215
+ console.log(chalk.cyan('All plan phases complete. Moving to REVIEW phase.'));
216
+ console.log(`\n Run: porch status ${state.id}`);
217
+ return;
656
218
  }
657
- }
658
- // Run consultation if configured for this phase/substate
659
- if (phase?.consultation && hasConsultation(phase) && !options.dryRun && !options.noClaude) {
660
- const consultConfig = phase.consultation;
661
- const currentSubstate = substate || parsePlanPhaseFromState(currentState.current_state).substate;
662
- // Check if consultation is triggered by current substate
663
- if (consultConfig.on === currentSubstate || consultConfig.on === phaseId) {
664
- const maxRounds = consultConfig.max_rounds || 3;
665
- const stateKey = currentState.current_state;
666
- // Get attempt count from state (persisted across porch iterations)
667
- const attemptCount = getConsultationAttempts(currentState, stateKey) + 1;
668
- console.log(chalk.blue(`[porch] Consultation triggered for phase ${phaseId} (attempt ${attemptCount}/${maxRounds})`));
669
- await notifier.consultationStart(phaseId, consultConfig.models || ['gemini', 'codex', 'claude']);
670
- const consultResult = await runConsultationLoop(consultConfig, {
671
- subcommand: consultConfig.type.includes('pr') ? 'pr' : consultConfig.type.includes('spec') ? 'spec' : 'plan',
672
- identifier: projectId,
673
- cwd: projectRoot,
674
- timeout: protocol.config?.consultation_timeout,
675
- dryRun: options.dryRun,
676
- });
677
- console.log(formatConsultationResults(consultResult));
678
- await notifier.consultationComplete(phaseId, consultResult.feedback, consultResult.allApproved);
679
- // If not all approved, track attempt and check for escalation
680
- if (!consultResult.allApproved) {
681
- // Increment attempt count in state (persists across iterations)
682
- currentState = incrementConsultationAttempts(currentState, stateKey);
683
- await writeState(statusFilePath, currentState);
684
- // Check if we've reached max attempts
685
- if (attemptCount >= maxRounds) {
686
- // Create escalation gate - requires human intervention
687
- const escalationGateId = `${phaseId}_consultation_escalation`;
688
- // Check if escalation gate was already approved (human override)
689
- if (currentState.gates[escalationGateId]?.status === 'passed') {
690
- console.log(chalk.green(`[porch] Consultation escalation gate already approved, continuing`));
691
- // Reset attempts and fall through to next state handling
692
- currentState = resetConsultationAttempts(currentState, stateKey);
693
- await writeState(statusFilePath, currentState);
694
- }
695
- else {
696
- console.log(chalk.red(`[porch] Consultation failed after ${attemptCount} attempts - escalating to human`));
697
- console.log(chalk.yellow(`[porch] To override and continue: porch approve ${projectId} ${escalationGateId}`));
698
- // Request human gate if not already requested
699
- if (!currentState.gates[escalationGateId]?.requested_at) {
700
- currentState = requestGateApproval(currentState, escalationGateId);
701
- await writeState(statusFilePath, currentState);
702
- await notifier.gatePending(phaseId, escalationGateId);
703
- }
704
- // Prompt user to approve escalation gate
705
- console.log('');
706
- console.log(chalk.red('═'.repeat(50)));
707
- console.log(chalk.red(` ESCALATION: ${escalationGateId}`));
708
- console.log(chalk.red('═'.repeat(50)));
709
- console.log(chalk.yellow(` Consultation failed after ${attemptCount} attempts`));
710
- console.log('');
711
- let escalationHandled = false;
712
- while (!escalationHandled) {
713
- const answer = await prompt(rl, chalk.red(`Override and continue? [y/n/help]: `));
714
- switch (answer) {
715
- case 'y':
716
- case 'yes':
717
- case 'approve':
718
- case 'override':
719
- currentState = approveGate(currentState, escalationGateId);
720
- currentState = resetConsultationAttempts(currentState, stateKey);
721
- await writeState(statusFilePath, currentState);
722
- console.log(chalk.green(`✓ Escalation gate ${escalationGateId} approved`));
723
- escalationHandled = true;
724
- break;
725
- case 'n':
726
- case 'no':
727
- console.log(chalk.yellow('Escalation not approved. Consultation loop will continue.'));
728
- break;
729
- case 'status':
730
- displayStatus(currentState, protocol);
731
- break;
732
- case 'help':
733
- case '?':
734
- showReplHelp();
735
- break;
736
- case 'quit':
737
- case 'exit':
738
- console.log(chalk.blue('Exiting porch...'));
739
- rl.close();
740
- return;
741
- default:
742
- console.log(chalk.gray('Type "y" to override and continue, "n" to decline, or "help" for commands'));
743
- }
744
- }
745
- continue;
746
- }
747
- }
748
- else {
749
- console.log(chalk.yellow(`[porch] Consultation requested changes (attempt ${attemptCount}/${maxRounds}), continuing for revision`));
750
- // Stay in same state for Claude to revise on next iteration
751
- continue;
752
- }
753
- }
754
- else {
755
- // All approved - reset attempt counter
756
- currentState = resetConsultationAttempts(currentState, stateKey);
757
- await writeState(statusFilePath, currentState);
758
- }
759
- // All approved (or escalation gate passed) - use consultation's next state if defined
760
- if (consultConfig.next) {
761
- if (planPhaseId) {
762
- currentState = updateState(currentState, `${consultConfig.next}:${planPhaseId}`);
763
- }
764
- else {
765
- currentState = updateState(currentState, consultConfig.next);
766
- }
767
- await writeState(statusFilePath, currentState);
768
- continue;
769
- }
219
+ // Update current plan phase tracker
220
+ const newCurrentPhase = getCurrentPlanPhase(state.plan_phases);
221
+ state.current_plan_phase = newCurrentPhase?.id || null;
222
+ writeState(statusPath, state);
223
+ if (newCurrentPhase) {
224
+ console.log(chalk.cyan(`NEXT: ${newCurrentPhase.id} - ${newCurrentPhase.title}`));
770
225
  }
226
+ console.log(`\n Run: porch status ${state.id}`);
227
+ return;
771
228
  }
772
- // Check if current state has a gate that should trigger AFTER this step
773
- // This is the gate trigger point - step has executed, now block before transition
774
- const gateInfo = getGateForState(protocol, currentState.current_state);
775
- if (gateInfo) {
776
- const { gateId } = gateInfo;
777
- // Request gate approval if not already requested
778
- if (!currentState.gates[gateId]?.requested_at) {
779
- currentState = requestGateApproval(currentState, gateId);
780
- await writeState(statusFilePath, currentState);
781
- console.log(chalk.yellow(`[porch] Step complete. Gate approval requested: ${gateId}`));
782
- await notifier.gatePending(phaseId, gateId);
783
- }
784
- // Gate not yet approved - prompt user interactively
785
- if (currentState.gates[gateId]?.status !== 'passed') {
786
- console.log('');
787
- console.log(chalk.yellow('═'.repeat(50)));
788
- console.log(chalk.yellow(` GATE PENDING: ${gateId}`));
789
- console.log(chalk.yellow('═'.repeat(50)));
790
- let gateHandled = false;
791
- while (!gateHandled) {
792
- const answer = await prompt(rl, chalk.yellow(`Approve ${gateId}? [y/n/help]: `));
793
- switch (answer) {
794
- case 'y':
795
- case 'yes':
796
- case 'approve':
797
- currentState = approveGate(currentState, gateId);
798
- await writeState(statusFilePath, currentState);
799
- console.log(chalk.green(`✓ Gate ${gateId} approved`));
800
- gateHandled = true;
801
- break;
802
- case 'n':
803
- case 'no':
804
- console.log(chalk.yellow('Gate not approved. Staying in current state.'));
805
- break;
806
- case 'status':
807
- displayStatus(currentState, protocol);
808
- break;
809
- case 'help':
810
- case '?':
811
- showReplHelp();
812
- break;
813
- case 'quit':
814
- case 'exit':
815
- console.log(chalk.blue('Exiting porch...'));
816
- rl.close();
817
- return;
818
- default:
819
- console.log(chalk.gray('Type "y" to approve, "n" to decline, or "help" for commands'));
820
- }
821
- }
822
- continue;
229
+ }
230
+ // Advance to next protocol phase
231
+ advanceProtocolPhase(state, protocol, statusPath);
232
+ }
233
+ function advanceProtocolPhase(state, protocol, statusPath) {
234
+ const nextPhase = getNextPhase(protocol, state.phase);
235
+ if (!nextPhase) {
236
+ state.phase = 'complete';
237
+ writeState(statusPath, state);
238
+ console.log('');
239
+ console.log(chalk.green.bold('🎉 PROTOCOL COMPLETE'));
240
+ console.log(`\n Project ${state.id} has completed the ${state.protocol} protocol.`);
241
+ return;
242
+ }
243
+ state.phase = nextPhase.id;
244
+ // If entering a phased phase (implement), extract plan phases
245
+ if (isPhased(protocol, nextPhase.id)) {
246
+ const planPath = findPlanFile(process.cwd(), state.id, state.title);
247
+ if (planPath) {
248
+ state.plan_phases = extractPhasesFromFile(planPath);
249
+ // extractPhasesFromFile already marks first phase as in_progress
250
+ if (state.plan_phases.length > 0) {
251
+ state.current_plan_phase = state.plan_phases[0].id;
823
252
  }
824
253
  }
825
- // Determine next state
826
- let nextState = null;
827
- if (signal) {
828
- console.log(chalk.green(`[porch] Signal received: ${signal}`));
829
- nextState = getSignalNextState(protocol, phaseId, signal);
830
- }
831
- if (!nextState) {
832
- // Check if this is a phased phase (IDE loop)
833
- if (isPhasedPhase(protocol, phaseId) && currentState.plan_phases?.length) {
834
- nextState = getNextIDEState(protocol, currentState.current_state, currentState.plan_phases, signal || undefined);
835
- // Mark current plan phase as complete if moving to next
836
- if (nextState && planPhaseId) {
837
- const { planPhaseId: nextPlanPhaseId } = parsePlanPhaseFromState(nextState);
838
- if (nextPlanPhaseId !== planPhaseId) {
839
- currentState = updatePhaseStatus(currentState, planPhaseId, 'complete');
840
- if (nextPlanPhaseId) {
841
- currentState = updatePhaseStatus(currentState, nextPlanPhaseId, 'in_progress');
842
- }
843
- }
844
- }
845
- }
846
- else {
847
- // Use default transition
848
- nextState = getDefaultNextState(protocol, currentState.current_state);
254
+ }
255
+ writeState(statusPath, state);
256
+ console.log('');
257
+ console.log(chalk.green(`ADVANCING TO: ${nextPhase.id} - ${nextPhase.name}`));
258
+ // If we just entered implement phase, show phase 1 info and the critical warning
259
+ if (isPhased(protocol, nextPhase.id) && state.plan_phases.length > 0) {
260
+ const firstPhase = state.plan_phases[0];
261
+ const nextPlanPhase = state.plan_phases[1];
262
+ console.log('');
263
+ console.log(chalk.bold(`YOUR TASK: ${firstPhase.id} - "${firstPhase.title}"`));
264
+ // Show phase content from plan
265
+ const planPath = findPlanFile(process.cwd(), state.id, state.title);
266
+ if (planPath) {
267
+ const content = fs.readFileSync(planPath, 'utf-8');
268
+ const phaseContent = getPhaseContent(content, firstPhase.id);
269
+ if (phaseContent) {
270
+ console.log(section('FROM THE PLAN', phaseContent.slice(0, 800)));
849
271
  }
850
272
  }
851
- if (nextState) {
852
- currentState = updateState(currentState, nextState, signal ? { signal } : undefined);
853
- await writeState(statusFilePath, currentState);
273
+ console.log('');
274
+ console.log(chalk.red.bold('╔══════════════════════════════════════════════════════════════╗'));
275
+ console.log(chalk.red.bold('║ 🛑 CRITICAL RULES ║'));
276
+ if (nextPlanPhase) {
277
+ console.log(chalk.red.bold(`║ 1. DO NOT start ${nextPlanPhase.id} until you run porch again!`.padEnd(63) + '║'));
854
278
  }
855
279
  else {
856
- console.log(chalk.yellow(`[porch] No transition defined, staying in current state`));
280
+ console.log(chalk.red.bold('║ 1. DO NOT start the next phase until you run porch again! ║'));
857
281
  }
282
+ console.log(chalk.red.bold('║ 2. Run /compact before starting each new phase ║'));
283
+ console.log(chalk.red.bold('║ 3. When phase complete, run: porch done ' + state.id.padEnd(20) + '║'));
284
+ console.log(chalk.red.bold('╚══════════════════════════════════════════════════════════════╝'));
858
285
  }
859
- rl.close();
860
- throw new Error(`Max iterations (${maxIterations}) reached!`);
286
+ console.log(`\n Run: porch status ${state.id}`);
861
287
  }
862
288
  /**
863
- * Approve a gate
289
+ * porch gate <id>
290
+ * Requests human approval for current gate.
864
291
  */
865
- export async function approve(projectId, gateId) {
866
- const projectRoot = findProjectRoot();
867
- const statusFilePath = findStatusFile(projectRoot, projectId);
868
- if (!statusFilePath) {
869
- throw new Error(`Status file not found for project: ${projectId}`);
292
+ export async function gate(projectRoot, projectId) {
293
+ const statusPath = findStatusPath(projectRoot, projectId);
294
+ if (!statusPath) {
295
+ throw new Error(`Project ${projectId} not found.`);
296
+ }
297
+ const state = readState(statusPath);
298
+ const protocol = loadProtocol(projectRoot, state.protocol);
299
+ const gateName = getPhaseGate(protocol, state.phase);
300
+ if (!gateName) {
301
+ console.log(chalk.dim('No gate required for this phase.'));
302
+ console.log(`\n Run: porch done ${state.id}`);
303
+ return;
870
304
  }
871
- const state = readState(statusFilePath);
872
- if (!state) {
873
- throw new Error(`Could not read state from: ${statusFilePath}`);
305
+ // Mark gate as requested
306
+ if (!state.gates[gateName]) {
307
+ state.gates[gateName] = { status: 'pending' };
874
308
  }
875
- const updatedState = approveGate(state, gateId);
876
- await writeState(statusFilePath, updatedState);
877
- console.log(chalk.green(`[porch] Approved: ${gateId}`));
878
- }
879
- /**
880
- * Show project status
881
- */
882
- export async function status(projectId) {
883
- const projectRoot = findProjectRoot();
884
- if (projectId) {
885
- // Show specific project
886
- const statusFilePath = findStatusFile(projectRoot, projectId);
887
- if (!statusFilePath) {
888
- throw new Error(`Status file not found for project: ${projectId}`);
889
- }
890
- const state = readState(statusFilePath);
891
- if (!state) {
892
- throw new Error(`Could not read state from: ${statusFilePath}`);
893
- }
894
- console.log(chalk.blue(`[porch] Status for project ${projectId}:`));
895
- console.log('');
896
- console.log(` ID: ${state.id}`);
897
- console.log(` Title: ${state.title}`);
898
- console.log(` Protocol: ${state.protocol}`);
899
- console.log(` State: ${state.current_state}`);
900
- console.log(` Iteration: ${state.iteration}`);
901
- console.log(` Started: ${state.started_at}`);
902
- console.log(` Updated: ${state.last_updated}`);
903
- console.log('');
904
- if (Object.keys(state.gates).length > 0) {
905
- console.log(' Gates:');
906
- for (const [gateId, gateStatus] of Object.entries(state.gates)) {
907
- const icon = gateStatus.status === 'passed' ? '✓' : gateStatus.status === 'failed' ? '✗' : '⏳';
908
- console.log(` ${icon} ${gateId}: ${gateStatus.status}`);
909
- }
910
- console.log('');
911
- }
912
- if (state.plan_phases && state.plan_phases.length > 0) {
913
- console.log(' Plan Phases:');
914
- for (const phase of state.plan_phases) {
915
- const phaseStatus = state.phases[phase.id]?.status || 'pending';
916
- const icon = phaseStatus === 'complete' ? '✓' : phaseStatus === 'in_progress' ? '🔄' : '○';
917
- console.log(` ${icon} ${phase.id}: ${phase.title}`);
918
- }
919
- }
309
+ if (!state.gates[gateName].requested_at) {
310
+ state.gates[gateName].requested_at = new Date().toISOString();
311
+ writeState(statusPath, state);
920
312
  }
921
- else {
922
- // Show all projects
923
- const projects = findProjects(projectRoot);
924
- const executions = findExecutions(projectRoot);
925
- if (projects.length === 0 && executions.length === 0) {
926
- console.log(chalk.yellow('[porch] No projects found'));
927
- return;
928
- }
929
- console.log(chalk.blue('[porch] Projects:'));
930
- for (const { id, path: statusPath } of projects) {
931
- const state = readState(statusPath);
932
- if (state) {
933
- const pendingGates = Object.entries(state.gates)
934
- .filter(([, g]) => g.status === 'pending' && g.requested_at)
935
- .map(([id]) => id);
936
- const gateStr = pendingGates.length > 0 ? chalk.yellow(` [${pendingGates.join(', ')}]`) : '';
937
- console.log(` ${id} ${state.title} - ${state.current_state}${gateStr}`);
938
- }
939
- }
940
- if (executions.length > 0) {
313
+ console.log('');
314
+ console.log(chalk.bold(`GATE: ${gateName}`));
315
+ console.log('');
316
+ // Show relevant artifact and open it for review
317
+ const artifact = getArtifactForPhase(projectRoot, state);
318
+ if (artifact) {
319
+ const fullPath = path.join(projectRoot, artifact);
320
+ if (fs.existsSync(fullPath)) {
321
+ console.log(` Artifact: ${artifact}`);
941
322
  console.log('');
942
- console.log(chalk.blue('[porch] Executions:'));
943
- for (const { protocol, id, path: statusPath } of executions) {
944
- const state = readState(statusPath);
945
- if (state) {
946
- console.log(` ${protocol}/${id} - ${state.current_state}`);
947
- }
948
- }
323
+ console.log(chalk.cyan(' Opening artifact for human review...'));
324
+ // Use af open to display in annotation viewer
325
+ const { spawn } = await import('node:child_process');
326
+ spawn('af', ['open', fullPath], {
327
+ stdio: 'inherit',
328
+ detached: true
329
+ }).unref();
949
330
  }
950
331
  }
332
+ console.log('');
333
+ console.log(chalk.yellow(' Human approval required. STOP and wait.'));
334
+ console.log(' Do not proceed until gate is approved.');
335
+ console.log('');
336
+ console.log(chalk.bold('STATUS: WAITING FOR HUMAN APPROVAL'));
337
+ console.log('');
338
+ console.log(chalk.dim(` To approve: porch approve ${state.id} ${gateName}`));
339
+ console.log('');
951
340
  }
952
341
  /**
953
- * List available protocols
342
+ * porch approve <id> <gate> --a-human-explicitly-approved-this
343
+ * Human approves a gate. Requires explicit flag to prevent automated approvals.
954
344
  */
955
- export async function list() {
956
- const projectRoot = findProjectRoot();
957
- const protocols = listProtocols(projectRoot);
958
- if (protocols.length === 0) {
959
- console.log(chalk.yellow('[porch] No protocols found'));
345
+ export async function approve(projectRoot, projectId, gateName, hasHumanFlag) {
346
+ const statusPath = findStatusPath(projectRoot, projectId);
347
+ if (!statusPath) {
348
+ throw new Error(`Project ${projectId} not found.`);
349
+ }
350
+ const state = readState(statusPath);
351
+ if (!state.gates[gateName]) {
352
+ const knownGates = Object.keys(state.gates).join(', ');
353
+ throw new Error(`Unknown gate: ${gateName}\nKnown gates: ${knownGates || 'none'}`);
354
+ }
355
+ if (state.gates[gateName].status === 'approved') {
356
+ console.log(chalk.yellow(`Gate ${gateName} is already approved.`));
960
357
  return;
961
358
  }
962
- console.log(chalk.blue('[porch] Available protocols:'));
963
- for (const name of protocols) {
964
- try {
965
- const protocol = loadProtocol(name, projectRoot);
966
- console.log(` - ${name}: ${protocol.description}`);
967
- }
968
- catch {
969
- console.log(` - ${name}: (error loading)`);
359
+ // Require explicit human flag
360
+ if (!hasHumanFlag) {
361
+ console.log('');
362
+ console.log(chalk.red('ERROR: Human approval required.'));
363
+ console.log('');
364
+ console.log(' To approve, please run:');
365
+ console.log('');
366
+ console.log(chalk.cyan(` porch approve ${projectId} ${gateName} --a-human-explicitly-approved-this`));
367
+ console.log('');
368
+ process.exit(1);
369
+ }
370
+ // Run phase checks before approving
371
+ const protocol = loadProtocol(projectRoot, state.protocol);
372
+ const checks = getPhaseChecks(protocol, state.phase);
373
+ if (Object.keys(checks).length > 0) {
374
+ const checkEnv = { PROJECT_ID: state.id, PROJECT_TITLE: state.title };
375
+ console.log('');
376
+ console.log(chalk.bold('RUNNING CHECKS...'));
377
+ const results = await runPhaseChecks(checks, projectRoot, checkEnv);
378
+ console.log(formatCheckResults(results));
379
+ if (!allChecksPassed(results)) {
380
+ console.log('');
381
+ console.log(chalk.red('CHECKS FAILED. Cannot approve gate.'));
382
+ console.log(`\n Fix the failures and try again.`);
383
+ process.exit(1);
970
384
  }
971
385
  }
972
- }
973
- /**
974
- * Show protocol definition
975
- */
976
- export async function show(protocolName) {
977
- const projectRoot = findProjectRoot();
978
- const protocol = loadProtocol(protocolName, projectRoot);
979
- console.log(chalk.blue(`[porch] Protocol: ${protocolName}`));
386
+ state.gates[gateName].status = 'approved';
387
+ state.gates[gateName].approved_at = new Date().toISOString();
388
+ writeState(statusPath, state);
389
+ console.log('');
390
+ console.log(chalk.green(`Gate ${gateName} approved.`));
391
+ console.log(`\n Run: porch done ${state.id} (to advance)`);
980
392
  console.log('');
981
- console.log(JSON.stringify(protocol, null, 2));
982
393
  }
983
394
  /**
984
- * Show pending gates across all projects
395
+ * porch init <protocol> <id> <name>
396
+ * Initialize a new project.
985
397
  */
986
- export async function pending() {
987
- const projectRoot = findProjectRoot();
988
- const gates = findPendingGates(projectRoot);
989
- if (gates.length === 0) {
990
- console.log(chalk.green('[porch] No pending gates'));
991
- return;
992
- }
993
- console.log(chalk.yellow('[porch] Pending gates:'));
994
- for (const gate of gates) {
995
- const requestedAt = gate.requestedAt ? ` (requested ${gate.requestedAt})` : '';
996
- console.log(` ${gate.projectId}: ${gate.gateId}${requestedAt}`);
997
- console.log(` porch approve ${gate.projectId} ${gate.gateId}`);
998
- }
398
+ export async function init(projectRoot, protocolName, projectId, projectName) {
399
+ const protocol = loadProtocol(projectRoot, protocolName);
400
+ const statusPath = getStatusPath(projectRoot, projectId, projectName);
401
+ // Check if already exists
402
+ if (fs.existsSync(statusPath)) {
403
+ throw new Error(`Project ${projectId}-${projectName} already exists.`);
404
+ }
405
+ const state = createInitialState(protocol, projectId, projectName, projectRoot);
406
+ writeState(statusPath, state);
407
+ console.log('');
408
+ console.log(chalk.green(`Project initialized: ${projectId}-${projectName}`));
409
+ console.log(` Protocol: ${protocolName}`);
410
+ console.log(` Starting phase: ${state.phase}`);
411
+ console.log(`\n Run: porch status ${projectId}`);
412
+ console.log('');
999
413
  }
1000
414
  // ============================================================================
1001
- // Auto-Detection
415
+ // Helpers
1002
416
  // ============================================================================
1003
- /**
1004
- * Auto-detect project ID from current directory
1005
- *
1006
- * Detection methods:
1007
- * 1. Check if cwd is a worktree matching pattern: .builders/<id> or worktrees/<protocol>_<id>_*
1008
- * 2. Check for a single project in codev/projects/
1009
- * 3. Check for .porch-project marker file
1010
- */
1011
- function autoDetectProject() {
1012
- const cwd = process.cwd();
1013
- // Method 1: Check path pattern for builder worktree
1014
- // Pattern: .builders/<id> or .builders/<id>-<name>
1015
- const buildersMatch = cwd.match(/[/\\]\.builders[/\\](\d+)(?:-[^/\\]*)?(?:[/\\]|$)/);
1016
- if (buildersMatch) {
1017
- return buildersMatch[1];
417
+ function getInstructions(state, protocol) {
418
+ const phase = state.phase;
419
+ if (isPhased(protocol, phase) && state.plan_phases.length > 0) {
420
+ const current = getCurrentPlanPhase(state.plan_phases);
421
+ if (current) {
422
+ return ` You are implementing ${current.id}: "${current.title}".\n\n Complete the work, then run: porch check ${state.id}`;
423
+ }
1018
424
  }
1019
- // Pattern: worktrees/<protocol>_<id>_<name>
1020
- const worktreeMatch = cwd.match(/[/\\]worktrees[/\\]\w+_(\d+)_[^/\\]*(?:[/\\]|$)/);
1021
- if (worktreeMatch) {
1022
- return worktreeMatch[1];
425
+ const phaseConfig = getPhaseConfig(protocol, phase);
426
+ return ` You are in the ${phaseConfig?.name || phase} phase.\n\n When complete, run: porch done ${state.id}`;
427
+ }
428
+ function getNextAction(state, protocol) {
429
+ const checks = getPhaseChecks(protocol, state.phase);
430
+ const gate = getPhaseGate(protocol, state.phase);
431
+ if (gate && state.gates[gate]?.status === 'pending' && state.gates[gate]?.requested_at) {
432
+ return chalk.yellow('Wait for human to approve the gate.');
1023
433
  }
1024
- // Method 2: Check for .porch-project marker file
1025
- const markerPath = path.join(cwd, '.porch-project');
1026
- if (fs.existsSync(markerPath)) {
1027
- const content = fs.readFileSync(markerPath, 'utf-8').trim();
1028
- if (content) {
1029
- return content;
434
+ if (isPhased(protocol, state.phase)) {
435
+ const current = getCurrentPlanPhase(state.plan_phases);
436
+ if (current) {
437
+ return `Implement ${current.title} as specified in the plan.`;
1030
438
  }
1031
439
  }
1032
- // Method 3: Check if there's exactly one project in codev/projects/
1033
- try {
1034
- const projectRoot = findProjectRoot();
1035
- const projects = findProjects(projectRoot);
1036
- if (projects.length === 1) {
1037
- return projects[0].id;
1038
- }
440
+ if (Object.keys(checks).length > 0) {
441
+ return `Complete the phase work, then run: porch check ${state.id}`;
1039
442
  }
1040
- catch {
1041
- // Not in a codev project
443
+ return `Complete the phase work, then run: porch done ${state.id}`;
444
+ }
445
+ function getArtifactForPhase(projectRoot, state) {
446
+ switch (state.phase) {
447
+ case 'specify':
448
+ return `codev/specs/${state.id}-${state.title}.md`;
449
+ case 'plan':
450
+ return `codev/plans/${state.id}-${state.title}.md`;
451
+ case 'review':
452
+ return `codev/reviews/${state.id}-${state.title}.md`;
453
+ default:
454
+ return null;
1042
455
  }
1043
- return null;
1044
456
  }
1045
- export async function porch(options) {
1046
- const { subcommand, args, dryRun, noClaude, pollInterval, description, worktree } = options;
1047
- switch (subcommand.toLowerCase()) {
1048
- case 'run': {
1049
- let projectId = args[0];
1050
- // Auto-detect project if not provided
1051
- if (!projectId) {
1052
- const detected = autoDetectProject();
1053
- if (!detected) {
1054
- throw new Error('Usage: porch run <project-id>\n' +
1055
- 'Or run from a project worktree to auto-detect.');
457
+ // ============================================================================
458
+ // CLI
459
+ // ============================================================================
460
+ export async function cli(args) {
461
+ const [command, ...rest] = args;
462
+ const projectRoot = process.cwd();
463
+ // Auto-detect project ID for commands that need it
464
+ function getProjectId(provided) {
465
+ if (provided)
466
+ return provided;
467
+ const detected = detectProjectId(projectRoot);
468
+ if (detected) {
469
+ console.log(chalk.dim(`[auto-detected project: ${detected}]`));
470
+ return detected;
471
+ }
472
+ throw new Error('No project ID provided and could not auto-detect.\nProvide ID explicitly or ensure exactly one project exists in codev/projects/');
473
+ }
474
+ try {
475
+ switch (command) {
476
+ case 'run':
477
+ const { run } = await import('./run.js');
478
+ // Parse options for run command
479
+ const runOptions = {};
480
+ let runProjectId;
481
+ for (let i = 0; i < rest.length; i++) {
482
+ if (rest[i] === '--single-iteration' || rest[i] === '-1') {
483
+ runOptions.singleIteration = true;
484
+ }
485
+ else if (rest[i] === '--single-phase') {
486
+ runOptions.singlePhase = true;
487
+ }
488
+ else if (!rest[i].startsWith('--')) {
489
+ runProjectId = rest[i];
490
+ }
1056
491
  }
1057
- projectId = detected;
1058
- console.log(chalk.blue(`[porch] Auto-detected project: ${projectId}`));
1059
- }
1060
- await run(projectId, { dryRun, noClaude, pollInterval });
1061
- break;
1062
- }
1063
- case 'init': {
1064
- if (args.length < 3) {
1065
- throw new Error('Usage: porch init <protocol> <project-id> <project-name>');
1066
- }
1067
- await init(args[0], args[1], args[2], { description, worktree });
1068
- break;
1069
- }
1070
- case 'approve': {
1071
- if (args.length < 2) {
1072
- throw new Error('Usage: porch approve <project-id> <gate-id>');
1073
- }
1074
- await approve(args[0], args[1]);
1075
- break;
1076
- }
1077
- case 'status': {
1078
- await status(args[0]);
1079
- break;
1080
- }
1081
- case 'pending': {
1082
- await pending();
1083
- break;
1084
- }
1085
- case 'list':
1086
- case 'list-protocols': {
1087
- await list();
1088
- break;
1089
- }
1090
- case 'show':
1091
- case 'show-protocol': {
1092
- if (args.length < 1) {
1093
- throw new Error('Usage: porch show <protocol>');
1094
- }
1095
- await show(args[0]);
1096
- break;
492
+ await run(projectRoot, getProjectId(runProjectId), runOptions);
493
+ break;
494
+ case 'status':
495
+ await status(projectRoot, getProjectId(rest[0]));
496
+ break;
497
+ case 'check':
498
+ await check(projectRoot, getProjectId(rest[0]));
499
+ break;
500
+ case 'done':
501
+ await done(projectRoot, getProjectId(rest[0]));
502
+ break;
503
+ case 'gate':
504
+ await gate(projectRoot, getProjectId(rest[0]));
505
+ break;
506
+ case 'approve':
507
+ if (!rest[0] || !rest[1])
508
+ throw new Error('Usage: porch approve <id> <gate> --a-human-explicitly-approved-this');
509
+ const hasHumanFlag = rest.includes('--a-human-explicitly-approved-this');
510
+ await approve(projectRoot, rest[0], rest[1], hasHumanFlag);
511
+ break;
512
+ case 'init':
513
+ if (!rest[0] || !rest[1] || !rest[2]) {
514
+ throw new Error('Usage: porch init <protocol> <id> <name>');
515
+ }
516
+ await init(projectRoot, rest[0], rest[1], rest[2]);
517
+ break;
518
+ default:
519
+ console.log('porch - Protocol Orchestrator');
520
+ console.log('');
521
+ console.log('Commands:');
522
+ console.log(' run [id] [options] Run the protocol (auto-detects if one project)');
523
+ console.log(' status [id] Show current state and instructions');
524
+ console.log(' check [id] Run checks for current phase');
525
+ console.log(' done [id] Advance to next phase (if checks pass)');
526
+ console.log(' gate [id] Request human approval');
527
+ console.log(' approve <id> <gate> --a-human-explicitly-approved-this');
528
+ console.log(' init <protocol> <id> <name> Initialize a new project');
529
+ console.log('');
530
+ console.log('Run options:');
531
+ console.log(' --single-iteration, -1 Run one build-verify cycle then exit');
532
+ console.log(' --single-phase Run one phase then exit (for Builder/Enforcer pattern)');
533
+ console.log('');
534
+ console.log('Project ID is auto-detected when exactly one project exists.');
535
+ console.log('');
536
+ process.exit(command ? 1 : 0);
1097
537
  }
1098
- default:
1099
- throw new Error(`Unknown subcommand: ${subcommand}\n` +
1100
- 'Valid subcommands: run, init, approve, status, pending, list, show');
538
+ }
539
+ catch (err) {
540
+ console.error(chalk.red(`Error: ${err.message}`));
541
+ process.exit(1);
1101
542
  }
1102
543
  }
1103
544
  //# sourceMappingURL=index.js.map