@phren/cli 0.2.14 → 0.2.16

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 (387) hide show
  1. package/README.md +2 -2
  2. package/dist/agent-instructions.d.ts +12 -0
  3. package/dist/agent-instructions.js +52 -0
  4. package/dist/bridge/agent-hook-stores.d.ts +32 -0
  5. package/dist/bridge/agent-hook-stores.js +67 -0
  6. package/dist/bridge/agent-hooks.d.ts +193 -2
  7. package/dist/bridge/agent-hooks.js +1045 -38
  8. package/dist/bridge/canary.d.ts +27 -0
  9. package/dist/bridge/canary.js +189 -0
  10. package/dist/bridge/changes.d.ts +57 -0
  11. package/dist/bridge/changes.js +403 -0
  12. package/dist/bridge/client.d.ts +3 -0
  13. package/dist/bridge/client.js +36 -0
  14. package/dist/bridge/code-note.d.ts +22 -0
  15. package/dist/bridge/code-note.js +42 -0
  16. package/dist/bridge/code-routes.d.ts +133 -0
  17. package/dist/bridge/code-routes.js +319 -0
  18. package/dist/bridge/codex-threads.d.ts +27 -0
  19. package/dist/bridge/codex-threads.js +442 -0
  20. package/dist/bridge/command.d.ts +7 -0
  21. package/dist/bridge/command.js +50 -5
  22. package/dist/bridge/computer-names.d.ts +4 -0
  23. package/dist/bridge/computer-names.js +16 -0
  24. package/dist/bridge/computers.d.ts +9 -0
  25. package/dist/bridge/computers.js +111 -0
  26. package/dist/bridge/context.d.ts +14 -0
  27. package/dist/bridge/context.js +149 -0
  28. package/dist/bridge/dispatch-command.d.ts +3 -0
  29. package/dist/bridge/dispatch-command.js +93 -0
  30. package/dist/bridge/dispatch-hosts.d.ts +23 -0
  31. package/dist/bridge/dispatch-hosts.js +25 -0
  32. package/dist/bridge/dispatch-returns.d.ts +123 -0
  33. package/dist/bridge/dispatch-returns.js +279 -0
  34. package/dist/bridge/dispatch-tree.d.ts +54 -0
  35. package/dist/bridge/dispatch-tree.js +198 -0
  36. package/dist/bridge/dispatch.d.ts +207 -0
  37. package/dist/bridge/dispatch.js +261 -0
  38. package/dist/bridge/enroll.d.ts +31 -0
  39. package/dist/bridge/enroll.js +236 -0
  40. package/dist/bridge/fanout-messages.d.ts +74 -0
  41. package/dist/bridge/fanout-messages.js +230 -0
  42. package/dist/bridge/fanouts.d.ts +160 -0
  43. package/dist/bridge/fanouts.js +702 -0
  44. package/dist/bridge/file-range.d.ts +16 -0
  45. package/dist/bridge/file-range.js +90 -0
  46. package/dist/bridge/files.d.ts +20 -0
  47. package/dist/bridge/files.js +54 -0
  48. package/dist/bridge/git-publish.d.ts +23 -0
  49. package/dist/bridge/git-publish.js +145 -0
  50. package/dist/bridge/git-worktrees.d.ts +21 -0
  51. package/dist/bridge/git-worktrees.js +150 -0
  52. package/dist/bridge/git.d.ts +54 -0
  53. package/dist/bridge/git.js +552 -0
  54. package/dist/bridge/grants.d.ts +31 -0
  55. package/dist/bridge/grants.js +181 -0
  56. package/dist/bridge/hand-off.d.ts +79 -0
  57. package/dist/bridge/hand-off.js +151 -0
  58. package/dist/bridge/health.d.ts +128 -0
  59. package/dist/bridge/health.js +260 -0
  60. package/dist/bridge/herdr.d.ts +79 -6
  61. package/dist/bridge/herdr.js +292 -27
  62. package/dist/bridge/hook-main.js +2 -0
  63. package/dist/bridge/install.d.ts +32 -1
  64. package/dist/bridge/install.js +225 -38
  65. package/dist/bridge/launch-worktree.d.ts +21 -0
  66. package/dist/bridge/launch-worktree.js +70 -0
  67. package/dist/bridge/limits.d.ts +20 -0
  68. package/dist/bridge/limits.js +65 -0
  69. package/dist/bridge/locate.d.ts +16 -0
  70. package/dist/bridge/locate.js +75 -0
  71. package/dist/bridge/metrics.d.ts +29 -0
  72. package/dist/bridge/metrics.js +71 -0
  73. package/dist/bridge/model-switch.d.ts +35 -0
  74. package/dist/bridge/model-switch.js +250 -0
  75. package/dist/bridge/models.d.ts +46 -0
  76. package/dist/bridge/models.js +257 -0
  77. package/dist/bridge/opencode-approvals.d.ts +6 -0
  78. package/dist/bridge/opencode-approvals.js +60 -0
  79. package/dist/bridge/pane-text.d.ts +15 -0
  80. package/dist/bridge/pane-text.js +23 -0
  81. package/dist/bridge/peers.d.ts +27 -0
  82. package/dist/bridge/peers.js +130 -0
  83. package/dist/bridge/projects.d.ts +12 -1
  84. package/dist/bridge/projects.js +268 -20
  85. package/dist/bridge/protocol.d.ts +35 -2
  86. package/dist/bridge/protocol.js +42 -7
  87. package/dist/bridge/push.d.ts +83 -0
  88. package/dist/bridge/push.js +199 -0
  89. package/dist/bridge/questions.d.ts +38 -0
  90. package/dist/bridge/questions.js +205 -0
  91. package/dist/bridge/schedule-format.d.ts +103 -0
  92. package/dist/bridge/schedule-format.js +266 -0
  93. package/dist/bridge/schedule-launch.d.ts +11 -0
  94. package/dist/bridge/schedule-launch.js +169 -0
  95. package/dist/bridge/schedule-watch.d.ts +52 -0
  96. package/dist/bridge/schedule-watch.js +242 -0
  97. package/dist/bridge/schedules.d.ts +48 -0
  98. package/dist/bridge/schedules.js +205 -0
  99. package/dist/bridge/server-launch.d.ts +14 -0
  100. package/dist/bridge/server-launch.js +218 -0
  101. package/dist/bridge/server-overview.d.ts +45 -0
  102. package/dist/bridge/server-overview.js +102 -0
  103. package/dist/bridge/server-pane-routes.d.ts +29 -0
  104. package/dist/bridge/server-pane-routes.js +400 -0
  105. package/dist/bridge/server-routes.d.ts +106 -0
  106. package/dist/bridge/server-routes.js +538 -0
  107. package/dist/bridge/server-stream.d.ts +46 -0
  108. package/dist/bridge/server-stream.js +253 -0
  109. package/dist/bridge/server.d.ts +3 -15
  110. package/dist/bridge/server.js +162 -264
  111. package/dist/bridge/session-servers.d.ts +24 -0
  112. package/dist/bridge/session-servers.js +136 -0
  113. package/dist/bridge/side-questions.d.ts +74 -0
  114. package/dist/bridge/side-questions.js +252 -0
  115. package/dist/bridge/simulators.d.ts +28 -0
  116. package/dist/bridge/simulators.js +198 -0
  117. package/dist/bridge/speech-transcribe.d.ts +24 -0
  118. package/dist/bridge/speech-transcribe.js +124 -0
  119. package/dist/bridge/speech.d.ts +35 -0
  120. package/dist/bridge/speech.js +98 -0
  121. package/dist/bridge/steps.d.ts +13 -0
  122. package/dist/bridge/steps.js +222 -0
  123. package/dist/bridge/tab-activity.d.ts +18 -0
  124. package/dist/bridge/tab-activity.js +99 -0
  125. package/dist/bridge/terminal-choice.d.ts +64 -0
  126. package/dist/bridge/terminal-choice.js +281 -0
  127. package/dist/bridge/transcript-claude.d.ts +22 -0
  128. package/dist/bridge/transcript-claude.js +353 -0
  129. package/dist/bridge/transcript-codex.d.ts +30 -0
  130. package/dist/bridge/transcript-codex.js +282 -0
  131. package/dist/bridge/transcript-copilot.d.ts +4 -0
  132. package/dist/bridge/transcript-copilot.js +14 -0
  133. package/dist/bridge/transcript-opencode.d.ts +5 -0
  134. package/dist/bridge/transcript-opencode.js +26 -0
  135. package/dist/bridge/transcript-preview.d.ts +94 -0
  136. package/dist/bridge/transcript-preview.js +476 -0
  137. package/dist/bridge/transcripts.d.ts +81 -4
  138. package/dist/bridge/transcripts.js +332 -67
  139. package/dist/bridge/transport.d.ts +3 -0
  140. package/dist/bridge/transport.js +96 -15
  141. package/dist/bridge/uploads.d.ts +15 -0
  142. package/dist/bridge/uploads.js +44 -2
  143. package/dist/bridge/usage.d.ts +124 -0
  144. package/dist/bridge/usage.js +859 -0
  145. package/dist/bridge-hook.mjs +41246 -21385
  146. package/dist/cli/actions.js +14 -1
  147. package/dist/cli/config-proactivity.d.ts +3 -1
  148. package/dist/cli/config-proactivity.js +35 -3
  149. package/dist/cli/config.js +4 -1
  150. package/dist/cli/extract.js +3 -6
  151. package/dist/cli/govern.js +5 -2
  152. package/dist/cli/hooks-globs.js +1 -1
  153. package/dist/cli/hooks.d.ts +1 -1
  154. package/dist/cli/hooks.js +9 -7
  155. package/dist/cli/namespaces-projects.js +12 -6
  156. package/dist/cli/namespaces-store.js +37 -6
  157. package/dist/cli/namespaces-tasks.js +1 -1
  158. package/dist/cli/schedules.d.ts +1 -0
  159. package/dist/cli/schedules.js +164 -0
  160. package/dist/cli/session-background.js +1 -1
  161. package/dist/cli/session-git.d.ts +8 -5
  162. package/dist/cli/session-git.js +45 -120
  163. package/dist/cli/session-start.js +3 -1
  164. package/dist/cli/session-stop.js +19 -8
  165. package/dist/cli/team.js +13 -10
  166. package/dist/cli-handlers.d.ts +1 -1
  167. package/dist/cli-handlers.js +8 -4
  168. package/dist/cli-help.d.ts +5 -4
  169. package/dist/cli-help.js +15 -15
  170. package/dist/cli-registry.d.ts +4 -1
  171. package/dist/cli-registry.js +119 -6
  172. package/dist/content/archive.js +2 -2
  173. package/dist/content/citation.d.ts +11 -0
  174. package/dist/content/citation.js +18 -0
  175. package/dist/content/learning.js +2 -0
  176. package/dist/content/summarize.d.ts +14 -15
  177. package/dist/content/summarize.js +60 -5
  178. package/dist/content/validate.d.ts +3 -1
  179. package/dist/content/validate.js +26 -8
  180. package/dist/core/project-registry.d.ts +26 -0
  181. package/dist/core/project-registry.js +573 -0
  182. package/dist/core/project.js +2 -3
  183. package/dist/data/access.d.ts +7 -1
  184. package/dist/data/access.js +13 -3
  185. package/dist/data/tasks.d.ts +18 -3
  186. package/dist/data/tasks.js +8 -7
  187. package/dist/entrypoint.js +44 -10
  188. package/dist/fanout/adapters/claude.d.ts +2 -0
  189. package/dist/fanout/adapters/claude.js +7 -0
  190. package/dist/fanout/adapters/codex.d.ts +2 -0
  191. package/dist/fanout/adapters/codex.js +9 -0
  192. package/dist/fanout/adapters/opencode.d.ts +4 -0
  193. package/dist/fanout/adapters/opencode.js +9 -0
  194. package/dist/fanout/adapters/types.d.ts +21 -0
  195. package/dist/fanout/adapters/types.js +3 -0
  196. package/dist/fanout/command.d.ts +2 -0
  197. package/dist/fanout/command.js +78 -0
  198. package/dist/fanout/launcher.d.ts +27 -0
  199. package/dist/fanout/launcher.js +156 -0
  200. package/dist/fanout/opencode-serve.d.ts +24 -0
  201. package/dist/fanout/opencode-serve.js +191 -0
  202. package/dist/fanout/picker.d.ts +91 -0
  203. package/dist/fanout/picker.js +51 -0
  204. package/dist/fanout/usage.d.ts +5 -0
  205. package/dist/fanout/usage.js +51 -0
  206. package/dist/fanout/watchdog.d.ts +10 -0
  207. package/dist/fanout/watchdog.js +27 -0
  208. package/dist/filenames.d.ts +9 -0
  209. package/dist/filenames.js +11 -0
  210. package/dist/finding/context.js +4 -22
  211. package/dist/generated/memory-ui-graph.browser.js +279 -283
  212. package/dist/governance/policy-constants.d.ts +11 -0
  213. package/dist/governance/policy-constants.js +9 -0
  214. package/dist/governance/policy.d.ts +5 -8
  215. package/dist/governance/policy.js +7 -5
  216. package/dist/graph-core/camera.d.ts +24 -0
  217. package/dist/graph-core/camera.js +18 -0
  218. package/dist/graph-core/index.d.ts +2 -0
  219. package/dist/graph-core/index.js +2 -0
  220. package/dist/graph-core/labels.d.ts +77 -0
  221. package/dist/graph-core/labels.js +124 -0
  222. package/dist/graph-core/model.d.ts +13 -0
  223. package/dist/graph-core/model.js +33 -0
  224. package/dist/graph-core/types.d.ts +2 -0
  225. package/dist/home-paths.d.ts +7 -0
  226. package/dist/home-paths.js +21 -0
  227. package/dist/hooks.d.ts +3 -0
  228. package/dist/hooks.js +13 -0
  229. package/dist/index.js +24 -2
  230. package/dist/init/guard-globals.d.ts +1 -1
  231. package/dist/init/guard-globals.js +4 -4
  232. package/dist/init/init-configure.js +3 -3
  233. package/dist/init/init-uninstall.js +2 -2
  234. package/dist/init/init-walkthrough.d.ts +2 -0
  235. package/dist/init/init-walkthrough.js +17 -6
  236. package/dist/init/init.js +26 -6
  237. package/dist/init/management-preset.d.ts +1 -1
  238. package/dist/init/management-preset.js +2 -2
  239. package/dist/init/preferences.js +1 -1
  240. package/dist/init/self-wiring.js +1 -1
  241. package/dist/init/setup.d.ts +3 -26
  242. package/dist/init/setup.js +49 -588
  243. package/dist/init/shared.js +2 -0
  244. package/dist/init/store-gitignore.d.ts +1 -1
  245. package/dist/init/store-gitignore.js +2 -0
  246. package/dist/init/teardown.d.ts +1 -1
  247. package/dist/init/teardown.js +2 -2
  248. package/dist/link/context.js +1 -1
  249. package/dist/link/doctor.d.ts +22 -1
  250. package/dist/link/doctor.js +100 -54
  251. package/dist/link/link.js +29 -61
  252. package/dist/link/refresh.js +2 -2
  253. package/dist/link/skills.js +26 -5
  254. package/dist/machine-identity.d.ts +3 -0
  255. package/dist/machine-identity.js +6 -0
  256. package/dist/mcp/profile.d.ts +2 -15
  257. package/dist/mcp/profile.js +64 -9
  258. package/dist/memory-ui-graph.runtime.js +279 -283
  259. package/dist/modules/code-package.d.ts +16 -0
  260. package/dist/modules/code-package.js +152 -0
  261. package/dist/modules/command.d.ts +2 -0
  262. package/dist/modules/command.js +67 -0
  263. package/dist/modules/config.d.ts +4 -0
  264. package/dist/modules/config.js +70 -0
  265. package/dist/modules/manifest.d.ts +41 -0
  266. package/dist/modules/manifest.js +1 -0
  267. package/dist/modules/provision.d.ts +3 -0
  268. package/dist/modules/provision.js +84 -0
  269. package/dist/modules/registry.d.ts +16 -0
  270. package/dist/modules/registry.js +250 -0
  271. package/dist/modules/runtime.d.ts +15 -0
  272. package/dist/modules/runtime.js +59 -0
  273. package/dist/package-metadata.js +10 -2
  274. package/dist/phren-dotenv.js +4 -2
  275. package/dist/phren-paths.d.ts +3 -2
  276. package/dist/phren-paths.js +4 -5
  277. package/dist/profile-store.js +4 -5
  278. package/dist/project-config.d.ts +19 -1
  279. package/dist/project-config.js +29 -3
  280. package/dist/project-topics.js +4 -4
  281. package/dist/provider-adapters.js +1 -4
  282. package/dist/query-correlation.js +6 -6
  283. package/dist/session/artifacts.js +5 -5
  284. package/dist/session/checkpoints.js +5 -0
  285. package/dist/session/utils.d.ts +2 -2
  286. package/dist/session/utils.js +6 -6
  287. package/dist/shared/content.d.ts +1 -1
  288. package/dist/shared/content.js +1 -1
  289. package/dist/shared/data-utils.js +1 -1
  290. package/dist/shared/fragment-graph.d.ts +1 -1
  291. package/dist/shared/fragment-graph.js +5 -5
  292. package/dist/shared/index.js +48 -7
  293. package/dist/shared/retrieval.d.ts +18 -1
  294. package/dist/shared/retrieval.js +100 -11
  295. package/dist/shared/search-fallback.js +4 -6
  296. package/dist/shared/sqljs.d.ts +2 -0
  297. package/dist/shared/sqljs.js +4 -2
  298. package/dist/shared.d.ts +0 -1
  299. package/dist/shared.js +0 -1
  300. package/dist/shell/input.d.ts +1 -5
  301. package/dist/shell/input.js +16 -10
  302. package/dist/shell/palette.d.ts +2 -2
  303. package/dist/shell/palette.js +3 -7
  304. package/dist/shell/render.d.ts +3 -1
  305. package/dist/shell/render.js +4 -4
  306. package/dist/shell/shell.js +4 -1
  307. package/dist/shell/types.d.ts +1 -0
  308. package/dist/shell/types.js +4 -0
  309. package/dist/shell/view.d.ts +0 -4
  310. package/dist/shell/view.js +19 -27
  311. package/dist/skill/registry.js +25 -17
  312. package/dist/skill/state.d.ts +3 -0
  313. package/dist/skill/state.js +13 -7
  314. package/dist/status.js +38 -17
  315. package/dist/store-registry.d.ts +44 -18
  316. package/dist/store-registry.js +169 -60
  317. package/dist/store-weight.d.ts +1 -6
  318. package/dist/store-weight.js +4 -2
  319. package/dist/sync/auth-doctor.d.ts +8 -0
  320. package/dist/sync/auth-doctor.js +27 -0
  321. package/dist/sync/auth.d.ts +27 -0
  322. package/dist/sync/auth.js +114 -0
  323. package/dist/sync/conflict-resolve.d.ts +9 -0
  324. package/dist/sync/conflict-resolve.js +146 -0
  325. package/dist/sync/git-state.d.ts +4 -0
  326. package/dist/sync/git-state.js +49 -0
  327. package/dist/sync/outcome.d.ts +34 -0
  328. package/dist/sync/outcome.js +57 -0
  329. package/dist/sync/pull.d.ts +15 -7
  330. package/dist/sync/pull.js +84 -35
  331. package/dist/sync/store-merge.d.ts +29 -0
  332. package/dist/sync/store-merge.js +137 -0
  333. package/dist/sync/task-merge.d.ts +22 -0
  334. package/dist/sync/task-merge.js +158 -0
  335. package/dist/task/github.js +1 -1
  336. package/dist/task/lifecycle.d.ts +5 -0
  337. package/dist/task/lifecycle.js +67 -23
  338. package/dist/terminal-text.d.ts +5 -0
  339. package/dist/terminal-text.js +11 -0
  340. package/dist/test-global-setup.js +7 -0
  341. package/dist/tool-registry.d.ts +1 -1
  342. package/dist/tool-registry.js +3 -1
  343. package/dist/tools/code.d.ts +3 -0
  344. package/dist/tools/code.js +178 -0
  345. package/dist/tools/config.js +5 -0
  346. package/dist/tools/data.js +14 -7
  347. package/dist/tools/dispatch.d.ts +2 -0
  348. package/dist/tools/dispatch.js +66 -0
  349. package/dist/tools/finding.js +43 -41
  350. package/dist/tools/ops.js +5 -2
  351. package/dist/tools/search.js +21 -8
  352. package/dist/tools/session.js +21 -22
  353. package/dist/tools/tasks.js +8 -2
  354. package/dist/tools/types.d.ts +2 -2
  355. package/dist/tools/types.js +2 -2
  356. package/dist/ui/assets.js +1 -1
  357. package/dist/ui/data.js +14 -15
  358. package/dist/ui/deep-void.d.ts +1 -1
  359. package/dist/ui/deep-void.js +0 -1
  360. package/dist/ui/graph-chrome.d.ts +1 -1
  361. package/dist/ui/graph-chrome.js +51 -0
  362. package/dist/ui/page.js +5 -5
  363. package/dist/ui/scripts.js +67 -30
  364. package/dist/ui/server.js +34 -6
  365. package/dist/update.js +1 -1
  366. package/dist/utils-fts.js +1 -0
  367. package/dist/utils-helpers.d.ts +7 -0
  368. package/dist/utils-helpers.js +17 -0
  369. package/dist/utils.d.ts +1 -1
  370. package/dist/utils.js +1 -1
  371. package/package.json +45 -3
  372. package/plugins/opencode/phren-transcript.js +340 -0
  373. package/starter/README.md +4 -4
  374. package/starter/global/{CLAUDE.md → AGENTS.md} +2 -2
  375. package/starter/global/skills/conductor/SKILL.md +106 -0
  376. package/starter/global/skills/fanout/SKILL.md +20 -0
  377. package/starter/global/skills/phren-discover/SKILL.md +6 -6
  378. package/starter/global/skills/phren-init/SKILL.md +4 -4
  379. package/starter/global/skills/phren-sync/SKILL.md +3 -3
  380. package/starter/templates/frontend/reference/README.md +1 -1
  381. package/starter/templates/library/reference/README.md +1 -1
  382. package/starter/templates/monorepo/reference/README.md +1 -1
  383. package/starter/templates/python-project/reference/README.md +1 -1
  384. /package/starter/templates/frontend/{CLAUDE.md → AGENTS.md} +0 -0
  385. /package/starter/templates/library/{CLAUDE.md → AGENTS.md} +0 -0
  386. /package/starter/templates/monorepo/{CLAUDE.md → AGENTS.md} +0 -0
  387. /package/starter/templates/python-project/{CLAUDE.md → AGENTS.md} +0 -0
