@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
package/dist/sync/pull.js CHANGED
@@ -3,14 +3,19 @@ import { execFile } from "child_process";
3
3
  import * as fs from "fs";
4
4
  import * as path from "path";
5
5
  import { promisify } from "util";
6
- import { atomicWriteText, readRootManifest, runtimeFile } from "../phren-paths.js";
7
- import { readInstallPreferences } from "../init/preferences.js";
8
- import { resolveManagementCapabilities } from "../init/management-preset.js";
9
6
  import { tryFileLock } from "../governance/locks.js";
10
- import { getNonPrimaryStores } from "../store-registry.js";
11
7
  import { updateRuntimeHealth } from "../governance/policy.js";
8
+ import { resolveManagementCapabilities } from "../init/management-preset.js";
9
+ import { readInstallPreferences } from "../init/preferences.js";
10
+ import { atomicWriteText, readRootManifest, runtimeFile } from "../phren-paths.js";
12
11
  import { debugLog } from "../shared.js";
12
+ import { getNonPrimaryStores } from "../store-registry.js";
13
13
  import { errorMessage } from "../utils.js";
14
+ import { nonInteractiveGitEnv } from "../utils-helpers.js";
15
+ import { activeStoreAuthFailure, authBackoffActive, storeAuthDetail, withStoreAuthBackoff } from "./auth.js";
16
+ import { inProgressGitOperation } from "./git-state.js";
17
+ import { aheadBehind, appendSyncLog, logSyncOutcome } from "./outcome.js";
18
+ import { mergeStoreUpstream } from "./store-merge.js";
14
19
  export const DEFAULT_PULL_INTERVAL_SECONDS = 0;
15
20
  export const MIN_PULL_INTERVAL_SECONDS = 30;
16
21
  export const MAX_PULL_INTERVAL_SECONDS = 86_400;
@@ -41,7 +46,7 @@ export const runPollGit = async (cwd, args) => {
41
46
  try {
42
47
  const { stdout } = await execAsync("git", args, {
43
48
  cwd, encoding: "utf8", timeout: 10_000, maxBuffer: 1024 * 1024,
44
- env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never", GIT_OPTIONAL_LOCKS: "0" },
49
+ env: nonInteractiveGitEnv({ ...process.env, GIT_OPTIONAL_LOCKS: "0" }),
45
50
  });
46
51
  return { ok: true, output: stdout.trim() };
47
52
  }
@@ -49,22 +54,52 @@ export const runPollGit = async (cwd, args) => {
49
54
  return { ok: false, output: "", error: errorMessage(err) };
50
55
  }
51
56
  };
