@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,403 @@
1
+ import { nonInteractiveGitEnv } from "../utils-helpers.js";
2
+ import { execFile } from "node:child_process";
3
+ import { appendFile, copyFile, mkdir, mkdtemp, readdir, readFile, realpath, rm, stat, unlink, utimes } from "node:fs/promises";
4
+ import { homeDir } from "../home-paths.js";
5
+ import path from "node:path";
6
+ import { promisify } from "node:util";
7
+ import { bridgeRoot, object } from "./protocol.js";
8
+ import { z } from "zod";
9
+ import { ProcessPool } from "./limits.js";
10
+ import { phrenStoreRoot } from "./transcripts.js";
11
+ import { countGit, countTick } from "./metrics.js";
12
+ const exec = promisify(execFile);
13
+ /** One file a shell command changed, with the patch between the working
14
+ * tree before the call and after it. `root` is the repository; `path` is
15
+ * relative to it. */
16
+ export const changedFileSchema = z.object({ root: z.string(), path: z.string(), status: z.string(), patch: z.string(),
17
+ added: z.number().int().nonnegative(), removed: z.number().int().nonnegative(), redacted: z.boolean().optional() });
18
+ const changeRowSchema = z.object({ toolUseId: z.string(), files: z.array(changedFileSchema) });
19
+ export const secretName = (file) => /^(?:\.env(?:\..*)?|.*\.(?:pem|key|p12|pfx|keychain-db|tfstate)|id_rsa.*|id_ed25519.*|(?:.*\.)?credentials\.json|\.netrc|\.npmrc|\.pypirc)$/i.test(path.basename(file));
20
+ const gitPool = new ProcessPool(2);
21
+ /** Tools whose filesystem changes are captured around the lifecycle callback. */
22
+ export const SHELL_TOOLS = new Set(["Bash", "bash", "shell", "Shell", "exec_command", "shell_command", "local_shell", "write_stdin"]);
23
+ const NAMED = /(?<![\w@:/])(?:~\/|\.\/|\/)[\w.@+~-]+(?:\/[\w.@+~-]+)*/g;
24
+ /** The places a command names — the same rule the phone applies. */
25
+ const FILE_TOOLS = new Set(["write", "edit", "multiedit", "notebookedit", "apply_patch", "str_replace_editor", "create_file", "replace_string_in_file", "multi_replace_string_in_file"]);
26
+ export function capturesChanges(tool, input) {
27
+ return SHELL_TOOLS.has(tool) || FILE_TOOLS.has(tool.split(".").at(-1).toLowerCase()) || typeof input.command === "string" || typeof input.cmd === "string";
28
+ }
29
+ export function namedPaths(command, input = {}) {
30
+ const found = new Set();
31
+ for (const match of command.slice(0, 65_536).matchAll(NAMED)) {
32
+ if (match[0].length > 2)
33
+ found.add(match[0]);
34
+ if (found.size === 24)
35
+ break;
36
+ }
37
+ for (const value of [input.file_path, input.path, input.notebook_path,
38
+ ...((Array.isArray(input.replacements) ? input.replacements : []).map(v => object(v).filePath))]) {
39
+ if (typeof value === "string" && value.length > 0 && value.length <= 4096 && !value.includes("\0"))
40
+ found.add(value);
41
+ }
42
+ // Patch headers are paths, never execute their content or scan new file text.
43
+ const patch = [input.patch, input.input, input.command, command].filter((v) => typeof v === "string").join("\n").slice(0, 262144);
44
+ for (const match of patch.matchAll(/^\*\*\* (?:Update|Add|Delete) File: (.+)$|^\*\*\* Move to: (.+)$/gm)) {
45
+ const value = (match[1] ?? match[2]).trim();
46
+ if (value && value.length <= 4096 && !value.includes("\0"))
47
+ found.add(value);
48
+ if (found.size >= 48)
49
+ break;
50
+ }
51
+ return [...found].slice(0, 48);
52
+ }
53
+ async function git(cwd, args, extra = {}, signal) {
54
+ return gitPool.run(signal, async () => (countGit("changes"), await exec("git", ["-C", cwd, "--no-pager", ...args], {
55
+ signal, timeout: 10_000, maxBuffer: 8_388_608, env: nonInteractiveGitEnv({ ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_CONFIG_NOSYSTEM: "1", ...extra }),
56
+ })).stdout);
57
+ }
58
+ /** The repository holding `target` (a file, a folder, or something not yet
59
+ * created), confined to the user's home; undefined otherwise. */
60
+ async function repositoryOf(target, cwd, home = homeDir(), signal) {
61
+ const absolute = target === "~" || target.startsWith("~/") ? path.join(home, target.slice(1)) : path.resolve(cwd, target);
62
+ let existing = absolute;
63
+ while (!(await stat(existing).catch(() => undefined))) {
64
+ const parent = path.dirname(existing);
65
+ if (parent === existing)
66
+ return undefined;
67
+ existing = parent;
68
+ }
69
+ const real = await realpath(existing);
70
+ home = await realpath(home);
71
+ if (real !== home && !real.startsWith(home + path.sep))
72
+ return undefined;
73
+ const dir = (await stat(real)).isDirectory() ? real : path.dirname(real);
74
+ try {
75
+ return await realpath((await git(dir, ["rev-parse", "--show-toplevel"], {}, signal)).trim());
76
+ }
77
+ catch {
78
+ return undefined;
79
+ }
80
+ }
81
+ async function scratchTree(root, signal) {
82
+ const dir = path.join(bridgeRoot(), "changes-scratch");
83
+ await mkdir(dir, { recursive: true, mode: 0o700 });
84
+ const scratch = await mkdtemp(path.join(dir, "repo-"));
85
+ try {
86
+ const objects = await realpath(path.resolve(root, (await git(root, ["rev-parse", "--git-path", "objects"], {}, signal)).trim()));
87
+ await mkdir(path.join(scratch, "objects"), { mode: 0o700 });
88
+ const env = { GIT_OBJECT_DIRECTORY: path.join(scratch, "objects"), GIT_ALTERNATE_OBJECT_DIRECTORIES: JSON.stringify(objects), GIT_INDEX_FILE: path.join(scratch, "index") };
89
+ return { hash: await treeHash(root, env, signal), scratch, env };
90
+ }
91
+ catch (error) {
92
+ await rm(scratch, { recursive: true, force: true });
93
+ throw error;
94
+ }
95
+ }
96
+ /** Both the index and all new blobs/trees stay in scratch storage. The real
97
+ * object store is a read-only alternate, including for linked worktrees. */
98
+ async function treeHash(root, env, signal) {
99
+ const index = path.resolve(root, (await git(root, ["rev-parse", "--git-path", "index"], {}, signal)).trim());
100
+ const temp = env.GIT_INDEX_FILE;
101
+ await unlink(temp).catch(() => undefined);
102
+ await copyFile(index, temp).catch(() => undefined);
103
+ // Force content checks for files rewritten to the same size in one instant.
104
+ await utimes(temp, 1, 1).catch(() => undefined);
105
+ await git(root, ["add", "-A", "--ignore-errors", "--", "."], env, signal);
106
+ return (await git(root, ["write-tree"], env, signal)).trim();
107
+ }
108
+ const NO_DIFF = ["diff", "--no-ext-diff", "--no-textconv", "--no-color"];
109
+ async function treeDiff(root, before, after, env, signal) {
110
+ if (before === after)
111
+ return [];
112
+ const records = (await git(root, [...NO_DIFF, "--name-status", "-z", before, after], env, signal)).split("\0");
113
+ const files = [];
114
+ for (let i = 0; i + 1 < records.length && files.length < 40; i += 2) {
115
+ const status = records[i].slice(0, 1), original = records[i + 1];
116
+ let file = original;
117
+ if (/[RC]/.test(status))
118
+ file = records[++i + 1]; // the new name follows the old
119
+ if (!file)
120
+ continue;
121
+ const spec = `:(literal)${file}`;
122
+ const counts = (await git(root, [...NO_DIFF, "--numstat", before, after, "--", spec], env, signal)).split("\t");
123
+ const redacted = secretName(original) || secretName(file) || counts[0] === "-" || counts[1] === "-";
124
+ let patch = redacted ? "" : await git(root, [...NO_DIFF, before, after, "--", spec], env, signal);
125
+ if (patch.length > 200_000)
126
+ patch = patch.slice(0, 200_000) + "\n… (truncated)\n";
127
+ const added = Number(counts[0]) || 0, removed = Number(counts[1]) || 0;
128
+ files.push({ root, path: file, status, patch, added, removed, ...(redacted ? { redacted: true } : {}) });
129
+ }
130
+ return files;
131
+ }
132
+ const CLAIM_RETENTION = 10 * 60_000;
133
+ /** The real path of a file that may not exist yet: its folder's real path plus its name. */
134
+ async function realPathOf(file) {
135
+ return realpath(file).catch(async () => path.join(await realpath(path.dirname(file)).catch(() => path.dirname(file)), path.basename(file)));
136
+ }
137
+ /** The files a call names in its structured input, never the words of a command line. */
138
+ export function claimedPaths(input, cwd, home = homeDir()) {
139
+ const found = new Set();
140
+ for (const value of [input.file_path, input.path, input.notebook_path,
141
+ ...((Array.isArray(input.replacements) ? input.replacements : []).map(v => object(v).filePath))]) {
142
+ if (typeof value === "string" && value.length > 0 && value.length <= 4096 && !value.includes("\0"))
143
+ found.add(value);
144
+ }
145
+ const patch = [input.patch, input.input].filter((v) => typeof v === "string").join("\n").slice(0, 262144);
146
+ for (const match of patch.matchAll(/^\*\*\* (?:Update|Add|Delete) File: (.+)$|^\*\*\* Move to: (.+)$/gm)) {
147
+ const value = (match[1] ?? match[2]).trim();
148
+ if (value && value.length <= 4096 && !value.includes("\0"))
149
+ found.add(value);
150
+ if (found.size >= 48)
151
+ break;
152
+ }
153
+ return [...found].map(value => value === "~" || value.startsWith("~/") ? path.join(home, value.slice(1)) : path.resolve(cwd, value));
154
+ }
155
+ const PENDING_FOR = 6_000;
156
+ const BUDGET = 2_500;
157
+ const DAY = 86_400_000;
158
+ /** Remove old records first, then oldest records until within the disk budget. */
159
+ export async function pruneChanges(now = Date.now()) {
160
+ const dir = path.join(bridgeRoot(), "changes");
161
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
162
+ const files = [];
163
+ for (const entry of entries) {
164
+ if (!entry.isFile() || !entry.name.endsWith(".jsonl"))
165
+ continue;
166
+ const file = path.join(dir, entry.name), info = await stat(file).catch(() => undefined);
167
+ if (info)
168
+ files.push({ file, size: info.size, at: info.mtimeMs });
169
+ }
170
+ files.sort((a, b) => b.at - a.at);
171
+ let size = 0;
172
+ for (const file of files) {
173
+ if (now - file.at > 30 * DAY || size + file.size > 268_435_456)
174
+ await unlink(file.file).catch(() => undefined);
175
+ else
176
+ size += file.size;
177
+ }
178
+ }
179
+ export async function startChangeRetention() {
180
+ await pruneChanges();
181
+ const timer = setInterval(async () => { countTick("change-retention"); await pruneChanges().catch(() => { }); }, DAY);
182
+ timer.unref();
183
+ return () => clearInterval(timer);
184
+ }
185
+ /** Snapshots live only around a shell call. Persisted results are validated
186
+ * when loaded; the LRU retains at most 16 conversations, including loads. */
187
+ export class ToolChanges {
188
+ /** Called after a non-empty change event is recorded, so modules that follow
189
+ * file changes (the code index) can react without polling. */
190
+ onRecord;
191
+ snapshots = new Map();
192
+ results = new Map();
193
+ controllers = new Set();
194
+ claims = [];
195
+ file(conversation) { return path.join(bridgeRoot(), "changes", conversation.replace(/[^A-Za-z0-9._-]/g, "_") + ".jsonl"); }
196
+ async budget(work) {
197
+ const controller = new AbortController();
198
+ this.controllers.add(controller);
199
+ const timer = setTimeout(() => controller.abort(), BUDGET);
200
+ try {
201
+ return await work(controller.signal);
202
+ }
203
+ finally {
204
+ clearTimeout(timer);
205
+ this.controllers.delete(controller);
206
+ }
207
+ }
208
+ async discard(snapshot) {
209
+ clearTimeout(snapshot.expiry);
210
+ await Promise.all([...snapshot.trees.values()].map(tree => rm(tree.scratch, { recursive: true, force: true })));
211
+ }
212
+ async close() {
213
+ for (const controller of this.controllers)
214
+ controller.abort();
215
+ for (const snapshot of this.snapshots.values()) {
216
+ await snapshot.result?.catch(() => { });
217
+ await this.discard(snapshot);
218
+ }
219
+ this.snapshots.clear();
220
+ }
221
+ async before(conversation, toolUseId, cwd, command, input = {}) {
222
+ const key = `${conversation}\0${toolUseId}`;
223
+ if (!toolUseId)
224
+ return;
225
+ // Real paths, like the repository roots the diff reports (/var → /private/var).
226
+ const claimed = await Promise.all(claimedPaths(input, cwd).map(realPathOf));
227
+ this.claim(conversation, toolUseId, claimed);
228
+ if (this.snapshots.size >= 64 || this.snapshots.has(key))
229
+ return;
230
+ const snapshot = { at: Date.now(), conversation, own: new Set(claimed), trees: new Map() };
231
+ this.snapshots.set(key, snapshot);
232
+ try {
233
+ await this.budget(async (signal) => {
234
+ const roots = new Set();
235
+ for (const target of [cwd, phrenStoreRoot(), ...namedPaths(command, input)]) {
236
+ signal.throwIfAborted();
237
+ if (roots.size >= 6)
238
+ break;
239
+ const root = await repositoryOf(target, cwd, homeDir(), signal);
240
+ if (root)
241
+ roots.add(root);
242
+ }
243
+ for (const root of roots) {
244
+ try {
245
+ snapshot.trees.set(root, await scratchTree(root, signal));
246
+ }
247
+ catch {
248
+ signal.throwIfAborted();
249
+ }
250
+ }
251
+ signal.throwIfAborted();
252
+ });
253
+ if (!snapshot.trees.size) {
254
+ this.snapshots.delete(key);
255
+ return;
256
+ }
257
+ // A missing PostToolUse/reader cannot retain untracked contents forever.
258
+ snapshot.expiry = setTimeout(() => {
259
+ if (!snapshot.result) {
260
+ this.snapshots.delete(key);
261
+ void this.discard(snapshot).catch(() => { });
262
+ }
263
+ }, 30 * 60_000);
264
+ snapshot.expiry.unref();
265
+ }
266
+ catch {
267
+ this.snapshots.delete(key);
268
+ await this.discard(snapshot);
269
+ }
270
+ }
271
+ claim(conversation, toolUseId, paths) {
272
+ const now = Date.now();
273
+ this.claims = this.claims.filter(claim => claim.end === undefined ? now - claim.start < 30 * 60_000 : now - claim.end < CLAIM_RETENTION);
274
+ if (paths.length && this.claims.length < 512)
275
+ this.claims.push({ conversation, toolUseId, paths: new Set(paths), start: now });
276
+ }
277
+ /** Whether another conversation's call named this file while `snapshot` ran. */
278
+ claimedElsewhere(snapshot, file, until) {
279
+ return this.claims.some(claim => claim.conversation !== snapshot.conversation && claim.paths.has(file)
280
+ && claim.start <= until && (claim.end ?? until) >= snapshot.at);
281
+ }
282
+ async after(conversation, toolUseId) {
283
+ const key = `${conversation}\0${toolUseId}`, snapshot = this.snapshots.get(key);
284
+ for (const claim of this.claims)
285
+ if (claim.conversation === conversation && claim.toolUseId === toolUseId)
286
+ claim.end ??= Date.now();
287
+ if (!snapshot)
288
+ return;
289
+ snapshot.result ??= this.compute(snapshot);
290
+ const files = await snapshot.result;
291
+ if (this.snapshots.get(key) === snapshot) {
292
+ this.snapshots.delete(key);
293
+ await this.record(conversation, toolUseId, files);
294
+ }
295
+ }
296
+ async compute(snapshot) {
297
+ try {
298
+ return await this.budget(async (signal) => {
299
+ const files = [];
300
+ for (const [root, before] of snapshot.trees) {
301
+ try {
302
+ files.push(...await treeDiff(root, before.hash, await treeHash(root, before.env, signal), before.env, signal));
303
+ }
304
+ catch {
305
+ signal.throwIfAborted();
306
+ }
307
+ }
308
+ // A file another agent's edit named during this call is its change,
309
+ // not this call's, even though it landed inside the same window.
310
+ // A call that names its files (an Edit, a Write, a patch) changed
311
+ // only those, whatever else moved in the repository meanwhile.
312
+ const until = Date.now();
313
+ const kept = [];
314
+ for (const file of files) {
315
+ // Both sides as real paths: a root reported through a symlinked
316
+ // folder (/var on macOS) still matches the call's own claim.
317
+ const absolute = await realPathOf(path.resolve(file.root, file.path));
318
+ if (snapshot.own.size ? snapshot.own.has(absolute) : !this.claimedElsewhere(snapshot, absolute, until))
319
+ kept.push(file);
320
+ }
321
+ return kept;
322
+ });
323
+ }
324
+ catch {
325
+ return [];
326
+ }
327
+ finally {
328
+ await this.discard(snapshot);
329
+ }
330
+ }
331
+ cache(conversation) {
332
+ const entry = this.results.get(conversation) ?? { files: new Map() };
333
+ this.results.delete(conversation);
334
+ this.results.set(conversation, entry);
335
+ while (this.results.size > 16)
336
+ this.results.delete(this.results.keys().next().value);
337
+ return entry;
338
+ }
339
+ async load(conversation) {
340
+ const entry = this.cache(conversation);
341
+ entry.loaded ??= (async () => {
342
+ const file = this.file(conversation);
343
+ const size = (await stat(file).catch(() => undefined))?.size ?? 0;
344
+ const text = size <= 16_777_216 ? await readFile(file, "utf8").catch(() => "") : "";
345
+ for (const line of text.split("\n")) {
346
+ if (!line)
347
+ continue;
348
+ try {
349
+ const row = changeRowSchema.parse(JSON.parse(line));
350
+ // Also sanitize old records made before patch redaction existed.
351
+ entry.files.set(row.toolUseId, row.files.map(file => secretName(file.path) || file.redacted || /^(?:Binary files |GIT binary patch)/m.test(file.patch)
352
+ ? { ...file, patch: "", redacted: true } : file));
353
+ }
354
+ catch { /* Torn or invalid rows are not transcript events. */ }
355
+ }
356
+ })();
357
+ await entry.loaded;
358
+ return entry;
359
+ }
360
+ async record(conversation, toolUseId, files) {
361
+ (await this.load(conversation)).files.set(toolUseId, files);
362
+ if (!files.length)
363
+ return;
364
+ const file = this.file(conversation);
365
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
366
+ const size = (await stat(file).catch(() => undefined))?.size ?? 0;
367
+ const line = JSON.stringify({ toolUseId, files }) + "\n";
368
+ if (size + Buffer.byteLength(line) <= 16_777_216)
369
+ await appendFile(file, line, { mode: 0o600 });
370
+ this.onRecord?.(files);
371
+ }
372
+ async recordedPaths(conversation) {
373
+ return [...new Set([...(await this.load(conversation)).files.values()].flatMap(files => files.flatMap(file => [file.root, path.resolve(file.root, file.path)])))];
374
+ }
375
+ view(conversation) {
376
+ return {
377
+ pending: toolUseId => {
378
+ const snapshot = this.snapshots.get(`${conversation}\0${toolUseId}`);
379
+ return !!snapshot && !snapshot.result && Date.now() - snapshot.at < PENDING_FOR;
380
+ },
381
+ changes: async (toolUseId) => {
382
+ await this.after(conversation, toolUseId);
383
+ const known = (await this.load(conversation)).files.get(toolUseId);
384
+ return known?.length ? known : undefined;
385
+ },
386
+ };
387
+ }
388
+ }
389
+ /** The tool calls whose output a transcript row carries. */
390
+ export function outputCallIds(raw, source) {
391
+ const ids = (value) => typeof value === "string" && value ? [value] : [];
392
+ if (source === "codex") {
393
+ const p = (raw.payload ?? {});
394
+ return ["function_call_output", "custom_tool_call_output"].includes(String(p.type)) ? ids(p.call_id) : [];
395
+ }
396
+ if (source === "copilot")
397
+ return raw.type === "tool.execution_complete" ? ids((raw.data ?? {}).toolCallId) : [];
398
+ const message = (source === "phren" || source === "opencode" ? (raw.data ?? {}).message : raw.message);
399
+ const content = message?.content;
400
+ if (!Array.isArray(content))
401
+ return [];
402
+ return content.flatMap(block => block && typeof block === "object" && block.type === "tool_result" ? ids(block.tool_use_id) : []);
403
+ }
@@ -0,0 +1,3 @@
1
+ import { type RequestOptions } from "node:http";
2
+ import { type Json } from "./protocol.js";
3
+ export declare function hookRequest(route: string, data?: Json, options?: RequestOptions, timeout?: number): Promise<Json>;
@@ -0,0 +1,36 @@
1
+ import { request } from "node:http";
2
+ import { BridgeError, object, socketPath } from "./protocol.js";
3
+ export async function hookRequest(route, data, options = { socketPath: socketPath() }, timeout = 75_000) {
4
+ return new Promise((resolve, reject) => {
5
+ const payload = data === undefined ? undefined : JSON.stringify(data);
6
+ const method = options.method ?? (payload === undefined ? "GET" : "POST");
7
+ const req = request({ ...options, path: route, method,
8
+ headers: { Host: "phren.local", Connection: "close", ...(payload ? { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(payload) } : {}) } }, response => {
9
+ const chunks = [];
10
+ let size = 0;
11
+ response.on("data", chunk => {
12
+ size += chunk.length;
13
+ if (size > 1_048_576)
14
+ req.destroy(new BridgeError(502, "Hook response is too large."));
15
+ else
16
+ chunks.push(Buffer.from(chunk));
17
+ });
18
+ response.on("error", reject);
19
+ response.on("end", () => {
20
+ try {
21
+ const value = object(JSON.parse(Buffer.concat(chunks).toString()));
22
+ if (response.statusCode !== 200)
23
+ throw new BridgeError(response.statusCode ?? 502, typeof value.error === "string" ? value.error.slice(0, 500) : "Hook rejected the request.");
24
+ resolve(value);
25
+ }
26
+ catch (error) {
27
+ reject(error);
28
+ }
29
+ });
30
+ });
31
+ const timer = setTimeout(() => req.destroy(new BridgeError(504, "Hook did not confirm the request. Do not retry a dispatch automatically.")), timeout);
32
+ req.on("close", () => clearTimeout(timer));
33
+ req.on("error", reject);
34
+ req.end(payload);
35
+ });
36
+ }
@@ -0,0 +1,22 @@
1
+ import { z } from "zod";
2
+ import { type Json } from "./protocol.js";
3
+ export declare const codeNoteSchema: z.ZodObject<{
4
+ store: z.ZodOptional<z.ZodString>;
5
+ project: z.ZodString;
6
+ symbol: z.ZodString;
7
+ file: z.ZodString;
8
+ line: z.ZodNumber;
9
+ text: z.ZodString;
10
+ target: z.ZodOptional<z.ZodUnion<readonly [z.ZodObject<{
11
+ session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
12
+ }, z.core.$strict>, z.ZodObject<{
13
+ harness: z.ZodEnum<{
14
+ claude: "claude";
15
+ codex: "codex";
16
+ opencode: "opencode";
17
+ }>;
18
+ }, z.core.$strict>]>>;
19
+ }, z.core.$strict>;
20
+ export type CodeNote = z.infer<typeof codeNoteSchema>;
21
+ export type CodeNoteDelivery = (note: CodeNote, brief: string) => Promise<Json>;
22
+ export declare function saveCodeNote(store: string, input: unknown, deliver?: CodeNoteDelivery): Promise<Json>;
@@ -0,0 +1,42 @@
1
+ import * as path from "node:path";
2
+ import { z } from "zod";
3
+ import { addFindingToFile } from "../shared/content.js";
4
+ import { requireCodePackage } from "./code-routes.js";
5
+ import { BridgeError, sessionId } from "./protocol.js";
6
+ import { projectName } from "./dispatch.js";
7
+ export const codeNoteSchema = z.object({
8
+ store: z.string().min(1).max(200).optional(),
9
+ project: projectName, symbol: z.string().min(1).max(4600),
10
+ file: z.string().min(1).max(4096).refine(file => !path.isAbsolute(file) && !file.includes("\0") && !file.split(/[\\/]/).includes("..")),
11
+ line: z.number().int().positive(), text: z.string().trim().min(1).max(4500).refine(text => !/[\x00-\x08\x0b-\x1f\x7f]/.test(text)),
12
+ target: z.union([z.object({ session: sessionId }).strict(), z.object({ harness: z.enum(["codex", "claude", "opencode"]) }).strict()]).optional(),
13
+ }).strict();
14
+ export async function saveCodeNote(store, input, deliver) {
15
+ const note = codeNoteSchema.parse(input);
16
+ if (note.target && !deliver)
17
+ throw new BridgeError(409, "Enable conductor to send code notes to an agent.");
18
+ const code = await requireCodePackage(store);
19
+ const result = await code.definition(store, note.project, note.symbol);
20
+ if (!result.available || !result.value)
21
+ throw new BridgeError(404, "The symbol is not in this project's code index.");
22
+ const definition = result.value;
23
+ const lastSnippetLine = definition.symbol.line + definition.snippet.split("\n").length - 1;
24
+ if (definition.symbol.file !== note.file || note.line < definition.symbol.line || note.line > Math.min(definition.symbol.endLine, lastSnippetLine)) {
25
+ throw new BridgeError(409, "The selected line no longer belongs to this symbol. Refresh its dossier.");
26
+ }
27
+ const citation = { file: note.file, line: note.line, symbol: code.citationSymbolName(definition.symbol) };
28
+ const saved = addFindingToFile(store, note.project, note.text, citation);
29
+ if (!saved.ok)
30
+ throw new BridgeError(400, saved.error);
31
+ const brief = `${note.project}: ${citation.symbol}\n${note.file}:${note.line}\n\n${definition.snippet}\n\nNote:\n${note.text}`;
32
+ let delivery;
33
+ if (note.target && deliver) {
34
+ try {
35
+ delivery = await deliver(note, brief);
36
+ }
37
+ catch (error) {
38
+ delivery = { ok: false, message: error instanceof Error ? error.message : String(error) };
39
+ }
40
+ }
41
+ return { ok: true, saved: true, findings: code.findingsCitingSymbol(store, note.project, citation.symbol), ...(delivery ? { delivery } : {}) };
42
+ }
@@ -0,0 +1,133 @@
1
+ import type { CodeStatus, OutlineEntry, ReferenceResult, SymbolDefinition, SymbolHit, UsageEntry } from "@phren/code";
2
+ declare const indexProject: typeof import("@phren/code").indexProject;
3
+ import type { ChangedFile } from "./changes.js";
4
+ export declare function requireCodePackage(store?: string): Promise<typeof import("@phren/code")>;
5
+ /** Resolve only registered stores. Phone IDs are repository names; no client
6
+ * path can select a filesystem location. Omitting the ID supports older phones. */
7
+ export declare function resolveCodeStore(base: string, value?: string | null, write?: boolean): Promise<string>;
8
+ /** The phone names a project and an optional query; both are validated here. */
9
+ export declare class CodeRoutes {
10
+ private readonly store;
11
+ constructor(store: string);
12
+ status(projectValue: string | null): Promise<CodeStatus>;
13
+ search(projectValue: string | null, queryValue: string | null, kindValue: string | null, limitValue: string | null, directoryValue?: string | null): Promise<{
14
+ project: string;
15
+ query: string;
16
+ symbols: SymbolHit[];
17
+ }>;
18
+ tree(projectValue: string | null, directoryValue?: string | null): Promise<{
19
+ project: string;
20
+ directory: string;
21
+ entries: import("@phren/code").CodeTreeEntry[];
22
+ }>;
23
+ usagePage(projectValue: string | null, values?: {
24
+ kind?: string | null;
25
+ file?: string | null;
26
+ directory?: string | null;
27
+ offset?: string | null;
28
+ limit?: string | null;
29
+ end?: string | null;
30
+ }): Promise<{
31
+ entries: SymbolHit[];
32
+ total: number;
33
+ offset: number;
34
+ limit: number;
35
+ maxUses: number;
36
+ project: string;
37
+ }>;
38
+ recent(projectValue: string | null, directoryValue?: string | null): Promise<{
39
+ project: string;
40
+ entries: {
41
+ id: number;
42
+ name: string;
43
+ kind: string;
44
+ file: string;
45
+ line: number;
46
+ endLine: number;
47
+ signature: string;
48
+ doc: string;
49
+ parent: string | null;
50
+ exported: boolean;
51
+ uses: number;
52
+ rank?: number;
53
+ indexedAt: number;
54
+ }[];
55
+ }>;
56
+ /** Turns code intelligence off for a project: its index is deleted, and
57
+ * the reindexer follows only projects that have one, so nothing rebuilds it
58
+ * until the phone turns it on again. */
59
+ disable(projectValue: string | null): Promise<{
60
+ project: string;
61
+ disabled: true;
62
+ }>;
63
+ reindex(projectValue: string | null): Promise<CodeStatus>;
64
+ outline(projectValue: string | null, pathValue: string | null): Promise<{
65
+ project: string;
66
+ path: string;
67
+ entries: OutlineEntry[];
68
+ }>;
69
+ /** Resolved uses made from one file, with the declaration each names, so the
70
+ * phone's code viewer can make those identifiers tappable. */
71
+ fileReferences(projectValue: string | null, pathValue: string | null): Promise<{
72
+ project: string;
73
+ path: string;
74
+ references: import("@phren/code").FileReference[];
75
+ }>;
76
+ outlineSummary(projectValue: string | null, pathsValue: string | null): Promise<{
77
+ project: string;
78
+ entries: import("@phren/code").OutlineSummary[];
79
+ }>;
80
+ definition(projectValue: string | null, symbolValue: string | null): Promise<{
81
+ project: string;
82
+ definition: SymbolDefinition & {
83
+ findings: import("@phren/code").CitingFinding[];
84
+ };
85
+ }>;
86
+ references(projectValue: string | null, symbolValue: string | null, limitValue: string | null): Promise<{
87
+ project: string;
88
+ references: ReferenceResult;
89
+ }>;
90
+ usage(projectValue: string | null, topValue: string | null): Promise<{
91
+ project: string;
92
+ usage: {
93
+ hot: UsageEntry[];
94
+ cold: UsageEntry[];
95
+ };
96
+ }>;
97
+ }
98
+ export interface CodeReindexOptions {
99
+ store: string;
100
+ /** Index function; injectable so tests do not need the real parser. */
101
+ index?: typeof indexProject;
102
+ /** Where the one-line-per-run report goes; defaults to the CLI logger. */
103
+ log?: (line: string) => void;
104
+ /** How long to wait for the writes to settle. */
105
+ debounceMs?: number;
106
+ }
107
+ /**
108
+ * Re-indexes a project when the git module's change capture records a file
109
+ * event inside it. The Hook only constructs this while the `code` module is on,
110
+ * and only projects that already have an index are followed. A branch switch
111
+ * (the repository's HEAD moved) upgrades the pending run to a full re-index.
112
+ */
113
+ export declare class CodeReindexer {
114
+ private readonly store;
115
+ private readonly index;
116
+ private readonly log;
117
+ private readonly debounceMs;
118
+ private readonly timers;
119
+ private readonly pendingFull;
120
+ private readonly running;
121
+ private readonly rerun;
122
+ private readonly heads;
123
+ private closed;
124
+ constructor(options: CodeReindexOptions);
125
+ /** One recorded change event; schedules an incremental re-index of the project it belongs to. */
126
+ record(files: ChangedFile[]): void;
127
+ private recordAsync;
128
+ close(): void;
129
+ private indexedProjects;
130
+ private schedule;
131
+ private run;
132
+ }
133
+ export {};