@@ -1,7 +1,6 @@
1
1
  import { type PhrenResult } from "../shared.js";
2
2
  export type TaskSection = "Active" | "Queue" | "Done";
3
- export declare const TASKS_FILENAME = "tasks.md";
4
- export declare const TASK_FILE_ALIASES: readonly ["tasks.md"];
3
+ export { TASK_FILE_ALIASES, TASKS_FILENAME, isTaskFileName } from "../filenames.js";
5
4
  export interface TaskItem {
6
5
  /** Positional ID for display (e.g. "A1", "Q3"). Recomputed on every read — use stableId for persistent references. */
7
6
  id: string;
@@ -31,13 +30,29 @@ export interface TaskDoc {
31
30
  issues: string[];
32
31
  path: string;
33
32
  }
33
+ export declare function stripBulletPrefix(line: string): {
34
+ checked: boolean;
35
+ body: string;
36
+ };
37
+ /** Strip the metadata comment from a raw line, returning the clean text and any extracted fields. */
38
+ export declare function stripBid(text: string): {
39
+ clean: string;
40
+ bid?: string;
41
+ rank?: number;
42
+ lastActivity?: string;
43
+ createdAt?: string;
44
+ sessionId?: string;
45
+ scope?: string;
46
+ childFindings?: string[];
47
+ parentFinding?: string;
48
+ speculative?: boolean;
49
+ };
34
50
  /**
35
51
  * Apply gravity to tasks: items with stale lastActivity drift toward higher rank numbers.
36
52
  * Only affects display order — does not mutate the file.
37
53
  */
38
54
  export declare function applyGravity(items: TaskItem[]): TaskItem[];
39
55
  export declare function canonicalTaskFilePath(phrenPath: string, project: string): string | null;
40
- export declare function isTaskFileName(filename: string): boolean;
41
56
  export declare function resolveTaskFilePath(phrenPath: string, project: string): string | null;
42
57
  export declare function readTasks(phrenPath: string, project: string): PhrenResult<TaskDoc>;
43
58
  export declare function readTasksAcrossProjects(phrenPath: string, profile?: string): TaskDoc[];
@@ -1,3 +1,5 @@
1
+ import { moduleEnabled } from "../modules/runtime.js";
2
+ import { disabledHint } from "../modules/registry.js";
1
3
  import * as fs from "fs";
2
4
  import * as path from "path";
3
5
  import { randomBytes, randomUUID } from "crypto";
@@ -6,11 +8,11 @@ import { validateTaskFormat } from "../shared/content.js";
6
8
  import { withSafeLock, ensureProject } from "../shared/data-utils.js";
7
9
  import { getNonPrimaryStores, getStoreProjectDirs } from "../store-registry.js";
8
10
  import { storeAwareProjectPath } from "../store-routing.js";
11
+ import { TASKS_FILENAME } from "../filenames.js";
9
12
  const ACTIVE_HEADINGS = new Set(["active", "in progress", "in-progress", "current", "wip"]);
10
13
  const QUEUE_HEADINGS = new Set(["queue", "queued", "task", "todo", "upcoming", "next"]);
11
14
  const DONE_HEADINGS = new Set(["done", "completed", "finished", "archived"]);
12
- export const TASKS_FILENAME = "tasks.md";
13
- export const TASK_FILE_ALIASES = [TASKS_FILENAME];
15
+ export { TASK_FILE_ALIASES, TASKS_FILENAME, isTaskFileName } from "../filenames.js";
14
16
  const TASK_SECTIONS = ["Active", "Queue", "Done"];
15
17
  function normalizePriority(text) {
16
18
  const m = text.replace(/\s*\[pinned\]/gi, "").match(/\[(high|medium|low)\]\s*$/i);
@@ -36,7 +38,7 @@ function detectPinned(text) {
36
38
  function stripPinnedTag(text) {
37
39
  return text.replace(/\s*\[pinned\]/gi, "").trim();
38
40
  }
39
- function stripBulletPrefix(line) {
41
+ export function stripBulletPrefix(line) {
40
42
  const checked = /^-\s*\[[xX]\]\s+/.test(line);
41
43
  const body = line
42
44
  .replace(/^-\s*\[[ xX]\]\s+/, "")
@@ -112,7 +114,7 @@ function newBid() {
112
114
  return randomBytes(4).toString("hex");
113
115
  }
114
116
  /** Strip the metadata comment from a raw line, returning the clean text and any extracted fields. */
115
- function stripBid(text) {
117
+ export function stripBid(text) {
116
118
  const m = text.match(METADATA_PATTERN);
117
119
  if (!m)
118
120
  return { clean: text };
@@ -170,9 +172,6 @@ export function canonicalTaskFilePath(phrenPath, project) {
170
172
  // phantom primary-store path.
171
173
  return storeAwareProjectPath(phrenPath, project, TASKS_FILENAME);
172
174
  }
173
- export function isTaskFileName(filename) {
174
- return filename.toLowerCase() === TASKS_FILENAME;
175
- }
176
175
  export function resolveTaskFilePath(phrenPath, project) {
177
176
  return canonicalTaskFilePath(phrenPath, project);
178
177
  }
@@ -342,6 +341,8 @@ function taskArchivePath(phrenPath, project) {
342
341
  return path.join(phrenPath, ".config", "task-archive", `${project}.md`);
343
342
  }
344
343
  export function readTasks(phrenPath, project) {
344
+ if (!moduleEnabled(phrenPath, "tasks"))
345
+ return phrenErr(disabledHint("tasks"), PhrenError.VALIDATION_ERROR);
345
346
  const ensured = ensureProject(phrenPath, project);
346
347
  if (!ensured.ok)
347
348
  return forwardErr(ensured);
@@ -1,8 +1,10 @@
1
+ import { activateModules, moduleSnapshot } from "./modules/runtime.js";
2
+ import { disabledCommand } from "./cli-registry.js";
1
3
  import * as fs from "fs";
2
4
  import * as path from "path";
3
5
  import { errorMessage } from "./utils.js";
4
6
  import { logger } from "./logger.js";
5
- import { defaultPhrenPath, ensureFtsCacheRootPrivate, expandHomePath, getPhrenPath, readRootManifest, } from "./shared.js";
7
+ import { defaultPhrenPath, findPhrenPath, ensureFtsCacheRootPrivate, expandHomePath, getPhrenPath, readRootManifest, } from "./shared.js";
6
8
  import { resolveRuntimeProfile } from "./runtime-profile.js";
7
9
  import { VERSION } from "./package-metadata.js";
8
10
  import { TOPIC_ORDER, helpTopicNames, lookupCommand, } from "./cli-registry.js";
@@ -28,7 +30,8 @@ export function resolveTopLevelInvocation(argv) {
28
30
  return { kind: "mcp", phrenArg: positional };
29
31
  }
30
32
  if (argvCommand === "--help" || argvCommand === "-h") {
31
- return { kind: "help" };
33
+ // `phren --help all` reads like `phren help all`, so it does the same.
34
+ return argv.length > 1 ? { kind: "manage", argv } : { kind: "help" };
32
35
  }
33
36
  if (argvCommand === "--version" || argvCommand === "-v" || argvCommand === "version") {
34
37
  return { kind: "version" };
@@ -45,7 +48,7 @@ export function resolveTopLevelInvocation(argv) {
45
48
  return { kind: "manage", argv };
46
49
  }
47
50
  export function printIntegratedHelp() {
48
- console.log(formatCheatSheet());
51
+ console.log(formatCheatSheet(helpSnapshot()));
49
52
  }
50
53
  export function printIntegratedVersion() {
51
54
  console.log(`phren v${VERSION}`);
@@ -68,24 +71,38 @@ function buildCliContext() {
68
71
  profile: () => resolveRuntimeProfile(getPhrenPath()),
69
72
  };
70
73
  }
74
+ function helpSnapshot() {
75
+ try {
76
+ return moduleSnapshot(findPhrenPath() ?? defaultPhrenPath());
77
+ }
78
+ catch {
79
+ return undefined;
80
+ }
81
+ }
71
82
  async function runHelp(args) {
83
+ const snapshot = helpSnapshot();
72
84
  const target = args[0]?.toLowerCase();
73
85
  if (!target) {
74
- console.log(formatCheatSheet());
86
+ console.log(formatCheatSheet(helpSnapshot()));
75
87
  return finish();
76
88
  }
77
89
  if (target === "all") {
78
- console.log(formatFullHelp());
90
+ console.log(formatFullHelp(snapshot));
79
91
  return finish();
80
92
  }
81
93
  // Topic precedence: a name that's both a topic and a command (e.g. "projects",
82
94
  // "skills") shows the topic view, which lists every command in that group.
83
95
  // Matches the legacy HELP_TOPICS behavior.
84
96
  if (TOPIC_ORDER.includes(target)) {
85
- console.log(formatTopic(target));
97
+ console.log(formatTopic(target, snapshot));
86
98
  return finish();
87
99
  }
88
- const cmdHelp = formatCommand(target);
100
+ const unavailable = snapshot && disabledCommand([target, ...args.slice(1)].join(" "), snapshot);
101
+ if (unavailable) {
102
+ console.log(unavailable);
103
+ return finish();
104
+ }
105
+ const cmdHelp = formatCommand(target, snapshot);
89
106
  if (cmdHelp !== null) {
90
107
  console.log(cmdHelp);
91
108
  return finish();
@@ -114,7 +131,7 @@ export async function runTopLevelCommand(argv, opts = {}) {
114
131
  if (!argvCommand) {
115
132
  if (process.stdin.isTTY && process.stdout.isTTY) {
116
133
  if (opts.allowDefaultShell === false) {
117
- console.log(formatCheatSheet());
134
+ console.log(formatCheatSheet(helpSnapshot()));
118
135
  return finish();
119
136
  }
120
137
  const shellCmd = lookupCommand("shell");
@@ -127,14 +144,31 @@ export async function runTopLevelCommand(argv, opts = {}) {
127
144
  const cmd = lookupCommand(argvCommand);
128
145
  if (!cmd)
129
146
  return false;
147
+ let snapshot;
148
+ try {
149
+ const store = findPhrenPath() ?? defaultPhrenPath();
150
+ snapshot = ["modules", "init", "quickstart", "verify", "uninstall", "doctor"].includes(cmd.name) || argv.includes("--help") || argv.includes("-h")
151
+ ? moduleSnapshot(store) : activateModules(store);
152
+ const unavailable = disabledCommand([cmd.name, ...argv.slice(1)].join(" "), snapshot);
153
+ if (unavailable) {
154
+ console.error(unavailable);
155
+ return finish(1);
156
+ }
157
+ }
158
+ catch (error) {
159
+ if (!["init", "modules", "doctor", "verify", "uninstall", "link"].includes(cmd.name)) {
160
+ console.error(errorMessage(error));
161
+ return finish(1);
162
+ }
163
+ }
130
164
  // Any command can end up building or reading the FTS snapshot cache, which
131
165
  // is a SQLite export of the whole store landing in os.tmpdir() — /tmp (1777)
132
166
  // on Linux and WSL. Harden the per-user cache root before the command runs.
133
167
  ensureFtsCacheRootPrivate();
134
168
  // Intercept before any handler runs - in particular before namespace
135
169
  // handlers that used to print their own per-subcommand help text.
136
- if (argv.includes("--help") || argv.includes("-h")) {
137
- const out = formatCommand(cmd.name);
170
+ if (argv.includes("--help") || argv.includes("-h") || (argv.length === 1 && ["maintain", "config", "bridge"].includes(cmd.name))) {
171
+ const out = formatCommand(cmd.name, snapshot);
138
172
  if (out)
139
173
  console.log(out);
140
174
  return finish();
@@ -0,0 +1,2 @@
1
+ import { type Adapter } from "./types.js";
2
+ export declare const claude: Adapter;
@@ -0,0 +1,7 @@
1
+ import { uuid } from "./types.js";
2
+ export const claude = {
3
+ command: "claude",
4
+ argv: o => ["-p", "--output-format", "stream-json", "--verbose", "--model", o.model,
5
+ ...(o.review ? ["--permission-mode", "plan"] : []), ...(o.resume ? ["--resume", o.resume] : []), ...(o.extra ?? [])],
6
+ session: event => uuid(event.session_id),
7
+ };
@@ -0,0 +1,2 @@
1
+ import { type Adapter } from "./types.js";
2
+ export declare const codex: Adapter;
@@ -0,0 +1,9 @@
1
+ import * as path from "node:path";
2
+ import { uuid } from "./types.js";
3
+ export const codex = {
4
+ command: "codex",
5
+ argv: o => ["exec", ...(o.resume ? ["resume"] : []), "--json",
6
+ ...(!o.resume ? ["--sandbox", o.review ? "read-only" : "workspace-write", "-C", o.worktree] : []),
7
+ "-o", path.join(o.job, "final.txt"), ...(o.model ? ["-m", o.model] : []), ...(o.extra ?? []), ...(o.resume ? [o.resume] : []), "-"],
8
+ session: event => event.type === "thread.started" ? uuid(event.thread_id) : undefined,
9
+ };
@@ -0,0 +1,4 @@
1
+ import type { Adapter } from "./types.js";
2
+ /** `opencode run` rejects every permission ask itself, so a worker runs under
3
+ * `opencode serve` and the launcher drives its session over HTTP. */
4
+ export declare const opencode: Adapter;
@@ -0,0 +1,9 @@
1
+ import { driveOpencode } from "../opencode-serve.js";
2
+ /** `opencode run` rejects every permission ask itself, so a worker runs under
3
+ * `opencode serve` and the launcher drives its session over HTTP. */
4
+ export const opencode = {
5
+ command: "opencode",
6
+ argv: () => ["serve", "--hostname", "127.0.0.1", "--port", "0"],
7
+ session: event => typeof event.sessionID === "string" && /^ses_[0-9a-z]{1,64}$/i.test(event.sessionID) ? event.sessionID : undefined,
8
+ drive: driveOpencode,
9
+ };
@@ -0,0 +1,21 @@
1
+ import type { ChildProcess } from "node:child_process";
2
+ import type { DriveOptions } from "../opencode-serve.js";
3
+ export type Provider = "codex" | "opencode" | "claude";
4
+ export interface LaunchOptions {
5
+ model: string;
6
+ worktree: string;
7
+ job: string;
8
+ review?: boolean;
9
+ resume?: string;
10
+ variant?: string;
11
+ extra?: string[];
12
+ }
13
+ export interface Adapter {
14
+ command: Provider;
15
+ argv(options: LaunchOptions): string[];
16
+ session(event: Record<string, unknown>): string | undefined;
17
+ /** A harness that serves an API instead of printing events: the launcher
18
+ * spawns `argv` and this drives the worker, returning its exit code. */
19
+ drive?(child: ChildProcess, options: DriveOptions): Promise<number>;
20
+ }
21
+ export declare function uuid(value: unknown): string | undefined;
@@ -0,0 +1,3 @@
1
+ export function uuid(value) {
2
+ return typeof value === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value) ? value : undefined;
3
+ }
@@ -0,0 +1,2 @@
1
+ import type { CliContext } from "../cli-registry.js";
2
+ export declare function runFanout(args: string[], ctx: CliContext): Promise<number | void>;
@@ -0,0 +1,78 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import * as yaml from "js-yaml";
4
+ import { withFileLock } from "../governance/locks.js";
5
+ import { archiveFinishedFanouts } from "../bridge/fanouts.js";
6
+ import { defaultPolicy, policySchema, pick } from "./picker.js";
7
+ import { readUsage, recentProviderErrors } from "./usage.js";
8
+ import { createJob, jobsRoot, launch, listJobs, readJob, swiftBuildCount } from "./launcher.js";
9
+ export async function runFanout(args, ctx) {
10
+ const [action, ...rest] = args, store = ctx.phrenPath();
11
+ if (action === "usage") {
12
+ console.log("Provider\tWindow\tUsed\tResets");
13
+ for (const account of await readUsage()) {
14
+ if (!account.windows.length)
15
+ console.log(`${account.source}\t${account.message ?? "Usage unavailable"}`);
16
+ for (const window of account.windows)
17
+ console.log(`${account.source}\t${window.name}\t${window.usedPercent === undefined ? "unknown" : window.usedPercent + " percent"}\t${window.resetsAt ?? "unknown"}`);
18
+ }
19
+ return;
20
+ }
21
+ if (action === "list") {
22
+ for (const job of listJobs(store))
23
+ console.log(`${job.id}\t${job.status}\t${job.provider}/${job.model}\t${job.taskLabel}`);
24
+ return;
25
+ }
26
+ if (action === "archive") {
27
+ if (rest.some(arg => arg !== "--dry-run"))
28
+ throw new Error("Usage: phren fanout archive [--dry-run]");
29
+ console.log(await archiveFinishedFanouts({ ...process.env, PHREN_PATH: store }, { dryRun: rest.includes("--dry-run") }));
30
+ return;
31
+ }
32
+ if (!["run", "resume", "review"].includes(action))
33
+ throw new Error("Usage: phren fanout run|usage|resume|review|list|archive");
34
+ const previous = action === "run" ? undefined : readJob(store, rest.shift() ?? "");
35
+ const flags = {}, extra = [];
36
+ while (rest.length) {
37
+ const key = rest.shift(), value = rest.shift();
38
+ if (!["--tier", "--provider", "--model", "--label", "--worktree", "--variant", "--extra"].includes(key) || !value)
39
+ throw new Error(`Invalid fan-out option ${key}`);
40
+ if (key === "--extra")
41
+ extra.push(value);
42
+ else
43
+ flags[key.slice(2)] = value;
44
+ }
45
+ const tier = flags.tier ?? (action === "review" ? "review" : "narrow");
46
+ if (!["narrow", "wide", "review"].includes(tier))
47
+ throw new Error("Choose tier narrow, wide or review.");
48
+ if (previous && !previous.session)
49
+ throw new Error("This job has no resumable session.");
50
+ if (previous && flags.provider && flags.provider !== previous.provider)
51
+ throw new Error("Resume must use the job's original provider.");
52
+ if (previous && flags.worktree && path.resolve(flags.worktree) !== path.resolve(previous.worktree))
53
+ throw new Error("Resume must use the job's original worktree.");
54
+ const label = flags.label ?? previous?.taskLabel, worktree = flags.worktree ?? previous?.worktree;
55
+ if (!label || !worktree)
56
+ throw new Error("phren fanout run needs --label and --worktree.");
57
+ let prompt = action === "review" && process.stdin.isTTY ? "Review your changes for correctness and regressions. Report findings without editing files." : fs.readFileSync(0, "utf8");
58
+ if (!prompt.trim() && action === "review")
59
+ prompt = "Review your changes for correctness and regressions. Report findings without editing files.";
60
+ if (!prompt.trim())
61
+ throw new Error("Provide a brief on stdin.");
62
+ const file = path.join(store, ".config", "fanout.yaml");
63
+ const policy = fs.existsSync(file) ? policySchema.parse(yaml.load(fs.readFileSync(file, "utf8"), { schema: yaml.CORE_SCHEMA })) : defaultPolicy;
64
+ const usage = await readUsage(), errors = recentProviderErrors(), needsSwift = /\b(swift|xcodebuild|ios)\b/i.test(prompt);
65
+ fs.mkdirSync(jobsRoot(store), { recursive: true, mode: 0o700 });
66
+ const reserved = withFileLock(path.join(jobsRoot(store), "launch"), () => {
67
+ const running = listJobs(store).filter(job => !fs.existsSync(path.join(jobsRoot(store), job.id, "exit.txt")));
68
+ const chosen = pick({ policy, tier: tier, usage, errors, running, swiftBuilds: needsSwift ? swiftBuildCount() : 0, needsSwift,
69
+ override: { provider: (flags.provider ?? previous?.provider), model: flags.model ?? previous?.model } });
70
+ // An OpenCode worker is driven over HTTP; there is no command line to extend.
71
+ if (chosen.provider === "opencode" && extra.length)
72
+ throw new Error("OpenCode workers take no --extra arguments.");
73
+ console.log(chosen.reason);
74
+ const options = { ...chosen, store, label, worktree, prompt, review: tier === "review", resume: previous?.session, variant: flags.variant, extra };
75
+ return { options, reservation: createJob(options) };
76
+ });
77
+ return launch(reserved.options, reserved.reservation);
78
+ }
@@ -0,0 +1,27 @@
1
+ import { type FanoutManifest } from "../bridge/fanouts.js";
2
+ import { type LaunchOptions, type Provider } from "./adapters/types.js";
3
+ export declare const adapters: {
4
+ codex: import("./adapters/types.js").Adapter;
5
+ opencode: import("./adapters/types.js").Adapter;
6
+ claude: import("./adapters/types.js").Adapter;
7
+ };
8
+ export interface JobOptions extends Omit<LaunchOptions, "job"> {
9
+ store: string;
10
+ provider: Provider;
11
+ label: string;
12
+ reason: string;
13
+ prompt: string;
14
+ }
15
+ export declare function jobsRoot(store: string): string;
16
+ export declare function readJob(store: string, id: string): FanoutManifest;
17
+ export declare function listJobs(store: string): FanoutManifest[];
18
+ export declare function swiftBuildCount(): number;
19
+ export declare function writeManifest(job: string, manifest: FanoutManifest): void;
20
+ export declare function createJob(options: JobOptions, env?: NodeJS.ProcessEnv): {
21
+ job: string;
22
+ manifest: FanoutManifest;
23
+ };
24
+ export declare function launch(options: JobOptions, reservation?: {
25
+ job: string;
26
+ manifest: FanoutManifest;
27
+ }): Promise<number>;
@@ -0,0 +1,156 @@
1
+ import { spawn, execFileSync } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import * as fs from "node:fs";
4
+ import * as path from "node:path";
5
+ import { atomicWriteText } from "../phren-paths.js";
6
+ import { manifestSchema } from "../bridge/fanouts.js";
7
+ import { codex } from "./adapters/codex.js";
8
+ import { opencode } from "./adapters/opencode.js";
9
+ import { claude } from "./adapters/claude.js";
10
+ import { uuid } from "./adapters/types.js";
11
+ import { LoopWatchdog, stderrRefusal } from "./watchdog.js";
12
+ export const adapters = { codex, opencode, claude };
13
+ export function jobsRoot(store) { return path.join(store, ".runtime", "agent-fanouts"); }
14
+ export function readJob(store, id) {
15
+ if (!/^[a-z0-9][a-z0-9._-]{0,127}$/i.test(id))
16
+ throw new Error("Invalid job id.");
17
+ const root = fs.realpathSync(jobsRoot(store)), job = path.join(root, id);
18
+ if (!fs.lstatSync(job).isDirectory() || fs.realpathSync(job) !== job)
19
+ throw new Error("Invalid job directory.");
20
+ const file = path.join(job, "manifest.json"), info = fs.lstatSync(file);
21
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 65_536)
22
+ throw new Error("Invalid job manifest.");
23
+ const result = manifestSchema.parse(JSON.parse(fs.readFileSync(file, "utf8")));
24
+ if (result.id !== id)
25
+ throw new Error("Job id does not match its manifest.");
26
+ return result;
27
+ }
28
+ export function listJobs(store) {
29
+ if (!fs.existsSync(jobsRoot(store)))
30
+ return [];
31
+ return fs.readdirSync(jobsRoot(store)).flatMap(id => { try {
32
+ return [readJob(store, id)];
33
+ }
34
+ catch {
35
+ return [];
36
+ } });
37
+ }
38
+ export function swiftBuildCount() {
39
+ const output = execFileSync("ps", ["-axo", "comm="], { encoding: "utf8", timeout: 5_000 });
40
+ return output.split("\n").filter(line => path.basename(line.trim()) === "xcodebuild").length;
41
+ }
42
+ export function writeManifest(job, manifest) {
43
+ atomicWriteText(path.join(job, "manifest.json"), JSON.stringify(manifestSchema.parse(manifest)) + "\n");
44
+ fs.chmodSync(path.join(job, "manifest.json"), 0o600);
45
+ }
46
+ export function createJob(options, env = process.env) {
47
+ if (!options.label.trim() || options.label.length > 200)
48
+ throw new Error("Choose a label of 1 to 200 characters.");
49
+ const worktree = fs.realpathSync(options.worktree);
50
+ if (!fs.statSync(worktree).isDirectory())
51
+ throw new Error("Choose a worktree directory.");
52
+ const id = `${options.provider}-${randomBytes(12).toString("hex")}`;
53
+ const root = jobsRoot(options.store), job = path.join(root, id);
54
+ fs.mkdirSync(job, { recursive: true, mode: 0o700 });
55
+ fs.chmodSync(root, 0o700);
56
+ const codexParent = uuid(env.CODEX_THREAD_ID || env.CODEX_SESSION_ID), claudeParent = uuid(env.CLAUDE_CODE_SESSION_ID);
57
+ const now = new Date().toISOString();
58
+ const manifest = { schemaVersion: 1, id, provider: options.provider, taskLabel: options.label,
59
+ cwd: worktree, worktree, model: options.model, eventLog: "events.jsonl", createdAt: now, startedAt: now, updatedAt: now,
60
+ status: "running", reason: options.reason, ...(options.resume ? { resumes: options.resume } : {}),
61
+ ...(codexParent ? { parent: { provider: "codex", session: codexParent } } : claudeParent ? { parent: { provider: "claude", session: claudeParent } } : {}) };
62
+ for (const [file, content] of Object.entries({ "prompt.txt": options.prompt, "events.jsonl": "", "stderr.log": "" }))
63
+ fs.writeFileSync(path.join(job, file), content, { mode: 0o600 });
64
+ writeManifest(job, manifest);
65
+ return { job, manifest };
66
+ }
67
+ export async function launch(options, reservation = createJob(options)) {
68
+ const { job, manifest } = reservation, adapter = adapters[options.provider];
69
+ console.log(job);
70
+ const out = fs.openSync(path.join(job, manifest.eventLog), "a"), err = fs.openSync(path.join(job, "stderr.log"), "a");
71
+ // A served harness answers only with this password, so another local
72
+ // process cannot approve the worker's permission asks.
73
+ const password = randomBytes(24).toString("hex");
74
+ const child = spawn("nice", ["-n", "15", adapter.command, ...adapter.argv({ ...options, job })], {
75
+ cwd: manifest.worktree, env: { ...process.env, PHREN_FANOUT_JOB: manifest.id, PHREN_FANOUT_DIR: job,
76
+ ...(adapter.drive ? { PHREN_FANOUT_APPROVALS: "1", OPENCODE_SERVER_USERNAME: "opencode", OPENCODE_SERVER_PASSWORD: password } : {}) },
77
+ stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32",
78
+ });
79
+ let pending = "", stderr = "", cancelled = false;
80
+ const watchdog = new LoopWatchdog();
81
+ const kill = () => { try {
82
+ if (process.platform !== "win32" && child.pid)
83
+ process.kill(-child.pid, "SIGTERM");
84
+ else
85
+ child.kill("SIGTERM");
86
+ }
87
+ catch { /* Already exited. */ } };
88
+ const cancel = () => { cancelled = true; kill(); };
89
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"])
90
+ process.on(signal, cancel);
91
+ const record = (session) => { if (session && !manifest.session) {
92
+ manifest.session = session;
93
+ writeManifest(job, manifest);
94
+ } };
95
+ const events = (chunk) => {
96
+ fs.writeSync(out, typeof chunk === "string" ? chunk : chunk.toString("utf8"));
97
+ pending += chunk.toString();
98
+ let newline;
99
+ while ((newline = pending.indexOf("\n")) >= 0) {
100
+ const line = pending.slice(0, newline);
101
+ pending = pending.slice(newline + 1);
102
+ try {
103
+ const event = JSON.parse(line);
104
+ watchdog.observe(event);
105
+ record(adapter.session(event));
106
+ }
107
+ catch { /* Partial or non-JSON provider output. */ }
108
+ }
109
+ if (pending.length > 1_048_576)
110
+ pending = "";
111
+ };
112
+ if (!adapter.drive)
113
+ child.stdout?.on("data", events);
114
+ child.stderr?.on("data", (chunk) => { fs.writeSync(err, chunk); stderr = (stderr + chunk.toString("utf8")).slice(-16_384); });
115
+ child.stdin?.on("error", () => { });
116
+ child.stdin?.end(adapter.drive ? undefined : options.prompt);
117
+ const closed = new Promise(resolve => { child.once("error", error => { fs.writeSync(err, `${error.message}\n`); resolve(127); }); child.once("close", code => resolve(cancelled ? 130 : code ?? 1)); });
118
+ const timer = setInterval(() => {
119
+ const reason = watchdog.reason();
120
+ if (!reason)
121
+ return;
122
+ fs.writeFileSync(path.join(job, "looped.txt"), reason + "\n", { mode: 0o600 });
123
+ atomicWriteText(path.join(job, "blocked.json"), JSON.stringify({ type: "tool_loop", pattern: "", message: reason, at: new Date().toISOString() }));
124
+ kill();
125
+ }, 30_000);
126
+ let exitCode;
127
+ if (adapter.drive) {
128
+ // The served harness never exits on its own: the driver's result is the
129
+ // worker's, and the server stops once the session is done.
130
+ const driven = await Promise.race([
131
+ adapter.drive(child, { ...options, worktree: manifest.worktree, job, jobId: manifest.id, password, emit: events, session: record })
132
+ .catch(error => { fs.writeSync(err, `${error instanceof Error ? error.message : String(error)}\n`); return 1; }),
133
+ closed.then(code => code === 0 ? 1 : code)
134
+ ]);
135
+ kill();
136
+ await closed;
137
+ exitCode = cancelled ? 130 : driven;
138
+ }
139
+ else
140
+ exitCode = await closed;
141
+ clearInterval(timer);
142
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"])
143
+ process.off(signal, cancel);
144
+ fs.closeSync(out);
145
+ fs.closeSync(err);
146
+ const blockedFile = path.join(job, "blocked.json"), refusal = stderrRefusal(stderr);
147
+ if (refusal && !fs.existsSync(blockedFile))
148
+ atomicWriteText(blockedFile, JSON.stringify({ ...refusal, at: new Date().toISOString() }));
149
+ const blocked = fs.existsSync(blockedFile);
150
+ if (blocked)
151
+ console.error(`blocked: ${fs.readFileSync(blockedFile, "utf8").slice(0, 4000)}`);
152
+ fs.writeFileSync(path.join(job, "exit.txt"), `${exitCode}\n`, { mode: 0o600 });
153
+ writeManifest(job, { ...manifest, status: blocked ? "failed" : cancelled ? "cancelled" : exitCode === 0 ? "completed" : "failed",
154
+ exitCode, updatedAt: new Date().toISOString(), finishedAt: new Date().toISOString() });
155
+ return blocked && exitCode === 0 ? 1 : exitCode;
156
+ }
@@ -0,0 +1,24 @@
1
+ import type { ChildProcess } from "node:child_process";
2
+ import type { LaunchOptions } from "./adapters/types.js";
3
+ export declare const DENIED_FEEDBACK = "The owner denied this request from the phone. Do not retry it; continue without it and say in your final report what you could not do because of it.";
4
+ export declare const UNANSWERED_FEEDBACK = "Nobody answered this permission request in time. Do not retry it; continue without it and say in your final report what you could not do because of it.";
5
+ export interface DriveOptions extends LaunchOptions {
6
+ store: string;
7
+ label: string;
8
+ prompt: string;
9
+ jobId: string;
10
+ password: string;
11
+ /** One `opencode run --format json` event line for the job's event log. */
12
+ emit(line: string): void;
13
+ /** The worker's session, as soon as it exists. */
14
+ session(id: string): void;
15
+ }
16
+ /** Drives one fan-out worker through `opencode serve` and its HTTP API rather
17
+ * than `opencode run`, which rejects every permission ask on its own. The
18
+ * events it writes are the ones `opencode run --format json` prints, so the
19
+ * Hook's transcript readers and the loop watchdog read them unchanged. A
20
+ * permission ask becomes the same request file the Phren plugin writes for a
21
+ * pane, the Hook shows it on the phone under the worker's parent, and the
22
+ * owner's answer resumes the same session: Allow runs the call, Deny rejects it
23
+ * with feedback so the worker carries on and reports the refusal. */
24
+ export declare function driveOpencode(child: ChildProcess, o: DriveOptions): Promise<number>;