52
- function readPollState(phrenPath) {
57
+ /**
58
+ * A missing state file is a first check. A corrupt one is logged and moved
59
+ * aside (kept for inspection) so the next check starts clean instead of
60
+ * silently resetting the backoff on every poll.
61
+ */
62
+ export function readPollState(phrenPath) {
63
+ const file = runtimeFile(phrenPath, "pull-poll.json");
64
+ let text;
53
65
  try {
54
- const value = JSON.parse(fs.readFileSync(runtimeFile(phrenPath, "pull-poll.json"), "utf8"));
55
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
66
+ text = fs.readFileSync(file, "utf8");
56
67
  }
57
- catch {
68
+ catch (err) {
69
+ if (err.code !== "ENOENT")
70
+ logPeriodicSync(phrenPath, `poll state unreadable: ${errorMessage(err).split("\n")[0]}`);
58
71
  return {};
59
72
  }
73
+ let reason;
74
+ try {
75
+ const value = JSON.parse(text);
76
+ if (value && typeof value === "object" && !Array.isArray(value))
77
+ return value;
78
+ reason = "not a JSON object";
79
+ }
80
+ catch (err) {
81
+ reason = errorMessage(err).split("\n")[0];
82
+ }
83
+ const aside = `${file}.corrupt-${Date.now()}`;
84
+ try {
85
+ fs.renameSync(file, aside);
86
+ }
87
+ catch (err) {
88
+ debugLog(`poll state rename: ${errorMessage(err)}`);
89
+ }
90
+ logPeriodicSync(phrenPath, `poll state was corrupt (${reason}); moved it to ${path.basename(aside)} and started fresh`);
91
+ return {};
60
92
  }
61
93
  /** Includes user-owned operations: polling never continues or aborts these. */
62
94
  async function worktreeBusy(cwd, git) {
63
95
  const dir = await git(cwd, ["rev-parse", "--absolute-git-dir"]);
64
96
  if (!dir.ok)
65
97
  return true;
66
- return ["rebase-merge", "rebase-apply", "MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "sequencer", "index.lock"]
67
- .some((name) => fs.existsSync(path.join(dir.output, name)));
98
+ return inProgressGitOperation(cwd) !== undefined;
99
+ }
100
+ /** The periodic pull writes its decisions to the same log a background sync uses. */
101
+ function logPeriodicSync(phrenPath, detail) {
102
+ appendSyncLog(phrenPath, "periodic-pull", detail);
68
103
  }
69
104
  /** Shared timestamps + a process lock give all MCP clients one check per store/interval. */
70
105
  export async function pollStore(phrenPath, seconds, git = runPollGit, now = Date.now()) {
@@ -75,23 +110,33 @@ export async function pollStore(phrenPath, seconds, git = runPollGit, now = Date
75
110
  if (!releasePoll)
76
111
  return skipped;
77
112
  try {
113
+ const auth = activeStoreAuthFailure(phrenPath);
114
+ if (authBackoffActive(auth, now))
115
+ return { status: "not-due", detail: storeAuthDetail(auth) };
116
+ git = withStoreAuthBackoff(git, () => now);
78
117
  const previous = readPollState(phrenPath);
79
118
  const failures = Math.min(10, Math.max(0, Number(previous.failures) || 0));
80
119
  const delay = Math.min(seconds * 2 ** failures, Math.max(seconds, 1800)) * 1000;
81
120
  if (typeof previous.checkedAt === "number" && now >= previous.checkedAt && now - previous.checkedAt < delay)
82
121
  return skipped;
83
- const finish = (result, verifiedRemote = false) => {
122
+ const finish = async (result, verifiedRemote = false) => {
84
123
  atomicWriteText(runtimeFile(phrenPath, "pull-poll.json"), JSON.stringify({
85
124
  checkedAt: now, failures: result.status === "error" ? failures + 1 : 0, ...result,
86
125
  }) + "\n");
87
126
  if (verifiedRemote || result.status === "updated" || result.status === "error" || result.status === "deferred") {
88
127
  const at = new Date(now).toISOString();
89
128
  const ok = result.status === "updated" || result.status === "unchanged";
129
+ const counts = await aheadBehind(phrenPath, git);
90
130
  updateRuntimeHealth(phrenPath, { lastSync: {
91
131
  lastPullAt: at, lastPullStatus: ok ? "ok" : "error",
92
132
  lastPullDetail: result.detail,
93
133
  ...(ok ? { lastSuccessfulPullAt: at } : {}),
134
+ ...(counts ?? {}),
94
135
  } });
136
+ // A quiet "unchanged" poll is logged only when it follows a different outcome.
137
+ if (result.status !== "unchanged" || previous.status !== "unchanged") {
138
+ logSyncOutcome(phrenPath, "periodic-pull", { ok, detail: `${result.status}: ${result.detail}`, counts });
139
+ }
95
140
  }
96
141
  return result;
97
142
  };
@@ -116,7 +161,12 @@ export async function pollStore(phrenPath, seconds, git = runPollGit, now = Date
116
161
  const head = await git(phrenPath, ["rev-parse", "HEAD"]);
117
162
  if (!head.ok)
118
163
  return failed("Cannot read the store's current commit.");
119
- if (remoteHead === head.output)
164
+ const status = await git(phrenPath, ["status", "--porcelain"]);
165
+ if (!status.ok)
166
+ return failed("Cannot read the store's working tree state.");
167
+ const remoteUnchanged = remoteHead === head.output;
168
+ // The common poll (clean tree, remote already at HEAD) needs no lock.
169
+ if (remoteUnchanged && !status.output)
120
170
  return finish({ status: "unchanged", detail: "Remote is unchanged." }, true);
121
171
  const releaseGit = tryFileLock(runtimeFile(phrenPath, "git-op"));
122
172
  if (!releaseGit)
@@ -126,29 +176,23 @@ export async function pollStore(phrenPath, seconds, git = runPollGit, now = Date
126
176
  if (await worktreeBusy(phrenPath, git))
127
177
  return deferred("Periodic pull deferred: a Git operation is in progress.");
128
178
  const currentBranch = await git(phrenPath, ["symbolic-ref", "--quiet", "HEAD"]);
129
- const status = await git(phrenPath, ["status", "--porcelain"]);
130
- if (!currentBranch.ok || currentBranch.output !== branch.output || !status.ok || status.output) {
131
- return deferred("Periodic pull deferred: the branch changed or the store has uncommitted edits.");
132
- }
133
- const tracking = await git(phrenPath, ["rev-parse", "--verify", trackingRef]);
134
- if (!tracking.ok || tracking.output !== remoteHead) {
135
- const fetched = await git(phrenPath, ["fetch", "--quiet", "--no-tags", "--no-recurse-submodules", "--", remote, `${remoteRef}:${trackingRef}`]);
136
- if (!fetched.ok)
137
- return failed(`Periodic fetch failed: ${fetched.error}`);
138
- }
139
- const target = await git(phrenPath, ["rev-parse", "--verify", trackingRef]);
140
- if (!target.ok)
141
- return failed("Cannot read the fetched tracking branch.");
142
- if ((await git(phrenPath, ["merge-base", "--is-ancestor", target.output, "HEAD"])).ok) {
143
- return finish({ status: "unchanged", detail: "The store already contains the remote changes." }, true);
179
+ if (!currentBranch.ok || currentBranch.output !== branch.output) {
180
+ return deferred("Periodic pull deferred: the branch changed while checking.");
144
181
  }
145
- if (!(await git(phrenPath, ["merge-base", "--is-ancestor", "HEAD", target.output])).ok) {
146
- return deferred("Periodic pull deferred: local and remote history diverged. Resolve the store's sync conflict before pulling.");
182
+ const merged = await mergeStoreUpstream(phrenPath, {
183
+ git,
184
+ advertisedHead: remoteHead,
185
+ commitMessage: "auto-save phren (periodic pull)",
186
+ });
187
+ if (merged.committedLocalWrites)
188
+ logPeriodicSync(phrenPath, "committed uncommitted store writes before pull");
189
+ if (merged.status === "busy" || merged.status === "conflict") {
190
+ const reason = merged.status === "conflict" ? `local and remote history diverged. ${merged.detail}` : merged.detail;
191
+ return deferred(`Periodic pull deferred: ${reason}`);
147
192
  }
148
- const merged = await git(phrenPath, ["merge", "--ff-only", "--no-edit", target.output]);
149
- return merged.ok
150
- ? finish({ status: "updated", detail: "Store fast-forwarded by periodic pull." })
151
- : deferred(`Periodic fast-forward deferred: ${merged.error}`);
193
+ if (merged.status === "error")
194
+ return failed(`Periodic pull failed: ${merged.detail}`);
195
+ return finish({ status: merged.status, detail: merged.detail }, true);
152
196
  }
153
197
  finally {
154
198
  releaseGit();
@@ -183,12 +227,17 @@ export function startPullPolling(phrenPath, options) {
183
227
  if (!before.ok)
184
228
  return;
185
229
  const previous = heads.get(store) ?? before.output;
230
+ // The remote check itself runs once per configured interval
231
+ // (pollStore keeps the shared timestamp); the 5 s tick only notices
232
+ // another client's pull, so HEAD is read again only after a check.
233
+ let after = before;
186
234
  if (Date.now() - startedAt >= seconds * 1000) {
187
235
  const result = await pollStore(store, seconds, git);
188
236
  if (result.status === "error")
189
237
  debugLog(result.detail);
238
+ if (result.status !== "not-due")
239
+ after = await git(store, ["rev-parse", "HEAD"]);
190
240
  }
191
- const after = await git(store, ["rev-parse", "HEAD"]);
192
241
  if (!after.ok)
193
242
  return;
194
243
  if (after.output !== previous)
@@ -0,0 +1,29 @@
1
+ export interface GitResult {
2
+ ok: boolean;
3
+ output: string;
4
+ error?: string;
5
+ }
6
+ export type RunStoreGit = (cwd: string, args: string[]) => Promise<GitResult>;
7
+ export type StoreMergeStatus = "unchanged" | "updated" | "conflict" | "busy" | "error";
8
+ export interface StoreMergeResult {
9
+ status: StoreMergeStatus;
10
+ detail: string;
11
+ conflicts?: string[];
12
+ committedLocalWrites?: boolean;
13
+ }
14
+ export interface StoreMergeOptions {
15
+ git: RunStoreGit;
16
+ /** A head advertised by ls-remote. Lets polling avoid an unnecessary fetch. */
17
+ advertisedHead?: string;
18
+ /** Callers that just made their own commit can skip the auto-save commit. */
19
+ commitLocalWrites?: boolean;
20
+ commitMessage?: string;
21
+ }
22
+ /**
23
+ * Fetch and integrate a store's configured upstream without rebasing local
24
+ * commits. Conflicts in tasks.md (per task id against the merge base), the
25
+ * generated summary and topic blocks, findings and the task archive resolve
26
+ * automatically (see conflict-resolve.ts). Any other conflict aborts the
27
+ * merge and names its files.
28
+ */
29
+ export declare function mergeStoreUpstream(cwd: string, options: StoreMergeOptions): Promise<StoreMergeResult>;
@@ -0,0 +1,137 @@
1
+ import { resolveStoreConflicts } from "./conflict-resolve.js";
2
+ import { gitOperationRecovery, inProgressGitOperation } from "./git-state.js";
3
+ import { storeCommitMessage } from "../machine-identity.js";
4
+ const SENSITIVE_STORE_PATHSPECS = [".env", "**/.env", "*.pem", "*.key", ".config/auth-profiles.json"];
5
+ async function commitLocalStoreWrites(cwd, git, message) {
6
+ const add = await git(cwd, ["add", "--sparse", "-A"]);
7
+ if (!add.ok)
8
+ return { committed: false, error: add.error || "git add failed" };
9
+ await git(cwd, ["reset", "HEAD", "--", ...SENSITIVE_STORE_PATHSPECS]);
10
+ const staged = await git(cwd, ["diff", "--cached", "--name-only"]);
11
+ if (!staged.ok)
12
+ return { committed: false, error: staged.error || "git diff failed" };
13
+ if (!staged.output)
14
+ return { committed: false };
15
+ const commit = await git(cwd, ["-c", "commit.gpgsign=false", "commit", "-m", storeCommitMessage(message)]);
16
+ return commit.ok ? { committed: true } : { committed: false, error: commit.error || "git commit failed" };
17
+ }
18
+ async function conflictedPaths(cwd, git) {
19
+ const result = await git(cwd, ["diff", "--name-only", "--diff-filter=U"]);
20
+ return result.ok ? result.output.split("\n").map((entry) => entry.trim()).filter(Boolean) : [];
21
+ }
22
+ async function abortMerge(cwd, git) {
23
+ if (inProgressGitOperation(cwd) !== "merge")
24
+ return true;
25
+ const aborted = await git(cwd, ["merge", "--abort"]);
26
+ if (aborted.ok)
27
+ return true;
28
+ const reset = await git(cwd, ["reset", "--merge", "ORIG_HEAD"]);
29
+ return reset.ok && inProgressGitOperation(cwd) !== "merge";
30
+ }
31
+ /**
32
+ * Fetch and integrate a store's configured upstream without rebasing local
33
+ * commits. Conflicts in tasks.md (per task id against the merge base), the
34
+ * generated summary and topic blocks, findings and the task archive resolve
35
+ * automatically (see conflict-resolve.ts). Any other conflict aborts the
36
+ * merge and names its files.
37
+ */
38
+ export async function mergeStoreUpstream(cwd, options) {
39
+ const { git } = options;
40
+ const operation = inProgressGitOperation(cwd);
41
+ if (operation) {
42
+ const recovery = gitOperationRecovery(operation);
43
+ return {
44
+ status: "busy",
45
+ detail: `The store already has a Git operation in progress (${operation}). Run '${recovery}' in the store before syncing again.`,
46
+ };
47
+ }
48
+ const branch = await git(cwd, ["symbolic-ref", "--quiet", "HEAD"]);
49
+ if (!branch.ok)
50
+ return { status: "error", detail: "No branch is checked out." };
51
+ let committedLocalWrites = false;
52
+ if (options.commitLocalWrites !== false) {
53
+ const saved = await commitLocalStoreWrites(cwd, git, options.commitMessage ?? "auto-save phren (store sync)");
54
+ if (saved.error)
55
+ return { status: "error", detail: `Cannot commit local store writes: ${saved.error}` };
56
+ committedLocalWrites = saved.committed;
57
+ }
58
+ const refs = await git(cwd, ["for-each-ref", "--format=%(upstream:remotename)%09%(upstream:remoteref)%09%(upstream)", branch.output]);
59
+ const [remote, remoteRef, trackingRef] = refs.output.split("\t");
60
+ if (!refs.ok || !remote || !remoteRef || !trackingRef) {
61
+ return {
62
+ status: "unchanged",
63
+ detail: committedLocalWrites ? "Committed local store writes; no tracking remote is configured." : "No tracking remote is configured.",
64
+ committedLocalWrites,
65
+ };
66
+ }
67
+ const tracked = await git(cwd, ["rev-parse", "--verify", trackingRef]);
68
+ if (!options.advertisedHead || !tracked.ok || tracked.output !== options.advertisedHead) {
69
+ const fetched = await git(cwd, ["fetch", "--quiet", "--no-tags", "--no-recurse-submodules", "--", remote, `${remoteRef}:${trackingRef}`]);
70
+ if (!fetched.ok)
71
+ return { status: "error", detail: `Fetch failed: ${fetched.error || "unknown Git error"}`, committedLocalWrites };
72
+ }
73
+ const target = await git(cwd, ["rev-parse", "--verify", trackingRef]);
74
+ if (!target.ok || !target.output)
75
+ return { status: "error", detail: "Cannot read the fetched tracking branch.", committedLocalWrites };
76
+ if ((await git(cwd, ["merge-base", "--is-ancestor", target.output, "HEAD"])).ok) {
77
+ return {
78
+ status: "unchanged",
79
+ detail: committedLocalWrites ? "Committed local store writes; the store already contains the remote changes." : "The store already contains the remote changes.",
80
+ committedLocalWrites,
81
+ };
82
+ }
83
+ const canFastForward = (await git(cwd, ["merge-base", "--is-ancestor", "HEAD", target.output])).ok;
84
+ const merged = await git(cwd, canFastForward
85
+ ? ["merge", "--ff-only", target.output]
86
+ : ["merge", "--no-edit", target.output]);
87
+ if (merged.ok) {
88
+ return {
89
+ status: "updated",
90
+ detail: canFastForward ? "Store fast-forwarded to the remote." : "Store merged with the remote.",
91
+ committedLocalWrites,
92
+ };
93
+ }
94
+ const initialConflicts = await conflictedPaths(cwd, git);
95
+ if (initialConflicts.length === 0 && inProgressGitOperation(cwd) !== "merge") {
96
+ return {
97
+ status: "error",
98
+ detail: `Merge failed before it started: ${merged.error || "unknown Git error"}`,
99
+ committedLocalWrites,
100
+ };
101
+ }
102
+ if (initialConflicts.length > 0 && resolveStoreConflicts(cwd).unresolved.length === 0) {
103
+ const commit = await git(cwd, ["-c", "commit.gpgsign=false", "commit", "--no-edit"]);
104
+ if (commit.ok) {
105
+ return {
106
+ status: "updated",
107
+ detail: `Store merged with the remote; resolved conflicts in ${initialConflicts.join(", ")}.`,
108
+ conflicts: initialConflicts,
109
+ committedLocalWrites,
110
+ };
111
+ }
112
+ }
113
+ const unresolvedConflicts = await conflictedPaths(cwd, git);
114
+ const conflicts = unresolvedConflicts.length > 0 ? unresolvedConflicts : initialConflicts;
115
+ const cleaned = await abortMerge(cwd, git);
116
+ if (!cleaned) {
117
+ return {
118
+ status: "error",
119
+ detail: `Merge cleanup failed${conflicts.length ? ` after conflicts in: ${conflicts.join(", ")}` : ""}. Run 'git merge --abort' in the store.`,
120
+ conflicts,
121
+ committedLocalWrites,
122
+ };
123
+ }
124
+ if (conflicts.length > 0) {
125
+ return {
126
+ status: "conflict",
127
+ detail: `Merge aborted; manual resolution is required for: ${conflicts.join(", ")}`,
128
+ conflicts,
129
+ committedLocalWrites,
130
+ };
131
+ }
132
+ return {
133
+ status: "error",
134
+ detail: `Merge failed and was aborted: ${merged.error || "unknown Git error"}`,
135
+ committedLocalWrites,
136
+ };
137
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Three-way merge of a tasks.md file by task id, for store sync conflicts.
3
+ *
4
+ * Each task is keyed by its `bid:` comment (or its normalized text when it has
5
+ * none) and compared across the merge base, the local side and the incoming
6
+ * side. The side that changed a task wins; when both changed it, a completed
7
+ * side wins, then an edit beats a removal, then the incoming side wins. The
8
+ * result keeps the incoming file's layout and section order.
9
+ */
10
+ interface TaskEntry {
11
+ key: string;
12
+ section: string;
13
+ lines: string[];
14
+ }
15
+ /** The winning version of one task, or undefined when it is removed. */
16
+ export declare function pickTask<T extends TaskEntry>(base: T | undefined, ours: T | undefined, theirs: T | undefined): T | undefined;
17
+ /**
18
+ * Merges three versions of a tasks.md. `base` is empty when the file was
19
+ * added on both sides.
20
+ */
21
+ export declare function mergeTasksByBid(base: string, ours: string, theirs: string): string;
22
+ export {};
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Three-way merge of a tasks.md file by task id, for store sync conflicts.
3
+ *
4
+ * Each task is keyed by its `bid:` comment (or its normalized text when it has
5
+ * none) and compared across the merge base, the local side and the incoming
6
+ * side. The side that changed a task wins; when both changed it, a completed
7
+ * side wins, then an edit beats a removal, then the incoming side wins. The
8
+ * result keeps the incoming file's layout and section order.
9
+ */
10
+ const BID_PATTERN = /<!--\s*bid:([a-z0-9]{8})\b[^>]*-->/;
11
+ const COMPLETED_PATTERN = /^- \[[xX]\]/;
12
+ function taskKey(bullet) {
13
+ const bid = BID_PATTERN.exec(bullet);
14
+ if (bid)
15
+ return `bid:${bid[1]}`;
16
+ return `text:${bullet.replace(/^- \[[ xX]\]\s*/, "").replace(/<!--[\s\S]*?-->/g, "").trim().toLowerCase()}`;
17
+ }
18
+ /** Splits a tasks file into a preamble and `## ` sections of task records and other lines. */
19
+ function parse(content) {
20
+ const sections = [{ heading: null, name: "", rows: [] }];
21
+ let current = sections[0];
22
+ let task = null;
23
+ for (const line of content.replace(/\r\n/g, "\n").split("\n")) {
24
+ if (line.startsWith("## ")) {
25
+ task = null;
26
+ current = { heading: line, name: line.slice(3).trim(), rows: [] };
27
+ sections.push(current);
28
+ }
29
+ else if (line.startsWith("- ") && current.heading !== null) {
30
+ task = { key: taskKey(line), section: current.name, lines: [line] };
31
+ current.rows.push({ kind: "task", entry: task });
32
+ }
33
+ else if (task && line.startsWith(" ") && line.trim()) {
34
+ task.lines.push(line);
35
+ }
36
+ else {
37
+ task = null;
38
+ current.rows.push({ kind: "line", text: line });
39
+ }
40
+ }
41
+ return sections;
42
+ }
43
+ function index(sections) {
44
+ const map = new Map();
45
+ for (const section of sections) {
46
+ for (const row of section.rows) {
47
+ if (row.kind === "task" && !map.has(row.entry.key))
48
+ map.set(row.entry.key, row.entry);
49
+ }
50
+ }
51
+ return map;
52
+ }
53
+ const value = (entry) => entry ? `${entry.section}\n${entry.lines.join("\n")}` : undefined;
54
+ const completed = (entry) => !!entry && COMPLETED_PATTERN.test(entry.lines[0]);
55
+ /** The winning version of one task, or undefined when it is removed. */
56
+ export function pickTask(base, ours, theirs) {
57
+ const [b, o, t] = [value(base), value(ours), value(theirs)];
58
+ if (o === t)
59
+ return theirs;
60
+ if (o === b)
61
+ return theirs;
62
+ if (t === b)
63
+ return ours;
64
+ if (completed(ours) !== completed(theirs))
65
+ return completed(ours) ? ours : theirs;
66
+ if (!theirs)
67
+ return ours;
68
+ return theirs;
69
+ }
70
+ /**
71
+ * Merges three versions of a tasks.md. `base` is empty when the file was
72
+ * added on both sides.
73
+ */
74
+ export function mergeTasksByBid(base, ours, theirs) {
75
+ const oursSections = parse(ours);
76
+ const theirsSections = parse(theirs);
77
+ const b = index(parse(base));
78
+ const o = index(oursSections);
79
+ const t = index(theirsSections);
80
+ const chosen = new Map();
81
+ for (const key of new Set([...b.keys(), ...o.keys(), ...t.keys()])) {
82
+ const winner = pickTask(b.get(key), o.get(key), t.get(key));
83
+ if (winner)
84
+ chosen.set(key, winner);
85
+ }
86
+ // Local order, per section, so a task only the local side placed there lands after its local predecessor.
87
+ const localOrder = new Map();
88
+ for (const section of oursSections) {
89
+ localOrder.set(section.name, section.rows.flatMap((row) => row.kind === "task" ? [row.entry.key] : []));
90
+ }
91
+ const emitted = new Set();
92
+ const out = [];
93
+ const renderSection = (section) => {
94
+ if (section.heading !== null)
95
+ out.push(section.heading);
96
+ const rows = section.rows.filter((row) => {
97
+ if (row.kind !== "task")
98
+ return true;
99
+ const winner = chosen.get(row.entry.key);
100
+ return !!winner && winner.section === section.name && !emitted.has(row.entry.key);
101
+ }).map((row) => row.kind === "task" ? { kind: "task", entry: chosen.get(row.entry.key) } : row);
102
+ for (const row of rows)
103
+ if (row.kind === "task")
104
+ emitted.add(row.entry.key);
105
+ if (section.heading !== null) {
106
+ const missing = [...chosen.values()].filter((entry) => entry.section === section.name && !emitted.has(entry.key));
107
+ const order = localOrder.get(section.name) ?? [];
108
+ for (const entry of missing) {
109
+ const at = order.indexOf(entry.key);
110
+ const before = order.slice(0, Math.max(at, 0)).reverse().find((key) => rows.some((row) => row.kind === "task" && row.entry.key === key));
111
+ let position;
112
+ if (before) {
113
+ position = rows.findIndex((row) => row.kind === "task" && row.entry.key === before) + 1;
114
+ }
115
+ else {
116
+ const first = rows.findIndex((row) => row.kind === "task");
117
+ if (at >= 0 && first >= 0) {
118
+ position = first;
119
+ }
120
+ else {
121
+ let last = -1;
122
+ rows.forEach((row, i) => { if (row.kind === "task")
123
+ last = i; });
124
+ position = last >= 0 ? last + 1 : (rows.length > 0 && rows[0].kind === "line" && rows[0].text === "" ? 1 : 0);
125
+ }
126
+ }
127
+ rows.splice(position, 0, { kind: "task", entry });
128
+ emitted.add(entry.key);
129
+ }
130
+ }
131
+ for (const row of rows) {
132
+ if (row.kind === "task")
133
+ out.push(...row.entry.lines);
134
+ else
135
+ out.push(row.text);
136
+ }
137
+ };
138
+ for (const section of theirsSections)
139
+ renderSection(section);
140
+ // Sections only the local side has, in local order.
141
+ const theirNames = new Set(theirsSections.map((section) => section.name));
142
+ for (const section of oursSections) {
143
+ if (section.heading === null || theirNames.has(section.name))
144
+ continue;
145
+ const entries = [...chosen.values()].filter((entry) => entry.section === section.name && !emitted.has(entry.key));
146
+ if (entries.length === 0)
147
+ continue;
148
+ if (out.length > 0 && out[out.length - 1] !== "")
149
+ out.push("");
150
+ out.push(section.heading, "");
151
+ for (const entry of entries) {
152
+ out.push(...entry.lines);
153
+ emitted.add(entry.key);
154
+ }
155
+ out.push("");
156
+ }
157
+ return out.join("\n");
158
+ }
@@ -22,7 +22,7 @@ export function extractGithubRepoFromText(content) {
22
22
  return match?.[1];
23
23
  }
24
24
  export function resolveProjectGithubRepo(phrenPath, project) {
25
- for (const file of ["CLAUDE.md", "summary.md"]) {
25
+ for (const file of ["AGENTS.md", "summary.md"]) {
26
26
  const fullPath = path.join(phrenPath, project, file);
27
27
  if (!fs.existsSync(fullPath))
28
28
  continue;
@@ -4,6 +4,11 @@ interface TaskPromptLifecycleResult {
4
4
  mode: TaskMode;
5
5
  noticeLines: string[];
6
6
  }
7
+ /** What the person typed: the prompt without pasted blocks. */
8
+ export declare function typedPromptText(prompt: string): string;
9
+ /** A frame from another agent or the harness, or a message relayed from one,
10
+ * rather than something the person asked. */
11
+ export declare function isAgentFramePrompt(prompt: string): boolean;
7
12
  export declare function handleTaskPromptLifecycle(args: {
8
13
  phrenPath: string;
9
14
  prompt: string;