@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,573 @@
1
+ /**
2
+ * Project registration and scaffold shared by `phren add`, `phren init` and
3
+ * the phone Hook's "Add project". Kept free of the init walkthrough, the
4
+ * agent-hooks installer and the skill/provision machinery so the Hook does not
5
+ * have to bundle `phren init`.
6
+ */
7
+ import * as fs from "fs";
8
+ import * as path from "path";
9
+ import { atomicWriteText, debugLog, findProjectNameCaseInsensitive, findProjectNamesByCanonicalKey, projectSlugFromPath, readRootManifest, } from "../phren-paths.js";
10
+ import { resolveWorktreeParent } from "../git-worktree.js";
11
+ import { moduleEnabled } from "../modules/runtime.js";
12
+ import { STOP_WORDS, errorMessage } from "../utils.js";
13
+ import { FINDINGS_FILENAME, TASKS_FILENAME } from "../filenames.js";
14
+ import { getProjectOwnershipDefault, getProjectSourcePath, parseProjectOwnershipMode, readProjectConfig, recordProjectSourcePath, } from "../project-config.js";
15
+ import { getBuiltinTopicConfig, normalizeBuiltinTopicDomain } from "../project-topics.js";
16
+ import { addProjectToProfile, resolveActiveProfile } from "../profile-store.js";
17
+ const DOMAIN_KEYWORD_HINTS = {
18
+ software: [
19
+ "api", "backend", "frontend", "typescript", "javascript", "python", "rust", "golang", "cli", "sdk", "library", "service",
20
+ "server", "database", "auth", "module", "package", "build", "test", "deploy",
21
+ ],
22
+ music: [
23
+ "music", "audio", "mix", "master", "track", "daw", "synth", "midi", "song", "composition", "arrangement", "producer",
24
+ ],
25
+ game: [
26
+ "game", "gameplay", "level", "shader", "physics", "npc", "engine", "unity", "godot", "unreal", "sprite", "multiplayer",
27
+ ],
28
+ research: [
29
+ "research", "paper", "study", "experiment", "dataset", "analysis", "methodology", "hypothesis", "results", "evaluation",
30
+ ],
31
+ writing: [
32
+ "writing", "manuscript", "chapter", "outline", "narrative", "character", "plot", "draft", "editorial",
33
+ ],
34
+ creative: [
35
+ "creative", "story", "design", "worldbuilding", "script", "concept", "illustration", "art direction",
36
+ ],
37
+ };
38
+ const DOMAIN_CONFIG_HINTS = {
39
+ "package.json": { software: 3 },
40
+ "tsconfig.json": { software: 3 },
41
+ "Cargo.toml": { software: 4, game: 1 },
42
+ "pyproject.toml": { software: 3, research: 1 },
43
+ "requirements.txt": { software: 2, research: 1 },
44
+ "go.mod": { software: 3 },
45
+ "CMakeLists.txt": { software: 3, game: 1 },
46
+ "pom.xml": { software: 3 },
47
+ "build.gradle": { software: 3 },
48
+ "project.godot": { game: 5 },
49
+ ".uproject": { game: 5 },
50
+ "paper.tex": { research: 4, writing: 1 },
51
+ "references.bib": { research: 4 },
52
+ };
53
+ const EXTENSION_DOMAIN_HINTS = {
54
+ ".ts": { software: 1 },
55
+ ".tsx": { software: 1, game: 1 },
56
+ ".js": { software: 1 },
57
+ ".jsx": { software: 1 },
58
+ ".py": { software: 1, research: 1 },
59
+ ".rs": { software: 1, game: 1 },
60
+ ".go": { software: 1 },
61
+ ".java": { software: 1 },
62
+ ".kt": { software: 1 },
63
+ ".swift": { software: 1 },
64
+ ".c": { software: 1, game: 1 },
65
+ ".cc": { software: 1, game: 1 },
66
+ ".cpp": { software: 1, game: 1 },
67
+ ".h": { software: 1, game: 1 },
68
+ ".hpp": { software: 1, game: 1 },
69
+ ".cs": { software: 1, game: 1 },
70
+ ".ipynb": { research: 2 },
71
+ ".tex": { research: 2, writing: 1 },
72
+ ".bib": { research: 2 },
73
+ ".wav": { music: 2 },
74
+ ".mp3": { music: 2 },
75
+ ".flac": { music: 2 },
76
+ ".mid": { music: 2 },
77
+ ".midi": { music: 2 },
78
+ ".als": { music: 2 },
79
+ ".logicx": { music: 2 },
80
+ ".unity": { game: 2 },
81
+ ".gd": { game: 2 },
82
+ ".glsl": { game: 2 },
83
+ };
84
+ function titleCase(text) {
85
+ return text
86
+ .split(/[\s_-]+/)
87
+ .filter(Boolean)
88
+ .map((token) => token.slice(0, 1).toUpperCase() + token.slice(1))
89
+ .join(" ");
90
+ }
91
+ function addTermCount(terms, rawText, weight = 1) {
92
+ const tokens = rawText
93
+ .toLowerCase()
94
+ .replace(/[^\w\s-]/g, " ")
95
+ .split(/\s+/)
96
+ .map((token) => token.trim())
97
+ .filter((token) => token.length >= 3 && token.length <= 48 && !STOP_WORDS.has(token));
98
+ for (const token of tokens) {
99
+ terms.set(token, (terms.get(token) ?? 0) + weight);
100
+ }
101
+ }
102
+ function maybeReadUtf8(filePath, maxBytes = 256_000) {
103
+ try {
104
+ const stat = fs.statSync(filePath);
105
+ if (!stat.isFile() || stat.size > maxBytes)
106
+ return "";
107
+ return fs.readFileSync(filePath, "utf8");
108
+ }
109
+ catch {
110
+ return "";
111
+ }
112
+ }
113
+ function addDomainScores(target, patch, weight = 1) {
114
+ for (const [domain, score] of Object.entries(patch)) {
115
+ const typedDomain = domain;
116
+ target[typedDomain] += (score ?? 0) * weight;
117
+ }
118
+ }
119
+ function scoreTopicsFromTerms(domain, terms, docsText) {
120
+ const baseTopics = getBuiltinTopicConfig(domain);
121
+ const scored = baseTopics
122
+ .filter((topic) => topic.name.toLowerCase() !== "general")
123
+ .map((topic) => {
124
+ const baseTerm = topic.name.toLowerCase();
125
+ let score = terms.get(baseTerm) ?? 0;
126
+ for (const keyword of topic.keywords) {
127
+ const normalized = keyword.toLowerCase().trim();
128
+ if (!normalized)
129
+ continue;
130
+ score += terms.get(normalized) ?? 0;
131
+ if (normalized.includes(" ") && docsText.includes(normalized))
132
+ score += 1;
133
+ }
134
+ return { topic, score };
135
+ });
136
+ const ranked = scored
137
+ .filter((entry) => entry.score > 0)
138
+ .sort((a, b) => b.score - a.score || a.topic.name.localeCompare(b.topic.name));
139
+ const takenNames = new Set(baseTopics.map((topic) => topic.name.toLowerCase()));
140
+ const customTopics = [];
141
+ for (const [term, count] of [...terms.entries()].sort((a, b) => b[1] - a[1])) {
142
+ if (customTopics.length >= 4)
143
+ break;
144
+ if (count < 3)
145
+ break;
146
+ if (term.includes("_"))
147
+ continue;
148
+ const topicName = titleCase(term);
149
+ const normalizedName = topicName.toLowerCase();
150
+ if (takenNames.has(normalizedName))
151
+ continue;
152
+ if (DOMAIN_KEYWORD_HINTS.software.includes(term) || DOMAIN_KEYWORD_HINTS.music.includes(term) || DOMAIN_KEYWORD_HINTS.game.includes(term)) {
153
+ continue;
154
+ }
155
+ takenNames.add(normalizedName);
156
+ customTopics.push({
157
+ name: topicName,
158
+ description: "Suggested from repeated terminology in project docs.",
159
+ keywords: [term],
160
+ });
161
+ }
162
+ if (ranked.length === 0 && customTopics.length === 0)
163
+ return baseTopics;
164
+ const orderedBase = [
165
+ ...ranked.map((entry) => entry.topic),
166
+ ...baseTopics.filter((topic) => topic.name.toLowerCase() !== "general"
167
+ && !ranked.some((entry) => entry.topic.name === topic.name)),
168
+ ];
169
+ const topics = [...orderedBase.slice(0, 8), ...customTopics];
170
+ if (!topics.some((topic) => topic.name.toLowerCase() === "general")) {
171
+ topics.push({ name: "General", description: "Fallback bucket for uncategorized findings.", keywords: [] });
172
+ }
173
+ return topics;
174
+ }
175
+ export function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
176
+ const resolvedRoot = path.resolve(repoRoot);
177
+ if (!fs.existsSync(resolvedRoot))
178
+ return null;
179
+ const signal = {
180
+ domainScores: { software: 0, music: 0, game: 0, research: 0, writing: 0, creative: 0, other: 0 },
181
+ terms: new Map(),
182
+ docsText: "",
183
+ referenceHints: [],
184
+ commandHints: [],
185
+ usefulSignals: 0,
186
+ };
187
+ const skipDirs = new Set([".git", ".phren", "node_modules", "dist", "build", "coverage", ".next", ".turbo", "target"]);
188
+ const packageJsonPath = path.join(resolvedRoot, "package.json");
189
+ if (fs.existsSync(packageJsonPath)) {
190
+ signal.usefulSignals++;
191
+ addDomainScores(signal.domainScores, DOMAIN_CONFIG_HINTS["package.json"]);
192
+ try {
193
+ const parsed = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
194
+ if (typeof parsed.description === "string") {
195
+ addTermCount(signal.terms, parsed.description, 3);
196
+ signal.docsText += ` ${parsed.description.toLowerCase()}`;
197
+ }
198
+ if (Array.isArray(parsed.keywords)) {
199
+ for (const keyword of parsed.keywords) {
200
+ if (typeof keyword === "string") {
201
+ addTermCount(signal.terms, keyword, 3);
202
+ signal.docsText += ` ${keyword.toLowerCase()}`;
203
+ }
204
+ }
205
+ }
206
+ if (parsed.scripts && typeof parsed.scripts === "object" && !Array.isArray(parsed.scripts)) {
207
+ const scriptObject = parsed.scripts;
208
+ for (const scriptName of ["dev", "start", "build", "test", "lint"]) {
209
+ if (typeof scriptObject[scriptName] === "string") {
210
+ signal.commandHints.push(`npm run ${scriptName}`);
211
+ }
212
+ }
213
+ }
214
+ }
215
+ catch (err) {
216
+ debugLog(`inferInitScaffoldFromRepo package.json parse failed: ${errorMessage(err)}`);
217
+ }
218
+ }
219
+ const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS)
220
+ .filter((fileName) => fs.existsSync(path.join(resolvedRoot, fileName)));
221
+ for (const configName of topLevelConfigs) {
222
+ signal.usefulSignals++;
223
+ const configScore = DOMAIN_CONFIG_HINTS[configName];
224
+ if (configScore)
225
+ addDomainScores(signal.domainScores, configScore);
226
+ }
227
+ const readmeCandidates = [
228
+ path.join(resolvedRoot, "README.md"),
229
+ path.join(resolvedRoot, "readme.md"),
230
+ ];
231
+ for (const readmePath of readmeCandidates) {
232
+ if (!fs.existsSync(readmePath))
233
+ continue;
234
+ const content = maybeReadUtf8(readmePath);
235
+ if (!content)
236
+ continue;
237
+ signal.usefulSignals++;
238
+ signal.referenceHints.push(path.relative(resolvedRoot, readmePath));
239
+ addTermCount(signal.terms, content, 2);
240
+ signal.docsText += ` ${content.toLowerCase()}`;
241
+ break;
242
+ }
243
+ const docsDir = path.join(resolvedRoot, "docs");
244
+ if (fs.existsSync(docsDir) && fs.statSync(docsDir).isDirectory()) {
245
+ signal.referenceHints.push("docs/");
246
+ for (const entry of fs.readdirSync(docsDir, { withFileTypes: true })) {
247
+ if (!entry.isFile())
248
+ continue;
249
+ if (!/\.(md|txt|rst)$/i.test(entry.name))
250
+ continue;
251
+ const docsContent = maybeReadUtf8(path.join(docsDir, entry.name));
252
+ if (!docsContent)
253
+ continue;
254
+ signal.usefulSignals++;
255
+ addTermCount(signal.terms, docsContent, 1);
256
+ signal.docsText += ` ${docsContent.toLowerCase()}`;
257
+ }
258
+ }
259
+ for (const folderName of ["reference", "specs", "design", "architecture", "src", "packages", "apps"]) {
260
+ const fullPath = path.join(resolvedRoot, folderName);
261
+ if (fs.existsSync(fullPath)) {
262
+ signal.referenceHints.push(`${folderName}/`);
263
+ }
264
+ }
265
+ let scannedFiles = 0;
266
+ const maxFiles = 3000;
267
+ const walk = (dir) => {
268
+ if (scannedFiles >= maxFiles)
269
+ return;
270
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
271
+ if (scannedFiles >= maxFiles)
272
+ return;
273
+ const fullPath = path.join(dir, entry.name);
274
+ if (entry.isDirectory()) {
275
+ if (skipDirs.has(entry.name))
276
+ continue;
277
+ walk(fullPath);
278
+ continue;
279
+ }
280
+ scannedFiles++;
281
+ const ext = path.extname(entry.name).toLowerCase();
282
+ if (!ext)
283
+ continue;
284
+ const extScore = EXTENSION_DOMAIN_HINTS[ext];
285
+ if (extScore) {
286
+ addDomainScores(signal.domainScores, extScore);
287
+ signal.usefulSignals++;
288
+ }
289
+ }
290
+ };
291
+ walk(resolvedRoot);
292
+ for (const [domain, hints] of Object.entries(DOMAIN_KEYWORD_HINTS)) {
293
+ for (const hint of hints) {
294
+ const hitCount = signal.terms.get(hint) ?? 0;
295
+ if (hitCount > 0) {
296
+ signal.domainScores[domain] += Math.min(4, hitCount);
297
+ signal.usefulSignals++;
298
+ }
299
+ }
300
+ }
301
+ const rankedDomains = Object.entries(signal.domainScores)
302
+ .sort((a, b) => b[1] - a[1]);
303
+ const [bestDomain, bestScore] = rankedDomains[0] ?? [fallbackDomain, 0];
304
+ const secondScore = rankedDomains[1]?.[1] ?? 0;
305
+ const inferredDomain = bestScore >= 2 ? bestDomain : fallbackDomain;
306
+ const confidence = bestScore <= 0
307
+ ? 0
308
+ : Math.max(0.15, Math.min(0.98, (bestScore - secondScore + 1) / (bestScore + 2)));
309
+ const topics = scoreTopicsFromTerms(inferredDomain, signal.terms, signal.docsText);
310
+ const references = Array.from(new Set(signal.referenceHints)).slice(0, 8);
311
+ const commands = Array.from(new Set(signal.commandHints)).slice(0, 5);
312
+ const reason = bestScore > 0
313
+ ? `inferred from repo files, config, and docs terminology (score ${bestScore})`
314
+ : "fallback defaults";
315
+ if (signal.usefulSignals === 0)
316
+ return null;
317
+ return {
318
+ domain: inferredDomain,
319
+ topics: topics.length > 0 ? topics : getBuiltinTopicConfig(inferredDomain),
320
+ referenceHints: references,
321
+ commandHints: commands,
322
+ confidence: Number(confidence.toFixed(2)),
323
+ reason,
324
+ };
325
+ }
326
+ function appendInferredSections(base, inference) {
327
+ if (!inference)
328
+ return base;
329
+ const lines = [];
330
+ if (inference.referenceHints.length > 0) {
331
+ lines.push("## Reference Structure");
332
+ for (const hint of inference.referenceHints) {
333
+ lines.push(`- ${hint}`);
334
+ }
335
+ lines.push("");
336
+ }
337
+ if (inference.topics.length > 0) {
338
+ lines.push("## Initial Focus Topics");
339
+ for (const topic of inference.topics.slice(0, 6)) {
340
+ lines.push(`- ${topic.name}: ${topic.description}`);
341
+ }
342
+ lines.push("");
343
+ }
344
+ if (inference.commandHints.length > 0) {
345
+ lines.push("## Commands");
346
+ lines.push("```bash");
347
+ for (const cmd of inference.commandHints)
348
+ lines.push(cmd);
349
+ lines.push("```");
350
+ lines.push("");
351
+ }
352
+ return lines.length > 0 ? `${base.trimEnd()}\n\n${lines.join("\n")}` : base;
353
+ }
354
+ function getDomainClaudeTemplate(projectName, domain, inference) {
355
+ if (domain === "software") {
356
+ return appendInferredSections(`# ${projectName}\n\nOne paragraph about what this project is.\n\n## Commands\n\n\`\`\`bash\n# Install:\n# Run:\n# Test:\n\`\`\`\n`, inference);
357
+ }
358
+ if (domain === "music") {
359
+ return appendInferredSections(`# ${projectName}\n\nThis is a music project. Keep notes on composition intent, arrangement choices, production workflow, and mixing/mastering decisions.\n\n## Session Focus\n\n- Capture creative intent before technical tweaks\n- Track instrument/sound-design decisions and why\n- Log mix/master changes with listening context\n`, inference);
360
+ }
361
+ if (domain === "game") {
362
+ return appendInferredSections(`# ${projectName}\n\nThis is a game project. Prioritize clear notes on mechanics, rendering/performance tradeoffs, level and UI decisions, and iteration outcomes.\n\n## Development Focus\n\n- Record gameplay/mechanics decisions with player impact\n- Track rendering/physics/AI issues with repro context\n- Note level-design and networking constraints early\n`, inference);
363
+ }
364
+ if (domain === "research") {
365
+ return appendInferredSections(`# ${projectName}\n\nThis is a research project. Focus on methodology, source quality, analysis assumptions, and review feedback loops.\n\n## Working Approach\n\n- Document hypotheses and evaluation criteria explicitly\n- Track source provenance and confidence level\n- Record analysis decisions and revision rationale\n`, inference);
366
+ }
367
+ if (domain === "writing" || domain === "creative") {
368
+ return appendInferredSections(`# ${projectName}\n\nThis is a creative writing project. Track worldbuilding rules, character arcs, plot structure, style constraints, and revision decisions.\n\n## Writing Workflow\n\n- Keep narrative intent and tone constraints visible\n- Capture character/plot changes with consequences\n- Log revision notes and unresolved questions\n`, inference);
369
+ }
370
+ return appendInferredSections(`# ${projectName}\n\nThis project is not software-first. Keep practical notes, references, and task decisions so future sessions can resume quickly.\n\n## Workflow\n\n- Capture non-obvious lessons and reusable patterns\n- Keep references curated and current\n- Track active tasks and follow-ups\n`, inference);
371
+ }
372
+ export function ensureProjectScaffold(projectDir, projectName, domain = "software", inference) {
373
+ const normalizedDomain = normalizeBuiltinTopicDomain(inference?.domain ?? domain);
374
+ const inferredTopics = Array.isArray(inference?.topics) && inference.topics.length > 0
375
+ ? inference.topics
376
+ : getBuiltinTopicConfig(normalizedDomain);
377
+ fs.mkdirSync(projectDir, { recursive: true });
378
+ if (!fs.existsSync(path.join(projectDir, "summary.md"))) {
379
+ atomicWriteText(path.join(projectDir, "summary.md"), `# ${projectName}\n\n**What:** Replace this with one sentence about what the project does\n**Stack:** The key tech\n**Status:** active\n**Run:** the command you use most\n**Watch out:** the one thing that will bite you if you forget\n`);
380
+ }
381
+ if (!fs.existsSync(path.join(projectDir, "AGENTS.md"))) {
382
+ atomicWriteText(path.join(projectDir, "AGENTS.md"), getDomainClaudeTemplate(projectName, inference?.domain ?? domain, inference));
383
+ }
384
+ if (!fs.existsSync(path.join(projectDir, "topic-config.json"))) {
385
+ atomicWriteText(path.join(projectDir, "topic-config.json"), JSON.stringify({ version: 1, domain: normalizedDomain, topics: inferredTopics }, null, 2) + "\n");
386
+ }
387
+ if (!fs.existsSync(path.join(projectDir, FINDINGS_FILENAME))) {
388
+ atomicWriteText(path.join(projectDir, FINDINGS_FILENAME), `# ${projectName} FINDINGS\n\n<!-- Findings are captured automatically during sessions and committed on exit -->\n`);
389
+ }
390
+ if (moduleEnabled(path.dirname(projectDir), "tasks") && !fs.existsSync(path.join(projectDir, TASKS_FILENAME))) {
391
+ atomicWriteText(path.join(projectDir, TASKS_FILENAME), `# ${projectName} tasks\n\n## Active\n\n## Queue\n\n## Done\n`);
392
+ }
393
+ }
394
+ /** Bootstrap a phren project from an existing project directory with AGENTS.md.
395
+ * @param profile - if provided, only this profile YAML is updated (avoids leaking project to unrelated profiles).
396
+ */
397
+ /**
398
+ * Find an already-registered project that `sourceRoot` should reuse rather than
399
+ * getting a near-duplicate directory of its own. Two signals, strongest first:
400
+ *
401
+ * 1. **Same source path.** Another project already points at this exact
402
+ * directory — unambiguous, reuse it whatever it is called.
403
+ * 2. **Same canonical slug.** `max4liveplugins` vs `max4live-plugins`: the same
404
+ * repo spelled two ways. Only reused when the existing project has no source
405
+ * path recorded, or records this one — if it points somewhere else it is a
406
+ * genuinely different project that merely slugs alike, and both are kept.
407
+ *
408
+ * Returns `null` when nothing matches, i.e. create the project normally.
409
+ */
410
+ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
411
+ let candidates;
412
+ try {
413
+ candidates = fs.readdirSync(phrenPath, { withFileTypes: true })
414
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
415
+ .map((entry) => entry.name);
416
+ }
417
+ catch (err) {
418
+ debugLog(`findExistingProjectForSource readdir: ${errorMessage(err)}`);
419
+ return null;
420
+ }
421
+ const sourceOf = (project) => {
422
+ try {
423
+ return getProjectSourcePath(phrenPath, project) ?? null;
424
+ }
425
+ catch (err) {
426
+ debugLog(`findExistingProjectForSource config ${project}: ${errorMessage(err)}`);
427
+ return null;
428
+ }
429
+ };
430
+ const resolvedSource = path.resolve(sourceRoot);
431
+ for (const project of candidates) {
432
+ if (sourceOf(project) === resolvedSource)
433
+ return project;
434
+ }
435
+ for (const project of findProjectNamesByCanonicalKey(phrenPath, derivedName)) {
436
+ if (project === derivedName)
437
+ return project; // exact match; nothing to reconcile
438
+ const existingSource = sourceOf(project);
439
+ if (existingSource === null || existingSource === resolvedSource)
440
+ return project;
441
+ }
442
+ return null;
443
+ }
444
+ export function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
445
+ const profile = typeof opts === "string" ? opts : opts.profile;
446
+ const profilePhrenPath = typeof opts === "string" ? phrenPath : (opts.profilePhrenPath ?? phrenPath);
447
+ const resolvedPath = path.resolve(projectPath);
448
+ if (!fs.existsSync(resolvedPath)) {
449
+ throw new Error(`Path does not exist: ${resolvedPath}`);
450
+ }
451
+ const manifest = readRootManifest(phrenPath);
452
+ const isProjectLocal = manifest?.installMode === "project-local";
453
+ // A git worktree — notably the agent-managed ones under `.claude/worktrees/`
454
+ // — is a checkout of a repository we may already track. Attribute it to that
455
+ // repository instead of registering the worktree's throwaway codename as a
456
+ // brand-new top-level project.
457
+ const worktree = isProjectLocal ? null : resolveWorktreeParent(resolvedPath);
458
+ const worktreeRepoRoot = worktree && fs.existsSync(worktree.repoRoot) ? worktree.repoRoot : null;
459
+ if (worktreeRepoRoot) {
460
+ debugLog(`bootstrapFromExisting: ${resolvedPath} is a ${worktree.reason}; attributing to ${worktreeRepoRoot}`);
461
+ }
462
+ const sourceRoot = isProjectLocal
463
+ ? path.resolve(manifest.workspaceRoot || resolvedPath)
464
+ : (worktreeRepoRoot ?? resolvedPath);
465
+ if (isProjectLocal) {
466
+ const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot + path.sep);
467
+ if (!matchesWorkspace) {
468
+ throw new Error(`Project-local phren can only enroll the owning workspace: ${sourceRoot}`);
469
+ }
470
+ }
471
+ let claudeMdPath = null;
472
+ const candidates = [
473
+ path.join(sourceRoot, "AGENTS.md"),
474
+ path.join(sourceRoot, ".claude", "CLAUDE.md"),
475
+ ];
476
+ for (const c of candidates) {
477
+ if (fs.existsSync(c)) {
478
+ claudeMdPath = c;
479
+ break;
480
+ }
481
+ }
482
+ const claudeContent = claudeMdPath ? fs.readFileSync(claudeMdPath, "utf8") : null;
483
+ const derivedName = isProjectLocal
484
+ ? String(manifest?.primaryProject)
485
+ : projectSlugFromPath(sourceRoot);
486
+ const projectName = isProjectLocal
487
+ ? derivedName
488
+ : (findExistingProjectForSource(phrenPath, sourceRoot, derivedName) ?? derivedName);
489
+ if (projectName !== derivedName) {
490
+ debugLog(`bootstrapFromExisting: reusing existing project "${projectName}" for ${sourceRoot} (derived "${derivedName}")`);
491
+ }
492
+ const existingProject = findProjectNameCaseInsensitive(phrenPath, projectName);
493
+ if (existingProject && existingProject !== projectName) {
494
+ throw new Error(`Project "${existingProject}" already exists with different casing. Refusing to bootstrap "${projectName}" because it would split the same project on case-sensitive filesystems.`);
495
+ }
496
+ const projDir = path.join(phrenPath, projectName);
497
+ fs.mkdirSync(projDir, { recursive: true });
498
+ const inferredScaffold = inferInitScaffoldFromRepo(sourceRoot);
499
+ const existingConfig = readProjectConfig(phrenPath, projectName);
500
+ const ownership = typeof opts === "string"
501
+ ? (parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath))
502
+ : (opts.ownership ?? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath));
503
+ const claudePath = path.join(projDir, "AGENTS.md");
504
+ if (ownership !== "repo-managed") {
505
+ if (claudeContent) {
506
+ if (!fs.existsSync(claudePath)) {
507
+ atomicWriteText(claudePath, claudeContent);
508
+ }
509
+ }
510
+ else {
511
+ // No AGENTS.md found — create a starter one
512
+ if (!fs.existsSync(claudePath)) {
513
+ atomicWriteText(claudePath, getDomainClaudeTemplate(projectName, inferredScaffold?.domain ?? "software", inferredScaffold));
514
+ }
515
+ }
516
+ }
517
+ const summaryLines = [];
518
+ if (claudeContent) {
519
+ const lines = claudeContent.split("\n");
520
+ let foundHeading = false;
521
+ for (const line of lines) {
522
+ if (line.startsWith("# ") && !foundHeading) {
523
+ foundHeading = true;
524
+ summaryLines.push(line);
525
+ continue;
526
+ }
527
+ if (foundHeading && line.trim() === "") {
528
+ if (summaryLines.length > 1)
529
+ break;
530
+ continue;
531
+ }
532
+ if (foundHeading && summaryLines.length < 10) {
533
+ summaryLines.push(line);
534
+ }
535
+ }
536
+ }
537
+ const sourceInfo = claudeMdPath ? `**Source AGENTS.md:** ${claudeMdPath}` : `**Source:** ${sourceRoot}`;
538
+ const summaryPath = path.join(projDir, "summary.md");
539
+ if (!fs.existsSync(summaryPath)) {
540
+ atomicWriteText(summaryPath, `# ${projectName}\n\n**What:** Bootstrapped from ${sourceRoot}\n${sourceInfo}\n\n${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}\n`);
541
+ }
542
+ if (!fs.existsSync(path.join(projDir, FINDINGS_FILENAME))) {
543
+ atomicWriteText(path.join(projDir, FINDINGS_FILENAME), `# ${projectName} FINDINGS\n\n<!-- Bootstrapped from ${sourceRoot} -->\n`);
544
+ }
545
+ if (moduleEnabled(phrenPath, "tasks") && !fs.existsSync(path.join(projDir, TASKS_FILENAME))) {
546
+ atomicWriteText(path.join(projDir, TASKS_FILENAME), `# ${projectName} tasks\n\n## Active\n\n## Queue\n\n## Done\n`);
547
+ }
548
+ if (!fs.existsSync(path.join(projDir, "topic-config.json"))) {
549
+ const inferredDomain = normalizeBuiltinTopicDomain(inferredScaffold?.domain ?? "software");
550
+ const inferredTopics = inferredScaffold?.topics?.length
551
+ ? inferredScaffold.topics
552
+ : getBuiltinTopicConfig(inferredDomain);
553
+ atomicWriteText(path.join(projDir, "topic-config.json"), JSON.stringify({ version: 1, domain: inferredDomain, topics: inferredTopics }, null, 2) + "\n");
554
+ }
555
+ const activeProfile = resolveActiveProfile(profilePhrenPath, profile);
556
+ if (activeProfile.ok && activeProfile.data) {
557
+ const addResult = addProjectToProfile(profilePhrenPath, activeProfile.data, projectName);
558
+ if (!addResult.ok) {
559
+ throw new Error(addResult.error);
560
+ }
561
+ }
562
+ else if (!activeProfile.ok && activeProfile.code !== "FILE_NOT_FOUND") {
563
+ throw new Error(activeProfile.error);
564
+ }
565
+ recordProjectSourcePath(phrenPath, projectName, sourceRoot, { ownership });
566
+ return {
567
+ project: projectName,
568
+ ownership,
569
+ claudePath: ownership === "repo-managed"
570
+ ? (claudeMdPath ?? null)
571
+ : (fs.existsSync(claudePath) ? claudePath : null),
572
+ };
573
+ }
@@ -1,9 +1,8 @@
1
1
  import * as path from "path";
