@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
@@ -0,0 +1,236 @@
1
+ import { nonInteractiveGitEnv } from "../utils-helpers.js";
2
+ import { execFile } from "node:child_process";
3
+ import { promisify } from "node:util";
4
+ import { realpathSync } from "node:fs";
5
+ import { readdir, readFile, stat, mkdir } from "node:fs/promises";
6
+ import { homedir } from "node:os";
7
+ import path from "node:path";
8
+ import { BridgeError } from "./protocol.js";
9
+ import { herdrRoot } from "./herdr.js";
10
+ import { phrenStoreRoot } from "./transcripts.js";
11
+ import { addProjectFromPath } from "../core/project.js";
12
+ import { getProjectOwnershipDefault, readProjectConfig } from "../project-config.js";
13
+ import { projectSlugFromPath } from "../phren-paths.js";
14
+ import { runBestEffortGit } from "../cli/session-git.js";
15
+ import { mergeStoreUpstream } from "../sync/store-merge.js";
16
+ import { countGit } from "./metrics.js";
17
+ import { storeCommitMessage } from "../machine-identity.js";
18
+ const exec = promisify(execFile);
19
+ const runEnrollStoreGit = async (cwd, args) => {
20
+ const result = await runBestEffortGit(args, cwd);
21
+ return { ok: result.ok, output: result.output ?? "", error: result.error };
22
+ };
23
+ const SEARCH_ROOTS = ["Sites", "Projects", "projects", "Code", "code", "dev", "src", "repos", "workspace"];
24
+ /** GitHub-style URLs only: https, or the ssh shorthand. No local paths, no
25
+ * `ext::` or other transports git would happily run. */
26
+ const CLONE_URL = /^(?:https:\/\/[a-z0-9.-]+\/[\w.-]+\/[\w.-]+?|git@[a-z0-9.-]+:[\w.-]+\/[\w.-]+?)(?:\.git)?\/?$/i;
27
+ function repoName(url) {
28
+ const last = url.replace(/\/+$/, "").split(/[/:]/).pop() ?? "";
29
+ return last.replace(/\.git$/i, "");
30
+ }
31
+ async function isRepository(directory) {
32
+ // `.git` is a folder for a checkout and a file for a worktree.
33
+ try {
34
+ await stat(path.join(directory, ".git"));
35
+ return true;
36
+ }
37
+ catch {
38
+ return false;
39
+ }
40
+ }
41
+ /** Every store project's registered source folder (real path), and the names
42
+ * themselves, so a candidate can be marked as already tracked. */
43
+ async function registeredSources(env) {
44
+ const store = phrenStoreRoot(env);
45
+ const paths = new Set(), names = new Set();
46
+ let entries = [];
47
+ try {
48
+ entries = (await readdir(store, { withFileTypes: true })).filter(e => e.isDirectory() && !e.name.startsWith(".")).map(e => e.name);
49
+ }
50
+ catch {
51
+ return { paths, names };
52
+ }
53
+ for (const project of entries) {
54
+ names.add(project);
55
+ const source = readProjectConfig(store, project).sourcePath;
56
+ if (typeof source === "string" && source) {
57
+ try {
58
+ paths.add(realpathSync.native(path.resolve(source)));
59
+ }
60
+ catch { /* not on this computer */ }
61
+ }
62
+ }
63
+ return { paths, names };
64
+ }
65
+ /** Git checkouts on this computer, newest activity first, then Herdr's
66
+ * saved workspaces, then one level under the usual project roots. */
67
+ export async function candidateRepos(activity, env = process.env) {
68
+ const registered = await registeredSources(env);
69
+ const found = [];
70
+ const seen = new Set();
71
+ const offer = async (directory, source, lastSeen) => {
72
+ let dir = path.resolve(directory);
73
+ try {
74
+ if (!(await stat(dir)).isDirectory())
75
+ return;
76
+ dir = realpathSync.native(dir);
77
+ }
78
+ catch {
79
+ return;
80
+ }
81
+ if (seen.has(dir) || !(await isRepository(dir)))
82
+ return;
83
+ seen.add(dir);
84
+ const name = projectSlugFromPath(dir);
85
+ found.push({ directory: dir, name, source, registered: registered.paths.has(dir) || registered.names.has(name), ...(lastSeen ? { lastSeen } : {}) });
86
+ };
87
+ // Where sessions ran: walk up to the repository root so a subfolder session
88
+ // still offers the checkout itself.
89
+ const toplevel = async (directory) => {
90
+ // A session folder may be gone (a worktree, a temp checkout); its nearest
91
+ // surviving parent still says which repository it was in.
92
+ let existing = directory;
93
+ while (!(await stat(existing).catch(() => undefined))) {
94
+ const parent = path.dirname(existing);
95
+ if (parent === existing)
96
+ return undefined;
97
+ existing = parent;
98
+ }
99
+ try {
100
+ countGit("enroll");
101
+ return (await exec("git", ["-C", existing, "rev-parse", "--show-toplevel"], { env: nonInteractiveGitEnv(), timeout: 5_000 })).stdout.trim() || undefined;
102
+ }
103
+ catch {
104
+ return undefined;
105
+ }
106
+ };
107
+ for (const event of [...activity].reverse()) {
108
+ const directory = typeof event.directory === "string" ? event.directory : undefined;
109
+ if (!directory || !path.isAbsolute(directory))
110
+ continue;
111
+ const root = await toplevel(directory);
112
+ if (root)
113
+ await offer(root, "activity", typeof event.at === "string" ? event.at : undefined);
114
+ }
115
+ try {
116
+ const session = JSON.parse(await readFile(path.join(herdrRoot(), "session.json"), "utf8"));
117
+ for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
118
+ const directory = JSON.parse(`"${match[1]}"`);
119
+ if (!path.isAbsolute(directory))
120
+ continue;
121
+ const root = await toplevel(directory);
122
+ if (root)
123
+ await offer(root, "herdr");
124
+ }
125
+ }
126
+ catch { /* no saved session */ }
127
+ const home = homedir();
128
+ for (const root of [...(env.PROJECTS_DIR ? [env.PROJECTS_DIR] : []), ...SEARCH_ROOTS.map(r => path.join(home, r))]) {
129
+ let children = [];
130
+ try {
131
+ children = (await readdir(root, { withFileTypes: true })).filter(e => e.isDirectory() && !e.name.startsWith(".")).map(e => path.join(root, e.name));
132
+ }
133
+ catch {
134
+ continue;
135
+ }
136
+ for (const child of children.slice(0, 200))
137
+ await offer(child, "search");
138
+ }
139
+ return found.slice(0, 64);
140
+ }
141
+ /** The folder new clones land in: `$PROJECTS_DIR`, else the first of the
142
+ * usual roots that exists, else `~/Projects` (created). */
143
+ async function cloneRoot(env) {
144
+ const home = homedir();
145
+ for (const root of [...(env.PROJECTS_DIR ? [env.PROJECTS_DIR] : []), ...SEARCH_ROOTS.filter(r => r !== "Sites").map(r => path.join(home, r))]) {
146
+ try {
147
+ if ((await stat(root)).isDirectory())
148
+ return root;
149
+ }
150
+ catch { /* next */ }
151
+ }
152
+ const fallback = path.join(home, "Projects");
153
+ await mkdir(fallback, { recursive: true });
154
+ return fallback;
155
+ }
156
+ /** Commit the store and push it when a remote exists, so the phone can pull
157
+ * the new project. Best effort: enrollment already succeeded. */
158
+ async function publishStore(store, project) {
159
+ const status = await runBestEffortGit(["status", "--porcelain"], store);
160
+ if (!status.ok)
161
+ return { store: "error", storeDetail: status.error };
162
+ if (!status.output)
163
+ return { store: "unchanged" };
164
+ const add = await runBestEffortGit(["add", "--sparse", "-A"], store);
165
+ // The same belt-and-suspenders unstage as the Stop hook's auto-save.
166
+ if (add.ok)
167
+ await runBestEffortGit(["reset", "HEAD", "--", ".env", "**/.env", "*.pem", "*.key", ".config/auth-profiles.json"], store);
168
+ const commit = add.ok ? await runBestEffortGit(["commit", "-m", storeCommitMessage(`Add project ${project} from iPhone`)], store) : add;
169
+ if (!commit.ok)
170
+ return { store: "error", storeDetail: commit.error };
171
+ const remotes = await runBestEffortGit(["remote"], store);
172
+ if (!remotes.ok || !remotes.output)
173
+ return { store: "committed", storeDetail: "no remote configured" };
174
+ const pull = await mergeStoreUpstream(store, { git: runEnrollStoreGit, commitLocalWrites: false });
175
+ if (pull.status !== "updated" && pull.status !== "unchanged")
176
+ return { store: "committed", storeDetail: pull.detail };
177
+ const push = await runBestEffortGit(["push"], store);
178
+ return push.ok ? { store: "pushed" } : { store: "committed", storeDetail: push.error };
179
+ }
180
+ export async function enrollProject(input, env = process.env) {
181
+ const store = phrenStoreRoot(env);
182
+ try {
183
+ if (!(await stat(path.join(store, ".config"))).isDirectory())
184
+ throw new Error();
185
+ }
186
+ catch {
187
+ throw new BridgeError(409, "phren is not set up on this computer. Run phren init there.");
188
+ }
189
+ let directory;
190
+ let cloned = false;
191
+ if (typeof input.cloneUrl === "string" && input.cloneUrl) {
192
+ const url = input.cloneUrl.trim();
193
+ if (url.length > 512 || !CLONE_URL.test(url))
194
+ throw new BridgeError(400, "Enter a GitHub repository URL (https://github.com/owner/repo).");
195
+ const name = repoName(url);
196
+ if (!name || name === "." || name === "..")
197
+ throw new BridgeError(400, "That URL has no repository name.");
198
+ directory = path.join(await cloneRoot(env), name);
199
+ try {
200
+ await stat(directory);
201
+ throw new BridgeError(409, `${directory} already exists on this computer. Add that folder instead.`);
202
+ }
203
+ catch (error) {
204
+ if (error instanceof BridgeError)
205
+ throw error;
206
+ }
207
+ try {
208
+ countGit("enroll");
209
+ await exec("git", ["clone", "--", url, directory], { timeout: 180_000, maxBuffer: 4_194_304, env: nonInteractiveGitEnv(env) });
210
+ }
211
+ catch (error) {
212
+ const detail = error instanceof Error && "stderr" in error ? String(error.stderr ?? "").trim().split("\n").pop() : undefined;
213
+ throw new BridgeError(502, `git clone failed${detail ? `: ${detail}` : ""}.`);
214
+ }
215
+ cloned = true;
216
+ }
217
+ else if (typeof input.directory === "string" && input.directory) {
218
+ const raw = input.directory;
219
+ if (raw.length > 4096 || raw.includes("\0") || !path.isAbsolute(raw))
220
+ throw new BridgeError(400, "Enter the full folder path on this computer.");
221
+ try {
222
+ directory = realpathSync.native(raw);
223
+ if (!(await stat(directory)).isDirectory())
224
+ throw new Error();
225
+ }
226
+ catch {
227
+ throw new BridgeError(404, "That folder is not on this computer.");
228
+ }
229
+ }
230
+ else
231
+ throw new BridgeError(400, "Choose a folder or a repository URL.");
232
+ const added = addProjectFromPath(store, directory, env.PHREN_PROFILE || undefined, getProjectOwnershipDefault(store));
233
+ if (!added.ok)
234
+ throw new BridgeError(409, added.error);
235
+ return { ok: true, project: added.data.project, directory, cloned, ...(await publishStore(store, added.data.project)) };
236
+ }
@@ -0,0 +1,74 @@
1
+ import { z } from "zod";
2
+ import { type FanoutManifest } from "./fanouts.js";
3
+ import { type Target } from "./protocol.js";
4
+ import { type ChildAgentRelation } from "./transcripts.js";
5
+ export declare const fanoutMessageSchema: z.ZodObject<{
6
+ target: z.ZodObject<{
7
+ server: z.ZodString;
8
+ workspace: z.ZodString;
9
+ tab: z.ZodString;
10
+ pane: z.ZodString;
11
+ source: z.ZodEnum<{
12
+ claude: "claude";
13
+ codex: "codex";
14
+ copilot: "copilot";
15
+ opencode: "opencode";
16
+ phren: "phren";
17
+ }>;
18
+ session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
19
+ }, z.core.$strip>;
20
+ child: z.ZodString;
21
+ text: z.ZodString;
22
+ }, z.core.$strict>;
23
+ declare const receiptSchema: z.ZodObject<{
24
+ id: z.ZodString;
25
+ text: z.ZodString;
26
+ status: z.ZodEnum<{
27
+ completed: "completed";
28
+ failed: "failed";
29
+ queued: "queued";
30
+ running: "running";
31
+ }>;
32
+ createdAt: z.ZodString;
33
+ }, z.core.$strip>;
34
+ export type FanoutMessage = z.infer<typeof receiptSchema>;
35
+ interface Job {
36
+ directory: string;
37
+ manifest: FanoutManifest;
38
+ }
39
+ interface Dependencies {
40
+ validate: (target: Target) => Promise<unknown>;
41
+ tree: (target: Target) => Promise<ChildAgentRelation[]>;
42
+ run?: (job: Job, text: string) => Promise<number>;
43
+ }
44
+ /** Durable per-job messages. A running receipt is never replayed after a Hook restart. */
45
+ export declare class FanoutMessages {
46
+ private readonly env;
47
+ private readonly deps;
48
+ private timer?;
49
+ private ticking;
50
+ constructor(env: NodeJS.ProcessEnv, deps: Dependencies);
51
+ start(): void;
52
+ close(): void;
53
+ private jobs;
54
+ private selected;
55
+ send(input: unknown): Promise<{
56
+ ok: true;
57
+ message: FanoutMessage;
58
+ }>;
59
+ /** Archive every finished worker of one live parent now, instead of after
60
+ * the sweep's 24 hours. The sweep's own checks apply: a job without an exit
61
+ * stamp, with a message lock or with queued messages stays put. */
62
+ archiveFinished(input: unknown): Promise<{
63
+ ok: true;
64
+ archived: number;
65
+ }>;
66
+ list(targetValue: unknown, childValue: unknown): Promise<{
67
+ messages: FanoutMessage[];
68
+ }>;
69
+ private messageDirectory;
70
+ private records;
71
+ tick(): Promise<void>;
72
+ private drain;
73
+ }
74
+ export {};
@@ -0,0 +1,230 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { appendFile, lstat, mkdir, readdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { z } from "zod";
5
+ import { archiveFinishedFanouts, containedFanoutRoot, fanoutChildID, manifestSchema, storeRoot } from "./fanouts.js";
6
+ import { atomic, BridgeError, targetSchema } from "./protocol.js";
7
+ import { childAgent } from "./transcripts.js";
8
+ import { countTick } from "./metrics.js";
9
+ export const fanoutMessageSchema = z.object({
10
+ target: targetSchema,
11
+ child: z.string().regex(/^[a-f0-9]{32}$/),
12
+ text: z.string().min(1).max(32768).refine(value => value.trim().length > 0 && !/[\x00-\x08\x0b-\x1f\x7f]/.test(value)),
13
+ }).strict();
14
+ const receiptSchema = z.object({
15
+ id: z.string().uuid(), text: z.string().max(32768),
16
+ status: z.enum(["queued", "running", "completed", "failed"]),
17
+ createdAt: z.string(),
18
+ });
19
+ /** Durable per-job messages. A running receipt is never replayed after a Hook restart. */
20
+ export class FanoutMessages {
21
+ env;
22
+ deps;
23
+ timer;
24
+ ticking = false;
25
+ constructor(env, deps) {
26
+ this.env = env;
27
+ this.deps = deps;
28
+ }
29
+ start() {
30
+ this.timer = setInterval(() => { countTick("fanout-messages"); void this.tick().catch(() => { }); }, 1000);
31
+ this.timer.unref();
32
+ void this.tick().catch(() => { });
33
+ }
34
+ close() { clearInterval(this.timer); }
35
+ async jobs() {
36
+ const root = await containedFanoutRoot(this.env);
37
+ if (!root)
38
+ return [];
39
+ const jobs = [];
40
+ for (const name of (await readdir(root)).slice(0, 1024)) {
41
+ const directory = path.join(root, name);
42
+ try {
43
+ if (!(await lstat(directory)).isDirectory() || await realpath(directory) !== directory)
44
+ continue;
45
+ const file = path.join(directory, "manifest.json"), info = await lstat(file);
46
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 65536)
47
+ continue;
48
+ const manifest = manifestSchema.parse(JSON.parse(await readFile(file, "utf8")));
49
+ if (manifest.id === name)
50
+ jobs.push({ directory, manifest });
51
+ }
52
+ catch { /* A torn or foreign job cannot receive input. */ }
53
+ }
54
+ return jobs;
55
+ }
56
+ async selected(target, child) {
57
+ await this.deps.validate(target);
58
+ const relation = childAgent(await this.deps.tree(target), child);
59
+ if (!relation?.fanout?.resumable)
60
+ throw new BridgeError(404, "That resumable worker is not part of this conversation.");
61
+ const root = await containedFanoutRoot(this.env);
62
+ const job = (await this.jobs()).find(job => root && fanoutChildID(root, job.manifest) === child);
63
+ if (!job || !job.manifest.session || !["codex", "opencode"].includes(job.manifest.provider)) {
64
+ throw new BridgeError(404, "That worker does not belong to this store.");
65
+ }
66
+ return job;
67
+ }
68
+ async send(input) {
69
+ const data = fanoutMessageSchema.parse(input);
70
+ const job = await this.selected(data.target, data.child);
71
+ const directory = await this.messageDirectory(job);
72
+ const message = { id: randomUUID(), text: data.text, status: "queued", createdAt: new Date().toISOString() };
73
+ const pending = (await this.records(job)).filter(row => row.message.status === "queued");
74
+ if (pending.length >= 32)
75
+ throw new BridgeError(429, "This worker already has 32 queued messages.");
76
+ const file = path.join(directory, `${message.createdAt.replace(/[:.]/g, "-")}-${message.id}.queued.json`);
77
+ await atomic(file, JSON.stringify(message));
78
+ await this.drain(job);
79
+ const fresh = (await this.records(job)).find(row => row.message.id === message.id)?.message;
80
+ return { ok: true, message: fresh ?? message };
81
+ }
82
+ /** Archive every finished worker of one live parent now, instead of after
83
+ * the sweep's 24 hours. The sweep's own checks apply: a job without an exit
84
+ * stamp, with a message lock or with queued messages stays put. */
85
+ async archiveFinished(input) {
86
+ const { target } = z.object({ target: targetSchema }).strict().parse(input);
87
+ await this.deps.validate(target);
88
+ const { moved } = await archiveFinishedFanouts(this.env, { olderThanMs: 0, parent: { session: target.session, provider: target.source } });
89
+ return { ok: true, archived: moved.length };
90
+ }
91
+ async list(targetValue, childValue) {
92
+ const target = targetSchema.parse(targetValue), child = fanoutMessageSchema.shape.child.parse(childValue);
93
+ const job = await this.selected(target, child);
94
+ return { messages: (await this.records(job)).map(row => row.message) };
95
+ }
96
+ async messageDirectory(job) {
97
+ const directory = path.join(job.directory, "messages");
98
+ await mkdir(directory, { recursive: true, mode: 0o700 });
99
+ if (await realpath(directory) !== directory)
100
+ throw new BridgeError(400, "Invalid worker message directory.");
101
+ return directory;
102
+ }
103
+ async records(job) {
104
+ const directory = path.join(job.directory, "messages");
105
+ const info = await lstat(directory).catch(() => undefined);
106
+ if (!info)
107
+ return [];
108
+ if (!info.isDirectory() || info.isSymbolicLink() || await realpath(directory) !== directory) {
109
+ throw new BridgeError(400, "Invalid worker message directory.");
110
+ }
111
+ const rows = [];
112
+ for (const name of (await readdir(directory)).sort().slice(-512)) {
113
+ if (!/^[0-9TZ-]+-[a-f0-9-]+\.(queued|sent)\.json$/.test(name))
114
+ continue;
115
+ const file = path.join(directory, name), info = await lstat(file);
116
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 262144)
117
+ continue;
118
+ try {
119
+ rows.push({ file, message: receiptSchema.parse(JSON.parse(await readFile(file, "utf8"))) });
120
+ }
121
+ catch { /* Ignore torn receipts. */ }
122
+ }
123
+ return rows;
124
+ }
125
+ async tick() {
126
+ if (this.ticking)
127
+ return;
128
+ this.ticking = true;
129
+ try {
130
+ for (const job of await this.jobs()) {
131
+ if (["queued", "running"].includes(job.manifest.status))
132
+ continue;
133
+ if ((await this.records(job).catch(() => [])).some(row => row.message.status === "queued"))
134
+ await this.drain(job).catch(() => { });
135
+ }
136
+ }
137
+ finally {
138
+ this.ticking = false;
139
+ }
140
+ }
141
+ async drain(job) {
142
+ const lock = path.join(job.directory, "message-lock");
143
+ try {
144
+ await mkdir(lock, { mode: 0o700 });
145
+ }
146
+ catch {
147
+ return;
148
+ }
149
+ let launched = false;
150
+ let pending;
151
+ let started;
152
+ try {
153
+ // Re-read under the job lock. The original launcher owns the manifest until it finishes.
154
+ const fresh = (await this.jobs()).find(candidate => candidate.directory === job.directory);
155
+ if (!fresh || ["queued", "running"].includes(fresh.manifest.status))
156
+ return;
157
+ if (!fresh.manifest.session || !["codex", "opencode"].includes(fresh.manifest.provider))
158
+ return;
159
+ const next = (await this.records(fresh)).find(row => row.message.status === "queued");
160
+ if (!next)
161
+ return;
162
+ pending = next;
163
+ if (!(await lstat(fresh.manifest.worktree)).isDirectory())
164
+ throw new BridgeError(409, "The worker's original worktree is unavailable.");
165
+ // Refuse redirected output files before the launcher opens them for writing.
166
+ for (const name of [fresh.manifest.eventLog, "events.jsonl", "stderr.log", "final.txt", "exit.txt", "blocked.json", "prompt.txt"]) {
167
+ const info = await lstat(path.join(fresh.directory, name)).catch(() => undefined);
168
+ if (info && (!info.isFile() || info.isSymbolicLink()))
169
+ throw new BridgeError(400, "Invalid worker output file.");
170
+ }
171
+ const round = path.join(fresh.directory, "rounds");
172
+ await mkdir(round, { recursive: true, mode: 0o700 });
173
+ if (await realpath(round) !== round)
174
+ throw new BridgeError(400, "Invalid worker round directory.");
175
+ const roundDir = path.join(round, next.message.id);
176
+ await mkdir(roundDir, { mode: 0o700 });
177
+ await writeFile(path.join(roundDir, "prompt.txt"), next.message.text, { mode: 0o600 });
178
+ for (const name of ["stderr.log", "final.txt", "exit.txt", "blocked.json", "prompt.txt"]) {
179
+ await rename(path.join(fresh.directory, name), path.join(roundDir, `previous-${name}`)).catch(error => {
180
+ if (error.code !== "ENOENT")
181
+ throw error;
182
+ });
183
+ }
184
+ await writeFile(path.join(fresh.directory, "prompt.txt"), next.message.text, { mode: 0o600 });
185
+ const sentFile = next.file.replace(/\.queued\.json$/, ".sent.json");
186
+ const message = { ...next.message, status: "running" };
187
+ await atomic(next.file, JSON.stringify(message));
188
+ await rename(next.file, sentFile);
189
+ pending = { file: sentFile, message };
190
+ const now = new Date().toISOString();
191
+ const manifest = { ...fresh.manifest, status: "running", updatedAt: now, startedAt: now,
192
+ resumes: fresh.manifest.session, finishedAt: undefined, exitCode: undefined };
193
+ await atomic(path.join(fresh.directory, "manifest.json"), JSON.stringify(manifest));
194
+ started = manifest;
195
+ await appendFile(path.join(fresh.directory, manifest.eventLog), JSON.stringify({
196
+ type: "phren/fanout-message", timestamp: now, id: message.id, text: message.text,
197
+ }) + "\n", { mode: 0o600 });
198
+ const run = this.deps.run ?? (async (job, text) => {
199
+ const { launch } = await import("../fanout/launcher.js");
200
+ return launch({ store: storeRoot(this.env), provider: job.manifest.provider, label: job.manifest.taskLabel,
201
+ reason: job.manifest.reason ?? "Continue worker", model: job.manifest.model ?? "", worktree: job.manifest.worktree,
202
+ resume: job.manifest.session, prompt: text }, { job: job.directory, manifest: job.manifest });
203
+ });
204
+ launched = true;
205
+ void run({ ...fresh, manifest }, message.text).then(async (code) => {
206
+ await atomic(sentFile, JSON.stringify({ ...message, status: code === 0 ? "completed" : "failed" }));
207
+ }).catch(async () => {
208
+ await atomic(sentFile, JSON.stringify({ ...message, status: "failed" }));
209
+ await atomic(path.join(fresh.directory, "manifest.json"), JSON.stringify({ ...manifest, status: "failed", finishedAt: new Date().toISOString() }));
210
+ }).finally(async () => { await rm(lock, { recursive: true, force: true }); }).catch(() => { });
211
+ }
212
+ catch (error) {
213
+ if (!pending)
214
+ throw error;
215
+ // Once accepted, report a failed receipt instead of leaving a hidden queued
216
+ // message behind an HTTP error that would invite the person to resend it.
217
+ await atomic(pending.file, JSON.stringify({ ...pending.message, status: "failed" }));
218
+ if (pending.file.endsWith(".queued.json"))
219
+ await rename(pending.file, pending.file.replace(/\.queued\.json$/, ".sent.json"));
220
+ if (started)
221
+ await atomic(path.join(job.directory, "manifest.json"), JSON.stringify({
222
+ ...started, status: "failed", finishedAt: new Date().toISOString(),
223
+ }));
224
+ }
225
+ finally {
226
+ if (!launched)
227
+ await rm(lock, { recursive: true, force: true });
228
+ }
229
+ }
230
+ }