@phren/cli 0.2.15 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (392) 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 +195 -2
  7. package/dist/bridge/agent-hooks.js +1049 -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 +23 -0
  15. package/dist/bridge/code-note.js +51 -0
  16. package/dist/bridge/code-routes.d.ts +151 -0
  17. package/dist/bridge/code-routes.js +442 -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 +125 -0
  33. package/dist/bridge/dispatch-returns.js +283 -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 +210 -0
  37. package/dist/bridge/dispatch.js +286 -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 +28 -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 +61 -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 +54 -0
  96. package/dist/bridge/schedule-watch.js +255 -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 +36 -0
  104. package/dist/bridge/server-pane-routes.js +479 -0
  105. package/dist/bridge/server-routes.d.ts +108 -0
  106. package/dist/bridge/server-routes.js +556 -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 +96 -0
  136. package/dist/bridge/transcript-preview.js +491 -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 +46545 -21051
  146. package/dist/cli/actions.js +14 -1
  147. package/dist/cli/config-policy.js +25 -0
  148. package/dist/cli/config-proactivity.d.ts +3 -1
  149. package/dist/cli/config-proactivity.js +35 -3
  150. package/dist/cli/config.js +4 -1
  151. package/dist/cli/extract.d.ts +0 -8
  152. package/dist/cli/extract.js +4 -7
  153. package/dist/cli/govern.js +5 -2
  154. package/dist/cli/hooks-globs.js +1 -1
  155. package/dist/cli/hooks.d.ts +1 -1
  156. package/dist/cli/hooks.js +9 -7
  157. package/dist/cli/namespaces-projects.js +12 -6
  158. package/dist/cli/namespaces-store.js +37 -6
  159. package/dist/cli/namespaces-tasks.js +1 -1
  160. package/dist/cli/schedules.d.ts +1 -0
  161. package/dist/cli/schedules.js +164 -0
  162. package/dist/cli/session-background.js +1 -1
  163. package/dist/cli/session-git.d.ts +8 -5
  164. package/dist/cli/session-git.js +45 -120
  165. package/dist/cli/session-start.js +3 -1
  166. package/dist/cli/session-stop.js +19 -8
  167. package/dist/cli/team.js +13 -10
  168. package/dist/cli-handlers.d.ts +1 -1
  169. package/dist/cli-handlers.js +8 -4
  170. package/dist/cli-help.d.ts +5 -4
  171. package/dist/cli-help.js +15 -15
  172. package/dist/cli-registry.d.ts +4 -1
  173. package/dist/cli-registry.js +119 -6
  174. package/dist/content/archive.js +2 -2
  175. package/dist/content/citation.d.ts +11 -0
  176. package/dist/content/citation.js +18 -0
  177. package/dist/content/learning.js +2 -0
  178. package/dist/content/summarize.d.ts +14 -15
  179. package/dist/content/summarize.js +60 -5
  180. package/dist/content/validate.d.ts +17 -4
  181. package/dist/content/validate.js +200 -122
  182. package/dist/core/project-registry.d.ts +26 -0
  183. package/dist/core/project-registry.js +573 -0
  184. package/dist/core/project.js +2 -3
  185. package/dist/data/access.d.ts +16 -1
  186. package/dist/data/access.js +31 -3
  187. package/dist/data/tasks.d.ts +18 -3
  188. package/dist/data/tasks.js +8 -7
  189. package/dist/entrypoint.js +44 -10
  190. package/dist/fanout/adapters/claude.d.ts +2 -0
  191. package/dist/fanout/adapters/claude.js +7 -0
  192. package/dist/fanout/adapters/codex.d.ts +2 -0
  193. package/dist/fanout/adapters/codex.js +9 -0
  194. package/dist/fanout/adapters/opencode.d.ts +4 -0
  195. package/dist/fanout/adapters/opencode.js +9 -0
  196. package/dist/fanout/adapters/types.d.ts +21 -0
  197. package/dist/fanout/adapters/types.js +3 -0
  198. package/dist/fanout/command.d.ts +2 -0
  199. package/dist/fanout/command.js +78 -0
  200. package/dist/fanout/launcher.d.ts +27 -0
  201. package/dist/fanout/launcher.js +156 -0
  202. package/dist/fanout/opencode-serve.d.ts +24 -0
  203. package/dist/fanout/opencode-serve.js +191 -0
  204. package/dist/fanout/picker.d.ts +91 -0
  205. package/dist/fanout/picker.js +51 -0
  206. package/dist/fanout/usage.d.ts +5 -0
  207. package/dist/fanout/usage.js +51 -0
  208. package/dist/fanout/watchdog.d.ts +10 -0
  209. package/dist/fanout/watchdog.js +27 -0
  210. package/dist/filenames.d.ts +9 -0
  211. package/dist/filenames.js +11 -0
  212. package/dist/finding/context.js +4 -22
  213. package/dist/generated/memory-ui-graph.browser.js +525 -419
  214. package/dist/governance/policy-constants.d.ts +11 -0
  215. package/dist/governance/policy-constants.js +9 -0
  216. package/dist/governance/policy.d.ts +5 -8
  217. package/dist/governance/policy.js +11 -8
  218. package/dist/graph-core/camera.d.ts +24 -0
  219. package/dist/graph-core/camera.js +18 -0
  220. package/dist/graph-core/index.d.ts +2 -0
  221. package/dist/graph-core/index.js +2 -0
  222. package/dist/graph-core/labels.d.ts +77 -0
  223. package/dist/graph-core/labels.js +124 -0
  224. package/dist/graph-core/model.d.ts +13 -0
  225. package/dist/graph-core/model.js +33 -0
  226. package/dist/graph-core/types.d.ts +2 -0
  227. package/dist/home-paths.d.ts +7 -0
  228. package/dist/home-paths.js +21 -0
  229. package/dist/hooks.d.ts +3 -15
  230. package/dist/hooks.js +14 -1
  231. package/dist/index.js +24 -2
  232. package/dist/init/guard-globals.d.ts +1 -1
  233. package/dist/init/guard-globals.js +4 -4
  234. package/dist/init/init-configure.js +3 -3
  235. package/dist/init/init-uninstall.js +15 -5
  236. package/dist/init/init-walkthrough.js +1 -1
  237. package/dist/init/init.js +26 -6
  238. package/dist/init/management-preset.d.ts +1 -1
  239. package/dist/init/management-preset.js +2 -2
  240. package/dist/init/preferences.js +1 -1
  241. package/dist/init/self-wiring.js +1 -1
  242. package/dist/init/setup.d.ts +3 -26
  243. package/dist/init/setup.js +68 -593
  244. package/dist/init/shared.js +2 -0
  245. package/dist/init/store-gitignore.d.ts +1 -6
  246. package/dist/init/store-gitignore.js +2 -8
  247. package/dist/init/teardown.d.ts +1 -1
  248. package/dist/init/teardown.js +2 -2
  249. package/dist/link/context-imports.d.ts +15 -0
  250. package/dist/link/context-imports.js +101 -0
  251. package/dist/link/context.js +1 -1
  252. package/dist/link/doctor.d.ts +22 -1
  253. package/dist/link/doctor.js +128 -58
  254. package/dist/link/link.js +29 -61
  255. package/dist/link/refresh.js +2 -2
  256. package/dist/link/skills.js +26 -5
  257. package/dist/machine-identity.d.ts +3 -0
  258. package/dist/machine-identity.js +6 -0
  259. package/dist/mcp/profile.d.ts +2 -19
  260. package/dist/mcp/profile.js +64 -22
  261. package/dist/memory-ui-graph.runtime.js +525 -419
  262. package/dist/modules/code-package.d.ts +16 -0
  263. package/dist/modules/code-package.js +160 -0
  264. package/dist/modules/command.d.ts +2 -0
  265. package/dist/modules/command.js +67 -0
  266. package/dist/modules/config.d.ts +4 -0
  267. package/dist/modules/config.js +70 -0
  268. package/dist/modules/manifest.d.ts +41 -0
  269. package/dist/modules/manifest.js +1 -0
  270. package/dist/modules/provision.d.ts +3 -0
  271. package/dist/modules/provision.js +84 -0
  272. package/dist/modules/registry.d.ts +16 -0
  273. package/dist/modules/registry.js +250 -0
  274. package/dist/modules/runtime.d.ts +15 -0
  275. package/dist/modules/runtime.js +59 -0
  276. package/dist/package-metadata.js +10 -2
  277. package/dist/phren-dotenv.js +4 -2
  278. package/dist/phren-paths.d.ts +3 -2
  279. package/dist/phren-paths.js +4 -5
  280. package/dist/profile-store.js +43 -8
  281. package/dist/project-config.d.ts +19 -1
  282. package/dist/project-config.js +29 -3
  283. package/dist/project-topics.d.ts +1 -0
  284. package/dist/project-topics.js +13 -10
  285. package/dist/provider-adapters.js +1 -4
  286. package/dist/query-correlation.js +6 -6
  287. package/dist/session/artifacts.js +5 -5
  288. package/dist/session/checkpoints.js +5 -0
  289. package/dist/session/utils.d.ts +2 -2
  290. package/dist/session/utils.js +6 -6
  291. package/dist/shared/content.d.ts +1 -1
  292. package/dist/shared/content.js +1 -1
  293. package/dist/shared/data-utils.js +1 -1
  294. package/dist/shared/fragment-graph.d.ts +1 -1
  295. package/dist/shared/fragment-graph.js +5 -5
  296. package/dist/shared/index.js +48 -7
  297. package/dist/shared/retrieval.d.ts +18 -3
  298. package/dist/shared/retrieval.js +101 -12
  299. package/dist/shared/search-fallback.js +4 -6
  300. package/dist/shared/sqljs.d.ts +2 -0
  301. package/dist/shared/sqljs.js +4 -2
  302. package/dist/shared.d.ts +0 -1
  303. package/dist/shared.js +0 -1
  304. package/dist/shell/input.d.ts +1 -5
  305. package/dist/shell/input.js +16 -10
  306. package/dist/shell/palette.d.ts +2 -2
  307. package/dist/shell/palette.js +3 -7
  308. package/dist/shell/render.d.ts +3 -1
  309. package/dist/shell/render.js +4 -4
  310. package/dist/shell/shell.js +4 -1
  311. package/dist/shell/types.d.ts +1 -0
  312. package/dist/shell/types.js +4 -0
  313. package/dist/shell/view.d.ts +0 -4
  314. package/dist/shell/view.js +19 -27
  315. package/dist/skill/registry.js +25 -17
  316. package/dist/skill/state.d.ts +3 -0
  317. package/dist/skill/state.js +13 -7
  318. package/dist/status.js +38 -17
  319. package/dist/store-registry.d.ts +44 -18
  320. package/dist/store-registry.js +169 -60
  321. package/dist/store-weight.d.ts +1 -6
  322. package/dist/store-weight.js +4 -2
  323. package/dist/sync/auth-doctor.d.ts +8 -0
  324. package/dist/sync/auth-doctor.js +27 -0
  325. package/dist/sync/auth.d.ts +27 -0
  326. package/dist/sync/auth.js +114 -0
  327. package/dist/sync/conflict-resolve.d.ts +9 -0
  328. package/dist/sync/conflict-resolve.js +146 -0
  329. package/dist/sync/git-state.d.ts +4 -0
  330. package/dist/sync/git-state.js +49 -0
  331. package/dist/sync/outcome.d.ts +34 -0
  332. package/dist/sync/outcome.js +57 -0
  333. package/dist/sync/pull.d.ts +15 -7
  334. package/dist/sync/pull.js +84 -35
  335. package/dist/sync/store-merge.d.ts +29 -0
  336. package/dist/sync/store-merge.js +137 -0
  337. package/dist/sync/task-merge.d.ts +22 -0
  338. package/dist/sync/task-merge.js +158 -0
  339. package/dist/task/github.js +1 -1
  340. package/dist/task/lifecycle.d.ts +5 -0
  341. package/dist/task/lifecycle.js +67 -23
  342. package/dist/terminal-text.d.ts +5 -0
  343. package/dist/terminal-text.js +11 -0
  344. package/dist/test-global-setup.js +7 -0
  345. package/dist/tool-registry.d.ts +1 -1
  346. package/dist/tool-registry.js +3 -1
  347. package/dist/tools/code.d.ts +3 -0
  348. package/dist/tools/code.js +186 -0
  349. package/dist/tools/config.js +8 -0
  350. package/dist/tools/data.js +14 -7
  351. package/dist/tools/dispatch.d.ts +2 -0
  352. package/dist/tools/dispatch.js +66 -0
  353. package/dist/tools/finding.d.ts +11 -0
  354. package/dist/tools/finding.js +180 -123
  355. package/dist/tools/ops.js +5 -2
  356. package/dist/tools/search.js +21 -8
  357. package/dist/tools/session.js +21 -22
  358. package/dist/tools/tasks.js +8 -2
  359. package/dist/tools/types.d.ts +2 -2
  360. package/dist/tools/types.js +2 -2
  361. package/dist/ui/assets.js +1 -1
  362. package/dist/ui/data.js +14 -15
  363. package/dist/ui/deep-void.d.ts +1 -1
  364. package/dist/ui/deep-void.js +0 -1
  365. package/dist/ui/graph-chrome.d.ts +1 -1
  366. package/dist/ui/graph-chrome.js +51 -0
  367. package/dist/ui/page.js +5 -5
  368. package/dist/ui/scripts.js +67 -30
  369. package/dist/ui/server.js +52 -7
  370. package/dist/update.js +22 -11
  371. package/dist/utils-fts.js +1 -0
  372. package/dist/utils-helpers.d.ts +7 -0
  373. package/dist/utils-helpers.js +17 -0
  374. package/dist/utils.d.ts +1 -1
  375. package/dist/utils.js +1 -1
  376. package/package.json +49 -7
  377. package/plugins/opencode/phren-transcript.js +340 -0
  378. package/starter/README.md +4 -4
  379. package/starter/global/{CLAUDE.md → AGENTS.md} +2 -2
  380. package/starter/global/skills/conductor/SKILL.md +106 -0
  381. package/starter/global/skills/fanout/SKILL.md +20 -0
  382. package/starter/global/skills/phren-discover/SKILL.md +6 -6
  383. package/starter/global/skills/phren-init/SKILL.md +4 -4
  384. package/starter/global/skills/phren-sync/SKILL.md +3 -3
  385. package/starter/templates/frontend/reference/README.md +1 -1
  386. package/starter/templates/library/reference/README.md +1 -1
  387. package/starter/templates/monorepo/reference/README.md +1 -1
  388. package/starter/templates/python-project/reference/README.md +1 -1
  389. /package/starter/templates/frontend/{CLAUDE.md → AGENTS.md} +0 -0
  390. /package/starter/templates/library/{CLAUDE.md → AGENTS.md} +0 -0
  391. /package/starter/templates/monorepo/{CLAUDE.md → AGENTS.md} +0 -0
  392. /package/starter/templates/python-project/{CLAUDE.md → AGENTS.md} +0 -0