2
2
  import { phrenErr, phrenOk, readRootManifest } from "../shared.js";
3
- import { bootstrapFromExisting } from "../init/setup.js";
3
+ import { bootstrapFromExisting } from "./project-registry.js";
4
4
  import { resolveActiveProfile } from "../profile-store.js";
5
- import { TASKS_FILENAME } from "../data/tasks.js";
6
- import { FINDINGS_FILENAME } from "../data/access.js";
5
+ import { FINDINGS_FILENAME, TASKS_FILENAME } from "../filenames.js";
7
6
  export function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership, options = {}) {
8
7
  if (!targetPath) {
9
8
  return phrenErr("Path is required. Pass the current project directory explicitly to avoid adding the wrong working directory.");
@@ -7,7 +7,7 @@ export { readTasks, readTasksAcrossProjects, resolveTaskItem, addTask, addTasks,
7
7
  export { addProjectToProfile, listMachines, listProfiles, listProjectCards, removeProjectFromProfile, setMachineProfile, type ProfileInfo, type ProjectCard, } from "../profile-store.js";
8
8
  export { loadShellState, resetShellState, saveShellState, type ShellState, } from "../shell/state-store.js";
9
9
  export { getRuntimeHealth as readRuntimeHealth } from "../shared/governance.js";
10
- export declare const FINDINGS_FILENAME = "FINDINGS.md";
10
+ export { FINDINGS_FILENAME } from "../filenames.js";
11
11
  export interface FindingItem {
12
12
  id: string;
13
13
  /** Stable 8-char hex ID embedded as `<!-- fid:XXXXXXXX -->`. Survives reordering and consolidation. */
@@ -64,6 +64,12 @@ export interface ProjectQueueItem extends QueueItem {
64
64
  project: string;
65
65
  }
66
66
  export declare function readFindings(phrenPath: string, project: string, opts?: ReadFindingsOptions): PhrenResult<FindingItem[]>;
67
+ /**
68
+ * Parse FINDINGS.md-shaped content into findings. Shared by `readFindings`
69
+ * (the project's FINDINGS.md) and the memory link's scan of archived topic
70
+ * files under `reference/topics/`, which use the same bullet + citation shape.
71
+ */
72
+ export declare function parseFindingsContent(content: string, opts?: ReadFindingsOptions): FindingItem[];
67
73
  export declare function readFindingHistory(phrenPath: string, project: string, findingId?: string): PhrenResult<FindingHistoryEntry[]>;
68
74
  export declare function addFinding(phrenPath: string, project: string, learning: string): PhrenResult<AddFindingResult>;
69
75
  export declare function removeFinding(phrenPath: string, project: string, match: string): PhrenResult<string>;
@@ -18,7 +18,8 @@ export { readTasks, readTasksAcrossProjects, resolveTaskItem, addTask, addTasks,
18
18
  export { addProjectToProfile, listMachines, listProfiles, listProjectCards, removeProjectFromProfile, setMachineProfile, } from "../profile-store.js";
19
19
  export { loadShellState, resetShellState, saveShellState, } from "../shell/state-store.js";
20
20
  export { getRuntimeHealth as readRuntimeHealth } from "../shared/governance.js";
21
- export const FINDINGS_FILENAME = "FINDINGS.md";
21
+ import { FINDINGS_FILENAME } from "../filenames.js";
22
+ export { FINDINGS_FILENAME } from "../filenames.js";
22
23
  function extractDateHeading(line) {
23
24
  const heading = line.match(/^##\s+(.+)$/);
24
25
  if (!heading)
@@ -131,7 +132,15 @@ export function readFindings(phrenPath, project, opts = {}) {
131
132
  const file = findingsPath;
132
133
  if (!fs.existsSync(file))
133
134
  return phrenOk([]);
134
- const lines = fs.readFileSync(file, "utf8").split("\n");
135
+ return phrenOk(parseFindingsContent(fs.readFileSync(file, "utf8"), opts));
136
+ }
137
+ /**
138
+ * Parse FINDINGS.md-shaped content into findings. Shared by `readFindings`
139
+ * (the project's FINDINGS.md) and the memory link's scan of archived topic
140
+ * files under `reference/topics/`, which use the same bullet + citation shape.
141
+ */
142
+ export function parseFindingsContent(content, opts = {}) {
143
+ const lines = content.split("\n");
135
144
  const items = [];
136
145
  let date = "unknown";
137
146
  let index = 1;
@@ -238,7 +247,7 @@ export function readFindings(phrenPath, project, opts = {}) {
238
247
  i += 1;
239
248
  index++;
240
249
  }
241
- return phrenOk(items);
250
+ return items;
242
251
  }
243
252
  export function readFindingHistory(phrenPath, project, findingId) {
244
253
  const result = readFindings(phrenPath, project, { includeArchived: true });
@@ -671,6 +680,7 @@ export function approveQueueItemDetailed(phrenPath, project, lineText) {
671
680
  ...(parsed.citation.file ? { file: parsed.citation.file } : {}),
672
681
  ...(parsed.citation.line !== undefined ? { line: parsed.citation.line } : {}),
673
682
  ...(parsed.citation.commit ? { commit: parsed.citation.commit } : {}),
683
+ ...(parsed.citation.symbol ? { symbol: parsed.citation.symbol } : {}),
674
684
  }
675
685
  : undefined;
676
686
  // The queue entry's own date is the day the observation was captured; the finding is