@@ -2,12 +2,23 @@ import * as fs from "fs";
2
2
  import * as crypto from "crypto";
3
3
  import * as path from "path";
4
4
  import * as yaml from "js-yaml";
5
- import { expandHomePath, atomicWriteText } from "./phren-paths.js";
5
+ import { expandHomePath, atomicWriteText, runtimeDir } from "./phren-paths.js";
6
6
  import { withFileLock } from "./governance/locks.js";
7
7
  import { isRecord, loadYamlDocument, PhrenError } from "./phren-core.js";
8
8
  import { getProjectDirs } from "./shared.js";
9
9
  // ── Constants ────────────────────────────────────────────────────────────────
10
+ /**
11
+ * The synced registry at the store root. It holds the primary store's entry
12
+ * only, so every machine on this personal store agrees on its id. Team and
13
+ * readonly stores used to live here too, which pushed one machine's `team
14
+ * join` onto every other machine and left doctor failing forever there.
15
+ */
10
16
  export const STORES_FILENAME = "stores.yaml";
17
+ /**
18
+ * The stores attached on this machine, under `.runtime/` (never synced).
19
+ * Using the personal store must never connect a machine to a team store.
20
+ */
21
+ export const ATTACHED_STORES_FILENAME = "attached-stores.yaml";
11
22
  const TEAM_BOOTSTRAP_FILENAME = ".phren-team.yaml";
12
23
  const VALID_ROLES = new Set(["primary", "team", "readonly"]);
13
24
  const VALID_SYNC_MODES = new Set(["managed-git", "pull-only"]);
@@ -15,6 +26,9 @@ const VALID_SYNC_MODES = new Set(["managed-git", "pull-only"]);
15
26
  export function storesFilePath(phrenPath) {
16
27
  return path.join(phrenPath, STORES_FILENAME);
17
28
  }
29
+ export function attachedStoresFilePath(phrenPath) {
30
+ return path.join(runtimeDir(phrenPath), ATTACHED_STORES_FILENAME);
31
+ }
18
32
  // ── ID generation ────────────────────────────────────────────────────────────
19
33
  export function generateStoreId() {
20
34
  return crypto.randomUUID().replace(/-/g, "").slice(0, 8);
@@ -27,25 +41,29 @@ function deterministicIdFromPath(storePath) {
27
41
  return crypto.createHash("sha256").update(storePath).digest("hex").slice(0, 8);
28
42
  }
29
43
  export function readStoreRegistryDetailed(phrenPath) {
30
- const filePath = storesFilePath(phrenPath);
31
- if (!fs.existsSync(filePath))
32
- return { registry: null, problems: [], lossy: false };
33
- let raw;
34
- try {
35
- raw = fs.readFileSync(filePath, "utf8");
36
- }
37
- catch (err) {
38
- return { registry: null, problems: [`${STORES_FILENAME} is unreadable: ${String(err)}`], lossy: true };
39
- }
40
- let parsed;
41
- try {
42
- parsed = loadYamlDocument(raw, (text) => yaml.load(text, { schema: yaml.CORE_SCHEMA }));
44
+ const synced = readSyncedRegistry(phrenPath);
45
+ const attached = readAttachedStores(phrenPath, synced.registry);
46
+ const problems = [...synced.problems, ...attached.problems];
47
+ const lossy = synced.lossy || attached.lossy;
48
+ if (!synced.registry && attached.stores.length === 0)
49
+ return { registry: null, problems, lossy };
50
+ const primary = synced.registry?.stores.find((s) => s.role === "primary") ?? implicitPrimaryStore(phrenPath);
51
+ const registry = { version: 1, stores: [primary, ...attached.stores] };
52
+ const err = validateRegistry(registry);
53
+ if (err) {
54
+ problems.push(`${ATTACHED_STORES_FILENAME} failed validation: ${err}`);
55
+ return { registry: synced.registry ? { version: 1, stores: [primary] } : null, problems, lossy: true };
43
56
  }
44
- catch (err) {
45
- return { registry: null, problems: [`${STORES_FILENAME} is not valid YAML: ${String(err)}`], lossy: true };
57
+ return { registry, problems, lossy };
58
+ }
59
+ /** The synced stores.yaml as written, including entries this machine ignores. */
60
+ function readSyncedRegistry(phrenPath) {
61
+ const parsed = readYamlFile(storesFilePath(phrenPath), STORES_FILENAME);
62
+ if (!parsed.exists || parsed.problems.length > 0) {
63
+ return { registry: null, problems: parsed.problems, lossy: parsed.exists };
46
64
  }
47
65
  const problems = [];
48
- const { registry, skippedEntries } = normalizeRegistry(parsed, problems);
66
+ const { registry, skippedEntries } = normalizeRegistry(parsed.value, problems, STORES_FILENAME);
49
67
  if (!registry) {
50
68
  return { registry: null, problems, lossy: true };
51
69
  }
@@ -57,6 +75,59 @@ export function readStoreRegistryDetailed(phrenPath) {
57
75
  }
58
76
  return { registry, problems, lossy: skippedEntries > 0 };
59
77
  }
78
+ function readAttachedStores(phrenPath, synced) {
79
+ const parsed = readYamlFile(attachedStoresFilePath(phrenPath), ATTACHED_STORES_FILENAME);
80
+ if (!parsed.exists)
81
+ return { stores: migrateSyncedAttachments(phrenPath, synced), problems: [], lossy: false };
82
+ if (parsed.problems.length > 0)
83
+ return { stores: [], problems: parsed.problems, lossy: true };
84
+ const problems = [];
85
+ const { registry, skippedEntries } = normalizeRegistry(parsed.value, problems, ATTACHED_STORES_FILENAME, true);
86
+ if (!registry)
87
+ return { stores: [], problems, lossy: true };
88
+ const stores = registry.stores.filter((s) => s.role !== "primary");
89
+ if (stores.length < registry.stores.length) {
90
+ problems.push(`${ATTACHED_STORES_FILENAME}: the primary store belongs in ${STORES_FILENAME} — entry skipped.`);
91
+ }
92
+ return { stores, problems, lossy: skippedEntries > 0 || stores.length < registry.stores.length };
93
+ }
94
+ /**
95
+ * One-time move from the old layout, where team stores were listed in the
96
+ * synced stores.yaml. Only stores whose folder exists here were ever attached
97
+ * on this machine; the rest came from another machine and are dropped. The
98
+ * synced file is left as it is: machines still on an older phren read it.
99
+ */
100
+ function migrateSyncedAttachments(phrenPath, synced) {
101
+ const listed = synced?.stores.filter((s) => s.role !== "primary") ?? [];
102
+ if (listed.length === 0)
103
+ return [];
104
+ const attached = listed.filter((s) => storePathExists(s.path));
105
+ try {
106
+ writeAttachedStores(phrenPath, attached);
107
+ }
108
+ catch (err) {
109
+ // Still honor them for this read; the next read retries the move.
110
+ console.warn(`phren: could not write ${attachedStoresFilePath(phrenPath)}: ${String(err)}`);
111
+ }
112
+ return attached;
113
+ }
114
+ function readYamlFile(filePath, label) {
115
+ if (!fs.existsSync(filePath))
116
+ return { exists: false, problems: [] };
117
+ let raw;
118
+ try {
119
+ raw = fs.readFileSync(filePath, "utf8");
120
+ }
121
+ catch (err) {
122
+ return { exists: true, problems: [`${label} is unreadable: ${String(err)}`] };
123
+ }
124
+ try {
125
+ return { exists: true, value: loadYamlDocument(raw, (text) => yaml.load(text, { schema: yaml.CORE_SCHEMA })), problems: [] };
126
+ }
127
+ catch (err) {
128
+ return { exists: true, problems: [`${label} is not valid YAML: ${String(err)}`] };
129
+ }
130
+ }
60
131
  /** Registry read problems already warned about, keyed by path + content. */
61
132
  const warnedRegistryProblems = new Set();
62
133
  export function readStoreRegistry(phrenPath) {
@@ -78,22 +149,45 @@ export function readStoreRegistry(phrenPath) {
78
149
  }
79
150
  return result.registry;
80
151
  }
152
+ /**
153
+ * Writes this machine's view of the stores: the primary entry to the synced
154
+ * stores.yaml (only when it changed) and every other store to the machine's
155
+ * own attached-stores.yaml.
156
+ */
81
157
  export function writeStoreRegistry(phrenPath, registry) {
82
158
  const err = validateRegistry(registry);
83
159
  if (err)
84
160
  throw new Error(`${PhrenError.VALIDATION_ERROR}: ${err}`);
85
- // Collapse paths to ~ prefix for portability. `available` is machine-local
86
- // state computed at resolve time — it must never be written to stores.yaml,
87
- // which is shared across machines via git.
88
- const portable = {
89
- version: 1,
90
- stores: registry.stores.map(({ available: _available, ...s }) => ({
91
- ...s,
92
- path: collapsePath(s.path),
93
- })),
94
- };
161
+ writeSyncedPrimary(phrenPath, registry.stores.find((s) => s.role === "primary"));
162
+ writeAttachedStores(phrenPath, registry.stores.filter((s) => s.role !== "primary"));
163
+ }
164
+ function writeSyncedPrimary(phrenPath, primary) {
165
+ const current = readSyncedRegistry(phrenPath);
166
+ const existing = current.registry?.stores.find((s) => s.role === "primary");
167
+ if (existing && sameEntry(existing, primary))
168
+ return;
169
+ // Keep what older phren versions on other machines still list here.
170
+ const others = current.lossy ? [] : current.registry?.stores.filter((s) => s.role !== "primary") ?? [];
171
+ const portable = { version: 1, stores: [primary, ...others].map(portableEntry) };
95
172
  atomicWriteText(storesFilePath(phrenPath), yaml.dump(portable, { lineWidth: 200 }));
96
173
  }
174
+ function writeAttachedStores(phrenPath, stores) {
175
+ fs.mkdirSync(runtimeDir(phrenPath), { recursive: true });
176
+ const portable = { version: 1, stores: stores.map(portableEntry) };
177
+ atomicWriteText(attachedStoresFilePath(phrenPath), yaml.dump(portable, { lineWidth: 200 }));
178
+ }
179
+ /**
180
+ * Collapse paths to a ~ prefix for portability. `available` is computed at
181
+ * resolve time and is never written.
182
+ */
183
+ function portableEntry({ available: _available, ...s }) {
184
+ return { ...s, path: collapsePath(s.path) };
185
+ }
186
+ function sameEntry(a, b) {
187
+ return a.id === b.id && a.name === b.name && a.path === b.path && a.role === b.role
188
+ && a.sync === b.sync && a.remote === b.remote
189
+ && (a.projects ?? []).join("\n") === (b.projects ?? []).join("\n");
190
+ }
97
191
  // ── Resolution ───────────────────────────────────────────────────────────────
98
192
  /** True when a store's directory exists on this machine. */
99
193
  export function storePathExists(storePath) {
@@ -105,16 +199,17 @@ export function storePathExists(storePath) {
105
199
  }
106
200
  }
107
201
  /**
108
- * Resolve the full list of stores. This is the **key backward-compat function**:
109
- * - If stores.yaml exists → parse and return entries
110
- * - If stores.yaml is missing → return a single implicit primary entry for phrenPath
111
- * - In both cases, append PHREN_FEDERATION_PATHS entries as readonly stores
202
+ * Resolve the full list of stores on this machine. This is the **key
203
+ * backward-compat function**:
204
+ * - The primary comes from the synced stores.yaml, or is implicit when the
205
+ * file is missing
206
+ * - Then every store attached on this machine (.runtime/attached-stores.yaml)
207
+ * - Then PHREN_FEDERATION_PATHS entries as readonly stores
112
208
  *
113
209
  * Every returned entry carries `available`, recording whether its path exists
114
- * here. Declared-but-absent stores are deliberately **still returned**: callers
115
- * must be able to see that a store claims a project before deciding what to do,
116
- * otherwise a team store that simply isn't cloned yet would look like "no store
117
- * claims this project" and its writes would land in the primary store.
210
+ * here. Attached stores whose folder is gone are deliberately **still
211
+ * returned**: callers must be able to see that a store claims a project before
212
+ * deciding what to do, otherwise its writes would land in the primary store.
118
213
  */
119
214
  export function resolveAllStores(phrenPath) {
120
215
  const registry = readStoreRegistry(phrenPath);
@@ -135,21 +230,30 @@ export function resolveAllStores(phrenPath) {
135
230
  }
136
231
  return stores.map((s) => ({ ...s, available: storePathExists(s.path) }));
137
232
  }
138
- /** Stores declared in stores.yaml whose directory is missing on this machine. */
233
+ /**
234
+ * Non-primary entries in the synced stores.yaml that this machine does not use:
235
+ * joined on another machine with an older phren. Attached ones were moved into
236
+ * attached-stores.yaml; the rest mean nothing here.
237
+ */
238
+ export function ignoredSyncedStores(phrenPath) {
239
+ readStoreRegistry(phrenPath); // runs the one-time move first
240
+ const synced = readSyncedRegistry(phrenPath).registry?.stores.filter((s) => s.role !== "primary") ?? [];
241
+ const attached = new Set(resolveAllStores(phrenPath).map((s) => s.id));
242
+ return synced.filter((s) => !attached.has(s.id));
243
+ }
244
+ /** Stores attached on this machine whose directory is missing. */
139
245
  export function getUnavailableStores(phrenPath) {
140
246
  return resolveAllStores(phrenPath).filter((s) => s.available === false);
141
247
  }
142
248
  /**
143
- * One actionable sentence about a store that is declared but not attached here.
144
- * Shared by write routing, `phren status`, and `phren doctor` so all three name
145
- * the same store, the same expected path, and the same remedy.
249
+ * One actionable sentence about a store attached on this machine whose folder
250
+ * is gone. Shared by write routing, `phren status`, and `phren doctor` so all
251
+ * three name the same store, the same expected path, and the same remedy.
146
252
  */
147
253
  export function describeUnavailableStore(store) {
148
- const attach = store.remote
149
- ? `git clone ${store.remote} "${store.path}" (or: phren team join ${store.remote})`
150
- : `phren team join <git-url> --name ${store.name}`;
151
- return (`Store "${store.name}" (role=${store.role}) is declared in ${STORES_FILENAME} but is not attached on this machine — ` +
152
- `expected path: ${store.path}. Attach it with: ${attach}`);
254
+ const restore = store.remote ? `git clone ${store.remote} "${store.path}"` : `restore the folder`;
255
+ return (`Store "${store.name}" (role=${store.role}) is attached on this machine but its folder is missing — ` +
256
+ `expected path: ${store.path}. Either ${restore}, or detach it with: phren store remove ${store.name}`);
153
257
  }
154
258
  /** The primary store (role=primary). Falls back to implicit entry. */
155
259
  export function getPrimaryStore(phrenPath) {
@@ -210,15 +314,20 @@ export function readTeamBootstrap(storePath) {
210
314
  function readRegistryForMutation(phrenPath) {
211
315
  const result = readStoreRegistryDetailed(phrenPath);
212
316
  if (result.lossy) {
213
- throw new Error(`${PhrenError.VALIDATION_ERROR}: ${storesFilePath(phrenPath)} exists but could not be fully read — ` +
317
+ throw new Error(`${PhrenError.VALIDATION_ERROR}: the store registry (${storesFilePath(phrenPath)} or ${attachedStoresFilePath(phrenPath)}) exists but could not be fully read — ` +
214
318
  `refusing to rewrite it (that would drop the entries phren cannot parse). ` +
215
319
  `Fix the file by hand first. Problems: ${result.problems.join(" | ")}`);
216
320
  }
217
321
  return result.registry;
218
322
  }
219
- /** Add a store entry to the registry. Creates stores.yaml if needed. Uses file locking. */
323
+ /** Mutations change this machine's attachments, so they lock that file. */
324
+ function registryLockPath(phrenPath) {
325
+ fs.mkdirSync(runtimeDir(phrenPath), { recursive: true });
326
+ return attachedStoresFilePath(phrenPath);
327
+ }
328
+ /** Attach a store on this machine. Creates stores.yaml for the primary if needed. Uses file locking. */
220
329
  export function addStoreToRegistry(phrenPath, entry) {
221
- withFileLock(storesFilePath(phrenPath), () => {
330
+ withFileLock(registryLockPath(phrenPath), () => {
222
331
  let registry = readRegistryForMutation(phrenPath);
223
332
  if (!registry) {
224
333
  // First time — also add the implicit primary store
@@ -233,7 +342,7 @@ export function addStoreToRegistry(phrenPath, entry) {
233
342
  }
234
343
  /** Remove a store entry by name. Refuses to remove primary. Uses file locking. */
235
344
  export function removeStoreFromRegistry(phrenPath, name) {
236
- return withFileLock(storesFilePath(phrenPath), () => {
345
+ return withFileLock(registryLockPath(phrenPath), () => {
237
346
  const registry = readRegistryForMutation(phrenPath);
238
347
  if (!registry)
239
348
  throw new Error(`${PhrenError.FILE_NOT_FOUND}: No stores.yaml found`);
@@ -250,7 +359,7 @@ export function removeStoreFromRegistry(phrenPath, name) {
250
359
  }
251
360
  /** Update the projects[] claim list for a store. Uses file locking. */
252
361
  export function updateStoreProjects(phrenPath, storeName, projects) {
253
- withFileLock(storesFilePath(phrenPath), () => {
362
+ withFileLock(registryLockPath(phrenPath), () => {
254
363
  const registry = readRegistryForMutation(phrenPath);
255
364
  if (!registry)
256
365
  throw new Error(`${PhrenError.FILE_NOT_FOUND}: No stores.yaml found`);
@@ -263,7 +372,7 @@ export function updateStoreProjects(phrenPath, storeName, projects) {
263
372
  }
264
373
  /** Add projects to a store's subscription list. Deduplicates. Uses file locking. */
265
374
  export function subscribeStoreProjects(phrenPath, storeName, projects) {
266
- withFileLock(storesFilePath(phrenPath), () => {
375
+ withFileLock(registryLockPath(phrenPath), () => {
267
376
  const registry = readRegistryForMutation(phrenPath);
268
377
  if (!registry)
269
378
  throw new Error(`${PhrenError.FILE_NOT_FOUND}: No stores.yaml found`);
@@ -280,7 +389,7 @@ export function subscribeStoreProjects(phrenPath, storeName, projects) {
280
389
  }
281
390
  /** Remove projects from a store's subscription list. Uses file locking. */
282
391
  export function unsubscribeStoreProjects(phrenPath, storeName, projects) {
283
- withFileLock(storesFilePath(phrenPath), () => {
392
+ withFileLock(registryLockPath(phrenPath), () => {
284
393
  const registry = readRegistryForMutation(phrenPath);
285
394
  if (!registry)
286
395
  throw new Error(`${PhrenError.FILE_NOT_FOUND}: No stores.yaml found`);
@@ -334,17 +443,17 @@ const ROLE_ALIASES = { secondary: "team" };
334
443
  * `problems`, and the valid remainder is kept. Callers see `skippedEntries`
335
444
  * so mutators can refuse to persist a lossy read.
336
445
  */
337
- function normalizeRegistry(parsed, problems) {
446
+ function normalizeRegistry(parsed, problems, label, allowEmpty = false) {
338
447
  if (!isRecord(parsed) || parsed.version !== 1 || !Array.isArray(parsed.stores)) {
339
- problems.push(`${STORES_FILENAME} has an unrecognized shape (expected \`version: 1\` and a \`stores:\` list).`);
448
+ problems.push(`${label} has an unrecognized shape (expected \`version: 1\` and a \`stores:\` list).`);
340
449
  return { registry: null, skippedEntries: 0 };
341
450
  }
342
451
  const stores = [];
343
452
  let skippedEntries = 0;
344
453
  for (const [index, raw] of parsed.stores.entries()) {
345
- const skip = (label, reason) => {
454
+ const skip = (entry, reason) => {
346
455
  skippedEntries += 1;
347
- problems.push(`${STORES_FILENAME}: store ${label} ${reason} — entry skipped.`);
456
+ problems.push(`${label}: store ${entry} ${reason} — entry skipped.`);
348
457
  };
349
458
  if (!isRecord(raw)) {
350
459
  skip(`#${index + 1}`, "is not a mapping");
@@ -352,12 +461,12 @@ function normalizeRegistry(parsed, problems) {
352
461
  }
353
462
  const id = typeof raw.id === "string" ? raw.id : "";
354
463
  const name = typeof raw.name === "string" ? raw.name : "";
355
- const label = name ? `"${name}"` : `#${index + 1}`;
464
+ const entryLabel = name ? `"${name}"` : `#${index + 1}`;
356
465
  const rawPath = typeof raw.path === "string" ? raw.path : "";
357
466
  const rawRole = typeof raw.role === "string" ? raw.role : "";
358
467
  const aliasedRole = ROLE_ALIASES[rawRole];
359
468
  if (aliasedRole) {
360
- problems.push(`${STORES_FILENAME}: store ${label} has role "${rawRole}" — reading it as "${aliasedRole}" (valid roles: primary|team|readonly).`);
469
+ problems.push(`${label}: store ${entryLabel} has role "${rawRole}" — reading it as "${aliasedRole}" (valid roles: primary|team|readonly).`);
361
470
  }
362
471
  const roleValue = aliasedRole ?? rawRole;
363
472
  const role = isStoreRole(roleValue) ? roleValue : null;
@@ -373,7 +482,7 @@ function normalizeRegistry(parsed, problems) {
373
482
  !rawPath && "path",
374
483
  !role && `a valid role (got "${rawRole || "(none)"}")`,
375
484
  ].filter(Boolean);
376
- skip(label, `is missing ${missing.join(", ")}`);
485
+ skip(entryLabel, `is missing ${missing.join(", ")}`);
377
486
  continue;
378
487
  }
379
488
  stores.push({
@@ -386,8 +495,8 @@ function normalizeRegistry(parsed, problems) {
386
495
  projects: projects && projects.length > 0 ? projects : undefined,
387
496
  });
388
497
  }
389
- if (stores.length === 0) {
390
- problems.push(`${STORES_FILENAME} contains no usable store entries.`);
498
+ if (stores.length === 0 && !allowEmpty) {
499
+ problems.push(`${label} contains no usable store entries.`);
391
500
  return { registry: null, skippedEntries };
392
501
  }
393
502
  return { registry: { version: 1, stores }, skippedEntries };
@@ -1,8 +1,3 @@
1
- /**
2
- * How much text a store carries, by kind. None of the tidying phren does stays
3
- * done unless the weight is visible, so `phren status` prints this and doctor
4
- * warns when the parts an agent pays for every session have grown.
5
- */
6
1
  import { homePath } from "./phren-paths.js";
7
2
  export interface StoreWeight {
8
3
  projects: number;
@@ -12,7 +7,7 @@ export interface StoreWeight {
12
7
  reference: number;
13
8
  tasks: number;
14
9
  skills: number;
15
- /** Words in the global CLAUDE.md every session loads. */
10
+ /** Words in the global AGENTS.md every session loads. */
16
11
  globalClaude: number;
17
12
  }
18
13
  export declare function storeWeight(phrenPath: string, profile?: string): StoreWeight;
@@ -1,3 +1,4 @@
1
+ import { moduleEnabled } from "./modules/runtime.js";
1
2
  /**
2
3
  * How much text a store carries, by kind. None of the tidying phren does stays
3
4
  * done unless the weight is visible, so `phren status` prints this and doctor
@@ -40,10 +41,11 @@ function walkWords(dir, match) {
40
41
  }
41
42
  export function storeWeight(phrenPath, profile = "") {
42
43
  const projectDirs = getProjectDirs(phrenPath, profile).filter((d) => path.basename(d) !== "global");
43
- const w = { projects: projectDirs.length, findings: 0, reference: 0, tasks: 0, skills: 0, globalClaude: words(path.join(phrenPath, "global", "CLAUDE.md")) };
44
+ const w = { projects: projectDirs.length, findings: 0, reference: 0, tasks: 0, skills: 0, globalClaude: words(path.join(phrenPath, "global", "AGENTS.md")) };
44
45
  for (const dir of projectDirs) {
45
46
  w.findings += words(path.join(dir, "FINDINGS.md"));
46
- w.tasks += words(path.join(dir, "tasks.md"));
47
+ if (moduleEnabled(phrenPath, "tasks", profile))
48
+ w.tasks += words(path.join(dir, "tasks.md"));
47
49
  w.reference += walkWords(path.join(dir, "reference"), (n) => n.endsWith(".md"));
48
50
  w.skills += walkWords(path.join(dir, "skills"), (n) => n.endsWith(".md"));
49
51
  }
@@ -0,0 +1,8 @@
1
+ import { type StoreEntry } from "../store-registry.js";
2
+ export type ConfirmStoreRemoval = (message: string) => Promise<boolean>;
3
+ /** Only the interactive CLI supplies confirmation; hooks and MCP never remove stores. */
4
+ export declare function storeCredentialCheck(phrenPath: string, store: StoreEntry, fix: boolean, confirm?: ConfirmStoreRemoval, now?: number): Promise<{
5
+ name: string;
6
+ ok: boolean;
7
+ detail: string;
8
+ } | undefined>;
@@ -0,0 +1,27 @@
1
+ import { findStoreByName, removeStoreFromRegistry } from "../store-registry.js";
2
+ import { activeStoreAuthFailure, AUTH_UNREGISTER_AFTER_MS, storeAuthDetail } from "./auth.js";
3
+ /** Only the interactive CLI supplies confirmation; hooks and MCP never remove stores. */
4
+ export async function storeCredentialCheck(phrenPath, store, fix, confirm, now = Date.now()) {
5
+ if (store.available === false || store.role === "primary")
6
+ return;
7
+ const auth = activeStoreAuthFailure(store.path);
8
+ if (!auth)
9
+ return;
10
+ const check = { name: `store:${store.name}`, ok: false, detail: storeAuthDetail(auth) };
11
+ if (now - auth.firstFailedAt <= AUTH_UNREGISTER_AFTER_MS)
12
+ return check;
13
+ check.detail += "; auth has failed for more than a week; phren doctor --fix can offer to unregister this store";
14
+ if (!fix || !confirm)
15
+ return check;
16
+ const projects = store.projects?.length ? ` Its project claims (${store.projects.join(", ")}) will be removed.` : "";
17
+ if (!await confirm(`Unregister store '${store.name}' (${auth.remote}) after more than a week of failed authentication? Local files will be kept.${projects}`))
18
+ return check;
19
+ // Recheck after the user answers: sync or registry configuration may have changed.
20
+ const current = findStoreByName(phrenPath, store.name);
21
+ const failure = activeStoreAuthFailure(store.path);
22
+ if (!current || current.id !== store.id || current.path !== store.path || current.role === "primary"
23
+ || failure?.remote !== auth.remote || failure.firstFailedAt !== auth.firstFailedAt)
24
+ return check;
25
+ removeStoreFromRegistry(phrenPath, store.name);
26
+ return { name: check.name, ok: true, detail: `unregistered '${store.name}'; local files kept` };
27
+ }
@@ -0,0 +1,27 @@
1
+ import type { RunStoreGit } from "./store-merge.js";
2
+ export declare const AUTH_BACKOFF_INITIAL_MS: number;
3
+ export declare const AUTH_BACKOFF_MAX_MS: number;
4
+ export declare const AUTH_UNREGISTER_AFTER_MS: number;
5
+ export interface StoreAuthFailure {
6
+ remote: string;
7
+ remoteName: string;
8
+ firstFailedAt: number;
9
+ lastFailedAt: number;
10
+ failures: number;
11
+ retryAt: number;
12
+ }
13
+ export declare function isGitAuthFailure(error: unknown): boolean;
14
+ export declare function readStoreAuthFailure(cwd: string): StoreAuthFailure | undefined;
15
+ export declare function clearStoreAuthFailure(cwd: string): void;
16
+ /** Read Git's effective URL, including insteadOf rewrites, without contacting it. */
17
+ export declare function storeSyncRemote(cwd: string, name?: string, push?: boolean): {
18
+ remoteName: string;
19
+ remote: string;
20
+ } | undefined;
21
+ /** Changing the configured remote immediately releases the old credential block. */
22
+ export declare function activeStoreAuthFailure(cwd: string): StoreAuthFailure | undefined;
23
+ export declare function authBackoffActive(state: StoreAuthFailure | undefined, now?: number): boolean;
24
+ export declare function storeAuthDetail(state: StoreAuthFailure): string;
25
+ export declare function recordStoreAuthFailure(cwd: string, remoteName: string, remote: string, now?: number): StoreAuthFailure;
26
+ /** Only transport failures affect credentials; local merge errors never do. */
27
+ export declare function withStoreAuthBackoff(git: RunStoreGit, now?: () => number): RunStoreGit;
@@ -0,0 +1,114 @@
1
+ /** Machine-local credential failures shared by session hooks, polling and doctor. */
2
+ import * as fs from "fs";
3
+ import { atomicWriteText, runtimeFile } from "../phren-paths.js";
4
+ import { tryFileLock, withFileLock } from "../governance/locks.js";
5
+ import { runGit } from "../utils-helpers.js";
6
+ export const AUTH_BACKOFF_INITIAL_MS = 60 * 60 * 1000;
7
+ export const AUTH_BACKOFF_MAX_MS = 24 * AUTH_BACKOFF_INITIAL_MS;
8
+ export const AUTH_UNREGISTER_AFTER_MS = 7 * AUTH_BACKOFF_MAX_MS;
9
+ export function isGitAuthFailure(error) {
10
+ const value = error;
11
+ const message = [typeof error === "string" ? error : value?.message, value?.stderr].filter(Boolean).join("\n");
12
+ return /could not read (?:Username|Password)|authentication failed|terminal prompts disabled|permission denied \(publickey\)|could not (?:read|get) (?:a )?password/i.test(message)
13
+ || /\b(?:HTTP(?:\/[\d.]+)?|(?:returned )?error|status(?: code)?)[:\s]+(?:401|403)\b|\b(?:401 Unauthorized|403 Forbidden)\b|^(?:401|403)$/im.test(message);
14
+ }
15
+ export function readStoreAuthFailure(cwd) {
16
+ try {
17
+ const state = JSON.parse(fs.readFileSync(runtimeFile(cwd, "sync-auth.json"), "utf8"));
18
+ if (typeof state?.remote !== "string" || !state.remote || typeof state.remoteName !== "string" || !state.remoteName)
19
+ return;
20
+ if (![state.firstFailedAt, state.lastFailedAt, state.retryAt, state.failures].every(Number.isFinite))
21
+ return;
22
+ if (state.firstFailedAt < 0 || state.lastFailedAt < state.firstFailedAt || state.retryAt < state.lastFailedAt || state.failures < 1)
23
+ return;
24
+ return state;
25
+ }
26
+ catch {
27
+ return;
28
+ }
29
+ }
30
+ export function clearStoreAuthFailure(cwd) {
31
+ fs.rmSync(runtimeFile(cwd, "sync-auth.json"), { force: true });
32
+ }
33
+ /** Read Git's effective URL, including insteadOf rewrites, without contacting it. */
34
+ export function storeSyncRemote(cwd, name, push = false) {
35
+ const git = (args) => runGit(cwd, args, 5000);
36
+ const branch = name ? null : git(["symbolic-ref", "--quiet", "--short", "HEAD"]);
37
+ const pushRemote = push && ((branch && git(["config", "--get", `branch.${branch}.pushRemote`])) || git(["config", "--get", "remote.pushDefault"]));
38
+ const remoteName = name || pushRemote || (branch && git(["config", "--get", `branch.${branch}.remote`])) || "origin";
39
+ if (remoteName === ".")
40
+ return;
41
+ const remote = git(["remote", "get-url", ...(push ? ["--push"] : []), "--", remoteName]);
42
+ return remote ? { remoteName, remote } : undefined;
43
+ }
44
+ /** Changing the configured remote immediately releases the old credential block. */
45
+ export function activeStoreAuthFailure(cwd) {
46
+ const state = readStoreAuthFailure(cwd);
47
+ if (!state)
48
+ return;
49
+ const current = storeSyncRemote(cwd);
50
+ return current?.remote === state.remote && current.remoteName === state.remoteName ? state : undefined;
51
+ }
52
+ export function authBackoffActive(state, now = Date.now()) {
53
+ return Boolean(state && now < state.retryAt);
54
+ }
55
+ export function storeAuthDetail(state) {
56
+ return `needs credentials: ${state.remote}; next retry ${new Date(state.retryAt).toISOString()}`;
57
+ }
58
+ export function recordStoreAuthFailure(cwd, remoteName, remote, now = Date.now()) {
59
+ return withFileLock(runtimeFile(cwd, "sync-auth-state"), () => {
60
+ const previous = readStoreAuthFailure(cwd);
61
+ const sameRemote = previous?.remote === remote && previous.remoteName === remoteName;
62
+ const failures = sameRemote ? Math.min(previous.failures + 1, 32) : 1;
63
+ const state = {
64
+ remote, remoteName, failures,
65
+ firstFailedAt: sameRemote ? previous.firstFailedAt : now,
66
+ lastFailedAt: now,
67
+ retryAt: now + Math.min(AUTH_BACKOFF_INITIAL_MS * 2 ** (failures - 1), AUTH_BACKOFF_MAX_MS),
68
+ };
69
+ atomicWriteText(runtimeFile(cwd, "sync-auth.json"), JSON.stringify(state) + "\n");
70
+ return state;
71
+ });
72
+ }
73
+ /** Only transport failures affect credentials; local merge errors never do. */
74
+ export function withStoreAuthBackoff(git, now = Date.now) {
75
+ return async (cwd, args) => {
76
+ if (!["fetch", "pull", "push", "ls-remote"].includes(args[0]))
77
+ return git(cwd, args);
78
+ const separator = args.indexOf("--");
79
+ const remote = storeSyncRemote(cwd, separator >= 0 ? args[separator + 1] : undefined, args[0] === "push");
80
+ if (!remote)
81
+ return git(cwd, args);
82
+ // Serialize transport probes across processes so startup and polling share one retry.
83
+ const release = tryFileLock(runtimeFile(cwd, "sync-auth-probe"));
84
+ if (!release)
85
+ return { ok: false, output: "", error: "Store remote check deferred: another sync is running." };
86
+ try {
87
+ const previous = readStoreAuthFailure(cwd);
88
+ const sameRemote = previous?.remote === remote.remote && previous.remoteName === remote.remoteName;
89
+ if (sameRemote && authBackoffActive(previous, now())) {
90
+ return { ok: false, output: "", error: storeAuthDetail(previous) };
91
+ }
92
+ const result = await git(cwd, args);
93
+ // A push-only permission failure must not disable otherwise readable stores.
94
+ if (args[0] === "push")
95
+ return result;
96
+ if (result.ok) {
97
+ if (sameRemote)
98
+ clearStoreAuthFailure(cwd);
99
+ }
100
+ else if (isGitAuthFailure(result.error)) {
101
+ const state = recordStoreAuthFailure(cwd, remote.remoteName, remote.remote, now());
102
+ return { ...result, error: storeAuthDetail(state) };
103
+ }
104
+ else if (sameRemote) {
105
+ // The last failure was not authentication; do not age it toward removal.
106
+ clearStoreAuthFailure(cwd);
107
+ }
108
+ return result;
109
+ }
110
+ finally {
111
+ release();
112
+ }
113
+ };
114
+ }
@@ -0,0 +1,9 @@
1
+ export interface ConflictResolution {
2
+ resolved: string[];
3
+ unresolved: string[];
4
+ }
5
+ type Strategy = "tasks" | "findings" | "archive" | "topic" | "summary" | null;
6
+ export declare function conflictStrategy(relFile: string): Strategy;
7
+ /** Resolves what it can in the store's in-progress merge and stages it. */
8
+ export declare function resolveStoreConflicts(cwd: string): ConflictResolution;
9
+ export {};